Skip to content

Commit

Permalink
Fix namespaced vs top-level type-name collisions
Browse files Browse the repository at this point in the history
Allow top-level property types to have the same name as DB-namespaced
ones.
  • Loading branch information
jgaskins committed Mar 10, 2024
1 parent 3eaac85 commit 133b78f
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
24 changes: 24 additions & 0 deletions spec/serializable_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,23 @@ struct ModelWithEnum
end
end

# Ensure types that happen to have the same name as types within the `DB`
# namespace don't clash here
struct Transaction
include DB::Serializable

@[DB::Field(key: "c0")]
getter id : Int32
@[DB::Field(key: "c1")]
getter status : Status

enum Status
Pending
Complete
Canceled
end
end

macro from_dummy(query, type)
with_dummy do |db|
rs = db.query({{ query }})
Expand Down Expand Up @@ -206,6 +223,13 @@ describe "DB::Serializable" do
end
end

it "should compile when top-level names collide with DB-namespaced names" do
expect_model("1,Pending", Transaction, {
id: 1,
status: Transaction::Status::Pending,
})
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
4 changes: 2 additions & 2 deletions src/db/serializable.cr
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ module DB
{% elsif value[:nilable] || value[:default] != nil %}
rs.read(::Union({{value[:type]}} | Nil))
{% else %}
rs.read({{value[:type]}})
rs.read(::{{value[:type]}})
{% end %}
rescue exc
::raise ::DB::MappingException.new(exc.message, self.class.to_s, {{name.stringify}}, cause: exc)
Expand Down Expand Up @@ -166,7 +166,7 @@ module DB
{% elsif value[:default] != nil %}
@{{key}} = %var{key}.is_a?(Nil) ? {{value[:default]}} : %var{key}
{% else %}
@{{key}} = %var{key}.as({{value[:type]}})
@{{key}} = %var{key}.as(::{{value[:type]}})
{% end %}
{% end %}
{% end %}
Expand Down

0 comments on commit 133b78f

Please sign in to comment.