Skip to content

Commit 6367c1a

Browse files
authored
feat: support upserting tables with only unique constraint(s) (#680)
* feat: support upserting tables with only unique constraint(s) * test: update tests * test: fix syntax * test: fix expected set size
1 parent f74429b commit 6367c1a

File tree

2 files changed

+18
-10
lines changed

2 files changed

+18
-10
lines changed

src/__tests__/main.test.ts

+9-2
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,12 @@ test.beforeEach(async (t) => {
8181
name text
8282
)
8383
`);
84+
await t.context.client.query(`
85+
create table just_unique_constraints (
86+
name text,
87+
unique (name)
88+
)
89+
`);
8490
await initializePostgraphile(t);
8591
});
8692

@@ -221,17 +227,18 @@ const create = async (
221227
return execGqlOp(t, nanographql(mutation));
222228
};
223229

224-
test("ignores tables without primary keys", async (t) => {
230+
test("ignores tables without primary keys or unique constraints", async (t) => {
225231
await create(t);
226232
const res = await fetchMutationTypes(t);
227233
const upsertMutations = new Set(
228234
res.data.__type.fields
229235
.map(({ name }) => name)
230236
.filter((name) => name.startsWith("upsert"))
231237
);
232-
t.assert(upsertMutations.size === 2);
238+
t.assert(upsertMutations.size === 3);
233239
t.assert(upsertMutations.has("upsertBike"));
234240
t.assert(upsertMutations.has("upsertRole"));
241+
t.assert(upsertMutations.has("upsertJustUniqueConstraint"));
235242
});
236243

237244
test("upsert crud - match primary key constraint", async (t) => {

src/postgraphile-upsert.ts

+9-8
Original file line numberDiff line numberDiff line change
@@ -27,14 +27,15 @@ export const PgMutationUpsertPlugin: Plugin = (builder) => {
2727
).filter((con) => con.type === "u" || con.type === "p");
2828
const upsertFieldsByName = (pgIntrospectionResultsByKind.class as PgTable[])
2929
.filter(
30-
(table) =>
31-
!!table.namespace &&
32-
!!table.primaryKeyConstraint &&
33-
!omit(table, "upsert") &&
34-
table.isSelectable &&
35-
table.isInsertable &&
36-
table.isUpdatable
37-
)
30+
(table) => {
31+
const hasUniqueConstraint = allUniqueConstraints.some((c) => c.classId === table.id);
32+
return !!table.namespace &&
33+
(!!table.primaryKeyConstraint || hasUniqueConstraint) &&
34+
!omit(table, "upsert") &&
35+
table.isSelectable &&
36+
table.isInsertable &&
37+
table.isUpdatable
38+
})
3839
.reduce<GraphQLFieldConfigMap<unknown, unknown>>((fnsByName, table) => {
3940
const gqlTable = pgGetGqlTypeByTypeIdAndModifier(table.type.id, null);
4041
if (!gqlTable) return fnsByName;

0 commit comments

Comments
 (0)