@graffy/pg 0.15.25-alpha.5 → 0.15.25-alpha.6

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.
Files changed (3) hide show
  1. package/index.cjs +772 -0
  2. package/index.mjs +63 -1
  3. package/package.json +8 -4
package/index.cjs ADDED
@@ -0,0 +1,772 @@
1
+ "use strict";
2
+ Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: "Module" } });
3
+ const common = require("@graffy/common");
4
+ const pg$1 = require("pg");
5
+ const debug = require("debug");
6
+ const _interopDefaultLegacy = (e) => e && typeof e === "object" && "default" in e ? e : { default: e };
7
+ const pg__default = /* @__PURE__ */ _interopDefaultLegacy(pg$1);
8
+ const debug__default = /* @__PURE__ */ _interopDefaultLegacy(debug);
9
+ class Sql {
10
+ constructor(rawStrings, rawValues) {
11
+ if (rawStrings.length - 1 !== rawValues.length) {
12
+ if (rawStrings.length === 0) {
13
+ throw new TypeError("Expected at least 1 string");
14
+ }
15
+ throw new TypeError(`Expected ${rawStrings.length} strings to have ${rawStrings.length - 1} values`);
16
+ }
17
+ const valuesLength = rawValues.reduce((len, value) => len + (value instanceof Sql ? value.values.length : 1), 0);
18
+ this.values = new Array(valuesLength);
19
+ this.strings = new Array(valuesLength + 1);
20
+ this.strings[0] = rawStrings[0];
21
+ let i = 0, pos = 0;
22
+ while (i < rawValues.length) {
23
+ const child = rawValues[i++];
24
+ const rawString = rawStrings[i];
25
+ if (child instanceof Sql) {
26
+ this.strings[pos] += child.strings[0];
27
+ let childIndex = 0;
28
+ while (childIndex < child.values.length) {
29
+ this.values[pos++] = child.values[childIndex++];
30
+ this.strings[pos] = child.strings[childIndex];
31
+ }
32
+ this.strings[pos] += rawString;
33
+ } else {
34
+ this.values[pos++] = child;
35
+ this.strings[pos] = rawString;
36
+ }
37
+ }
38
+ }
39
+ get text() {
40
+ let i = 1, value = this.strings[0];
41
+ while (i < this.strings.length)
42
+ value += `$${i}${this.strings[i++]}`;
43
+ return value;
44
+ }
45
+ get sql() {
46
+ let i = 1, value = this.strings[0];
47
+ while (i < this.strings.length)
48
+ value += `?${this.strings[i++]}`;
49
+ return value;
50
+ }
51
+ inspect() {
52
+ return {
53
+ text: this.text,
54
+ sql: this.sql,
55
+ values: this.values
56
+ };
57
+ }
58
+ }
59
+ function join(values, separator = ",", prefix = "", suffix = "") {
60
+ if (values.length === 0) {
61
+ throw new TypeError("Expected `join([])` to be called with an array of multiple elements, but got an empty array");
62
+ }
63
+ return new Sql([prefix, ...Array(values.length - 1).fill(separator), suffix], values);
64
+ }
65
+ function raw(value) {
66
+ return new Sql([value], []);
67
+ }
68
+ const empty = raw("");
69
+ function sql(strings, ...values) {
70
+ return new Sql(strings, values);
71
+ }
72
+ const valid = {
73
+ $eq: true,
74
+ $lt: true,
75
+ $gt: true,
76
+ $lte: true,
77
+ $gte: true,
78
+ $re: true,
79
+ $ire: true,
80
+ $text: true,
81
+ $and: true,
82
+ $or: true,
83
+ $any: true,
84
+ $all: true,
85
+ $has: true,
86
+ $cts: true,
87
+ $ctd: true
88
+ };
89
+ const inverse = {
90
+ $eq: "$neq",
91
+ $neq: "$eq",
92
+ $in: "$nin",
93
+ $nin: "$in",
94
+ $lt: "$gte",
95
+ $gte: "$lt",
96
+ $gt: "$lte",
97
+ $lte: "$gt"
98
+ };
99
+ function getAst(filter) {
100
+ return simplify(construct(filter));
101
+ }
102
+ function construct(node, prop, op) {
103
+ if (!node || typeof node !== "object" || prop && op) {
104
+ if (op && prop)
105
+ return [op, prop, node];
106
+ if (prop)
107
+ return ["$eq", prop, node];
108
+ throw Error("pgast.expected_prop_before:" + JSON.stringify(node));
109
+ }
110
+ if (Array.isArray(node)) {
111
+ return ["$or", node.map((item) => construct(item, prop, op))];
112
+ }
113
+ return [
114
+ "$and",
115
+ Object.entries(node).map(([key, val]) => {
116
+ if (key === "$or" || key === "$and") {
117
+ return [key, construct(val, prop, op)[1]];
118
+ }
119
+ if (key === "$not") {
120
+ return [key, construct(val, prop, op)];
121
+ }
122
+ if (key[0] === "$") {
123
+ if (!valid[key])
124
+ throw Error("pgast.invalid_op:" + key);
125
+ if (op)
126
+ throw Error("pgast.unexpected_op:" + op + " before:" + key);
127
+ if (!prop)
128
+ throw Error("pgast.expected_prop_before:" + key);
129
+ return construct(val, prop, key);
130
+ }
131
+ if (prop) {
132
+ if (key[0] === ".")
133
+ return construct(val, prop + key);
134
+ throw Error("pgast.unexpected_prop: " + key);
135
+ }
136
+ return construct(val, key);
137
+ })
138
+ ];
139
+ }
140
+ function simplify(node) {
141
+ const op = node[0];
142
+ if (op === "$and" || op === "$or") {
143
+ node[1] = node[1].map((subnode) => simplify(subnode));
144
+ } else if (op === "$not") {
145
+ node[1] = simplify(node[1]);
146
+ }
147
+ if (op === "$and") {
148
+ if (!node[1].length)
149
+ return true;
150
+ if (node[1].includes(false))
151
+ return false;
152
+ node[1] = node[1].filter((item) => item !== true);
153
+ } else if (op === "$or") {
154
+ if (!node[1].length)
155
+ return false;
156
+ if (node[1].includes(true))
157
+ return true;
158
+ node[1] = node[1].filter((item) => item !== false);
159
+ } else if (op === "$not" && typeof node[1] === "boolean") {
160
+ return !node[1];
161
+ }
162
+ if (op === "$or") {
163
+ const { eqmap, noneq, change } = node[1].reduce(
164
+ (acc, item) => {
165
+ if (item[0] !== "$eq") {
166
+ acc.noneq.push(item);
167
+ } else if (acc.eqmap[item[1]]) {
168
+ acc.change = true;
169
+ acc.eqmap[item[1]].push(item[2]);
170
+ return acc;
171
+ } else {
172
+ acc.eqmap[item[1]] = [item[2]];
173
+ }
174
+ return acc;
175
+ },
176
+ { eqmap: {}, noneq: [], change: false }
177
+ );
178
+ if (change) {
179
+ node[1] = [
180
+ ...noneq,
181
+ ...Object.entries(eqmap).map(
182
+ ([prop, val]) => val.length > 1 ? ["$in", prop, val] : ["$eq", prop, val[0]]
183
+ )
184
+ ];
185
+ }
186
+ }
187
+ if ((op === "$and" || op === "$or") && node[1].length === 1) {
188
+ return node[1][0];
189
+ }
190
+ if (op === "$not") {
191
+ const [subop, ...subargs] = node[1];
192
+ const invop = inverse[subop];
193
+ return invop ? [invop, ...subargs] : node;
194
+ }
195
+ return node;
196
+ }
197
+ const getJsonBuildTrusted = (variadic) => {
198
+ const args = join(
199
+ Object.entries(variadic).map(([name, value]) => {
200
+ return sql`'${raw(name)}', ${getJsonBuildValue(value)}`;
201
+ })
202
+ );
203
+ return sql`jsonb_build_object(${args})`;
204
+ };
205
+ const getJsonBuildValue = (value) => {
206
+ if (value instanceof Sql)
207
+ return value;
208
+ if (typeof value === "string")
209
+ return sql`${value}::text`;
210
+ return sql`${JSON.stringify(stripAttributes(value))}::jsonb`;
211
+ };
212
+ const lookup = (prop) => {
213
+ const [prefix, ...suffix] = common.encodePath(prop);
214
+ return suffix.length ? sql`"${raw(prefix)}" #> ${suffix}` : sql`"${raw(prefix)}"`;
215
+ };
216
+ const lookupNumeric = (prop) => {
217
+ const [prefix, ...suffix] = common.encodePath(prop);
218
+ return suffix.length ? sql`CASE WHEN "${raw(prefix)}" #> ${suffix} = 'null'::jsonb THEN 0 ELSE ("${raw(
219
+ prefix
220
+ )}" #> ${suffix})::numeric END` : sql`"${raw(prefix)}"`;
221
+ };
222
+ const aggSql = {
223
+ $sum: (prop) => sql`sum((${lookupNumeric(prop)})::numeric)`,
224
+ $card: (prop) => sql`count(distinct(${lookup(prop)}))`,
225
+ $avg: (prop) => sql`avg((${lookupNumeric(prop)})::numeric)`,
226
+ $max: (prop) => sql`max((${lookupNumeric(prop)})::numeric)`,
227
+ $min: (prop) => sql`min((${lookupNumeric(prop)})::numeric)`
228
+ };
229
+ const getSelectCols = (table, projection = null) => {
230
+ if (!projection)
231
+ return sql`*`;
232
+ const sqls = [];
233
+ for (const key in projection) {
234
+ if (key === "$count") {
235
+ sqls.push(sql`count(*) AS "$count"`);
236
+ } else if (aggSql[key]) {
237
+ const subSqls = [];
238
+ for (const prop in projection[key]) {
239
+ subSqls.push(sql`${prop}::text, ${aggSql[key](prop)}`);
240
+ }
241
+ sqls.push(
242
+ sql`jsonb_build_object(${join(subSqls, ", ")}) AS "${raw(key)}"`
243
+ );
244
+ } else {
245
+ sqls.push(sql`"${raw(key)}"`);
246
+ }
247
+ }
248
+ return join(sqls, ", ");
249
+ };
250
+ function vertexSql(array, nullValue) {
251
+ return sql`array[${join(
252
+ array.map((num) => num === null ? nullValue : num)
253
+ )}]::float8[]`;
254
+ }
255
+ function cubeLiteralSql(value) {
256
+ if (!Array.isArray(value) || !value.length || Array.isArray(value[0]) && value.length !== 2) {
257
+ throw Error("pg.castValue_bad_cube" + JSON.stringify(value));
258
+ }
259
+ return Array.isArray(value[0]) ? sql`cube(${vertexSql(value[0], sql`'-Infinity'`)}, ${vertexSql(
260
+ value[1],
261
+ sql`'Infinity'`
262
+ )})` : sql`cube(${vertexSql(value, 0)})`;
263
+ }
264
+ function castValue(value, type, name, isPut) {
265
+ if (!type)
266
+ throw Error("pg.write_no_column " + name);
267
+ if (value instanceof Sql)
268
+ return value;
269
+ if (value === null)
270
+ return sql`NULL`;
271
+ if (type === "jsonb") {
272
+ return isPut ? JSON.stringify(stripAttributes(value)) : sql`jsonb_strip_nulls(${getJsonUpdate(value, name, [])})`;
273
+ }
274
+ if (type === "cube")
275
+ return cubeLiteralSql(value);
276
+ return value;
277
+ }
278
+ const getInsert = (row, options) => {
279
+ const cols = [];
280
+ const vals = [];
281
+ Object.entries(row).filter(([col]) => col !== options.verCol && col[0] !== "$").concat([[options.verCol, sql`default`]]).forEach(([col, val]) => {
282
+ cols.push(sql`"${raw(col)}"`);
283
+ vals.push(castValue(val, options.schema.types[col], col, row.$put));
284
+ });
285
+ return { cols: join(cols, ", "), vals: join(vals, ", ") };
286
+ };
287
+ const getUpdates = (row, options) => {
288
+ return join(
289
+ Object.entries(row).filter(([col]) => col !== options.idCol && col[0] !== "$").map(
290
+ ([col, val]) => sql`"${raw(col)}" = ${castValue(
291
+ val,
292
+ options.schema.types[col],
293
+ col,
294
+ row.$put
295
+ )}`
296
+ ).concat(sql`"${raw(options.verCol)}" = default`),
297
+ ", "
298
+ );
299
+ };
300
+ function getJsonUpdate(object, col, path) {
301
+ if (!object || typeof object !== "object" || Array.isArray(object) || object.$put) {
302
+ return getJsonBuildValue(object);
303
+ }
304
+ const curr = sql`"${raw(col)}"${path.length ? sql`#>${path}` : empty}`;
305
+ if (common.isEmpty(object))
306
+ return curr;
307
+ return sql`(case jsonb_typeof(${curr})
308
+ when 'object' then ${curr}
309
+ else '{}'::jsonb
310
+ end) || jsonb_build_object(${join(
311
+ Object.entries(object).map(
312
+ ([key, value]) => sql`${key}::text, ${getJsonUpdate(value, col, path.concat(key))}`
313
+ ),
314
+ ", "
315
+ )})`;
316
+ }
317
+ function stripAttributes(object) {
318
+ if (typeof object !== "object" || !object)
319
+ return object;
320
+ if (Array.isArray(object)) {
321
+ return object.map((item) => stripAttributes(item));
322
+ }
323
+ return Object.entries(object).reduce((out, [key, val]) => {
324
+ if (key === "$put")
325
+ return out;
326
+ out[key] = stripAttributes(val);
327
+ return out;
328
+ }, {});
329
+ }
330
+ const opSql = {
331
+ $and: `AND`,
332
+ $or: `OR`,
333
+ $not: sql`NOT`,
334
+ $eq: sql`=`,
335
+ $neq: sql`<>`,
336
+ $in: sql`IN`,
337
+ $nin: sql`NOT IN`,
338
+ $lt: sql`<`,
339
+ $lte: sql`<=`,
340
+ $gt: sql`>`,
341
+ $gte: sql`>=`,
342
+ $re: sql`~`,
343
+ $ire: sql`~*`,
344
+ $cts: sql`@>`,
345
+ $ctd: sql`<@`
346
+ };
347
+ function getBinarySql(lhs, type, op, value, textLhs) {
348
+ if (value === null && op === "$eq")
349
+ return sql`${lhs} IS NULL`;
350
+ if (value === null && op === "$neq")
351
+ return sql`${lhs} IS NOT NULL`;
352
+ const sqlOp = opSql[op];
353
+ if (!sqlOp)
354
+ throw Error("pg.getSql_unknown_operator " + op);
355
+ if (op === "$in" || op === "$nin") {
356
+ if (type === "jsonb" && typeof value[0] === "string")
357
+ lhs = textLhs;
358
+ return sql`${lhs} ${sqlOp} (${join(value)})`;
359
+ }
360
+ if (op === "$re" || op === "$ire") {
361
+ if (type === "jsonb") {
362
+ lhs = textLhs;
363
+ } else if (type !== "text") {
364
+ lhs = sql`(${lhs})::text`;
365
+ }
366
+ return sql`${lhs} ${sqlOp} ${String(value)}`;
367
+ }
368
+ if (type === "jsonb") {
369
+ if (typeof value === "string") {
370
+ return sql`${textLhs} ${sqlOp} ${value}`;
371
+ }
372
+ return sql`${lhs} ${sqlOp} ${JSON.stringify(value)}::jsonb`;
373
+ }
374
+ if (type === "cube")
375
+ return sql`${lhs} ${sqlOp} ${cubeLiteralSql(value)}`;
376
+ return sql`${lhs} ${sqlOp} ${value}`;
377
+ }
378
+ function getSql(filter, options) {
379
+ function getNodeSql(ast) {
380
+ if (typeof ast === "boolean")
381
+ return ast;
382
+ const op = ast[0];
383
+ if (op === "$and" || op === "$or") {
384
+ return sql`(${join(
385
+ ast[1].map((node) => getNodeSql(node)),
386
+ `) ${opSql[op]} (`
387
+ )})`;
388
+ } else if (op === "$not") {
389
+ return sql`${opSql[op]} (${getNodeSql(ast[1])})`;
390
+ }
391
+ const [prefix, ...suffix] = common.encodePath(ast[1]);
392
+ const { types: types2 } = options.schema;
393
+ if (!types2[prefix])
394
+ throw Error("pg.no_column " + prefix);
395
+ if (types2[prefix] === "jsonb") {
396
+ const [lhs, textLhs] = suffix.length ? [
397
+ sql`"${raw(prefix)}" #> ${suffix}`,
398
+ sql`"${raw(prefix)}" #>> ${suffix}`
399
+ ] : [sql`"${raw(prefix)}"`, sql`"${raw(prefix)}" #>> '{}'`];
400
+ return getBinarySql(lhs, "jsonb", op, ast[2], textLhs);
401
+ } else {
402
+ if (suffix.length)
403
+ throw Error("pg.lookup_not_jsonb " + prefix);
404
+ return getBinarySql(sql`"${raw(prefix)}"`, types2[prefix], op, ast[2]);
405
+ }
406
+ }
407
+ return getNodeSql(getAst(filter));
408
+ }
409
+ const getIdMeta = ({ idCol, verDefault }) => sql`"${raw(idCol)}" AS "$key", ${raw(verDefault)} AS "$ver"`;
410
+ const getArgMeta = (key, { prefix, idCol, verDefault }) => sql`
411
+ ${key} AS "$key",
412
+ ${raw(verDefault)} AS "$ver",
413
+ array[
414
+ ${join(prefix.map((k) => sql`${k}::text`))},
415
+ "${raw(idCol)}"
416
+ ]::text[] AS "$ref"
417
+ `;
418
+ const getAggMeta = (key, { verDefault }) => sql`${key} AS "$key", ${raw(verDefault)} AS "$ver"`;
419
+ function getArgSql({ $first, $last, $after, $before, $since, $until, $all, $cursor: _, ...rest }, options) {
420
+ const { $order, $group, ...filter } = rest;
421
+ const { prefix, idCol } = options;
422
+ const meta = (key2) => $group ? getAggMeta(key2, options) : getArgMeta(key2, options);
423
+ const hasRangeArg = $before || $after || $since || $until || $first || $last || $all;
424
+ if ($order && $group) {
425
+ throw Error("pg_arg.order_and_group_unsupported in " + prefix);
426
+ }
427
+ if (($order || $group && $group !== true) && !hasRangeArg) {
428
+ throw Error("pg_arg.range_arg_expected in " + prefix);
429
+ }
430
+ const baseKey = sql`${JSON.stringify(rest)}::jsonb`;
431
+ const where = [];
432
+ if (!common.isEmpty(filter))
433
+ where.push(getSql(filter, options));
434
+ if (!hasRangeArg)
435
+ return { meta: meta(baseKey), where, limit: 1 };
436
+ const groupCols = Array.isArray($group) && $group.length && $group.map(lookup);
437
+ const group = groupCols ? join(groupCols, ", ") : void 0;
438
+ const orderCols = ($order || [idCol]).map(
439
+ (orderItem) => orderItem[0] === "!" ? sql`-(${lookup(orderItem.slice(1))})::float8` : lookup(orderItem)
440
+ );
441
+ Object.entries({ $after, $before, $since, $until }).forEach(
442
+ ([name, value]) => {
443
+ if (value)
444
+ where.push(getBoundCond(orderCols, value, name));
445
+ }
446
+ );
447
+ const order = !$group && join(
448
+ ($order || [idCol]).map(
449
+ (orderItem) => orderItem[0] === "!" ? sql`${lookup(orderItem.slice(1))} ${$last ? sql`ASC` : sql`DESC`}` : sql`${lookup(orderItem)} ${$last ? sql`DESC` : sql`ASC`}`
450
+ ),
451
+ `, `
452
+ );
453
+ const cursorKey = getJsonBuildTrusted({
454
+ $cursor: $group === true ? sql`''` : sql`jsonb_build_array(${join(groupCols || orderCols)})`
455
+ });
456
+ const key = sql`(${baseKey} || ${cursorKey})`;
457
+ return {
458
+ meta: meta(key),
459
+ where,
460
+ order,
461
+ group,
462
+ limit: $first || $last
463
+ };
464
+ }
465
+ function getBoundCond(orderCols, bound, kind) {
466
+ if (!Array.isArray(bound)) {
467
+ throw Error("pg_arg.bad_query bound : " + JSON.stringify(bound));
468
+ }
469
+ const lhs = orderCols[0];
470
+ const rhs = bound[0];
471
+ if (orderCols.length > 1 && bound.length > 1) {
472
+ const subCond = getBoundCond(orderCols.slice(1), bound.slice(1), kind);
473
+ switch (kind) {
474
+ case "$after":
475
+ case "$since":
476
+ return sql`${lhs} > ${rhs} OR ${lhs} = ${rhs} AND (${subCond})`;
477
+ case "$before":
478
+ case "$until":
479
+ return sql`${lhs} < ${rhs} OR ${lhs} = ${rhs} AND (${subCond})`;
480
+ }
481
+ } else {
482
+ switch (kind) {
483
+ case "$after":
484
+ return sql`${lhs} > ${rhs}`;
485
+ case "$since":
486
+ return sql`${lhs} >= ${rhs}`;
487
+ case "$before":
488
+ return sql`${lhs} < ${rhs}`;
489
+ case "$until":
490
+ return sql`${lhs} <= ${rhs}`;
491
+ }
492
+ }
493
+ }
494
+ const MAX_LIMIT = 4096;
495
+ function selectByArgs(args, projection, options) {
496
+ const { table } = options;
497
+ const { where, order, group, limit, meta } = getArgSql(args, options);
498
+ const clampedLimit = Math.min(MAX_LIMIT, limit || MAX_LIMIT);
499
+ return sql`
500
+ SELECT
501
+ ${getSelectCols(table, projection)}, ${meta}
502
+ FROM "${raw(table)}"
503
+ ${where.length ? sql`WHERE ${join(where, ` AND `)}` : empty}
504
+ ${group ? sql`GROUP BY ${group}` : empty}
505
+ ${order ? sql`ORDER BY ${order}` : empty}
506
+ LIMIT ${clampedLimit}
507
+ `;
508
+ }
509
+ function selectByIds(ids, projection, options) {
510
+ const { table, idCol } = options;
511
+ return sql`
512
+ SELECT
513
+ ${getSelectCols(table, projection)}, ${getIdMeta(options)}
514
+ FROM "${raw(table)}"
515
+ WHERE "${raw(idCol)}" IN (${join(ids)})
516
+ `;
517
+ }
518
+ function getSingleSql(arg, options) {
519
+ const { table, idCol } = options;
520
+ if (!common.isPlainObject(arg)) {
521
+ return {
522
+ where: sql`"${raw(idCol)}" = ${arg}`,
523
+ meta: getIdMeta(options)
524
+ };
525
+ }
526
+ const { where, meta } = getArgSql(arg, options);
527
+ if (!where || !where.length)
528
+ throw Error("pg_write.no_condition");
529
+ return {
530
+ where: sql`"${raw(idCol)}" = (
531
+ SELECT "${raw(idCol)}"
532
+ FROM "${raw(table)}"
533
+ WHERE ${join(where, ` AND `)}
534
+ LIMIT 1
535
+ )`,
536
+ meta
537
+ };
538
+ }
539
+ function patch(object, arg, options) {
540
+ const { table } = options;
541
+ const { where, meta } = getSingleSql(arg, options);
542
+ const row = object;
543
+ return sql`
544
+ UPDATE "${raw(table)}" SET ${getUpdates(row, options)}
545
+ WHERE ${where}
546
+ RETURNING ${getSelectCols()}, ${meta}`;
547
+ }
548
+ function put(object, arg, options) {
549
+ const { idCol, table } = options;
550
+ const row = object;
551
+ let meta, conflictTarget;
552
+ if (common.isPlainObject(arg)) {
553
+ ({ meta } = getArgSql(arg, options));
554
+ conflictTarget = join(Object.keys(arg).map((col) => sql`"${raw(col)}"`));
555
+ } else {
556
+ meta = getIdMeta(options);
557
+ conflictTarget = sql`"${raw(idCol)}"`;
558
+ }
559
+ const { cols, vals } = getInsert(row, options);
560
+ return sql`
561
+ INSERT INTO "${raw(table)}" (${cols}) VALUES (${vals})
562
+ ON CONFLICT (${conflictTarget}) DO UPDATE SET (${cols}) = (${vals})
563
+ RETURNING ${getSelectCols()}, ${meta}`;
564
+ }
565
+ function del(arg, options) {
566
+ const { table } = options;
567
+ const { where } = getSingleSql(arg, options);
568
+ return sql`
569
+ DELETE FROM "${raw(table)}"
570
+ WHERE ${where}
571
+ RETURNING ${arg} "$key"`;
572
+ }
573
+ const log = debug__default.default("graffy:pg:db");
574
+ const { Pool, Client, types } = pg__default.default;
575
+ class Db {
576
+ constructor(connection) {
577
+ if (typeof connection === "object" && connection && (connection instanceof Pool || connection instanceof Client)) {
578
+ this.client = connection;
579
+ } else {
580
+ this.client = new Pool(connection);
581
+ }
582
+ }
583
+ async query(sql2) {
584
+ log("Making SQL query: " + sql2.text, sql2.values);
585
+ try {
586
+ sql2.types = {
587
+ getTypeParser: (oid, format) => {
588
+ if (oid === types.builtins.INT8) {
589
+ return (value) => parseInt(value, 10);
590
+ }
591
+ return types.getTypeParser(oid, format);
592
+ }
593
+ };
594
+ return await this.client.query(sql2);
595
+ } catch (e) {
596
+ const message = [
597
+ e.message,
598
+ e.detail,
599
+ e.hint,
600
+ e.where,
601
+ sql2.text,
602
+ JSON.stringify(sql2.values)
603
+ ].filter(Boolean).join("; ");
604
+ throw Error("pg.sql_error " + message);
605
+ }
606
+ }
607
+ async readSql(sql2) {
608
+ const result = (await this.query(sql2)).rows;
609
+ log("Read result", result);
610
+ return result;
611
+ }
612
+ async writeSql(sql2) {
613
+ const res = await this.query(sql2);
614
+ log("Rows written", res.rowCount);
615
+ if (!res.rowCount) {
616
+ throw Error("pg.nothing_written " + sql2.text + " with " + sql2.values);
617
+ }
618
+ return res.rows[0];
619
+ }
620
+ async ensureSchema(tableOptions) {
621
+ if (tableOptions.schema)
622
+ return;
623
+ const { table, verCol } = tableOptions;
624
+ const tableSchema = (await this.query(sql`
625
+ SELECT table_schema
626
+ FROM information_schema.tables
627
+ WHERE table_name = ${table}
628
+ ORDER BY array_position(current_schemas(false)::text[], table_schema::text) ASC
629
+ LIMIT 1`)).rows[0].table_schema;
630
+ const types2 = (await this.query(sql`
631
+ SELECT jsonb_object_agg(column_name, udt_name) AS column_types
632
+ FROM information_schema.columns
633
+ WHERE
634
+ table_name = ${table} AND
635
+ table_schema = ${tableSchema}`)).rows[0].column_types;
636
+ if (!types2)
637
+ throw Error(`pg.missing_table ${table}`);
638
+ const verDefault = (await this.query(sql`
639
+ SELECT column_default
640
+ FROM information_schema.columns
641
+ WHERE
642
+ table_name = ${table} AND
643
+ table_schema = ${tableSchema} AND
644
+ column_name = ${verCol}`)).rows[0].column_default;
645
+ if (!verDefault) {
646
+ throw Error(`pg.verCol_without_default ${verCol}`);
647
+ }
648
+ log("ensureSchema", types2);
649
+ tableOptions.schema = { types: types2 };
650
+ tableOptions.verDefault = verDefault;
651
+ }
652
+ async read(rootQuery, tableOptions) {
653
+ const idQueries = {};
654
+ const promises = [];
655
+ const results = [];
656
+ const { prefix } = tableOptions;
657
+ await this.ensureSchema(tableOptions);
658
+ const getByArgs = async (args, projection) => {
659
+ const result = await this.readSql(
660
+ selectByArgs(args, projection, tableOptions)
661
+ );
662
+ const wrappedGraph = common.encodeGraph(common.wrapObject(result, prefix));
663
+ log("getByArgs", wrappedGraph);
664
+ common.merge(results, wrappedGraph);
665
+ };
666
+ const getByIds = async () => {
667
+ const result = await this.readSql(
668
+ selectByIds(Object.keys(idQueries), null, tableOptions)
669
+ );
670
+ result.forEach((object) => {
671
+ const wrappedGraph = common.encodeGraph(common.wrapObject(object, prefix));
672
+ log("getByIds", wrappedGraph);
673
+ common.merge(results, wrappedGraph);
674
+ });
675
+ };
676
+ const query = common.unwrap(rootQuery, prefix);
677
+ for (const node of query) {
678
+ const args = common.decodeArgs(node);
679
+ if (common.isPlainObject(args)) {
680
+ if (node.prefix) {
681
+ for (const childNode of node.children) {
682
+ const childArgs = common.decodeArgs(childNode);
683
+ const projection = childNode.children ? common.decodeQuery(childNode.children) : null;
684
+ promises.push(getByArgs({ ...args, ...childArgs }, projection));
685
+ }
686
+ } else {
687
+ const projection = node.children ? common.decodeQuery(node.children) : null;
688
+ promises.push(getByArgs(args, projection));
689
+ }
690
+ } else {
691
+ idQueries[node.key] = node.children;
692
+ }
693
+ }
694
+ if (!common.isEmpty(idQueries))
695
+ promises.push(getByIds());
696
+ await Promise.all(promises);
697
+ log("dbRead", rootQuery, results);
698
+ return common.finalize(results, common.wrap(query, prefix));
699
+ }
700
+ async write(rootChange, tableOptions) {
701
+ const { prefix } = tableOptions;
702
+ await this.ensureSchema(tableOptions);
703
+ const change = common.unwrap(rootChange, prefix);
704
+ const sqls = change.map((node) => {
705
+ const arg = common.decodeArgs(node);
706
+ if (common.isRange(node)) {
707
+ if (node.key === node.end)
708
+ return del(arg, tableOptions);
709
+ throw Error("pg_write.write_range_unsupported");
710
+ }
711
+ const object = common.decodeGraph(node.children);
712
+ if (common.isPlainObject(arg)) {
713
+ common.mergeObject(object, arg);
714
+ } else {
715
+ object.id = arg;
716
+ }
717
+ if (object.$put && object.$put !== true) {
718
+ throw Error("pg_write.partial_put_unsupported");
719
+ }
720
+ return object.$put ? put(object, arg, tableOptions) : patch(object, arg, tableOptions);
721
+ });
722
+ const result = [];
723
+ await Promise.all(
724
+ sqls.map(
725
+ (sql2) => this.writeSql(sql2).then((object) => {
726
+ common.merge(result, common.encodeGraph(common.wrapObject(object, prefix)));
727
+ })
728
+ )
729
+ );
730
+ log("dbWrite", rootChange, result);
731
+ return result;
732
+ }
733
+ }
734
+ const pg = ({ table, idCol, verCol, connection, schema, verDefault }) => (store) => {
735
+ store.on("read", read);
736
+ store.on("write", write);
737
+ const prefix = store.path;
738
+ const tableOpts = {
739
+ prefix,
740
+ table: table || prefix[prefix.length - 1] || "default",
741
+ idCol: idCol || "id",
742
+ verCol: verCol || "updatedAt",
743
+ schema,
744
+ verDefault
745
+ };
746
+ const defaultDb = new Db(connection);
747
+ function read(query, options, next) {
748
+ const { pgClient } = options;
749
+ const db = pgClient ? new Db(pgClient) : defaultDb;
750
+ const readPromise = db.read(query, tableOpts);
751
+ const remainingQuery = common.remove(query, prefix);
752
+ const nextPromise = next(remainingQuery);
753
+ return Promise.all([readPromise, nextPromise]).then(
754
+ ([readRes, nextRes]) => {
755
+ return common.merge(readRes, nextRes);
756
+ }
757
+ );
758
+ }
759
+ function write(change, options, next) {
760
+ const { pgClient } = options;
761
+ const db = pgClient ? new Db(pgClient) : defaultDb;
762
+ const writePromise = db.write(change, tableOpts);
763
+ const remainingChange = common.remove(change, prefix);
764
+ const nextPromise = next(remainingChange);
765
+ return Promise.all([writePromise, nextPromise]).then(
766
+ ([writeRes, nextRes]) => {
767
+ return common.merge(writeRes, nextRes);
768
+ }
769
+ );
770
+ }
771
+ };
772
+ exports.pg = pg;
package/index.mjs CHANGED
@@ -1,7 +1,69 @@
1
1
  import { encodePath, isEmpty, isPlainObject, unwrap, decodeArgs, decodeQuery, finalize, wrap, isRange, decodeGraph, mergeObject, merge, encodeGraph, wrapObject, remove } from "@graffy/common";
2
2
  import pg$1 from "pg";
3
- import sql, { join, raw, Sql, empty } from "sql-template-tag";
4
3
  import debug from "debug";
4
+ class Sql {
5
+ constructor(rawStrings, rawValues) {
6
+ if (rawStrings.length - 1 !== rawValues.length) {
7
+ if (rawStrings.length === 0) {
8
+ throw new TypeError("Expected at least 1 string");
9
+ }
10
+ throw new TypeError(`Expected ${rawStrings.length} strings to have ${rawStrings.length - 1} values`);
11
+ }
12
+ const valuesLength = rawValues.reduce((len, value) => len + (value instanceof Sql ? value.values.length : 1), 0);
13
+ this.values = new Array(valuesLength);
14
+ this.strings = new Array(valuesLength + 1);
15
+ this.strings[0] = rawStrings[0];
16
+ let i = 0, pos = 0;
17
+ while (i < rawValues.length) {
18
+ const child = rawValues[i++];
19
+ const rawString = rawStrings[i];
20
+ if (child instanceof Sql) {
21
+ this.strings[pos] += child.strings[0];
22
+ let childIndex = 0;
23
+ while (childIndex < child.values.length) {
24
+ this.values[pos++] = child.values[childIndex++];
25
+ this.strings[pos] = child.strings[childIndex];
26
+ }
27
+ this.strings[pos] += rawString;
28
+ } else {
29
+ this.values[pos++] = child;
30
+ this.strings[pos] = rawString;
31
+ }
32
+ }
33
+ }
34
+ get text() {
35
+ let i = 1, value = this.strings[0];
36
+ while (i < this.strings.length)
37
+ value += `$${i}${this.strings[i++]}`;
38
+ return value;
39
+ }
40
+ get sql() {
41
+ let i = 1, value = this.strings[0];
42
+ while (i < this.strings.length)
43
+ value += `?${this.strings[i++]}`;
44
+ return value;
45
+ }
46
+ inspect() {
47
+ return {
48
+ text: this.text,
49
+ sql: this.sql,
50
+ values: this.values
51
+ };
52
+ }
53
+ }
54
+ function join(values, separator = ",", prefix = "", suffix = "") {
55
+ if (values.length === 0) {
56
+ throw new TypeError("Expected `join([])` to be called with an array of multiple elements, but got an empty array");
57
+ }
58
+ return new Sql([prefix, ...Array(values.length - 1).fill(separator), suffix], values);
59
+ }
60
+ function raw(value) {
61
+ return new Sql([value], []);
62
+ }
63
+ const empty = raw("");
64
+ function sql(strings, ...values) {
65
+ return new Sql(strings, values);
66
+ }
5
67
  const valid = {
6
68
  $eq: true,
7
69
  $lt: true,
package/package.json CHANGED
@@ -2,8 +2,13 @@
2
2
  "name": "@graffy/pg",
3
3
  "description": "The standard Postgres module for Graffy. Each instance this module mounts a Postgres table as a Graffy subtree.",
4
4
  "author": "aravind (https://github.com/aravindet)",
5
- "version": "0.15.25-alpha.5",
6
- "main": "./index.mjs",
5
+ "version": "0.15.25-alpha.6",
6
+ "main": "./index.cjs",
7
+ "exports": {
8
+ "import": "./index.mjs",
9
+ "require": "./index.cjs"
10
+ },
11
+ "module": "./index.mjs",
7
12
  "types": "./types/index.d.ts",
8
13
  "repository": {
9
14
  "type": "git",
@@ -11,8 +16,7 @@
11
16
  },
12
17
  "license": "Apache-2.0",
13
18
  "dependencies": {
14
- "@graffy/common": "0.15.25-alpha.5",
15
- "sql-template-tag": "^5.0.3",
19
+ "@graffy/common": "0.15.25-alpha.6",
16
20
  "debug": "^4.3.3"
17
21
  },
18
22
  "peerDependencies": {