@clickup/ent-framework
Version:
A PostgreSQL graph-database-alike library with microsharding and row-level security
97 lines • 4.51 kB
JavaScript
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.PgQueryUpsert = void 0;
const pickBy_1 = __importDefault(require("lodash/pickBy"));
const QueryBase_1 = require("../abstract/QueryBase");
const misc_1 = require("../internal/misc");
const types_1 = require("../types");
const PgRunner_1 = require("./PgRunner");
class PgQueryUpsert extends QueryBase_1.QueryBase {
constructor() {
super(...arguments);
// TODO: we need to do the same as we did with PgQueryUpdate() here. Because
// currently upsert ignores autoInsert fields in ON CONFLICT UPDATE ...
// clause, so if some field is auto-insertable (i.e. has default value on
// insert), it will be ignored by upsert even if it's provided in the input
// row. It may be not simple though; not clear, is it expressible in SQL at
// all or not.
/** @ignore */
this.RUNNER_CLASS = PgRunnerUpsert;
}
}
exports.PgQueryUpsert = PgQueryUpsert;
class PgRunnerUpsert extends PgRunner_1.PgRunner {
constructor(schema, client) {
super(schema, client);
this.op = "UPSERT";
this.maxBatchSize = 100;
// TODO: there is a bug here, autoInsert fields are NOT updated during the
// upsert (they are only inserted). Not clear how to fix this, because we
// don't want e.g. created_at to be updated (and it's an autoInsert field).
const fields = this.addPK(Object.keys(this.schema.table), "prepend");
const uniqueKeyFields = this.schema.uniqueKey
.map((field) => this.escapeField(field))
.join(",");
this.builder = this.createValuesBuilder({
prefix: this.fmt("INSERT INTO %T (%FIELDS) VALUES", { fields }),
indent: " ",
fields,
skipSorting: true, // we rely on the order of rows returned; see FRAGILE! comment below
suffix: this.fmt("\n" +
` ON CONFLICT (${uniqueKeyFields}) DO UPDATE ` +
`SET %UPDATE_FIELD_VALUE_PAIRS(EXCLUDED) RETURNING %PK AS ${types_1.ID}`, {
fields: Object.keys((0, pickBy_1.default)(this.schema.table, ({ autoInsert }) => autoInsert === undefined)),
}),
});
}
// Upsert always succeed, or if it fails, we have troubles with the whole batch!
get default() {
throw Error("BUG: upsert must always return a value");
}
key(inputIn) {
// This is not fast. Upsert is not fast and is ugly in general.
if (!this.schema.uniqueKey.length) {
throw Error(`Define unique key fields to use upsert for ${this.name}`);
}
const input = inputIn;
const key = [];
for (const field of this.schema.uniqueKey) {
key.push(input[field] === null || input[field] === undefined
? { guaranteed_unique_value: super.key(inputIn) }
: input[field]);
}
return JSON.stringify(key);
}
async runSingle(input, annotations) {
const sql = this.builder.prefix +
this.builder.func([["", input]]) +
this.builder.suffix;
const rows = await this.clientQuery(sql, annotations, 1);
return (0, misc_1.nullthrows)(rows[0], sql)[types_1.ID];
}
async runBatch(inputs, annotations) {
const sql = this.builder.prefix + this.builder.func(inputs) + this.builder.suffix;
const rows = await this.clientQuery(sql, annotations, inputs.size);
if (rows.length !== inputs.size) {
throw Error(`BUG: number of rows returned from upsert (${rows.length}) ` +
`is different from the number of input rows (${inputs.size}): ${sql}`);
}
// FRAGILE! In "INSERT ... VALUES ... ON CONFLICT DO UPDATE ... RETURNING
// ..." in case insert didn't happen we can't match the updated row id with
// the key. Luckily, the order of rows returned is the same as the input
// rows order, and "ON CONFLICT DO UPDATE" update always succeeds entirely
// (or fails entirely).
const outputs = new Map();
let i = 0;
for (const key of inputs.keys()) {
outputs.set(key, rows[i][types_1.ID]);
i++;
}
return outputs;
}
}
PgRunnerUpsert.IS_WRITE = true;
//# sourceMappingURL=PgQueryUpsert.js.map
;