Allow the use of enums (#168)

This commit is contained in:
Jamie Gaskins 2022-10-26 10:06:14 -04:00 committed by GitHub
parent 07c68d38e4
commit 167b55966e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 74 additions and 2 deletions

View file

@ -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