Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update mapping macro to support case-insensitive comparisons when matching column name to property name #195

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading