Skip to content

Commit

Permalink
Use the first registered connection if none are provided
Browse files Browse the repository at this point in the history
  • Loading branch information
Blacksmoke16 committed Jul 30, 2019
1 parent 984a3a9 commit 542fc2f
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 2 deletions.
12 changes: 11 additions & 1 deletion spec/adapter/adapters_spec.cr
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
require "../spec_helper"

class Foo < Granite::Base
connection mysql
connection sqlite

column id : Int64, primary: true
end

class Bar < Granite::Base
column id : Int64, primary: true
end

describe Granite::Connections do
describe "registration" do
it "should allow connections to be be saved and looked up" do
Expand All @@ -24,6 +28,12 @@ describe Granite::Connections do

it "should assign the correct connections to a model" do
adapter = Foo.adapter
adapter.name.should eq "sqlite"
adapter.url.should eq ENV["SQLITE_DATABASE_URL"]
end

it "should use the first registered connection if none are specified" do
adapter = Bar.adapter
adapter.name.should eq "mysql"
adapter.url.should eq ENV["MYSQL_DATABASE_URL"]
end
Expand Down
2 changes: 1 addition & 1 deletion src/granite/connections.cr
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ module Granite
@@registered_connections << adapter
end

def self.[](name : String) : Granite::Adapter::Base?
def self.[](name : String?) : Granite::Adapter::Base?
registered_connections.find { |conn| conn.name == name }
end
end
Expand Down
4 changes: 4 additions & 0 deletions src/granite/table.cr
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ end

module Granite::Tables
module ClassMethods
def adapter : Granite::Adapter::Base
Granite::Connections.registered_connections.first? || raise "No connections have been registered."
end

def primary_name
{% begin %}
{% primary_key = @type.instance_vars.find { |ivar| (ann = ivar.annotation(Granite::Column)) && ann[:primary] } %}
Expand Down

0 comments on commit 542fc2f

Please sign in to comment.