mirror of
https://gitea.invidious.io/iv-org/shard-crystal-db.git
synced 2024-08-15 00:53:32 +00:00
Allow the use of enums
This commit is contained in:
parent
3e9ed7a304
commit
7e64e6a275
2 changed files with 74 additions and 0 deletions
|
@ -81,6 +81,29 @@ class ModelWithJSON
|
|||
property c1 : String
|
||||
end
|
||||
|
||||
struct ModelWithEnum
|
||||
include DB::Serializable
|
||||
|
||||
getter c0 : Int32
|
||||
getter c1 : MyEnum
|
||||
# Ensure multiple enum types work together
|
||||
getter c2 : MyOtherEnum
|
||||
|
||||
enum MyEnum
|
||||
Foo
|
||||
Bar
|
||||
Baz
|
||||
Quux
|
||||
end
|
||||
|
||||
enum MyOtherEnum
|
||||
OMG
|
||||
LOL
|
||||
WTF
|
||||
BBQ
|
||||
end
|
||||
end
|
||||
|
||||
macro from_dummy(query, type)
|
||||
with_dummy do |db|
|
||||
rs = db.query({{ query }})
|
||||
|
@ -172,6 +195,17 @@ describe "DB::Serializable" do
|
|||
expect_model("1,a", ModelWithJSON, {c0: 1, c1: "a"})
|
||||
end
|
||||
|
||||
it "should initialize a model with an enum property" do
|
||||
expect_model("1,Baz,LOL", ModelWithEnum, {
|
||||
c0: 1,
|
||||
c1: ModelWithEnum::MyEnum::Baz,
|
||||
c2: ModelWithEnum::MyOtherEnum::LOL,
|
||||
})
|
||||
expect_raises DB::MappingException, "Unknown enum ModelWithEnum::MyEnum value: adsf" do
|
||||
from_dummy("1,adsf,BBQ", ModelWithEnum)
|
||||
end
|
||||
end
|
||||
|
||||
it "should initialize multiple instances from a single resultset" do
|
||||
with_dummy do |db|
|
||||
db.query("1,a 2,b") do |rs|
|
||||
|
|
|
@ -96,6 +96,23 @@ module DB
|
|||
end
|
||||
end
|
||||
|
||||
# Read the value based on the given `enum` type, supporting both string and
|
||||
# numeric column types.
|
||||
#
|
||||
# ```
|
||||
# enum Status
|
||||
# Pending
|
||||
# Complete
|
||||
# end
|
||||
#
|
||||
# db.query "SELECT 'complete'" do |rs|
|
||||
# rs.read Status # => Status::Complete
|
||||
# end
|
||||
# ```
|
||||
def read(type : Enum.class)
|
||||
type.new(self)
|
||||
end
|
||||
|
||||
# Reads the next columns and returns a tuple of the values.
|
||||
def read(*types : Class)
|
||||
internal_read(*types)
|
||||
|
@ -135,3 +152,26 @@ module DB
|
|||
# end
|
||||
end
|
||||
end
|
||||
|
||||
struct Enum
|
||||
def self.new(rs : DB::ResultSet) : self
|
||||
index = rs.next_column_index
|
||||
|
||||
case value = rs.read
|
||||
when String
|
||||
result = parse value
|
||||
when Int
|
||||
result = from_value value
|
||||
else
|
||||
raise DB::ColumnTypeMismatchError.new(
|
||||
context: "#{self}#new(rs : DB::ResultSet)",
|
||||
column_index: index,
|
||||
column_name: rs.column_name(index),
|
||||
column_type: to_s,
|
||||
expected_type: "String | Int",
|
||||
)
|
||||
end
|
||||
|
||||
result
|
||||
end
|
||||
end
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue