@graffy/pg 0.18.1-alpha.2 → 0.19.1-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.cjs DELETED
@@ -1,996 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const common = require("@graffy/common");
4
- const debug = require("debug");
5
- const pg$1 = require("pg");
6
- const sqlFormatter = require("sql-formatter");
7
- class Sql {
8
- constructor(rawStrings, rawValues) {
9
- if (rawStrings.length - 1 !== rawValues.length) {
10
- if (rawStrings.length === 0) {
11
- throw new TypeError("Expected at least 1 string");
12
- }
13
- throw new TypeError(`Expected ${rawStrings.length} strings to have ${rawStrings.length - 1} values`);
14
- }
15
- const valuesLength = rawValues.reduce((len, value) => len + (value instanceof Sql ? value.values.length : 1), 0);
16
- this.values = new Array(valuesLength);
17
- this.strings = new Array(valuesLength + 1);
18
- this.strings[0] = rawStrings[0];
19
- let i = 0, pos = 0;
20
- while (i < rawValues.length) {
21
- const child = rawValues[i++];
22
- const rawString = rawStrings[i];
23
- if (child instanceof Sql) {
24
- this.strings[pos] += child.strings[0];
25
- let childIndex = 0;
26
- while (childIndex < child.values.length) {
27
- this.values[pos++] = child.values[childIndex++];
28
- this.strings[pos] = child.strings[childIndex];
29
- }
30
- this.strings[pos] += rawString;
31
- } else {
32
- this.values[pos++] = child;
33
- this.strings[pos] = rawString;
34
- }
35
- }
36
- }
37
- get sql() {
38
- const len = this.strings.length;
39
- let i = 1;
40
- let value = this.strings[0];
41
- while (i < len)
42
- value += `?${this.strings[i++]}`;
43
- return value;
44
- }
45
- get statement() {
46
- const len = this.strings.length;
47
- let i = 1;
48
- let value = this.strings[0];
49
- while (i < len)
50
- value += `:${i}${this.strings[i++]}`;
51
- return value;
52
- }
53
- get text() {
54
- const len = this.strings.length;
55
- let i = 1;
56
- let value = this.strings[0];
57
- while (i < len)
58
- value += `$${i}${this.strings[i++]}`;
59
- return value;
60
- }
61
- inspect() {
62
- return {
63
- sql: this.sql,
64
- statement: this.statement,
65
- text: this.text,
66
- values: this.values
67
- };
68
- }
69
- }
70
- function join(values, separator = ",", prefix = "", suffix = "") {
71
- if (values.length === 0) {
72
- throw new TypeError("Expected `join([])` to be called with an array of multiple elements, but got an empty array");
73
- }
74
- return new Sql([prefix, ...Array(values.length - 1).fill(separator), suffix], values);
75
- }
76
- function raw(value) {
77
- return new Sql([value], []);
78
- }
79
- const empty = raw("");
80
- function sql(strings, ...values) {
81
- return new Sql(strings, values);
82
- }
83
- function formatSqlParam(value) {
84
- if (value === null || value === void 0) return "null";
85
- if (["number", "boolean"].includes(typeof value)) return value.toString();
86
- switch (typeof value) {
87
- case "number":
88
- case "boolean":
89
- return value.toString();
90
- case "string":
91
- return pg$1.escapeLiteral(value);
92
- case "object":
93
- if (Array.isArray(value))
94
- return `array[${value.map(formatSqlParam).join(", ")}]`;
95
- return `'${JSON.stringify(value)}'`;
96
- default:
97
- return "";
98
- }
99
- }
100
- function formatSql(sql2) {
101
- return sqlFormatter.format(sql2.text, {
102
- language: "postgresql",
103
- params: Object.fromEntries(
104
- sql2.values.map((value, idx) => [idx + 1, formatSqlParam(value)])
105
- )
106
- });
107
- }
108
- const getJsonBuildTrusted = (variadic) => {
109
- const args = join(
110
- Object.entries(variadic).map(([name, value]) => {
111
- return sql`'${raw(name)}', ${getJsonBuildValue(value)}`;
112
- })
113
- );
114
- return sql`jsonb_build_object(${args})`;
115
- };
116
- const getJsonBuildValue = (value) => {
117
- if (value instanceof Sql) return value;
118
- if (typeof value === "string") return sql`${value}::text`;
119
- return sql`${JSON.stringify(stripAttributes(value))}::jsonb`;
120
- };
121
- function colName(prefix, options) {
122
- if (!options.schema.types[prefix]) throw Error(`pg.no_column ${prefix}`);
123
- return raw(prefix);
124
- }
125
- const lookup = (prop, options) => {
126
- const [prefix, ...suffix] = prop.split(".");
127
- if (!suffix.length) return sql`"${colName(prefix, options)}"`;
128
- const { types: types2 } = options.schema;
129
- if (types2[prefix] === "jsonb") {
130
- return sql`"${raw(prefix)}" #> ${suffix}`;
131
- }
132
- if (types2[prefix] === "cube" && suffix.length === 1) {
133
- return sql`"${raw(prefix)}" ~> ${Number.parseInt(suffix[0], 10)}`;
134
- }
135
- throw Error(`pg.cannot_lookup ${prop}`);
136
- };
137
- const lookupNumeric = (prop) => {
138
- const [prefix, ...suffix] = prop.split(".");
139
- return suffix.length ? sql`CASE WHEN "${raw(prefix)}" #> ${suffix} = 'null'::jsonb
140
- THEN 0 ELSE ("${raw(prefix)}" #> ${suffix})::numeric END` : sql`"${raw(prefix)}"`;
141
- };
142
- const aggSql = {
143
- $sum: (prop) => sql`sum((${lookupNumeric(prop)})::numeric)`,
144
- $card: (prop, options) => sql`count(distinct(${lookup(prop, options)}))`,
145
- $avg: (prop) => sql`avg((${lookupNumeric(prop)})::numeric)`,
146
- $max: (prop) => sql`max((${lookupNumeric(prop)})::numeric)`,
147
- $min: (prop) => sql`min((${lookupNumeric(prop)})::numeric)`
148
- };
149
- const getOptimisedJsonBuild = (object, path, parentPropertyName, options) => {
150
- const propertyNames = Object.keys(object);
151
- const propertyPath = [...path, parentPropertyName];
152
- const buildConfig = [];
153
- path = path || [];
154
- propertyNames.forEach((propertyName) => {
155
- const property = object[propertyName];
156
- if (typeof property === "object") {
157
- const childJSONBuild = getOptimisedJsonBuild(
158
- property,
159
- propertyPath,
160
- propertyName,
161
- options
162
- );
163
- buildConfig.push(
164
- sql`${propertyName}::text, jsonb_build_object(${join(childJSONBuild, ", ")})`
165
- );
166
- } else {
167
- if (property === true) {
168
- buildConfig.push(
169
- sql`${propertyName}::text, ${lookup([...propertyPath, propertyName].join("."), options)}`
170
- );
171
- }
172
- }
173
- });
174
- return buildConfig;
175
- };
176
- const getSelectCols = (options, projection = null) => {
177
- if (!projection) return sql`*`;
178
- const sqls = [];
179
- for (const key in projection) {
180
- if (key === "$count") {
181
- sqls.push(sql`count(*) AS "$count"`);
182
- } else if (aggSql[key]) {
183
- const subSqls = [];
184
- for (const prop in projection[key]) {
185
- subSqls.push(sql`${prop}::text, ${aggSql[key](prop, options)}`);
186
- }
187
- sqls.push(
188
- sql`jsonb_build_object(${join(subSqls, ", ")}) AS "${raw(key)}"`
189
- );
190
- } else {
191
- if (typeof projection[key] === "object") {
192
- const optimisedJsonBuild = getOptimisedJsonBuild(
193
- projection[key],
194
- [],
195
- key,
196
- options
197
- );
198
- sqls.push(
199
- sql`jsonb_build_object(${join(optimisedJsonBuild, ", ")}) AS "${raw(key)}"`
200
- );
201
- } else {
202
- sqls.push(sql`"${raw(key)}"`);
203
- }
204
- }
205
- }
206
- return join(sqls, ", ");
207
- };
208
- function vertexSql(array, nullValue) {
209
- return sql`array[${join(
210
- array.map((num) => num === null ? nullValue : num)
211
- )}]::float8[]`;
212
- }
213
- function cubeLiteralSql(value) {
214
- if (!(Array.isArray(value) && value.length) || Array.isArray(value[0]) && value.length !== 2) {
215
- throw Error(`pg.castValue_bad_cube${JSON.stringify(value)}`);
216
- }
217
- return Array.isArray(value[0]) ? sql`cube(${vertexSql(value[0], sql`'-Infinity'`)}, ${vertexSql(
218
- value[1],
219
- sql`'Infinity'`
220
- )})` : sql`cube(${vertexSql(value, 0)})`;
221
- }
222
- function castValue(value, type, name, isPut) {
223
- if (!type) throw Error(`pg.write_no_column ${name}`);
224
- if (value instanceof Sql) return value;
225
- if (value === null) return sql`NULL`;
226
- if (type === "jsonb") {
227
- return isPut ? JSON.stringify(stripAttributes(value)) : getJsonUpdate(value, name, [])[0];
228
- }
229
- if (type === "cube") return cubeLiteralSql(value);
230
- return value;
231
- }
232
- const getInsert = (rows, options) => {
233
- const { verCol, schema } = options;
234
- const cols = [];
235
- const colSqls = [];
236
- const colIx = {};
237
- const colUsed = [];
238
- for (const col of Object.keys(options.schema.types)) {
239
- colIx[col] = cols.length;
240
- colUsed[cols.length] = false;
241
- cols.push(col);
242
- colSqls.push(sql`"${raw(col)}"`);
243
- }
244
- colUsed[colIx[verCol]] = true;
245
- const vals = [];
246
- for (const row of rows) {
247
- const rowVals = Array(cols.length).fill(sql`default`);
248
- for (const col of cols) {
249
- if (col === verCol || !(col in row)) continue;
250
- const ix = colIx[col];
251
- colUsed[ix] = true;
252
- rowVals[ix] = castValue(row[col], schema.types[col], col, row.$put);
253
- }
254
- vals.push(rowVals);
255
- }
256
- const isUsed = (_, ix) => colUsed[ix];
257
- return {
258
- cols: join(colSqls.filter(isUsed), ", "),
259
- vals: join(
260
- vals.map((rowVals) => sql`(${join(rowVals.filter(isUsed), ", ")})`),
261
- ", "
262
- ),
263
- updates: join(
264
- colSqls.map((col, _ix) => sql`${col} = "excluded".${col}`).filter(isUsed),
265
- ", "
266
- )
267
- };
268
- };
269
- const getUpdates = (row, options) => {
270
- return join(
271
- Object.entries(row).filter(([col]) => col !== options.idCol && col[0] !== "$").map(
272
- ([col, val]) => sql`"${raw(col)}" = ${castValue(
273
- val,
274
- options.schema.types[col],
275
- col,
276
- row.$put
277
- )}`
278
- ).concat(sql`"${raw(options.verCol)}" = default`),
279
- ", "
280
- );
281
- };
282
- function getJsonUpdate(object, col, path) {
283
- if (!object || typeof object !== "object" || Array.isArray(object) || object.$put) {
284
- const patch2 = stripAttributes(object);
285
- return [sql`${JSON.stringify(patch2)}::jsonb`, patch2 === null];
286
- }
287
- if ("$val" in object) {
288
- const value = object.$val === true ? stripAttributes(object) : object.$val;
289
- return [sql`${JSON.stringify({ $val: value })}::jsonb`, false];
290
- }
291
- const curr = sql`"${raw(col)}"${path.length ? sql`#>${path}` : empty}`;
292
- if (common.isEmpty(object)) return [curr, false];
293
- const baseSql = sql`case jsonb_typeof(${curr})
294
- when 'object' then ${curr}
295
- else '{}'::jsonb
296
- end`;
297
- let maybeNull = true;
298
- let hasNulls = false;
299
- const patchSqls = Object.entries(object).map(([key, value]) => {
300
- const [valSql, nullable] = getJsonUpdate(value, col, path.concat(key));
301
- maybeNull &&= nullable;
302
- hasNulls ||= nullable;
303
- return sql`${key}::text, ${valSql}`;
304
- });
305
- let clause = sql`${baseSql} || jsonb_build_object(${join(patchSqls, ", ")})`;
306
- if (hasNulls) {
307
- clause = sql`(select jsonb_object_agg(key, value)
308
- from jsonb_each(${clause}) where value <> 'null'::jsonb)`;
309
- }
310
- if (maybeNull) {
311
- clause = sql`nullif(${clause}, '{}'::jsonb)`;
312
- }
313
- return [clause, maybeNull];
314
- }
315
- function stripAttributes(object) {
316
- if (typeof object !== "object" || !object) return object;
317
- if (Array.isArray(object)) {
318
- return object.map((item) => stripAttributes(item));
319
- }
320
- return Object.entries(object).reduce(
321
- (out, [key, val]) => {
322
- if (key === "$put" || val === null) return out;
323
- if (out === null) out = {};
324
- out[key] = stripAttributes(val);
325
- return out;
326
- },
327
- null
328
- );
329
- }
330
- const valid = {
331
- $eq: true,
332
- $lt: true,
333
- $gt: true,
334
- $lte: true,
335
- $gte: true,
336
- $re: true,
337
- $ire: true,
338
- $text: true,
339
- $and: true,
340
- $or: true,
341
- $any: true,
342
- $all: true,
343
- $has: true,
344
- $cts: true,
345
- $ctd: true,
346
- $keycts: true,
347
- $keyctd: true
348
- };
349
- const inverse = {
350
- $eq: "$neq",
351
- $neq: "$eq",
352
- $in: "$nin",
353
- $nin: "$in",
354
- $lt: "$gte",
355
- $gte: "$lt",
356
- $gt: "$lte",
357
- $lte: "$gt"
358
- };
359
- function getAst(filter) {
360
- return simplify(construct(filter));
361
- }
362
- function isValidSubQuery(node) {
363
- if (!node || typeof node !== "object") return false;
364
- const keys = Object.keys(node);
365
- for (const key of keys) {
366
- if (key[0] === "$" && !["$and", "$or", "$not"].includes(key)) return false;
367
- if (key[0] !== "$") return true;
368
- }
369
- for (const key in node) {
370
- if (!isValidSubQuery(node[key])) return false;
371
- }
372
- return false;
373
- }
374
- function construct(node, prop, op) {
375
- if (!node || typeof node !== "object" || prop && op) {
376
- if (op && prop) return [op, prop, node];
377
- if (prop) return ["$eq", prop, node];
378
- throw Error(`pgast.expected_prop_before:${JSON.stringify(node)}`);
379
- }
380
- if (Array.isArray(node)) {
381
- return ["$or", node.map((item) => construct(item, prop, op))];
382
- }
383
- if (prop && isValidSubQuery(node)) {
384
- return ["$sub", prop, construct(node)];
385
- }
386
- return [
387
- "$and",
388
- Object.entries(node).map(([key, val]) => {
389
- if (key === "$or" || key === "$and") {
390
- return [key, construct(val, prop, op)[1]];
391
- }
392
- if (key === "$not") {
393
- return [key, construct(val, prop, op)];
394
- }
395
- if (key[0] === "$") {
396
- if (!valid[key]) throw Error(`pgast.invalid_op:${key}`);
397
- if (op) throw Error(`pgast.unexpected_op:${op} before:${key}`);
398
- if (!prop) throw Error(`pgast.expected_prop_before:${key}`);
399
- return construct(val, prop, key);
400
- }
401
- return construct(val, key);
402
- })
403
- ];
404
- }
405
- function simplify(node) {
406
- const op = node[0];
407
- if (op === "$and" || op === "$or") {
408
- node[1] = node[1].map((subnode) => simplify(subnode));
409
- } else if (op === "$not") {
410
- node[1] = simplify(node[1]);
411
- } else if (op === "$sub") {
412
- node[2] = simplify(node[2]);
413
- }
414
- if (op === "$and") {
415
- if (!node[1].length) return true;
416
- if (node[1].includes(false)) return false;
417
- node[1] = node[1].filter((item) => item !== true);
418
- } else if (op === "$or") {
419
- if (!node[1].length) return false;
420
- if (node[1].includes(true)) return true;
421
- node[1] = node[1].filter((item) => item !== false);
422
- } else if (op === "$not" && typeof node[1] === "boolean") {
423
- return !node[1];
424
- }
425
- if (op === "$or") {
426
- const { eqmap, noneq, change } = node[1].reduce(
427
- (acc, item) => {
428
- if (item[0] !== "$eq" || item[2] === null) {
429
- acc.noneq.push(item);
430
- } else if (acc.eqmap[item[1]]) {
431
- acc.change = true;
432
- acc.eqmap[item[1]].push(item[2]);
433
- return acc;
434
- } else {
435
- acc.eqmap[item[1]] = [item[2]];
436
- }
437
- return acc;
438
- },
439
- { eqmap: {}, noneq: [], change: false }
440
- );
441
- if (change) {
442
- node[1] = [
443
- ...noneq,
444
- ...Object.entries(eqmap).map(
445
- ([prop, val]) => val.length > 1 ? ["$in", prop, val] : ["$eq", prop, val[0]]
446
- )
447
- ];
448
- }
449
- }
450
- if ((op === "$and" || op === "$or") && node[1].length === 1) {
451
- return node[1][0];
452
- }
453
- if (op === "$not") {
454
- const [subop, ...subargs] = node[1];
455
- const invop = inverse[subop];
456
- return invop ? [invop, ...subargs] : node;
457
- }
458
- return node;
459
- }
460
- const opSql = {
461
- $and: "AND",
462
- // Not SQL as these are used as delimiters
463
- $or: "OR",
464
- $not: sql`NOT`,
465
- $eq: sql`=`,
466
- $neq: sql`<>`,
467
- $in: sql`IN`,
468
- $nin: sql`NOT IN`,
469
- $lt: sql`<`,
470
- $lte: sql`<=`,
471
- $gt: sql`>`,
472
- $gte: sql`>=`,
473
- $re: sql`~`,
474
- $ire: sql`~*`,
475
- $cts: sql`@>`,
476
- $ctd: sql`<@`,
477
- $keycts: sql`?|`,
478
- $keyctd: sql`?&`
479
- };
480
- function getBinarySql(lhs, type, op, value, textLhs) {
481
- if (value === null && op === "$eq") return sql`${lhs} IS NULL`;
482
- if (value === null && op === "$neq") return sql`${lhs} IS NOT NULL`;
483
- const sqlOp = opSql[op];
484
- if (!sqlOp) throw Error(`pg.getSql_unknown_operator ${op}`);
485
- if (op === "$in" || op === "$nin") {
486
- if (type === "jsonb" && typeof value[0] === "string") lhs = textLhs;
487
- return sql`${lhs} ${sqlOp} (${join(value)})`;
488
- }
489
- if (op === "$re" || op === "$ire") {
490
- if (type === "jsonb") {
491
- lhs = textLhs;
492
- } else if (type !== "text") {
493
- lhs = sql`(${lhs})::text`;
494
- }
495
- return sql`${lhs} ${sqlOp} ${String(value)}`;
496
- }
497
- if (type === "jsonb") {
498
- if (typeof value === "string") {
499
- return sql`${textLhs} ${sqlOp} ${value}`;
500
- }
501
- if ((op === "$keycts" || op === "$keyctd") && Array.isArray(value))
502
- return sql`${lhs} ${sqlOp} ${value}::text[]`;
503
- return sql`${lhs} ${sqlOp} ${JSON.stringify(value)}::jsonb`;
504
- }
505
- if (type === "cube") return sql`${lhs} ${sqlOp} ${cubeLiteralSql(value)}`;
506
- return sql`${lhs} ${sqlOp} ${value}`;
507
- }
508
- function getNodeSql(ast, options) {
509
- if (typeof ast === "boolean") return ast;
510
- const op = ast[0];
511
- if (op === "$and" || op === "$or") {
512
- return sql`(${join(
513
- ast[1].map((node) => getNodeSql(node, options)),
514
- `) ${opSql[op]} (`
515
- )})`;
516
- }
517
- if (op === "$not") {
518
- return sql`${opSql[op]} (${getNodeSql(ast[1], options)})`;
519
- }
520
- if (op === "$sub") {
521
- const joinName = ast[1];
522
- if (!options.joins[joinName]) throw Error(`pg.no_join ${joinName}`);
523
- const { idCol, schema } = options;
524
- const joinOptions = options.joins[joinName];
525
- const { table: joinTable, refCol } = options.joins[joinName];
526
- return sql`"${raw(idCol)}" IN (SELECT "${raw(refCol)}"::${raw(
527
- schema.types[idCol]
528
- )} FROM "${raw(joinTable)}" WHERE ${getNodeSql(ast[2], joinOptions)})`;
529
- }
530
- const [prefix, ...suffix] = ast[1].split(".");
531
- const { types: types2 = {} } = options.schema;
532
- if (!types2[prefix]) throw Error(`pg.no_column ${prefix}`);
533
- if (types2[prefix] === "jsonb") {
534
- const [lhs, textLhs] = suffix.length ? [
535
- sql`"${raw(prefix)}" #> ${suffix}`,
536
- sql`"${raw(prefix)}" #>> ${suffix}`
537
- ] : [sql`"${raw(prefix)}"`, sql`"${raw(prefix)}" #>> '{}'`];
538
- return getBinarySql(lhs, "jsonb", op, ast[2], textLhs);
539
- }
540
- if (suffix.length) throw Error(`pg.lookup_not_jsonb ${prefix}`);
541
- return getBinarySql(sql`"${raw(prefix)}"`, types2[prefix], op, ast[2]);
542
- }
543
- function getSql(filter, options) {
544
- const ast = getAst(filter);
545
- return getNodeSql(ast, options);
546
- }
547
- const getIdMeta = ({ idCol, verDefault }) => sql`"${raw(idCol)}" AS "$key", ${raw(verDefault)} AS "$ver"`;
548
- const getArgMeta = (key, { prefix, idCol, verDefault }) => sql`
549
- ${key} AS "$key",
550
- ${raw(verDefault)} AS "$ver",
551
- array[
552
- ${join(prefix.map((k) => sql`${k}::text`))},
553
- "${raw(idCol)}"
554
- ]::text[] AS "$ref"
555
- `;
556
- const getAggMeta = (key, { verDefault }) => sql`${key} AS "$key", ${raw(verDefault)} AS "$ver"`;
557
- function getArgSql({ $first, $last, $after, $before, $since, $until, $all, $cursor: _, ...rest }, options) {
558
- const { $order, $group, ...filter } = rest;
559
- const { prefix, idCol } = options;
560
- const meta = (key2) => $group ? getAggMeta(key2, options) : getArgMeta(key2, options);
561
- const hasRangeArg = $before || $after || $since || $until || $first || $last || $all;
562
- if ($order && $group) {
563
- throw Error(`pg_arg.order_and_group_unsupported in ${prefix}`);
564
- }
565
- if (($order || $group && $group !== true) && !hasRangeArg) {
566
- throw Error(`pg_arg.range_arg_expected in ${prefix}`);
567
- }
568
- const baseKey = sql`${JSON.stringify(rest)}::jsonb`;
569
- const where = [];
570
- if (!common.isEmpty(filter)) where.push(getSql(filter, options));
571
- if (!hasRangeArg)
572
- return {
573
- meta: meta(baseKey),
574
- where,
575
- limit: 1,
576
- ensureSingleRow: $group === true
577
- };
578
- const groupCols = Array.isArray($group) && $group.length && $group.map((prop) => lookup(prop, options));
579
- const group = groupCols ? join(groupCols, ", ") : void 0;
580
- const orderCols = ($order || [idCol]).map(
581
- (orderItem) => orderItem[0] === "!" ? sql`-(${lookup(orderItem.slice(1), options)})::float8` : lookup(orderItem, options)
582
- );
583
- Object.entries({ $after, $before, $since, $until }).forEach(
584
- ([name, value]) => {
585
- if (value) where.push(getBoundCond(orderCols, value, name));
586
- }
587
- );
588
- const order = !$group && join(
589
- ($order || [idCol]).map(
590
- (orderItem) => orderItem[0] === "!" ? sql`${lookup(orderItem.slice(1), options)} ${$last ? sql`ASC` : sql`DESC`}` : sql`${lookup(orderItem, options)} ${$last ? sql`DESC` : sql`ASC`}`
591
- ),
592
- ", "
593
- );
594
- const cursorKey = getJsonBuildTrusted({
595
- $cursor: $group === true ? sql`''` : sql`jsonb_build_array(${join(groupCols || orderCols)})`
596
- });
597
- const key = sql`(${baseKey} || ${cursorKey})`;
598
- return {
599
- meta: meta(key),
600
- where,
601
- order,
602
- group,
603
- limit: $first || $last,
604
- ensureSingleRow: true
605
- };
606
- }
607
- function getBoundCond(orderCols, bound, kind) {
608
- if (!Array.isArray(bound) || orderCols.length === 0 || bound.length === 0) {
609
- throw Error(`pg_arg.bad_query bound : ${JSON.stringify(bound)}`);
610
- }
611
- switch (kind) {
612
- case "$after":
613
- return sql`(${join(orderCols, ",")}) > (${join(bound, ",")})`;
614
- case "$since":
615
- return sql`(${join(orderCols, ",")}) >= (${join(bound, ",")})`;
616
- case "$before":
617
- return sql`(${join(orderCols, ",")}) < (${join(bound, ",")})`;
618
- case "$until":
619
- return sql`(${join(orderCols, ",")}) <= (${join(bound, ",")})`;
620
- }
621
- }
622
- const MAX_LIMIT = 4096;
623
- function selectByArgs(args, projection, options) {
624
- const { table, idCol } = options;
625
- const { where, order, group, limit, meta, ensureSingleRow } = getArgSql(
626
- args,
627
- options
628
- );
629
- const clampedLimit = Math.min(MAX_LIMIT, limit || MAX_LIMIT);
630
- if (!ensureSingleRow) {
631
- return sql`
632
- SELECT
633
- ${getSelectCols(options, projection)}, ${meta}
634
- FROM "${raw(table)}" WHERE "${raw(idCol)}" = (
635
- SELECT "${raw(idCol)}" FROM "${raw(table)}"
636
- ${where.length ? sql`WHERE ${join(where, " AND ")}` : empty}
637
- LIMIT 2
638
- )
639
- `;
640
- }
641
- return sql`
642
- SELECT
643
- ${getSelectCols(options, projection)}, ${meta}
644
- FROM "${raw(table)}"
645
- ${where.length ? sql`WHERE ${join(where, " AND ")}` : empty}
646
- ${group ? sql`GROUP BY ${group}` : empty}
647
- ${order ? sql`ORDER BY ${order}` : empty}
648
- LIMIT ${clampedLimit}
649
- `;
650
- }
651
- function selectByIds(ids, projection, options) {
652
- const { table, idCol } = options;
653
- return sql`
654
- SELECT
655
- ${getSelectCols(options, projection)}, ${getIdMeta(options)}
656
- FROM "${raw(table)}"
657
- WHERE "${raw(idCol)}" IN (${join(ids)})
658
- `;
659
- }
660
- function getSingleSql(arg, options) {
661
- const { table, idCol } = options;
662
- if (!common.isPlainObject(arg)) {
663
- return {
664
- where: sql`"${raw(idCol)}" = ${arg}`,
665
- meta: getIdMeta(options)
666
- };
667
- }
668
- const { where, meta } = getArgSql(arg, options);
669
- if (!where?.length) throw Error("pg_write.no_condition");
670
- return {
671
- where: sql`"${raw(idCol)}" = (
672
- SELECT "${raw(idCol)}"
673
- FROM "${raw(table)}"
674
- WHERE ${join(where, " AND ")}
675
- LIMIT 2
676
- )`,
677
- meta
678
- };
679
- }
680
- function patch(object, arg, options) {
681
- const { table } = options;
682
- const { where, meta } = getSingleSql(arg, options);
683
- const row = object;
684
- return sql`
685
- UPDATE "${raw(table)}" SET ${getUpdates(row, options)}
686
- WHERE ${where}
687
- RETURNING ${getSelectCols(options)}, ${meta}`;
688
- }
689
- function put(puts, options) {
690
- const { idCol, table } = options;
691
- const sqls = [];
692
- const addSql = (rows, meta, conflictTarget) => {
693
- const { cols, vals, updates } = getInsert(rows, options);
694
- sqls.push(sql`
695
- INSERT INTO "${raw(table)}" (${cols}) VALUES ${vals}
696
- ON CONFLICT (${conflictTarget}) DO UPDATE SET ${updates}
697
- RETURNING ${getSelectCols(options)}, ${meta}`);
698
- };
699
- const idRows = [];
700
- for (const put2 of puts) {
701
- const [row, arg] = put2;
702
- if (!common.isPlainObject(arg)) {
703
- idRows.push(row);
704
- continue;
705
- }
706
- const { meta } = getArgSql(arg, options);
707
- const conflictTarget = join(
708
- Object.keys(arg).map((col) => sql`"${raw(col)}"`)
709
- );
710
- addSql([row], meta, conflictTarget);
711
- }
712
- if (idRows.length) {
713
- const meta = getIdMeta(options);
714
- const conflictTarget = sql`"${raw(idCol)}"`;
715
- addSql(idRows, meta, conflictTarget);
716
- }
717
- return sqls;
718
- }
719
- function del(arg, options) {
720
- const { table } = options;
721
- const { where } = getSingleSql(arg, options);
722
- return sql`
723
- DELETE FROM "${raw(table)}"
724
- WHERE ${where}
725
- RETURNING ${arg} "$key"`;
726
- }
727
- const log = debug("graffy:pg:db");
728
- const { Pool, Client, types } = pg$1;
729
- class Db {
730
- constructor(connection) {
731
- if (typeof connection === "object" && connection && (connection instanceof Pool || connection instanceof Client)) {
732
- this.client = connection;
733
- } else {
734
- this.client = new Pool(connection);
735
- }
736
- }
737
- async query(sql2, tableOptions) {
738
- log(`Making SQL query: ${sql2.text}`, sql2.values);
739
- const cubeOid = Number.parseInt(tableOptions?.schema?.typeOids?.cube || "0", 10) || null;
740
- try {
741
- sql2.types = {
742
- getTypeParser: (oid, format) => {
743
- if (oid === types.builtins.INT8) {
744
- return (value) => Number.parseInt(value, 10);
745
- }
746
- if (oid === cubeOid) {
747
- return (value) => {
748
- const array = value.slice(1, -1).split(/\)\s*,\s*\(/).map(
749
- (corner) => corner.split(",").map((coord) => Number.parseFloat(coord.trim()))
750
- );
751
- return array.length > 1 ? array : array[0];
752
- };
753
- }
754
- return types.getTypeParser(oid, format);
755
- }
756
- };
757
- return await this.client.query(sql2);
758
- } catch (e) {
759
- const message = [
760
- e.message,
761
- e.detail,
762
- e.hint,
763
- e.where,
764
- sql2.text,
765
- JSON.stringify(sql2.values)
766
- ].filter(Boolean).join("; ");
767
- throw Error(`pg.sql_error ${message}`);
768
- }
769
- }
770
- async readSql(sql2, tableOptions) {
771
- const result = (await this.query(sql2, tableOptions)).rows;
772
- log("Read result", result);
773
- return result;
774
- }
775
- async writeSql(sql2, tableOptions) {
776
- const res = await this.query(sql2, tableOptions);
777
- log("Rows written", res.rowCount);
778
- if (!res.rowCount) {
779
- throw Error(`pg.nothing_written ${sql2.text} with ${sql2.values}`);
780
- }
781
- return res.rows;
782
- }
783
- /*
784
- Adds .schema to tableOptions if it doesn't exist yet.
785
- It mutates the argument, to "persist" the results and
786
- avoid this query in every operation.
787
- */
788
- async ensureSchema(tableOptions, typeOids) {
789
- if (tableOptions.schema) return;
790
- const { table, verCol, joins } = tableOptions;
791
- const tableInfoSchema = (await this.query(sql`
792
- SELECT table_schema, table_type
793
- FROM information_schema.tables
794
- WHERE table_name = ${table}
795
- ORDER BY array_position(current_schemas(false)::text[], table_schema::text) ASC
796
- LIMIT 1`)).rows[0];
797
- const tableSchema = tableInfoSchema.table_schema;
798
- const tableType = tableInfoSchema.table_type;
799
- const types2 = (await this.query(sql`
800
- SELECT jsonb_object_agg(column_name, udt_name) AS column_types
801
- FROM information_schema.columns
802
- WHERE
803
- table_name = ${table} AND
804
- table_schema = ${tableSchema}`)).rows[0].column_types;
805
- if (!types2) throw Error(`pg.missing_table ${table}`);
806
- typeOids = typeOids || (await this.query(sql`
807
- SELECT jsonb_object_agg(typname, oid) AS type_oids
808
- FROM pg_type
809
- WHERE typname = 'cube'`)).rows[0].type_oids;
810
- const verDefault = (await this.query(sql`
811
- SELECT column_default
812
- FROM information_schema.columns
813
- WHERE
814
- table_name = ${table} AND
815
- table_schema = ${tableSchema} AND
816
- column_name = ${verCol}`)).rows[0].column_default;
817
- if (!verDefault && tableType !== "VIEW") {
818
- throw Error(`pg.verCol_without_default ${verCol}`);
819
- }
820
- await Promise.all(
821
- Object.values(joins).map(
822
- (joinOptions) => this.ensureSchema(joinOptions, typeOids)
823
- )
824
- );
825
- log("ensureSchema", types2);
826
- tableOptions.schema = { types: types2, typeOids };
827
- tableOptions.verDefault = verDefault;
828
- }
829
- async read(rootQuery, tableOptions) {
830
- const idQueries = {};
831
- const promises = [];
832
- const results = [];
833
- const { prefix: rawPrefix } = tableOptions;
834
- const prefix = common.encodePath(rawPrefix);
835
- await this.ensureSchema(tableOptions);
836
- const getByArgs = async (args, projection) => {
837
- const sql2 = selectByArgs(args, projection, tableOptions);
838
- const result = await this.readSql(sql2, tableOptions);
839
- const wrappedGraph = common.encodeGraph(common.wrapObject(result, rawPrefix));
840
- log("getByArgs", wrappedGraph);
841
- common.merge(results, wrappedGraph);
842
- };
843
- const explainArgs = async (args, _projection) => {
844
- const { analyze, $explain: qArgs } = args;
845
- const qSql = selectByArgs(qArgs, null, tableOptions);
846
- const sql$1 = sql`EXPLAIN (${analyze ? sql`ANALYZE, BUFFERS, TIMING, ` : sql``}COSTS, VERBOSE, FORMAT JSON) ${qSql}`;
847
- const result = await this.readSql(sql$1, tableOptions);
848
- const wrappedGraph = common.encodeGraph(
849
- common.wrapObject(
850
- {
851
- $key: args,
852
- sql: formatSql(qSql),
853
- plan: result[0]["QUERY PLAN"][0]
854
- },
855
- rawPrefix
856
- )
857
- );
858
- log("explainArgs", wrappedGraph);
859
- common.merge(results, wrappedGraph);
860
- };
861
- const getByIds = async () => {
862
- const sql2 = selectByIds(Object.keys(idQueries), null, tableOptions);
863
- const result = await this.readSql(sql2, tableOptions);
864
- for (const object of result) {
865
- const wrappedGraph = common.encodeGraph(common.wrapObject(object, rawPrefix));
866
- log("getByIds", wrappedGraph);
867
- common.merge(results, wrappedGraph);
868
- }
869
- };
870
- const query = common.unwrap(rootQuery, prefix);
871
- for (const node of query) {
872
- const args = common.decodeArgs(node);
873
- if (common.isPlainObject(args)) {
874
- if (node.prefix) {
875
- for (const childNode of node.children) {
876
- const childArgs = common.decodeArgs(childNode);
877
- const projection = childNode.children ? common.decodeQuery(childNode.children) : null;
878
- promises.push(getByArgs({ ...args, ...childArgs }, projection));
879
- }
880
- } else {
881
- const projection = node.children ? common.decodeQuery(node.children) : null;
882
- if (args.$explain) {
883
- promises.push(explainArgs(args));
884
- } else {
885
- promises.push(getByArgs(args, projection));
886
- }
887
- }
888
- } else {
889
- idQueries[args] = node.children;
890
- }
891
- }
892
- if (!common.isEmpty(idQueries)) promises.push(getByIds());
893
- await Promise.all(promises);
894
- log("dbRead", rootQuery, results);
895
- return common.finalize(results, common.wrap(query, prefix));
896
- }
897
- async write(rootChange, tableOptions) {
898
- const { prefix: rawPrefix } = tableOptions;
899
- const prefix = common.encodePath(rawPrefix);
900
- await this.ensureSchema(tableOptions);
901
- const change = common.unwrap(rootChange, prefix);
902
- const puts = [];
903
- const sqls = [];
904
- for (const node of change) {
905
- const arg = common.decodeArgs(node);
906
- if (common.isRange(node)) {
907
- if (common.cmp(node.key, node.end) === 0) {
908
- log("delete", node);
909
- sqls.push(del(arg, tableOptions));
910
- continue;
911
- }
912
- throw Error("pg_write.write_range_unsupported");
913
- }
914
- const object = common.decodeGraph(node.children);
915
- if (common.isPlainObject(arg)) {
916
- common.mergeObject(object, arg);
917
- } else {
918
- object[tableOptions.idCol] = arg;
919
- }
920
- if (object.$put && object.$put !== true) {
921
- throw Error("pg_write.partial_put_unsupported");
922
- }
923
- if (object.$put) {
924
- puts.push([object, arg]);
925
- } else {
926
- sqls.push(patch(object, arg, tableOptions));
927
- }
928
- }
929
- if (puts.length) sqls.push(...put(puts, tableOptions));
930
- const result = [];
931
- await Promise.all(
932
- sqls.map(
933
- (sql2) => this.writeSql(sql2, tableOptions).then((object) => {
934
- log("returned_object_wrapped", common.wrapObject(object, rawPrefix));
935
- common.merge(result, common.encodeGraph(common.wrapObject(object, rawPrefix)));
936
- })
937
- )
938
- );
939
- log("dbWrite", rootChange, result);
940
- return result;
941
- }
942
- }
943
- function getTableOpts(name, { table, idCol, verCol, joins, schema, verDefault } = {}, parentName = null) {
944
- const tableName = table || name;
945
- return {
946
- table: table || name,
947
- idCol: idCol || "id",
948
- verCol: verCol || "updatedAt",
949
- joins: Object.fromEntries(
950
- Object.entries(joins || {}).map(
951
- ([joinName, { refCol = parentName, ...joinOptions }]) => [
952
- joinName,
953
- {
954
- refCol,
955
- ...getTableOpts(joinName, joinOptions, tableName)
956
- }
957
- ]
958
- )
959
- ),
960
- schema,
961
- verDefault
962
- };
963
- }
964
- const pg = ({ connection, ...rawOptions }) => (store) => {
965
- store.on("read", read);
966
- store.on("write", write);
967
- const prefix = store.path;
968
- const tableOpts = getTableOpts(prefix[prefix.length - 1], rawOptions);
969
- tableOpts.prefix = prefix;
970
- const defaultDb = new Db(connection);
971
- function read(query, options, next) {
972
- const { pgClient } = options;
973
- const db = pgClient ? new Db(pgClient) : defaultDb;
974
- const readPromise = db.read(query, tableOpts);
975
- const remainingQuery = common.remove(query, common.encodePath(prefix));
976
- const nextPromise = next(remainingQuery);
977
- return Promise.all([readPromise, nextPromise]).then(
978
- ([readRes, nextRes]) => {
979
- return common.merge(readRes, nextRes);
980
- }
981
- );
982
- }
983
- function write(change, options, next) {
984
- const { pgClient } = options;
985
- const db = pgClient ? new Db(pgClient) : defaultDb;
986
- const writePromise = db.write(change, tableOpts);
987
- const remainingChange = common.remove(change, common.encodePath(prefix));
988
- const nextPromise = next(remainingChange);
989
- return Promise.all([writePromise, nextPromise]).then(
990
- ([writeRes, nextRes]) => {
991
- return common.merge(writeRes, nextRes);
992
- }
993
- );
994
- }
995
- };
996
- exports.pg = pg;