Skip to content

Commit

Permalink
don't attempt to store the last id on model if primary key is composi…
Browse files Browse the repository at this point in the history
…te object #689
  • Loading branch information
leafo committed Feb 15, 2023
1 parent af1f4f0 commit adf7a9c
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 11 deletions.
10 changes: 6 additions & 4 deletions lapis/db/mysql/model.lua
Original file line number Diff line number Diff line change
Expand Up @@ -134,11 +134,13 @@ do
values.created_at = values.created_at or time
values.updated_at = values.updated_at or time
end
local res = db.insert(self:table_name(), values, self:primary_keys())
local res = db.insert(self:table_name(), values)
if res then
local new_id = res.last_auto_id or res.insert_id
if not values[self.primary_key] and new_id and new_id ~= 0 then
values[self.primary_key] = new_id
if type(self.primary_key) == "string" then
local new_id = res.last_auto_id or res.insert_id
if not values[self.primary_key] and new_id and new_id ~= 0 then
values[self.primary_key] = new_id
end
end
return self:load(values)
else
Expand Down
15 changes: 8 additions & 7 deletions lapis/db/mysql/model.moon
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,16 @@ class Model extends BaseModel
values.created_at or= time
values.updated_at or= time

res = db.insert @table_name!, values, @primary_keys!
res = db.insert @table_name!, values

if res
-- FIXME this code works only if mysql backend is
-- either luasql (field res.last_auto_id) or
-- lua-resty-mysql (field res.insert_id) and
new_id = res.last_auto_id or res.insert_id
if not values[@primary_key] and new_id and new_id != 0
values[@primary_key] = new_id
-- NOTE: Due to limitation of mysql bindings, we can't handle setting
-- auto-incrementing id if it's part of a composite primary key.
-- Recommendation: use mariadb which supports RETURNING syntax
if type(@primary_key) == "string"
new_id = res.last_auto_id or res.insert_id
if not values[@primary_key] and new_id and new_id != 0
values[@primary_key] = new_id
@load values
else
nil, "Failed to create #{@__name}"
Expand Down

0 comments on commit adf7a9c

Please sign in to comment.