Skip to content

Commit

Permalink
Dj/271 maintain one database connection (#274)
Browse files Browse the repository at this point in the history
* fix multiple connection issue #271

* create a single connection per registered adapter
  • Loading branch information
drujensen authored Aug 29, 2018
1 parent 094db58 commit 8d8eadc
Show file tree
Hide file tree
Showing 4 changed files with 10 additions and 5 deletions.
2 changes: 1 addition & 1 deletion shard.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ name: granite

version: 0.13.0

crystal: 0.25.1
crystal: 0.26.0

authors:
- drujensen <drujensen@gmail.com>
Expand Down
2 changes: 1 addition & 1 deletion spec/adapter/adapters_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ describe Granite::Adapters do

it "should disallow multiple adapters with the same name" do
expect_raises(Exception, "Adapter with name 'mysql' has already been registered.") do
Granite::Adapters << Granite::Adapter::Pg.new({name: "mysql", url: "PG_DATABASE_URL"})
Granite::Adapters << Granite::Adapter::Pg.new({name: "mysql", url: ENV["PG_DATABASE_URL"]})
end
end

Expand Down
7 changes: 5 additions & 2 deletions spec/spec_helper.cr
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
require "spec"
require "mysql"
require "pg"
require "sqlite3"

Granite::Adapters << Granite::Adapter::Mysql.new({name: "mysql", url: ENV["MYSQL_DATABASE_URL"]})
Granite::Adapters << Granite::Adapter::Pg.new({name: "pg", url: ENV["PG_DATABASE_URL"]})
Granite::Adapters << Granite::Adapter::Sqlite.new({name: "sqlite", url: ENV["SQLITE_DATABASE_URL"]})

require "spec"

module GraniteExample
ADAPTERS = ["pg", "mysql", "sqlite"]
end
Expand Down
4 changes: 3 additions & 1 deletion src/adapter/base.cr
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,16 @@ require "db"
abstract class Granite::Adapter::Base
getter name : String
getter url : String
private property database : DB::Database

def initialize(connection_hash : NamedTuple(url: String, name: String))
@name = connection_hash[:name]
@url = connection_hash[:url]
@database = DB.open(@url)
end

def open(&block)
yield DB.open(@url)
yield database
end

def log(query : String, params = [] of String) : Nil
Expand Down

0 comments on commit 8d8eadc

Please sign in to comment.