mirror of
https://gitea.invidious.io/iv-org/shard-crystal-db.git
synced 2024-08-15 00:53:32 +00:00
Support mappable classes in query_one and query_all methods
This commit is contained in:
parent
99352d9d2d
commit
9ca0b19d9e
3 changed files with 29 additions and 0 deletions
|
@ -131,4 +131,23 @@ describe "DB.mapping" do
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
it "should initialize from a query_one" do
|
||||||
|
with_dummy do |db|
|
||||||
|
obj = db.query_one "1,a", as: SimpleMapping
|
||||||
|
obj.c0.should eq(1)
|
||||||
|
obj.c1.should eq("a")
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
it "should initialize from a query_all" do
|
||||||
|
with_dummy do |db|
|
||||||
|
objs = db.query_all "1,a 2,b", as: SimpleMapping
|
||||||
|
objs.size.should eq(2)
|
||||||
|
objs[0].c0.should eq(1)
|
||||||
|
objs[0].c1.should eq("a")
|
||||||
|
objs[1].c0.should eq(2)
|
||||||
|
objs[1].c1.should eq("b")
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
end
|
end
|
||||||
|
|
|
@ -1,5 +1,8 @@
|
||||||
module DB
|
module DB
|
||||||
|
|
||||||
|
# Empty module used for marking a class as supporting DB:Mapping
|
||||||
|
module Mappable; end
|
||||||
|
|
||||||
# The `DB.mapping` macro defines how an object is built from a DB::ResultSet.
|
# The `DB.mapping` macro defines how an object is built from a DB::ResultSet.
|
||||||
#
|
#
|
||||||
# It takes hash literal as argument, in which attributes and types are defined.
|
# It takes hash literal as argument, in which attributes and types are defined.
|
||||||
|
@ -56,6 +59,8 @@ module DB
|
||||||
#
|
#
|
||||||
# This macro also declares instance variables of the types given in the mapping.
|
# This macro also declares instance variables of the types given in the mapping.
|
||||||
macro mapping(properties, strict = true)
|
macro mapping(properties, strict = true)
|
||||||
|
include DB::Mappable
|
||||||
|
|
||||||
{% for key, value in properties %}
|
{% for key, value in properties %}
|
||||||
{% properties[key] = {type: value} unless value.is_a?(HashLiteral) || value.is_a?(NamedTupleLiteral) %}
|
{% properties[key] = {type: value} unless value.is_a?(HashLiteral) || value.is_a?(NamedTupleLiteral) %}
|
||||||
{% end %}
|
{% end %}
|
||||||
|
|
|
@ -64,6 +64,11 @@ module DB
|
||||||
# Reads the next column value
|
# Reads the next column value
|
||||||
abstract def read
|
abstract def read
|
||||||
|
|
||||||
|
# Reads the next columns and maps them to a class
|
||||||
|
def read(type : DB::Mappable.class)
|
||||||
|
type.new(self)
|
||||||
|
end
|
||||||
|
|
||||||
# Reads the next column value as a **type**
|
# Reads the next column value as a **type**
|
||||||
def read(type : T.class) : T
|
def read(type : T.class) : T
|
||||||
read.as(T)
|
read.as(T)
|
||||||
|
|
Loading…
Reference in a new issue