Update mapping macro to support both case-sensitive and -insensitive

comparisons when matching column name to property name

Column to property name matching remains case-sensitive by default,
but the matching can be set to be case-insensitive as follows:

    # will match column names "foo" or "Foo" or "fOo" or FOO" etc.
    # to property name "foo"
    DB.mapping({ foo: String }, case_sensitive: false)
This commit is contained in:
Lachlan Dowding 2023-11-07 17:07:26 +10:00
parent 285e865e3a
commit 90fd3ae2c2
2 changed files with 13 additions and 3 deletions

View file

@ -63,6 +63,12 @@ class MappingWithConverter
}) })
end end
class MappingWithCaseInsensitivity
DB.mapping({
foo: {type: Int32, key: "C0"},
}, case_sensitive: false)
end
macro from_dummy(query, type) macro from_dummy(query, type)
with_dummy do |db| with_dummy do |db|
rs = db.query({{ query }}) rs = db.query({{ query }})
@ -146,6 +152,10 @@ describe "DB.mapping" do
expect_mapping("Zm9v,a", MappingWithConverter, {c0: "foo".to_slice, c1: "a"}) expect_mapping("Zm9v,a", MappingWithConverter, {c0: "foo".to_slice, c1: "a"})
end end
it "should perform column name to property name match with case insensitivity" do
expect_mapping("1", MappingWithCaseInsensitivity, {foo: 1})
end
it "should initialize multiple instances from a single resultset" do it "should initialize multiple instances from a single resultset" do
with_dummy do |db| with_dummy do |db|
db.query("1,a 2,b") do |rs| db.query("1,a 2,b") do |rs|

View file

@ -57,7 +57,7 @@ module DB
# it and initializes this type's instance variables. # it and initializes this type's instance variables.
# #
# 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, case_sensitive = true)
include ::DB::Mappable include ::DB::Mappable
{% for key, value in properties %} {% for key, value in properties %}
@ -102,9 +102,9 @@ module DB
{% end %} {% end %}
%rs.each_column do |col_name| %rs.each_column do |col_name|
case col_name case col_name{% if !case_sensitive %}.downcase{% end %}
{% for key, value in properties %} {% for key, value in properties %}
when {{value[:key] || key.id.stringify}} when {{value[:key] || key.id.stringify}}{% if !case_sensitive %}.downcase{% end %}
%found{key.id} = true %found{key.id} = true
%var{key.id} = %var{key.id} =
{% if value[:converter] %} {% if value[:converter] %}