@dataplan/pg
Version:
PostgreSQL step classes for Grafast
78 lines • 2.79 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.assertPgClassSingleStep = assertPgClassSingleStep;
exports.makeScopedSQL = makeScopedSQL;
exports.runtimeScopedSQL = runtimeScopedSQL;
const tslib_1 = require("tslib");
const grafast_1 = require("grafast");
const pg_sql2_1 = tslib_1.__importDefault(require("pg-sql2"));
const pgDeleteSingle_ts_1 = require("./steps/pgDeleteSingle.js");
const pgInsertSingle_ts_1 = require("./steps/pgInsertSingle.js");
const pgSelectSingle_ts_1 = require("./steps/pgSelectSingle.js");
const pgUpdateSingle_ts_1 = require("./steps/pgUpdateSingle.js");
function assertPgClassSingleStep(step) {
if (!(step instanceof pgSelectSingle_ts_1.PgSelectSingleStep ||
step instanceof pgInsertSingle_ts_1.PgInsertSingleStep ||
step instanceof pgUpdateSingle_ts_1.PgUpdateSingleStep ||
step instanceof pgDeleteSingle_ts_1.PgDeleteSingleStep)) {
throw new Error(`Expected a PgSelectSingleStep, PgInsertSingleStep, PgUpdateSingleStep or PgDeleteSingleStep, however we received '${step}'.`);
}
}
function hasAlias(t) {
return t != null && t.alias != null && pg_sql2_1.default.isSQL(t.alias);
}
function hasGetPgRoot(t) {
return t != null && typeof t.getPgRoot === "function";
}
function makeScopedSQL(that) {
function isThis(value) {
return value === that;
}
const sqlTransformer = (sql, value) => {
if (isThis(value)) {
if (hasAlias(that)) {
return that.alias;
}
else if (hasGetPgRoot(that)) {
return that.getPgRoot().alias;
}
else {
throw new Error(`Don't know how to embed ${(0, grafast_1.inspect)(value)}`);
}
}
if (value instanceof grafast_1.ExecutableStep && "pgCodec" in value) {
if (value.pgCodec) {
return that.placeholder(value);
}
else {
throw new Error(`${value} has invalid value for pgCodec`);
}
}
else if (hasAlias(value)) {
return value.alias;
}
else {
return value;
}
};
return (cb) => typeof cb === "function"
? pg_sql2_1.default.withTransformer(sqlTransformer, cb)
: cb;
}
const runtimeSQLTransformer = (sql, value) => {
if (hasAlias(value)) {
return value.alias;
}
else {
if (value instanceof grafast_1.ExecutableStep) {
throw new Error(`Cannot reference steps at runtime`);
}
return value;
}
};
function runtimeScopedSQL(cb) {
return typeof cb === "function"
? pg_sql2_1.default.withTransformer(runtimeSQLTransformer, cb)
: cb;
}
//# sourceMappingURL=utils.js.map