mirror of
https://gitea.invidious.io/iv-org/shard-crystal-db.git
synced 2024-08-15 00:53:32 +00:00
introduce database as driver wrapper.
expose list of types to support by the drivers implementors. deal with nilable types with `#read?(T.class) : T?` methods. change `#has_next` to `#move_next`
This commit is contained in:
parent
c16dc42e96
commit
1572062501
7 changed files with 91 additions and 51 deletions
20
src/db/database.cr
Normal file
20
src/db/database.cr
Normal file
|
@ -0,0 +1,20 @@
|
|||
module DB
|
||||
# Acts as an entry point for database access.
|
||||
# Offers a com
|
||||
class Database
|
||||
getter driver_class
|
||||
getter options
|
||||
|
||||
def initialize(@driver_class, @options)
|
||||
@driver = @driver_class.new(@options)
|
||||
end
|
||||
|
||||
def prepare(query)
|
||||
@driver.prepare(query)
|
||||
end
|
||||
|
||||
def exec(query, *args)
|
||||
prepare(query).exec(*args)
|
||||
end
|
||||
end
|
||||
end
|
|
@ -1,4 +1,6 @@
|
|||
module DB
|
||||
TYPES = [String, Int32, Int64, Float32, Float64]
|
||||
|
||||
def self.driver_class(name) # : Driver.class
|
||||
@@drivers.not_nil![name]
|
||||
end
|
||||
|
@ -8,11 +10,12 @@ module DB
|
|||
@@drivers.not_nil![name] = klass
|
||||
end
|
||||
|
||||
def self.driver(name, options)
|
||||
driver_class(name).new(options)
|
||||
def self.open(name, options)
|
||||
Database.new(driver_class(name), options)
|
||||
end
|
||||
end
|
||||
|
||||
require "./database"
|
||||
require "./driver"
|
||||
require "./statement"
|
||||
require "./result_set"
|
||||
|
|
|
@ -6,32 +6,21 @@ module DB
|
|||
end
|
||||
|
||||
def each
|
||||
while has_next
|
||||
while move_next
|
||||
yield
|
||||
end
|
||||
end
|
||||
|
||||
abstract def has_next : Bool
|
||||
|
||||
# def read(t : T.class) : T
|
||||
# end
|
||||
abstract def move_next : Bool
|
||||
|
||||
# list datatypes that must be supported form the driver
|
||||
# implementors will override read_string
|
||||
# users will call read(String) due to overloads read(T) will be a T
|
||||
# TODO: unable to write unions (nillables)
|
||||
{% for t in [String, UInt64] %}
|
||||
# users will call read(String) or read?(String) for nillables
|
||||
{% for t in DB::TYPES %}
|
||||
abstract def read?(t : {{t}}.class) : {{t}}?
|
||||
|
||||
def read(t : {{t}}.class) : {{t}}
|
||||
read_{{t.name.underscore}}
|
||||
read?({{t}}).not_nil!
|
||||
end
|
||||
|
||||
protected abstract def read_{{t.name.underscore}} : {{t}}
|
||||
{% end %}
|
||||
|
||||
# def read(t : String.class) : String
|
||||
# read_string
|
||||
# end
|
||||
#
|
||||
# protected abstract def read_string : String
|
||||
end
|
||||
end
|
||||
|
|
|
@ -1,5 +1,7 @@
|
|||
module DB
|
||||
abstract class Statement
|
||||
getter driver
|
||||
|
||||
def initialize(@driver)
|
||||
end
|
||||
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue