diff --git a/spec/mapping_spec.cr b/spec/mapping_spec.cr index dc9b516..2969e07 100644 --- a/spec/mapping_spec.cr +++ b/spec/mapping_spec.cr @@ -29,6 +29,13 @@ class MappingWithNilables }) end +class MappingWithNilTypes + DB.mapping({ + c0: {type: Int32?, default: 10}, + c1: String?, + }) +end + class MappingWithKeys DB.mapping({ foo: {type: Int32, key: "c0"}, @@ -100,14 +107,22 @@ describe "DB.mapping" do expect_mapping("1,NULL", MappingWithDefaults, {c0: 1, c1: "c"}) end - it "should initialize a mapping with nils if columns are missing" do + it "should initialize a mapping with nilable set if columns are missing" do expect_mapping("1", MappingWithNilables, {c0: 1, c1: nil}) end - it "should initialize a mapping with nils ignoring default value is type is nilable" do + it "should initialize a mapping with nilable set ignoring default value if NULL" do expect_mapping("NULL,a", MappingWithNilables, {c0: nil, c1: "a"}) end + it "should initialize a mapping with nilable types if columns are missing" do + expect_mapping("1", MappingWithNilTypes, {c0: 1, c1: nil}) + end + + it "should initialize a mapping with nilable types ignoring default value if NULL" do + expect_mapping("NULL,a", MappingWithNilTypes, {c0: nil, c1: "a"}) + end + it "should initialize a mapping with different keys" do expect_mapping("1,a", MappingWithKeys, {foo: 1, bar: "a"}) end diff --git a/src/db/mapping.cr b/src/db/mapping.cr index 148e791..f627ec1 100644 --- a/src/db/mapping.cr +++ b/src/db/mapping.cr @@ -64,6 +64,10 @@ module DB {% properties[key] = {type: value} unless value.is_a?(HashLiteral) || value.is_a?(NamedTupleLiteral) %} {% end %} + {% for key, value in properties %} + {% value[:nilable] = true if value[:type].is_a?(Generic) && value[:type].type_vars.map(&.resolve).includes?(Nil) %} + {% end %} + {% for key, value in properties %} @{{key.id}} : {{value[:type]}} {{ (value[:nilable] ? "?" : "").id }} @@ -131,7 +135,7 @@ module DB {% elsif value[:default] != nil %} @{{key.id}} = %var{key.id}.is_a?(Nil) ? {{value[:default]}} : %var{key.id} {% else %} - @{{key.id}} = %var{key.id}.not_nil! + @{{key.id}} = %var{key.id}.as({{value[:type]}}) {% end %} {% end %} end