Skip to content

Commit

Permalink
code-gen: support setting primary key in generated insert queries (#491)
Browse files Browse the repository at this point in the history
  • Loading branch information
dirkdev98 authored Nov 14, 2020
1 parent ff2fff1 commit f336ead
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 15 deletions.
8 changes: 5 additions & 3 deletions packages/code-gen/src/generator/sql/query-basics.js
Original file line number Diff line number Diff line change
Expand Up @@ -218,17 +218,19 @@ function insertQuery(context, imports, type) {
/**
* @param {Postgres} sql
* @param {${type.partial.insertType}|(${type.partial.insertType}[])} insert
* @param {{ withPrimaryKey: boolean }=} options
* @returns {Promise<${type.uniqueName}[]>}
*/
export function ${type.name}Insert(sql, insert) {
export function ${type.name}Insert(sql, insert, options = {}) {
if (insert === undefined || insert.length === 0) {
return [];
}
options.withPrimaryKey = options.withPrimaryKey ?? false;
return query\`
INSERT INTO "${type.name}" ($\{${type.name}Fields(
"", { excludePrimaryKey: true })})
VALUES $\{${type.name}InsertValues(insert)}
"", { excludePrimaryKey: !options.withPrimaryKey })})
VALUES $\{${type.name}InsertValues(insert, { includePrimaryKey: options.withPrimaryKey })}
RETURNING $\{${type.name}Fields("")}
\`.exec(sql);
}
Expand Down
11 changes: 11 additions & 0 deletions packages/code-gen/test/sql.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,17 @@ test("code-gen/e2e/sql", async (t) => {
}
});

t.test("Insert with primary key", async (t) => {
const id = uuid();
const [category] = await client.queries.categoryInsert(
sql,
{ id, label: "TestPK" },
{ withPrimaryKey: true },
);

t.equal(category.id, id);
});

t.test("deletedAt in the future", async (t) => {
const future = new Date();
future.setUTCDate(future.getUTCDate() + 1);
Expand Down
46 changes: 34 additions & 12 deletions packages/store/src/generated/query-basics.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit f336ead

Please sign in to comment.