Skip to content

Commit

Permalink
Allow models to specifiy conflict keys
Browse files Browse the repository at this point in the history
fixes Kong#12288

The upsert DAO function generated uses the primary
key as an "ON CONFLICT" match. This might not be the case
if a field uses a unique flag or if that field is also
workgroupable. Postgresql requires an index to be specified.

I tried autodetecting the correct behavior but it failed
on other models. Changing the primary key also did not work.
I added a way to specify the conflict index.
It defaults to the primary key.
  • Loading branch information
poelzi committed Feb 13, 2024
1 parent f9f4111 commit ee392e9
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 1 deletion.
7 changes: 7 additions & 0 deletions kong/db/schema/metaschema.lua
Original file line number Diff line number Diff line change
Expand Up @@ -608,6 +608,13 @@ local MetaSchema = Schema.new({
nilable = true,
},
},
{
unique_key = {
type = "array",
elements = { type = "string" },
nilable = true,
},
},
{
generate_admin_api = {
type = "boolean",
Expand Down
5 changes: 4 additions & 1 deletion kong/db/strategies/postgres/init.lua
Original file line number Diff line number Diff line change
Expand Up @@ -818,6 +818,8 @@ function _M.new(connector, schema, errors)

local unique_fields = {}

local unique_key = schema.unique_key


for field_name, field in schema:each_field() do
if field.type == "foreign" then
Expand Down Expand Up @@ -998,6 +1000,7 @@ function _M.new(connector, schema, errors)
insert(page_next_names, LIMIT)

local pk_escaped = concat(primary_key_escaped, ", ")
local unique_escaped = concat(unique_key or primary_key_escaped, ", ")

select_expressions = concat(select_expressions, ", ")
primary_key_placeholders = concat(primary_key_placeholders, ", ")
Expand Down Expand Up @@ -1129,7 +1132,7 @@ function _M.new(connector, schema, errors)
code = {
"INSERT INTO ", table_name_escaped, " (", insert_columns, ")\n",
" VALUES (", insert_expressions, ")\n",
"ON CONFLICT (", pk_escaped, ") DO UPDATE\n",
"ON CONFLICT (", unique_escaped, ") DO UPDATE\n",
" SET ", upsert_expressions, "\n",
" RETURNING ", select_expressions, ";",
}
Expand Down
1 change: 1 addition & 0 deletions kong/plugins/key-auth/daos.lua
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ return {
endpoint_key = "key",
cache_key = { "key" },
workspaceable = true,
unique_key = { "ws_id", "key" },
admin_api_name = "key-auths",
admin_api_nested_name = "key-auth",
fields = {
Expand Down

0 comments on commit ee392e9

Please sign in to comment.