@compas/code-gen
Advanced tools
Comparing version
{ | ||
"name": "@compas/code-gen", | ||
"version": "0.0.155", | ||
"version": "0.0.156", | ||
"description": "Generate various boring parts of your server", | ||
@@ -18,4 +18,4 @@ "main": "./index.js", | ||
"dependencies": { | ||
"@compas/cli": "0.0.155", | ||
"@compas/stdlib": "0.0.155" | ||
"@compas/cli": "0.0.156", | ||
"@compas/stdlib": "0.0.156" | ||
}, | ||
@@ -22,0 +22,0 @@ "maintainers": [ |
@@ -21,2 +21,7 @@ import { upperCaseFirst } from "../../utils.js"; | ||
const primaryKey = getPrimaryKeyWithType(type); | ||
const upsertByPrimaryKey = `${type.name}UpsertOn${upperCaseFirst( | ||
primaryKey.key, | ||
)}`; | ||
if (!type.queryOptions.isView) { | ||
@@ -26,2 +31,3 @@ names.push( | ||
`${type.name}Insert`, | ||
upsertByPrimaryKey, | ||
`${type.name}Update`, | ||
@@ -31,2 +37,3 @@ ); | ||
src.push(insertQuery(context, imports, type)); | ||
src.push(upsertQueryByPrimaryKey(context, imports, type)); | ||
src.push(updateQuery(context, imports, type)); | ||
@@ -209,2 +216,46 @@ | ||
*/ | ||
function upsertQueryByPrimaryKey(context, imports, type) { | ||
const primaryKey = getPrimaryKeyWithType(type); | ||
const name = `${type.name}UpsertOn${upperCaseFirst(primaryKey.key)}`; | ||
return js` | ||
/** | ||
* @param {Postgres} sql | ||
* @param {${type.partial.insertType}|(${type.partial.insertType}[])} insert | ||
* @param {{}} [options={}] | ||
* @returns {Promise<${type.uniqueName}[]>} | ||
*/ | ||
async function ${name}(sql, insert, options = {}) { | ||
if (insert === undefined || insert.length === 0) { | ||
return []; | ||
} | ||
const fieldString = [...${type.name}FieldSet] | ||
.filter(it => it !== "${primaryKey.key}" && it !== "createdAt") | ||
.map((column) => \`"$\{column}" = COALESCE(EXCLUDED."$\{column}", "${ | ||
type.name | ||
}"."$\{column}")\`) | ||
.join(","); | ||
const result = await query\` | ||
INSERT INTO "${type.name}" ($\{${type.name}Fields( | ||
"", { excludePrimaryKey: false })}) | ||
VALUES $\{${type.name}InsertValues( | ||
insert, { includePrimaryKey: true })} | ||
ON CONFLICT ("${primaryKey.key}") DO UPDATE SET $\{query([fieldString])} | ||
RETURNING $\{${type.name}Fields("")} | ||
\`.exec(sql); | ||
transform${upperCaseFirst(type.name)}(result); | ||
return result; | ||
} | ||
`; | ||
} | ||
/** | ||
* @param {CodeGenContext} context | ||
* @param {ImportCreator} imports | ||
* @param {CodeGenObjectType} type | ||
*/ | ||
function updateQuery(context, imports, type) { | ||
@@ -211,0 +262,0 @@ return js` |
425214
0.38%13729
0.32%+ Added
+ Added
+ Added
- Removed
- Removed
- Removed
Updated
Updated