From adf7a9c4d1bc4dba105bfddac0b086e51f486d99 Mon Sep 17 00:00:00 2001 From: leaf corcoran Date: Wed, 15 Feb 2023 12:40:30 -0800 Subject: [PATCH] don't attempt to store the last id on model if primary key is composite object #689 --- lapis/db/mysql/model.lua | 10 ++++++---- lapis/db/mysql/model.moon | 15 ++++++++------- 2 files changed, 14 insertions(+), 11 deletions(-) diff --git a/lapis/db/mysql/model.lua b/lapis/db/mysql/model.lua index ff9414df..6958ef4d 100644 --- a/lapis/db/mysql/model.lua +++ b/lapis/db/mysql/model.lua @@ -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 diff --git a/lapis/db/mysql/model.moon b/lapis/db/mysql/model.moon index e4dd7796..42493b8a 100644 --- a/lapis/db/mysql/model.moon +++ b/lapis/db/mysql/model.moon @@ -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}"