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 (#168)
This commit is contained in:
parent
07c68d38e4
commit
167b55966e
4 changed files with 74 additions and 2 deletions
|
@ -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,24 @@ 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
|
||||
parse value
|
||||
when Int
|
||||
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: value.class.to_s,
|
||||
expected_type: "String | Int",
|
||||
)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue