Skip to content

Commit

Permalink
feat: support upserting tables with only unique constraint(s) (#680)
Browse files Browse the repository at this point in the history
* feat: support upserting tables with only unique constraint(s)

* test: update tests

* test: fix syntax

* test: fix expected set size
  • Loading branch information
bchrobot authored Jul 29, 2023
1 parent f74429b commit 6367c1a
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 10 deletions.
11 changes: 9 additions & 2 deletions src/__tests__/main.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,12 @@ test.beforeEach(async (t) => {
name text
)
`);
await t.context.client.query(`
create table just_unique_constraints (
name text,
unique (name)
)
`);
await initializePostgraphile(t);
});

Expand Down Expand Up @@ -221,17 +227,18 @@ const create = async (
return execGqlOp(t, nanographql(mutation));
};

test("ignores tables without primary keys", async (t) => {
test("ignores tables without primary keys or unique constraints", async (t) => {
await create(t);
const res = await fetchMutationTypes(t);
const upsertMutations = new Set(
res.data.__type.fields
.map(({ name }) => name)
.filter((name) => name.startsWith("upsert"))
);
t.assert(upsertMutations.size === 2);
t.assert(upsertMutations.size === 3);
t.assert(upsertMutations.has("upsertBike"));
t.assert(upsertMutations.has("upsertRole"));
t.assert(upsertMutations.has("upsertJustUniqueConstraint"));
});

test("upsert crud - match primary key constraint", async (t) => {
Expand Down
17 changes: 9 additions & 8 deletions src/postgraphile-upsert.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,14 +27,15 @@ export const PgMutationUpsertPlugin: Plugin = (builder) => {
).filter((con) => con.type === "u" || con.type === "p");
const upsertFieldsByName = (pgIntrospectionResultsByKind.class as PgTable[])
.filter(
(table) =>
!!table.namespace &&
!!table.primaryKeyConstraint &&
!omit(table, "upsert") &&
table.isSelectable &&
table.isInsertable &&
table.isUpdatable
)
(table) => {
const hasUniqueConstraint = allUniqueConstraints.some((c) => c.classId === table.id);
return !!table.namespace &&
(!!table.primaryKeyConstraint || hasUniqueConstraint) &&
!omit(table, "upsert") &&
table.isSelectable &&
table.isInsertable &&
table.isUpdatable
})
.reduce<GraphQLFieldConfigMap<unknown, unknown>>((fnsByName, table) => {
const gqlTable = pgGetGqlTypeByTypeIdAndModifier(table.type.id, null);
if (!gqlTable) return fnsByName;
Expand Down

0 comments on commit 6367c1a

Please sign in to comment.