Skip to content

Commit

Permalink
Update mapping macro to support both case-sensitive and -insensitive
Browse files Browse the repository at this point in the history
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)
  • Loading branch information
lachlan committed Nov 8, 2023
1 parent 285e865 commit 90fd3ae
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 3 deletions.
10 changes: 10 additions & 0 deletions spec/mapping_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,12 @@ class MappingWithConverter
})
end

class MappingWithCaseInsensitivity
DB.mapping({
foo: {type: Int32, key: "C0"},
}, case_sensitive: false)
end

macro from_dummy(query, type)
with_dummy do |db|
rs = db.query({{ query }})
Expand Down Expand Up @@ -146,6 +152,10 @@ describe "DB.mapping" do
expect_mapping("Zm9v,a", MappingWithConverter, {c0: "foo".to_slice, c1: "a"})
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
with_dummy do |db|
db.query("1,a 2,b") do |rs|
Expand Down
6 changes: 3 additions & 3 deletions src/db/mapping.cr
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ module DB
# it and initializes this type's instance variables.
#
# 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

{% for key, value in properties %}
Expand Down Expand Up @@ -102,9 +102,9 @@ module DB
{% end %}

%rs.each_column do |col_name|
case col_name
case col_name{% if !case_sensitive %}.downcase{% end %}
{% 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
%var{key.id} =
{% if value[:converter] %}
Expand Down

0 comments on commit 90fd3ae

Please sign in to comment.