Skip to content

Commit adf7a9c

Browse files
committed
don't attempt to store the last id on model if primary key is composite object #689
1 parent af1f4f0 commit adf7a9c

File tree

2 files changed

+14
-11
lines changed

2 files changed

+14
-11
lines changed

lapis/db/mysql/model.lua

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -134,11 +134,13 @@ do
134134
values.created_at = values.created_at or time
135135
values.updated_at = values.updated_at or time
136136
end
137-
local res = db.insert(self:table_name(), values, self:primary_keys())
137+
local res = db.insert(self:table_name(), values)
138138
if res then
139-
local new_id = res.last_auto_id or res.insert_id
140-
if not values[self.primary_key] and new_id and new_id ~= 0 then
141-
values[self.primary_key] = new_id
139+
if type(self.primary_key) == "string" then
140+
local new_id = res.last_auto_id or res.insert_id
141+
if not values[self.primary_key] and new_id and new_id ~= 0 then
142+
values[self.primary_key] = new_id
143+
end
142144
end
143145
return self:load(values)
144146
else

lapis/db/mysql/model.moon

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -26,15 +26,16 @@ class Model extends BaseModel
2626
values.created_at or= time
2727
values.updated_at or= time
2828

29-
res = db.insert @table_name!, values, @primary_keys!
29+
res = db.insert @table_name!, values
3030

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

0 commit comments

Comments
 (0)