@crvouga/mockingbird-service-postgres 1.3.1 → 1.5.0

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/dist/index.js CHANGED
@@ -1,3 +1,164 @@
1
+ // ../../core/dist/timeline.js
2
+ var BRANCH_PATTERN = /^[A-Za-z0-9_.-]{1,64}$/;
3
+ var Timeline = class {
4
+ maxCheckpoints;
5
+ now;
6
+ makeId;
7
+ nodes = /* @__PURE__ */ new Map();
8
+ heads = /* @__PURE__ */ new Map();
9
+ /** Unreferenced nodes in the exact order they became collectible. */
10
+ evictable = /* @__PURE__ */ new Set();
11
+ /** Branch heads plus explicit retainers. Absent means zero. */
12
+ references = /* @__PURE__ */ new Map();
13
+ explicitPins = /* @__PURE__ */ new Map();
14
+ sequence = 0;
15
+ constructor(options = {}) {
16
+ const max = options.maxCheckpoints ?? 1e3;
17
+ if (!Number.isSafeInteger(max) || max < 1)
18
+ throw new RangeError("maxCheckpoints must be a positive integer");
19
+ this.maxCheckpoints = max;
20
+ this.now = options.now ?? (() => this.sequence);
21
+ this.makeId = options.id ?? ((sequence) => `cp_${sequence.toString(36).padStart(8, "0")}`);
22
+ }
23
+ /** Capture a new immutable value and move `branch` to it. */
24
+ commit(value, options = {}) {
25
+ const branch = options.branch ?? "main";
26
+ this.assertBranch(branch);
27
+ const parent = options.parent === void 0 ? this.heads.get(branch) ?? null : options.parent;
28
+ if (parent !== null && !this.nodes.has(parent))
29
+ throw new RangeError(`no checkpoint ${parent}`);
30
+ const id = this.makeId(++this.sequence);
31
+ if (this.nodes.has(id))
32
+ throw new RangeError(`duplicate checkpoint id ${id}`);
33
+ const checkpoint = Object.freeze({ id, branch, parent, at: this.now(), value });
34
+ this.nodes.set(id, checkpoint);
35
+ this.moveHead(branch, id);
36
+ this.collect(this.maxCheckpoints);
37
+ return checkpoint;
38
+ }
39
+ /** Create a branch pointer without copying its checkpoint value. */
40
+ fork(branch, options = {}) {
41
+ this.assertBranch(branch);
42
+ if (this.heads.has(branch))
43
+ throw new RangeError(`branch already exists: ${branch}`);
44
+ const from = options.from ?? this.heads.get("main");
45
+ if (from === void 0)
46
+ return void 0;
47
+ const checkpoint = this.get(from);
48
+ this.moveHead(branch, checkpoint.id);
49
+ return checkpoint;
50
+ }
51
+ /** Move a branch pointer to an existing checkpoint. */
52
+ checkout(branch, id) {
53
+ this.assertBranch(branch);
54
+ const checkpoint = this.get(id);
55
+ this.moveHead(branch, checkpoint.id);
56
+ return checkpoint;
57
+ }
58
+ get(id) {
59
+ const checkpoint = this.nodes.get(id);
60
+ if (!checkpoint)
61
+ throw new RangeError(`no checkpoint ${id}`);
62
+ return checkpoint;
63
+ }
64
+ head(branch = "main") {
65
+ const id = this.heads.get(branch);
66
+ return id === void 0 ? void 0 : this.get(id);
67
+ }
68
+ hasBranch(branch) {
69
+ return this.heads.has(branch);
70
+ }
71
+ branches() {
72
+ return Object.freeze(Object.fromEntries([...this.heads].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)));
73
+ }
74
+ checkpoints() {
75
+ return [...this.nodes.values()];
76
+ }
77
+ /** Number of retained checkpoints without allocating an array. */
78
+ get size() {
79
+ return this.nodes.size;
80
+ }
81
+ /** Pin a checkpoint independently of branch heads (used by compatibility snapshot handles). */
82
+ retain(id) {
83
+ const checkpoint = this.get(id);
84
+ this.explicitPins.set(id, (this.explicitPins.get(id) ?? 0) + 1);
85
+ this.addReference(id);
86
+ return checkpoint;
87
+ }
88
+ /** Release one explicit pin. Branch heads remain pinned until moved or deleted. */
89
+ release(id) {
90
+ if (!this.nodes.has(id))
91
+ return false;
92
+ const pins = this.explicitPins.get(id) ?? 0;
93
+ if (pins === 0)
94
+ return false;
95
+ if (pins === 1)
96
+ this.explicitPins.delete(id);
97
+ else
98
+ this.explicitPins.set(id, pins - 1);
99
+ this.removeReference(id);
100
+ this.collect(this.maxCheckpoints);
101
+ return true;
102
+ }
103
+ deleteBranch(branch) {
104
+ if (branch === "main")
105
+ throw new RangeError("cannot delete main branch");
106
+ const previous = this.heads.get(branch);
107
+ const deleted = this.heads.delete(branch);
108
+ if (previous !== void 0)
109
+ this.removeReference(previous);
110
+ this.collect(this.maxCheckpoints);
111
+ return deleted;
112
+ }
113
+ /**
114
+ * Deterministically discard oldest unpinned checkpoints. Collection is O(number removed):
115
+ * commits never scan pinned nodes or the retained history. Parents are metadata rather than a
116
+ * storage dependency, so a retained node remains usable after pruning.
117
+ */
118
+ gc(max = this.maxCheckpoints) {
119
+ if (!Number.isSafeInteger(max) || max < 1)
120
+ throw new RangeError("max must be a positive integer");
121
+ const removed = [];
122
+ this.collect(max, removed);
123
+ return removed;
124
+ }
125
+ collect(max, removed) {
126
+ while (this.nodes.size > max && this.evictable.size > 0) {
127
+ const id = this.evictable.values().next().value;
128
+ this.evictable.delete(id);
129
+ this.nodes.delete(id);
130
+ removed?.push(id);
131
+ }
132
+ }
133
+ moveHead(branch, id) {
134
+ const previous = this.heads.get(branch);
135
+ if (previous === id)
136
+ return;
137
+ if (previous !== void 0)
138
+ this.removeReference(previous);
139
+ this.heads.set(branch, id);
140
+ this.addReference(id);
141
+ }
142
+ addReference(id) {
143
+ this.references.set(id, (this.references.get(id) ?? 0) + 1);
144
+ this.evictable.delete(id);
145
+ }
146
+ removeReference(id) {
147
+ const next = (this.references.get(id) ?? 0) - 1;
148
+ if (next > 0)
149
+ this.references.set(id, next);
150
+ else {
151
+ this.references.delete(id);
152
+ if (this.nodes.has(id))
153
+ this.evictable.add(id);
154
+ }
155
+ }
156
+ assertBranch(branch) {
157
+ if (!BRANCH_PATTERN.test(branch))
158
+ throw new RangeError(`branch must match ${BRANCH_PATTERN}`);
159
+ }
160
+ };
161
+
1
162
  // src/errors/error.ts
2
163
  var CATEGORY_TO_SQLSTATE = {
3
164
  syntax: "42601",
@@ -4196,7 +4357,13 @@ var RowScope = class {
4196
4357
  }
4197
4358
  };
4198
4359
  function childEnv(env, outer) {
4199
- return { ctx: env.ctx, params: env.params, ctes: env.ctes, outer };
4360
+ return {
4361
+ ctx: env.ctx,
4362
+ params: env.params,
4363
+ ctes: env.ctes,
4364
+ outer,
4365
+ allowUnpopulatedMatviews: env.allowUnpopulatedMatviews
4366
+ };
4200
4367
  }
4201
4368
  function relationResult(rel2, command) {
4202
4369
  const visible = rel2.columns.map((c, i) => ({ i, c })).filter(({ c }) => !c.hidden);
@@ -8536,6 +8703,234 @@ function callScalarFunction(ctx, name, args) {
8536
8703
  return fn(ctx, args);
8537
8704
  }
8538
8705
 
8706
+ // src/functions/pgtrgm.ts
8707
+ var PGTRGM_BODY = "pg_trgm";
8708
+ var WORD_SIMILARITY_THRESHOLD = Math.fround(0.6);
8709
+ var GIN_TRGM_TYPES = /* @__PURE__ */ new Set(["text", "varchar"]);
8710
+ var WORD_CHAR = /[\p{L}\p{N}]+/gu;
8711
+ function pgTrgmSchema(state) {
8712
+ for (const schema of state.schemas.values()) {
8713
+ for (const fns of schema.functions.values()) {
8714
+ if (fns.some((fn) => fn.language === "internal" && fn.rawBody === PGTRGM_BODY)) return schema.name;
8715
+ }
8716
+ }
8717
+ return null;
8718
+ }
8719
+ function pgTrgmInstalled(state) {
8720
+ return pgTrgmSchema(state) !== null;
8721
+ }
8722
+ function installPgTrgm(state, schemaName) {
8723
+ const schema = state.getSchema(schemaName);
8724
+ const existing = schema.functions.get("similarity") ?? [];
8725
+ const fn = {
8726
+ name: "similarity",
8727
+ schema: schema.name,
8728
+ argNames: [null, null],
8729
+ argTypes: ["text", "text"],
8730
+ argDefaults: [null, null],
8731
+ returns: "float4",
8732
+ returnsSet: false,
8733
+ returnsTable: null,
8734
+ language: "internal",
8735
+ body: null,
8736
+ rawBody: PGTRGM_BODY,
8737
+ strict: true,
8738
+ oid: state.nextOid()
8739
+ };
8740
+ existing.push(fn);
8741
+ schema.functions.set("similarity", existing);
8742
+ }
8743
+ function uninstallPgTrgm(state) {
8744
+ let removed = false;
8745
+ for (const schema of state.schemas.values()) {
8746
+ for (const [name, fns] of [...schema.functions.entries()]) {
8747
+ const keep = fns.filter((fn) => fn.language !== "internal" || fn.rawBody !== PGTRGM_BODY);
8748
+ if (keep.length === fns.length) continue;
8749
+ removed = true;
8750
+ if (keep.length === 0) schema.functions.delete(name);
8751
+ else schema.functions.set(name, keep);
8752
+ }
8753
+ }
8754
+ return removed;
8755
+ }
8756
+ function evalPgTrgmFunction(ctx, fn, args) {
8757
+ const ret = fn.returns ?? "float4";
8758
+ if (fn.strict && args.some((arg) => arg.v === null)) return tv(ret, null);
8759
+ if (fn.name !== "similarity" || args.length !== 2) {
8760
+ throw pgError("undefined_function", `function ${fn.schema}.${fn.name} is not implemented`, "42883");
8761
+ }
8762
+ const left = castTo(ctx, args[0], "text");
8763
+ const right = castTo(ctx, args[1], "text");
8764
+ if (left.v === null || right.v === null) return tv("float4", null);
8765
+ return tv("float4", trigramSimilarity(left.v, right.v));
8766
+ }
8767
+ function evalTrgmWordSimilar(ctx, left, right) {
8768
+ const missing = () => {
8769
+ throw pgError(
8770
+ "undefined_function",
8771
+ `operator does not exist: ${typeDisplayName(left.t)} <% ${typeDisplayName(right.t)}`
8772
+ );
8773
+ };
8774
+ if (!pgTrgmInstalled(ctx.state)) missing();
8775
+ if (!canImplicitCast(left.t, "text") || !canImplicitCast(right.t, "text")) missing();
8776
+ const a = castTo(ctx, left, "text");
8777
+ const b = castTo(ctx, right, "text");
8778
+ if (a.v === null || b.v === null) return tv("bool", null);
8779
+ const score = wordSimilarity(a.v, b.v);
8780
+ return tv("bool", score >= WORD_SIMILARITY_THRESHOLD);
8781
+ }
8782
+ function assertGinTrgmIndex(state, table, stmt) {
8783
+ const trgmCols = stmt.columns.filter((col2) => isGinTrgmOpclass(col2.opclass));
8784
+ if (trgmCols.length === 0) return;
8785
+ if (trgmCols.length !== stmt.columns.length || stmt.columns.length !== 1) {
8786
+ throw unsupported("multicolumn gin_trgm_ops");
8787
+ }
8788
+ const method = stmt.using ?? "btree";
8789
+ const col = trgmCols[0];
8790
+ const opclass = col.opclass;
8791
+ const label = opclass.join(".");
8792
+ if (method !== "gin" || !opclassVisible(state, opclass)) {
8793
+ throw pgError(
8794
+ "undefined_object",
8795
+ `operator class "${label}" does not exist for access method "${method}"`,
8796
+ "42704"
8797
+ );
8798
+ }
8799
+ if (stmt.unique) {
8800
+ throw pgError("feature_not_supported", `access method "gin" does not support unique indexes`, "0A000");
8801
+ }
8802
+ if (col.expr.type !== "colref" || col.expr.parts.length !== 1) {
8803
+ throw unsupported("expression gin_trgm_ops");
8804
+ }
8805
+ const index = table.columnIndex(col.expr.parts[0]);
8806
+ const typeId = table.columns[index].type.id;
8807
+ if (!GIN_TRGM_TYPES.has(typeId)) {
8808
+ throw pgError(
8809
+ "datatype_mismatch",
8810
+ `operator class "${label}" does not accept data type ${typeDisplayName(typeId)}`,
8811
+ "42804"
8812
+ );
8813
+ }
8814
+ }
8815
+ function isGinTrgmOpclass(opclass) {
8816
+ return opclass !== null && opclass[opclass.length - 1] === "gin_trgm_ops";
8817
+ }
8818
+ function opclassVisible(state, opclass) {
8819
+ const schema = pgTrgmSchema(state);
8820
+ if (schema === null || opclass[opclass.length - 1] !== "gin_trgm_ops") return false;
8821
+ if (opclass.length === 1) return state.effectiveSearchPath().includes(schema);
8822
+ if (opclass.length === 2) return opclass[0] === schema;
8823
+ return false;
8824
+ }
8825
+ function trigramSimilarity(left, right) {
8826
+ const a = uniqueSorted(orderedTrigrams(left));
8827
+ const b = uniqueSorted(orderedTrigrams(right));
8828
+ if (a.length === 0 || b.length === 0) return 0;
8829
+ let i = 0;
8830
+ let j = 0;
8831
+ let count = 0;
8832
+ while (i < a.length && j < b.length) {
8833
+ const cmp = a[i] < b[j] ? -1 : a[i] > b[j] ? 1 : 0;
8834
+ if (cmp < 0) i++;
8835
+ else if (cmp > 0) j++;
8836
+ else {
8837
+ count++;
8838
+ i++;
8839
+ j++;
8840
+ }
8841
+ }
8842
+ return calcSml(count, a.length, b.length);
8843
+ }
8844
+ function wordSimilarity(pattern, haystack) {
8845
+ const trg1 = orderedTrigrams(pattern);
8846
+ const trg2 = orderedTrigrams(haystack);
8847
+ const len1 = trg1.length;
8848
+ const len2 = trg2.length;
8849
+ if (len1 === 0 || len2 === 0) return 0;
8850
+ const positional = [];
8851
+ for (let i = 0; i < len1; i++) positional.push({ trg: trg1[i], index: -1 });
8852
+ for (let i = 0; i < len2; i++) positional.push({ trg: trg2[i], index: i });
8853
+ positional.sort((x, y) => x.trg < y.trg ? -1 : x.trg > y.trg ? 1 : x.index - y.index);
8854
+ const len = len1 + len2;
8855
+ const trg2indexes = new Array(len2);
8856
+ const found = new Array(len).fill(false);
8857
+ let ulen1 = 0;
8858
+ let group = 0;
8859
+ for (let i = 0; i < len; i++) {
8860
+ if (i > 0 && positional[i - 1].trg !== positional[i].trg) {
8861
+ if (found[group]) ulen1++;
8862
+ group++;
8863
+ }
8864
+ const index = positional[i].index;
8865
+ if (index >= 0) trg2indexes[index] = group;
8866
+ else found[group] = true;
8867
+ }
8868
+ if (found[group]) ulen1++;
8869
+ return iterateWordSimilarity(trg2indexes, found, ulen1, len2);
8870
+ }
8871
+ function orderedTrigrams(input) {
8872
+ const out = [];
8873
+ for (const match of input.matchAll(WORD_CHAR)) {
8874
+ const padded = ` ${match[0].toLowerCase()} `;
8875
+ for (let i = 0; i + 3 <= padded.length; i++) out.push(padded.slice(i, i + 3));
8876
+ }
8877
+ return out;
8878
+ }
8879
+ function uniqueSorted(trigrams) {
8880
+ return [...new Set(trigrams)].sort();
8881
+ }
8882
+ function calcSml(count, len1, len2) {
8883
+ const denom = len1 + len2 - count;
8884
+ if (denom <= 0) return 0;
8885
+ return Math.fround(count / denom);
8886
+ }
8887
+ function iterateWordSimilarity(trg2indexes, found, ulen1, len2) {
8888
+ const lastpos = new Array(found.length).fill(-1);
8889
+ let ulen2 = 0;
8890
+ let count = 0;
8891
+ let lower = -1;
8892
+ let smlrMax = 0;
8893
+ for (let i = 0; i < len2; i++) {
8894
+ const trgindex = trg2indexes[i];
8895
+ if (lower >= 0 || found[trgindex]) {
8896
+ if (lastpos[trgindex] < 0) {
8897
+ ulen2++;
8898
+ if (found[trgindex]) count++;
8899
+ }
8900
+ lastpos[trgindex] = i;
8901
+ }
8902
+ if (!found[trgindex]) continue;
8903
+ if (lower === -1) {
8904
+ lower = i;
8905
+ ulen2 = 1;
8906
+ }
8907
+ let smlrCur = calcSml(count, ulen1, ulen2);
8908
+ let tmpCount = count;
8909
+ let tmpUlen2 = ulen2;
8910
+ const prevLower = lower;
8911
+ for (let tmpLower = lower; tmpLower <= i; tmpLower++) {
8912
+ const smlrTmp = calcSml(tmpCount, ulen1, tmpUlen2);
8913
+ if (smlrTmp > smlrCur) {
8914
+ smlrCur = smlrTmp;
8915
+ ulen2 = tmpUlen2;
8916
+ lower = tmpLower;
8917
+ count = tmpCount;
8918
+ }
8919
+ const tmpTrgindex = trg2indexes[tmpLower];
8920
+ if (lastpos[tmpTrgindex] === tmpLower) {
8921
+ tmpUlen2--;
8922
+ if (found[tmpTrgindex]) tmpCount--;
8923
+ }
8924
+ }
8925
+ if (smlrCur > smlrMax) smlrMax = smlrCur;
8926
+ for (let tmpLower = prevLower; tmpLower < lower; tmpLower++) {
8927
+ const tmpTrgindex = trg2indexes[tmpLower];
8928
+ if (lastpos[tmpTrgindex] === tmpLower) lastpos[tmpTrgindex] = -1;
8929
+ }
8930
+ }
8931
+ return smlrMax;
8932
+ }
8933
+
8539
8934
  // src/expressions/operators.ts
8540
8935
  var NUM_LADDER = ["int2", "int4", "int8", "numeric", "float4", "float8"];
8541
8936
  function opNotExist(op, l, r) {
@@ -8679,6 +9074,8 @@ function evalBinary(ctx, op, l0, r0) {
8679
9074
  return evalJsonbDeletePath(ctx, l, r);
8680
9075
  case "@@":
8681
9076
  return evalTextSearchMatch(ctx, l, r);
9077
+ case "<%":
9078
+ return evalTrgmWordSimilar(ctx, l, r);
8682
9079
  default:
8683
9080
  opNotExist(op, l.t, r.t);
8684
9081
  }
@@ -10899,6 +11296,634 @@ function unifyAggType(a, b) {
10899
11296
  return unifyTypes(a, b) ?? a;
10900
11297
  }
10901
11298
 
11299
+ // src/functions/pgcrypto.ts
11300
+ var PGCRYPTO_BODY = "pgcrypto";
11301
+ var utf82 = new TextEncoder();
11302
+ var MD5_S = [
11303
+ 7,
11304
+ 12,
11305
+ 17,
11306
+ 22,
11307
+ 7,
11308
+ 12,
11309
+ 17,
11310
+ 22,
11311
+ 7,
11312
+ 12,
11313
+ 17,
11314
+ 22,
11315
+ 7,
11316
+ 12,
11317
+ 17,
11318
+ 22,
11319
+ 5,
11320
+ 9,
11321
+ 14,
11322
+ 20,
11323
+ 5,
11324
+ 9,
11325
+ 14,
11326
+ 20,
11327
+ 5,
11328
+ 9,
11329
+ 14,
11330
+ 20,
11331
+ 5,
11332
+ 9,
11333
+ 14,
11334
+ 20,
11335
+ 4,
11336
+ 11,
11337
+ 16,
11338
+ 23,
11339
+ 4,
11340
+ 11,
11341
+ 16,
11342
+ 23,
11343
+ 4,
11344
+ 11,
11345
+ 16,
11346
+ 23,
11347
+ 4,
11348
+ 11,
11349
+ 16,
11350
+ 23,
11351
+ 6,
11352
+ 10,
11353
+ 15,
11354
+ 21,
11355
+ 6,
11356
+ 10,
11357
+ 15,
11358
+ 21,
11359
+ 6,
11360
+ 10,
11361
+ 15,
11362
+ 21,
11363
+ 6,
11364
+ 10,
11365
+ 15,
11366
+ 21
11367
+ ];
11368
+ var MD5_K = new Uint32Array([
11369
+ 3614090360,
11370
+ 3905402710,
11371
+ 606105819,
11372
+ 3250441966,
11373
+ 4118548399,
11374
+ 1200080426,
11375
+ 2821735955,
11376
+ 4249261313,
11377
+ 1770035416,
11378
+ 2336552879,
11379
+ 4294925233,
11380
+ 2304563134,
11381
+ 1804603682,
11382
+ 4254626195,
11383
+ 2792965006,
11384
+ 1236535329,
11385
+ 4129170786,
11386
+ 3225465664,
11387
+ 643717713,
11388
+ 3921069994,
11389
+ 3593408605,
11390
+ 38016083,
11391
+ 3634488961,
11392
+ 3889429448,
11393
+ 568446438,
11394
+ 3275163606,
11395
+ 4107603335,
11396
+ 1163531501,
11397
+ 2850285829,
11398
+ 4243563512,
11399
+ 1735328473,
11400
+ 2368359562,
11401
+ 4294588738,
11402
+ 2272392833,
11403
+ 1839030562,
11404
+ 4259657740,
11405
+ 2763975236,
11406
+ 1272893353,
11407
+ 4139469664,
11408
+ 3200236656,
11409
+ 681279174,
11410
+ 3936430074,
11411
+ 3572445317,
11412
+ 76029189,
11413
+ 3654602809,
11414
+ 3873151461,
11415
+ 530742520,
11416
+ 3299628645,
11417
+ 4096336452,
11418
+ 1126891415,
11419
+ 2878612391,
11420
+ 4237533241,
11421
+ 1700485571,
11422
+ 2399980690,
11423
+ 4293915773,
11424
+ 2240044497,
11425
+ 1873313359,
11426
+ 4264355552,
11427
+ 2734768916,
11428
+ 1309151649,
11429
+ 4149444226,
11430
+ 3174756917,
11431
+ 718787259,
11432
+ 3951481745
11433
+ ]);
11434
+ var SHA256_K = new Uint32Array([
11435
+ 1116352408,
11436
+ 1899447441,
11437
+ 3049323471,
11438
+ 3921009573,
11439
+ 961987163,
11440
+ 1508970993,
11441
+ 2453635748,
11442
+ 2870763221,
11443
+ 3624381080,
11444
+ 310598401,
11445
+ 607225278,
11446
+ 1426881987,
11447
+ 1925078388,
11448
+ 2162078206,
11449
+ 2614888103,
11450
+ 3248222580,
11451
+ 3835390401,
11452
+ 4022224774,
11453
+ 264347078,
11454
+ 604807628,
11455
+ 770255983,
11456
+ 1249150122,
11457
+ 1555081692,
11458
+ 1996064986,
11459
+ 2554220882,
11460
+ 2821834349,
11461
+ 2952996808,
11462
+ 3210313671,
11463
+ 3336571891,
11464
+ 3584528711,
11465
+ 113926993,
11466
+ 338241895,
11467
+ 666307205,
11468
+ 773529912,
11469
+ 1294757372,
11470
+ 1396182291,
11471
+ 1695183700,
11472
+ 1986661051,
11473
+ 2177026350,
11474
+ 2456956037,
11475
+ 2730485921,
11476
+ 2820302411,
11477
+ 3259730800,
11478
+ 3345764771,
11479
+ 3516065817,
11480
+ 3600352804,
11481
+ 4094571909,
11482
+ 275423344,
11483
+ 430227734,
11484
+ 506948616,
11485
+ 659060556,
11486
+ 883997877,
11487
+ 958139571,
11488
+ 1322822218,
11489
+ 1537002063,
11490
+ 1747873779,
11491
+ 1955562222,
11492
+ 2024104815,
11493
+ 2227730452,
11494
+ 2361852424,
11495
+ 2428436474,
11496
+ 2756734187,
11497
+ 3204031479,
11498
+ 3329325298
11499
+ ]);
11500
+ var SHA512_K = [
11501
+ 0x428a2f98d728ae22n,
11502
+ 0x7137449123ef65cdn,
11503
+ 0xb5c0fbcfec4d3b2fn,
11504
+ 0xe9b5dba58189dbbcn,
11505
+ 0x3956c25bf348b538n,
11506
+ 0x59f111f1b605d019n,
11507
+ 0x923f82a4af194f9bn,
11508
+ 0xab1c5ed5da6d8118n,
11509
+ 0xd807aa98a3030242n,
11510
+ 0x12835b0145706fben,
11511
+ 0x243185be4ee4b28cn,
11512
+ 0x550c7dc3d5ffb4e2n,
11513
+ 0x72be5d74f27b896fn,
11514
+ 0x80deb1fe3b1696b1n,
11515
+ 0x9bdc06a725c71235n,
11516
+ 0xc19bf174cf692694n,
11517
+ 0xe49b69c19ef14ad2n,
11518
+ 0xefbe4786384f25e3n,
11519
+ 0x0fc19dc68b8cd5b5n,
11520
+ 0x240ca1cc77ac9c65n,
11521
+ 0x2de92c6f592b0275n,
11522
+ 0x4a7484aa6ea6e483n,
11523
+ 0x5cb0a9dcbd41fbd4n,
11524
+ 0x76f988da831153b5n,
11525
+ 0x983e5152ee66dfabn,
11526
+ 0xa831c66d2db43210n,
11527
+ 0xb00327c898fb213fn,
11528
+ 0xbf597fc7beef0ee4n,
11529
+ 0xc6e00bf33da88fc2n,
11530
+ 0xd5a79147930aa725n,
11531
+ 0x06ca6351e003826fn,
11532
+ 0x142929670a0e6e70n,
11533
+ 0x27b70a8546d22ffcn,
11534
+ 0x2e1b21385c26c926n,
11535
+ 0x4d2c6dfc5ac42aedn,
11536
+ 0x53380d139d95b3dfn,
11537
+ 0x650a73548baf63den,
11538
+ 0x766a0abb3c77b2a8n,
11539
+ 0x81c2c92e47edaee6n,
11540
+ 0x92722c851482353bn,
11541
+ 0xa2bfe8a14cf10364n,
11542
+ 0xa81a664bbc423001n,
11543
+ 0xc24b8b70d0f89791n,
11544
+ 0xc76c51a30654be30n,
11545
+ 0xd192e819d6ef5218n,
11546
+ 0xd69906245565a910n,
11547
+ 0xf40e35855771202an,
11548
+ 0x106aa07032bbd1b8n,
11549
+ 0x19a4c116b8d2d0c8n,
11550
+ 0x1e376c085141ab53n,
11551
+ 0x2748774cdf8eeb99n,
11552
+ 0x34b0bcb5e19b48a8n,
11553
+ 0x391c0cb3c5c95a63n,
11554
+ 0x4ed8aa4ae3418acbn,
11555
+ 0x5b9cca4f7763e373n,
11556
+ 0x682e6ff3d6b2b8a3n,
11557
+ 0x748f82ee5defb2fcn,
11558
+ 0x78a5636f43172f60n,
11559
+ 0x84c87814a1f0ab72n,
11560
+ 0x8cc702081a6439ecn,
11561
+ 0x90befffa23631e28n,
11562
+ 0xa4506cebde82bde9n,
11563
+ 0xbef9a3f7b2c67915n,
11564
+ 0xc67178f2e372532bn,
11565
+ 0xca273eceea26619cn,
11566
+ 0xd186b8c721c0c207n,
11567
+ 0xeada7dd6cde0eb1en,
11568
+ 0xf57d4f7fee6ed178n,
11569
+ 0x06f067aa72176fban,
11570
+ 0x0a637dc5a2c898a6n,
11571
+ 0x113f9804bef90daen,
11572
+ 0x1b710b35131c471bn,
11573
+ 0x28db77f523047d84n,
11574
+ 0x32caab7b40c72493n,
11575
+ 0x3c9ebe0a15c9bebcn,
11576
+ 0x431d67c49c100d4cn,
11577
+ 0x4cc5d4becb3e42b6n,
11578
+ 0x597f299cfc657e2an,
11579
+ 0x5fcb6fab3ad6faecn,
11580
+ 0x6c44198c4a475817n
11581
+ ];
11582
+ var MASK64 = (1n << 64n) - 1n;
11583
+ function rotl32(x, n) {
11584
+ return (x << n | x >>> 32 - n) >>> 0;
11585
+ }
11586
+ function rotr32(x, n) {
11587
+ return (x >>> n | x << 32 - n) >>> 0;
11588
+ }
11589
+ function rotr64(x, n) {
11590
+ return (x >> n | x << 64n - n) & MASK64;
11591
+ }
11592
+ function padBe(data, block, lengthBytes) {
11593
+ const bitLen = BigInt(data.length) * 8n;
11594
+ let len = data.length + 1 + lengthBytes;
11595
+ const rem = len % block;
11596
+ if (rem !== 0) len += block - rem;
11597
+ const out = new Uint8Array(len);
11598
+ out.set(data);
11599
+ out[data.length] = 128;
11600
+ const view = new DataView(out.buffer);
11601
+ view.setUint32(out.length - 8, Number(bitLen >> 32n & 0xffffffffn), false);
11602
+ view.setUint32(out.length - 4, Number(bitLen & 0xffffffffn), false);
11603
+ return out;
11604
+ }
11605
+ function padMd5(data) {
11606
+ const bitLen = BigInt(data.length) * 8n;
11607
+ let len = data.length + 1 + 8;
11608
+ const rem = len % 64;
11609
+ if (rem !== 0) len += 64 - rem;
11610
+ const out = new Uint8Array(len);
11611
+ out.set(data);
11612
+ out[data.length] = 128;
11613
+ const view = new DataView(out.buffer);
11614
+ view.setUint32(out.length - 8, Number(bitLen & 0xffffffffn), true);
11615
+ view.setUint32(out.length - 4, Number(bitLen >> 32n & 0xffffffffn), true);
11616
+ return out;
11617
+ }
11618
+ function md5(data) {
11619
+ const bytes = padMd5(data);
11620
+ const view = new DataView(bytes.buffer);
11621
+ let a0 = 1732584193;
11622
+ let b0 = 4023233417;
11623
+ let c0 = 2562383102;
11624
+ let d0 = 271733878;
11625
+ const m = new Uint32Array(16);
11626
+ for (let off = 0; off < bytes.length; off += 64) {
11627
+ for (let i = 0; i < 16; i++) m[i] = view.getUint32(off + i * 4, true);
11628
+ let a = a0;
11629
+ let b = b0;
11630
+ let c = c0;
11631
+ let d = d0;
11632
+ for (let i = 0; i < 64; i++) {
11633
+ let f;
11634
+ let g;
11635
+ if (i < 16) {
11636
+ f = b & c | ~b & d;
11637
+ g = i;
11638
+ } else if (i < 32) {
11639
+ f = d & b | ~d & c;
11640
+ g = (5 * i + 1) % 16;
11641
+ } else if (i < 48) {
11642
+ f = b ^ c ^ d;
11643
+ g = (3 * i + 5) % 16;
11644
+ } else {
11645
+ f = c ^ (b | ~d);
11646
+ g = 7 * i % 16;
11647
+ }
11648
+ const sum = f + a + MD5_K[i] + m[g] >>> 0;
11649
+ a = d;
11650
+ d = c;
11651
+ c = b;
11652
+ b = b + rotl32(sum, MD5_S[i]) >>> 0;
11653
+ }
11654
+ a0 = a0 + a >>> 0;
11655
+ b0 = b0 + b >>> 0;
11656
+ c0 = c0 + c >>> 0;
11657
+ d0 = d0 + d >>> 0;
11658
+ }
11659
+ const out = new Uint8Array(16);
11660
+ const ov = new DataView(out.buffer);
11661
+ ov.setUint32(0, a0, true);
11662
+ ov.setUint32(4, b0, true);
11663
+ ov.setUint32(8, c0, true);
11664
+ ov.setUint32(12, d0, true);
11665
+ return out;
11666
+ }
11667
+ function sha1(data) {
11668
+ const bytes = padBe(data, 64, 8);
11669
+ const view = new DataView(bytes.buffer);
11670
+ let h0 = 1732584193;
11671
+ let h1 = 4023233417;
11672
+ let h2 = 2562383102;
11673
+ let h3 = 271733878;
11674
+ let h4 = 3285377520;
11675
+ const w = new Uint32Array(80);
11676
+ for (let off = 0; off < bytes.length; off += 64) {
11677
+ for (let t = 0; t < 16; t++) w[t] = view.getUint32(off + t * 4, false);
11678
+ for (let t = 16; t < 80; t++) w[t] = rotl32(w[t - 3] ^ w[t - 8] ^ w[t - 14] ^ w[t - 16], 1);
11679
+ let a = h0;
11680
+ let b = h1;
11681
+ let c = h2;
11682
+ let d = h3;
11683
+ let e = h4;
11684
+ for (let t = 0; t < 80; t++) {
11685
+ let f;
11686
+ let k;
11687
+ if (t < 20) {
11688
+ f = b & c | ~b & d;
11689
+ k = 1518500249;
11690
+ } else if (t < 40) {
11691
+ f = b ^ c ^ d;
11692
+ k = 1859775393;
11693
+ } else if (t < 60) {
11694
+ f = b & c | b & d | c & d;
11695
+ k = 2400959708;
11696
+ } else {
11697
+ f = b ^ c ^ d;
11698
+ k = 3395469782;
11699
+ }
11700
+ const temp = rotl32(a, 5) + f + e + k + w[t] >>> 0;
11701
+ e = d;
11702
+ d = c;
11703
+ c = rotl32(b, 30);
11704
+ b = a;
11705
+ a = temp;
11706
+ }
11707
+ h0 = h0 + a >>> 0;
11708
+ h1 = h1 + b >>> 0;
11709
+ h2 = h2 + c >>> 0;
11710
+ h3 = h3 + d >>> 0;
11711
+ h4 = h4 + e >>> 0;
11712
+ }
11713
+ const out = new Uint8Array(20);
11714
+ const ov = new DataView(out.buffer);
11715
+ ov.setUint32(0, h0, false);
11716
+ ov.setUint32(4, h1, false);
11717
+ ov.setUint32(8, h2, false);
11718
+ ov.setUint32(12, h3, false);
11719
+ ov.setUint32(16, h4, false);
11720
+ return out;
11721
+ }
11722
+ function sha256(data, sha224) {
11723
+ const bytes = padBe(data, 64, 8);
11724
+ const view = new DataView(bytes.buffer);
11725
+ let h0 = sha224 ? 3238371032 : 1779033703;
11726
+ let h1 = sha224 ? 914150663 : 3144134277;
11727
+ let h2 = sha224 ? 812702999 : 1013904242;
11728
+ let h3 = sha224 ? 4144912697 : 2773480762;
11729
+ let h4 = sha224 ? 4290775857 : 1359893119;
11730
+ let h5 = sha224 ? 1750603025 : 2600822924;
11731
+ let h6 = sha224 ? 1694076839 : 528734635;
11732
+ let h7 = sha224 ? 3204075428 : 1541459225;
11733
+ const w = new Uint32Array(64);
11734
+ for (let off = 0; off < bytes.length; off += 64) {
11735
+ for (let t = 0; t < 16; t++) w[t] = view.getUint32(off + t * 4, false);
11736
+ for (let t = 16; t < 64; t++) {
11737
+ const x15 = w[t - 15];
11738
+ const x2 = w[t - 2];
11739
+ const s0 = rotr32(x15, 7) ^ rotr32(x15, 18) ^ x15 >>> 3;
11740
+ const s1 = rotr32(x2, 17) ^ rotr32(x2, 19) ^ x2 >>> 10;
11741
+ w[t] = w[t - 16] + s0 + w[t - 7] + s1 >>> 0;
11742
+ }
11743
+ let a = h0;
11744
+ let b = h1;
11745
+ let c = h2;
11746
+ let d = h3;
11747
+ let e = h4;
11748
+ let f = h5;
11749
+ let g = h6;
11750
+ let h = h7;
11751
+ for (let t = 0; t < 64; t++) {
11752
+ const s1 = rotr32(e, 6) ^ rotr32(e, 11) ^ rotr32(e, 25);
11753
+ const ch = e & f ^ ~e & g;
11754
+ const t1 = h + s1 + ch + SHA256_K[t] + w[t] >>> 0;
11755
+ const s0 = rotr32(a, 2) ^ rotr32(a, 13) ^ rotr32(a, 22);
11756
+ const maj = a & b ^ a & c ^ b & c;
11757
+ const t2 = s0 + maj >>> 0;
11758
+ h = g;
11759
+ g = f;
11760
+ f = e;
11761
+ e = d + t1 >>> 0;
11762
+ d = c;
11763
+ c = b;
11764
+ b = a;
11765
+ a = t1 + t2 >>> 0;
11766
+ }
11767
+ h0 = h0 + a >>> 0;
11768
+ h1 = h1 + b >>> 0;
11769
+ h2 = h2 + c >>> 0;
11770
+ h3 = h3 + d >>> 0;
11771
+ h4 = h4 + e >>> 0;
11772
+ h5 = h5 + f >>> 0;
11773
+ h6 = h6 + g >>> 0;
11774
+ h7 = h7 + h >>> 0;
11775
+ }
11776
+ const words = sha224 ? 7 : 8;
11777
+ const out = new Uint8Array(words * 4);
11778
+ const ov = new DataView(out.buffer);
11779
+ const hs = [h0, h1, h2, h3, h4, h5, h6, h7];
11780
+ for (let i = 0; i < words; i++) ov.setUint32(i * 4, hs[i], false);
11781
+ return out;
11782
+ }
11783
+ function readUint64BE(view, offset) {
11784
+ return BigInt(view.getUint32(offset, false)) << 32n | BigInt(view.getUint32(offset + 4, false));
11785
+ }
11786
+ function sha512(data, sha384) {
11787
+ const bytes = padBe(data, 128, 16);
11788
+ const view = new DataView(bytes.buffer);
11789
+ let h0 = sha384 ? 0xcbbb9d5dc1059ed8n : 0x6a09e667f3bcc908n;
11790
+ let h1 = sha384 ? 0x629a292a367cd507n : 0xbb67ae8584caa73bn;
11791
+ let h2 = sha384 ? 0x9159015a3070dd17n : 0x3c6ef372fe94f82bn;
11792
+ let h3 = sha384 ? 0x152fecd8f70e5939n : 0xa54ff53a5f1d36f1n;
11793
+ let h4 = sha384 ? 0x67332667ffc00b31n : 0x510e527fade682d1n;
11794
+ let h5 = sha384 ? 0x8eb44a8768581511n : 0x9b05688c2b3e6c1fn;
11795
+ let h6 = sha384 ? 0xdb0c2e0d64f98fa7n : 0x1f83d9abfb41bd6bn;
11796
+ let h7 = sha384 ? 0x47b5481dbefa4fa4n : 0x5be0cd19137e2179n;
11797
+ const w = new Array(80);
11798
+ for (let off = 0; off < bytes.length; off += 128) {
11799
+ for (let t = 0; t < 16; t++) w[t] = readUint64BE(view, off + t * 8);
11800
+ for (let t = 16; t < 80; t++) {
11801
+ const x15 = w[t - 15];
11802
+ const x2 = w[t - 2];
11803
+ const s0 = rotr64(x15, 1n) ^ rotr64(x15, 8n) ^ x15 >> 7n;
11804
+ const s1 = rotr64(x2, 19n) ^ rotr64(x2, 61n) ^ x2 >> 6n;
11805
+ w[t] = w[t - 16] + s0 + w[t - 7] + s1 & MASK64;
11806
+ }
11807
+ let a = h0;
11808
+ let b = h1;
11809
+ let c = h2;
11810
+ let d = h3;
11811
+ let e = h4;
11812
+ let f = h5;
11813
+ let g = h6;
11814
+ let h = h7;
11815
+ for (let t = 0; t < 80; t++) {
11816
+ const s1 = rotr64(e, 14n) ^ rotr64(e, 18n) ^ rotr64(e, 41n);
11817
+ const ch = e & f ^ ~e & g & MASK64;
11818
+ const t1 = h + s1 + ch + SHA512_K[t] + w[t] & MASK64;
11819
+ const s0 = rotr64(a, 28n) ^ rotr64(a, 34n) ^ rotr64(a, 39n);
11820
+ const maj = a & b ^ a & c ^ b & c;
11821
+ const t2 = s0 + maj & MASK64;
11822
+ h = g;
11823
+ g = f;
11824
+ f = e;
11825
+ e = d + t1 & MASK64;
11826
+ d = c;
11827
+ c = b;
11828
+ b = a;
11829
+ a = t1 + t2 & MASK64;
11830
+ }
11831
+ h0 = h0 + a & MASK64;
11832
+ h1 = h1 + b & MASK64;
11833
+ h2 = h2 + c & MASK64;
11834
+ h3 = h3 + d & MASK64;
11835
+ h4 = h4 + e & MASK64;
11836
+ h5 = h5 + f & MASK64;
11837
+ h6 = h6 + g & MASK64;
11838
+ h7 = h7 + h & MASK64;
11839
+ }
11840
+ const words = sha384 ? 6 : 8;
11841
+ const out = new Uint8Array(words * 8);
11842
+ const ov = new DataView(out.buffer);
11843
+ const hs = [h0, h1, h2, h3, h4, h5, h6, h7];
11844
+ for (let i = 0; i < words; i++) {
11845
+ const word = hs[i];
11846
+ ov.setUint32(i * 8, Number(word >> 32n & 0xffffffffn), false);
11847
+ ov.setUint32(i * 8 + 4, Number(word & 0xffffffffn), false);
11848
+ }
11849
+ return out;
11850
+ }
11851
+ function digestBytes(data, algorithm) {
11852
+ switch (algorithm.toLowerCase().replaceAll("-", "")) {
11853
+ case "md5":
11854
+ return md5(data);
11855
+ case "sha1":
11856
+ return sha1(data);
11857
+ case "sha224":
11858
+ return sha256(data, true);
11859
+ case "sha256":
11860
+ return sha256(data, false);
11861
+ case "sha384":
11862
+ return sha512(data, true);
11863
+ case "sha512":
11864
+ return sha512(data, false);
11865
+ default:
11866
+ throw pgError("invalid_parameter_value", `Cannot use "${algorithm}": No such hash algorithm`, "22023");
11867
+ }
11868
+ }
11869
+ function pgcryptoInstalled(state) {
11870
+ for (const schema of state.schemas.values()) {
11871
+ for (const fns of schema.functions.values()) {
11872
+ if (fns.some((fn) => fn.language === "internal" && fn.rawBody === PGCRYPTO_BODY)) return true;
11873
+ }
11874
+ }
11875
+ return false;
11876
+ }
11877
+ function installPgcrypto(state, schemaName) {
11878
+ const schema = state.getSchema(schemaName);
11879
+ const existing = schema.functions.get("digest") ?? [];
11880
+ const arg0Types = ["text", "bytea"];
11881
+ for (const arg0 of arg0Types) {
11882
+ const fn = {
11883
+ name: "digest",
11884
+ schema: schema.name,
11885
+ argNames: [null, null],
11886
+ argTypes: [arg0, "text"],
11887
+ argDefaults: [null, null],
11888
+ returns: "bytea",
11889
+ returnsSet: false,
11890
+ returnsTable: null,
11891
+ language: "internal",
11892
+ body: null,
11893
+ rawBody: PGCRYPTO_BODY,
11894
+ strict: true,
11895
+ oid: state.nextOid()
11896
+ };
11897
+ existing.push(fn);
11898
+ }
11899
+ schema.functions.set("digest", existing);
11900
+ }
11901
+ function uninstallPgcrypto(state) {
11902
+ let removed = false;
11903
+ for (const schema of state.schemas.values()) {
11904
+ for (const [name, fns] of [...schema.functions.entries()]) {
11905
+ const keep = fns.filter((fn) => fn.language !== "internal" || fn.rawBody !== PGCRYPTO_BODY);
11906
+ if (keep.length === fns.length) continue;
11907
+ removed = true;
11908
+ if (keep.length === 0) schema.functions.delete(name);
11909
+ else schema.functions.set(name, keep);
11910
+ }
11911
+ }
11912
+ return removed;
11913
+ }
11914
+ function evalPgcryptoFunction(ctx, fn, args) {
11915
+ const ret = fn.returns ?? "bytea";
11916
+ if (fn.strict && args.some((arg) => arg.v === null)) return tv(ret, null);
11917
+ if (fn.name !== "digest" || args.length !== 2) {
11918
+ throw pgError("undefined_function", `function ${fn.schema}.${fn.name} is not implemented`, "42883");
11919
+ }
11920
+ const data = castTo(ctx, args[0], fn.argTypes[0] ?? "bytea", {});
11921
+ const algorithm = castTo(ctx, args[1], "text", {});
11922
+ if (data.v === null || algorithm.v === null) return tv("bytea", null);
11923
+ const bytes = fn.argTypes[0] === "bytea" ? data.v : utf82.encode(data.v);
11924
+ return tv("bytea", digestBytes(bytes, algorithm.v));
11925
+ }
11926
+
10902
11927
  // src/functions/srf.ts
10903
11928
  function jsonInput(ctx, a) {
10904
11929
  void ctx;
@@ -13092,10 +14117,32 @@ var Parser = class {
13092
14117
  }
13093
14118
  if (this.atKw("extension")) {
13094
14119
  this.pos++;
13095
- this.parseIfNotExists();
14120
+ const ifNotExists = this.parseIfNotExists();
13096
14121
  const name = this.ident(true);
13097
- while (!this.atPunct(";") && this.peek().type !== "eof") this.pos++;
13098
- throw unsupported(`extension "${name}"`);
14122
+ let schema = null;
14123
+ let version = null;
14124
+ let cascade = false;
14125
+ this.eatKw("with");
14126
+ while (!this.atPunct(";") && this.peek().type !== "eof") {
14127
+ if (this.eatKw("schema")) {
14128
+ schema = this.ident(true);
14129
+ continue;
14130
+ }
14131
+ if (this.eatKw("version")) {
14132
+ const token = this.next();
14133
+ if (token.type !== "string" && token.type !== "ident" && token.type !== "quoted_ident") {
14134
+ this.errorAt(token, "expected extension version");
14135
+ }
14136
+ version = token.value;
14137
+ continue;
14138
+ }
14139
+ if (this.eatKw("cascade")) {
14140
+ cascade = true;
14141
+ continue;
14142
+ }
14143
+ throw unsupported("CREATE EXTENSION option");
14144
+ }
14145
+ return { type: "create_extension", name, ifNotExists, schema, version, cascade };
13099
14146
  }
13100
14147
  if (this.atKw("database")) throw unsupported("CREATE DATABASE");
13101
14148
  if (this.atKw("role") || this.atKw("user") || this.atKw("group")) throw unsupported("roles");
@@ -13572,7 +14619,11 @@ var Parser = class {
13572
14619
  let opclass = null;
13573
14620
  const t = this.peek();
13574
14621
  if (t.type === "ident" && !RESERVED.has(t.value) && !["asc", "desc", "nulls", "with", "where", "include"].includes(t.value)) {
13575
- opclass = this.ident();
14622
+ opclass = [this.ident()];
14623
+ while (this.atPunct(".")) {
14624
+ this.pos++;
14625
+ opclass.push(this.ident(true));
14626
+ }
13576
14627
  }
13577
14628
  let dir = null;
13578
14629
  if (this.eatKw("asc")) dir = "asc";
@@ -15808,7 +16859,13 @@ function runStmt(env, stmt, vars, emit, tableNames) {
15808
16859
  return;
15809
16860
  }
15810
16861
  case "for": {
15811
- const forEnv = { ctx: env.ctx, params: env.params, ctes: env.ctes, outer: vars.scope() };
16862
+ const forEnv = {
16863
+ ctx: env.ctx,
16864
+ params: env.params,
16865
+ ctes: env.ctes,
16866
+ outer: vars.scope(),
16867
+ allowUnpopulatedMatviews: env.allowUnpopulatedMatviews
16868
+ };
15812
16869
  const rel2 = executeSelectStmt(forEnv, stmt.query);
15813
16870
  for (const row of rel2.rows) {
15814
16871
  for (let i = 0; i < stmt.targets.length; i++) {
@@ -15850,7 +16907,13 @@ function initVars(env, fn, bound, program) {
15850
16907
  if (fn.returnsTable) {
15851
16908
  for (const c of fn.returnsTable) vars.declare(c.name, c.type, null);
15852
16909
  }
15853
- const seed = () => ({ ctx: env.ctx, params: bound, ctes: /* @__PURE__ */ new Map(), outer: vars.scope() });
16910
+ const seed = () => ({
16911
+ ctx: env.ctx,
16912
+ params: bound,
16913
+ ctes: /* @__PURE__ */ new Map(),
16914
+ outer: vars.scope(),
16915
+ allowUnpopulatedMatviews: env.allowUnpopulatedMatviews
16916
+ });
15854
16917
  for (const d of program.decls) {
15855
16918
  const id = resolveTypeName(env.ctx.state, d.typeName).column.id;
15856
16919
  let val = null;
@@ -15863,7 +16926,13 @@ function initVars(env, fn, bound, program) {
15863
16926
  return vars;
15864
16927
  }
15865
16928
  function plpgsqlEnv(env, bound, vars) {
15866
- return { ctx: env.ctx, params: bound, ctes: /* @__PURE__ */ new Map(), outer: vars.scope() };
16929
+ return {
16930
+ ctx: env.ctx,
16931
+ params: bound,
16932
+ ctes: /* @__PURE__ */ new Map(),
16933
+ outer: vars.scope(),
16934
+ allowUnpopulatedMatviews: env.allowUnpopulatedMatviews
16935
+ };
15867
16936
  }
15868
16937
  function callPlpgsqlScalar(env, fn, args) {
15869
16938
  const retT = fn.returns ?? "text";
@@ -16462,7 +17531,13 @@ function functionEnv(env, fn, args) {
16462
17531
  bound.push(castTo(env.ctx, evalScalar(env, null, dflt), fn.argTypes[i], {}));
16463
17532
  }
16464
17533
  }
16465
- const fnEnv = { ctx: env.ctx, params: bound, ctes: /* @__PURE__ */ new Map(), outer: null };
17534
+ const fnEnv = {
17535
+ ctx: env.ctx,
17536
+ params: bound,
17537
+ ctes: /* @__PURE__ */ new Map(),
17538
+ outer: null,
17539
+ allowUnpopulatedMatviews: env.allowUnpopulatedMatviews
17540
+ };
16466
17541
  const namedCols = fn.argNames.map((n, i) => ({ n, i })).filter((x) => x.n !== null);
16467
17542
  if (namedCols.length > 0) {
16468
17543
  const cols = namedCols.map(({ n, i }) => ({ name: n, type: fn.argTypes[i] ?? "text", table: null }));
@@ -16488,6 +17563,10 @@ function callSqlFunctionScalar(env, fn, args) {
16488
17563
  if (fn.language === "plpgsql") {
16489
17564
  return callPlpgsqlScalar(env, fn, args);
16490
17565
  }
17566
+ if (fn.language === "internal") {
17567
+ if (fn.rawBody === "pg_trgm") return evalPgTrgmFunction(env.ctx, fn, args);
17568
+ return evalPgcryptoFunction(env.ctx, fn, args);
17569
+ }
16491
17570
  if (fn.language === "js") {
16492
17571
  if (!fn.jsImpl) {
16493
17572
  throw pgError("undefined_function", `JavaScript function ${fn.name} is not registered`, "42883");
@@ -16564,7 +17643,13 @@ function applyWith(env, w) {
16564
17643
  if (!w) return env;
16565
17644
  const ctes = new Map(env.ctes);
16566
17645
  for (const cte of w.ctes) {
16567
- const scopedEnv = { ctx: env.ctx, params: env.params, ctes, outer: env.outer };
17646
+ const scopedEnv = {
17647
+ ctx: env.ctx,
17648
+ params: env.params,
17649
+ ctes,
17650
+ outer: env.outer,
17651
+ allowUnpopulatedMatviews: env.allowUnpopulatedMatviews
17652
+ };
16568
17653
  let rel2;
16569
17654
  if (w.recursive && cte.query.type === "select" && cte.query.body.type === "setop" && cte.query.body.op === "union" && referencesRelation(cte.query.body.right, cte.name)) {
16570
17655
  rel2 = executeRecursiveCte(scopedEnv, cte, cte.query);
@@ -16579,7 +17664,13 @@ function applyWith(env, w) {
16579
17664
  }
16580
17665
  ctes.set(cte.name, applyCteColumnNames(rel2, cte));
16581
17666
  }
16582
- return { ctx: env.ctx, params: env.params, ctes, outer: env.outer };
17667
+ return {
17668
+ ctx: env.ctx,
17669
+ params: env.params,
17670
+ ctes,
17671
+ outer: env.outer,
17672
+ allowUnpopulatedMatviews: env.allowUnpopulatedMatviews
17673
+ };
16583
17674
  }
16584
17675
  var MAX_RECURSION_ITERATIONS = 2e5;
16585
17676
  var MAX_RECURSION_ROWS = 5e6;
@@ -16611,7 +17702,13 @@ function executeRecursiveCte(env, cte, query) {
16611
17702
  }
16612
17703
  const iterCtes = new Map(env.ctes);
16613
17704
  iterCtes.set(cte.name, { columns, rows: working });
16614
- const iterEnv = { ctx: env.ctx, params: env.params, ctes: iterCtes, outer: env.outer };
17705
+ const iterEnv = {
17706
+ ctx: env.ctx,
17707
+ params: env.params,
17708
+ ctes: iterCtes,
17709
+ outer: env.outer,
17710
+ allowUnpopulatedMatviews: env.allowUnpopulatedMatviews
17711
+ };
16615
17712
  const step = executeBody(iterEnv, body.right);
16616
17713
  if (step.columns.length !== columns.length) {
16617
17714
  throw pgError("syntax", "each UNION query must have the same number of columns", "42601");
@@ -16683,7 +17780,7 @@ function materializeItem(env, item, scope) {
16683
17780
  if (view) {
16684
17781
  let rel2;
16685
17782
  if (view.materialized) {
16686
- if (view.matRows === null || view.matColumns === null) {
17783
+ if (view.matColumns === null || view.matRows === null && !env.allowUnpopulatedMatviews) {
16687
17784
  throw pgError(
16688
17785
  "object_not_in_prerequisite_state",
16689
17786
  `materialized view "${view.name}" has not been populated`,
@@ -16692,10 +17789,16 @@ function materializeItem(env, item, scope) {
16692
17789
  }
16693
17790
  rel2 = {
16694
17791
  columns: view.matColumns.map((c) => ({ name: c.name, type: c.type, table: label })),
16695
- rows: view.matRows
17792
+ rows: view.matRows ?? []
16696
17793
  };
16697
17794
  } else {
16698
- const viewEnv = { ctx: env.ctx, params: null, ctes: /* @__PURE__ */ new Map(), outer: null };
17795
+ const viewEnv = {
17796
+ ctx: env.ctx,
17797
+ params: null,
17798
+ ctes: /* @__PURE__ */ new Map(),
17799
+ outer: null,
17800
+ allowUnpopulatedMatviews: env.allowUnpopulatedMatviews
17801
+ };
16699
17802
  rel2 = executeSelectStmt(viewEnv, view.query);
16700
17803
  rel2 = {
16701
17804
  columns: rel2.columns.map((c, i) => ({
@@ -18830,7 +19933,13 @@ function applyUpdateSets(env, table, sets, scope, row) {
18830
19933
  });
18831
19934
  if (typeof set.value === "object" && "kind" in set.value && set.value.kind === "row_subquery") {
18832
19935
  const rel2 = executeSelectStmt(
18833
- { ctx: env.ctx, params: env.params, ctes: env.ctes, outer: scope },
19936
+ {
19937
+ ctx: env.ctx,
19938
+ params: env.params,
19939
+ ctes: env.ctes,
19940
+ outer: scope,
19941
+ allowUnpopulatedMatviews: env.allowUnpopulatedMatviews
19942
+ },
18834
19943
  set.value.query
18835
19944
  );
18836
19945
  if (rel2.rows.length > 1) {
@@ -20613,6 +21722,9 @@ function executeTrigger(env, table, trigger, _event, oldRow, newRow) {
20613
21722
  setTriggerExecutor(executeTrigger);
20614
21723
 
20615
21724
  // src/executor/ddl.ts
21725
+ function matviewQueryEnv(env, allowUnpopulatedMatviews) {
21726
+ return { ctx: env.ctx, params: null, ctes: /* @__PURE__ */ new Map(), outer: null, allowUnpopulatedMatviews };
21727
+ }
20616
21728
  function targetSchema(env, parts) {
20617
21729
  const state = env.ctx.state;
20618
21730
  if (parts.length >= 2) {
@@ -21016,6 +22128,7 @@ function executeCreateIndex(env, stmt) {
21016
22128
  }
21017
22129
  }
21018
22130
  }
22131
+ assertGinTrgmIndex(state, table, stmt);
21019
22132
  schema.indexes.set(name, {
21020
22133
  name,
21021
22134
  schema: schema.name,
@@ -21060,7 +22173,7 @@ function executeCreateView(env, stmt) {
21060
22173
  let matRows = null;
21061
22174
  let matColumns = null;
21062
22175
  if (stmt.materialized) {
21063
- const rel2 = executeSelectStmt({ ctx: env.ctx, params: null, ctes: /* @__PURE__ */ new Map(), outer: null }, stmt.query);
22176
+ const rel2 = executeSelectStmt(matviewQueryEnv(env, !stmt.withData), stmt.query);
21064
22177
  matColumns = rel2.columns.map((c, i) => ({
21065
22178
  name: stmt.columns?.[i] ?? c.name,
21066
22179
  type: c.type === UNKNOWN ? "text" : c.type
@@ -21086,7 +22199,7 @@ function executeRefreshMatView(env, stmt) {
21086
22199
  throw pgError("undefined_table", `materialized view "${stmt.name.join(".")}" does not exist`, "42P01");
21087
22200
  }
21088
22201
  const view = env.ctx.state.ensureWritableView(found);
21089
- const rel2 = executeSelectStmt({ ctx: env.ctx, params: null, ctes: /* @__PURE__ */ new Map(), outer: null }, view.query);
22202
+ const rel2 = executeSelectStmt(matviewQueryEnv(env, !stmt.withData), view.query);
21090
22203
  view.matColumns = rel2.columns.map((c, i) => ({
21091
22204
  name: view.columns?.[i] ?? c.name,
21092
22205
  type: c.type === UNKNOWN ? "text" : c.type
@@ -21094,6 +22207,32 @@ function executeRefreshMatView(env, stmt) {
21094
22207
  view.matRows = stmt.withData ? rel2.rows : null;
21095
22208
  return commandResult("REFRESH MATERIALIZED VIEW", 0);
21096
22209
  }
22210
+ function executeCreateExtension(env, stmt) {
22211
+ const state = env.ctx.state;
22212
+ const schemaName = stmt.schema ?? state.currentSchema();
22213
+ const install = () => {
22214
+ if (stmt.name === "pgcrypto") {
22215
+ if (pgcryptoInstalled(state)) return "exists";
22216
+ installPgcrypto(state, state.getSchema(schemaName).name);
22217
+ return "installed";
22218
+ }
22219
+ if (stmt.name === "pg_trgm") {
22220
+ if (pgTrgmInstalled(state)) return "exists";
22221
+ installPgTrgm(state, state.getSchema(schemaName).name);
22222
+ return "installed";
22223
+ }
22224
+ return "unsupported";
22225
+ };
22226
+ const outcome = install();
22227
+ if (outcome === "unsupported") {
22228
+ throw pgError("feature_not_supported", `extension "${stmt.name}" is not available`, "0A000");
22229
+ }
22230
+ if (outcome === "exists") {
22231
+ if (stmt.ifNotExists) return commandResult("CREATE EXTENSION", 0);
22232
+ throw pgError("duplicate_object", `extension "${stmt.name}" already exists`, "42710");
22233
+ }
22234
+ return commandResult("CREATE EXTENSION", 0);
22235
+ }
21097
22236
  function executeCreateSchema(env, stmt) {
21098
22237
  const state = env.ctx.state;
21099
22238
  if (state.schemas.has(stmt.name)) {
@@ -21882,8 +23021,19 @@ function executeDrop(env, stmt) {
21882
23021
  table.triggers.splice(idx, 1);
21883
23022
  break;
21884
23023
  }
21885
- case "extension":
21886
- break;
23024
+ case "extension": {
23025
+ const ext = parts[parts.length - 1];
23026
+ if (ext === "pgcrypto" && pgcryptoInstalled(state)) {
23027
+ uninstallPgcrypto(state);
23028
+ break;
23029
+ }
23030
+ if (ext === "pg_trgm" && pgTrgmInstalled(state)) {
23031
+ uninstallPgTrgm(state);
23032
+ break;
23033
+ }
23034
+ if (stmt.ifExists) break;
23035
+ throw pgError("undefined_object", `extension "${ext}" does not exist`, "42704");
23036
+ }
21887
23037
  }
21888
23038
  }
21889
23039
  const label = stmt.kind === "materialized_view" ? "MATERIALIZED VIEW" : stmt.kind.toUpperCase();
@@ -21965,6 +23115,8 @@ function executeStatement(env, stmt) {
21965
23115
  return executeAlterSequence(env, stmt);
21966
23116
  case "create_schema":
21967
23117
  return executeCreateSchema(env, stmt);
23118
+ case "create_extension":
23119
+ return executeCreateExtension(env, stmt);
21968
23120
  case "create_enum":
21969
23121
  return executeCreateEnum(env, stmt);
21970
23122
  case "alter_enum":
@@ -22120,6 +23272,9 @@ var ADOPT = /* @__PURE__ */ Symbol("postgres-mem.adopt");
22120
23272
  function isAdopted(value) {
22121
23273
  return ADOPT in value;
22122
23274
  }
23275
+ function project(point) {
23276
+ return { id: point.id, branch: point.branch, parent: point.parent, at: point.at };
23277
+ }
22123
23278
  var Database = class {
22124
23279
  /** @internal Engine catalog, tables, session settings. */
22125
23280
  state;
@@ -22140,6 +23295,10 @@ var Database = class {
22140
23295
  closed = false;
22141
23296
  transactionSequence = 0;
22142
23297
  apiTransactionDepth = 0;
23298
+ /** @internal Shared checkpoint DAG. Omitted from published declarations. */
23299
+ timeline;
23300
+ historyBranch = "main";
23301
+ originId = "";
22143
23302
  constructor(options = {}) {
22144
23303
  if (isAdopted(options)) {
22145
23304
  this.seed = options.seed;
@@ -22152,16 +23311,23 @@ var Database = class {
22152
23311
  this.state.prng = this.prng;
22153
23312
  this.state.clock = () => this.now();
22154
23313
  this.transactions = txManagerFor(this.state);
22155
- return;
23314
+ } else {
23315
+ this.seed = options.seed ?? DEFAULT_DATABASE_SEED;
23316
+ this.randomMode = options.random ?? "deterministic";
23317
+ this.systemClock = options.now === "system";
23318
+ this.int8Mode = options.int8 ?? "bigint";
23319
+ this.prng = this.randomMode === "os" ? new OsEntropy() : new Prng(this.seed);
23320
+ this.now = resolveClock(options.now);
23321
+ this.state = new DatabaseState(this.prng, () => this.now());
23322
+ this.transactions = txManagerFor(this.state);
22156
23323
  }
22157
- this.seed = options.seed ?? DEFAULT_DATABASE_SEED;
22158
- this.randomMode = options.random ?? "deterministic";
22159
- this.systemClock = options.now === "system";
22160
- this.int8Mode = options.int8 ?? "bigint";
22161
- this.prng = this.randomMode === "os" ? new OsEntropy() : new Prng(this.seed);
22162
- this.now = resolveClock(options.now);
22163
- this.state = new DatabaseState(this.prng, () => this.now());
22164
- this.transactions = txManagerFor(this.state);
23324
+ this.timeline = new Timeline({
23325
+ now: () => this.now().getTime(),
23326
+ ...options.maxCheckpoints !== void 0 ? { maxCheckpoints: options.maxCheckpoints } : {}
23327
+ });
23328
+ const origin = this.timeline.commit(this.captureLive());
23329
+ this.originId = origin.id;
23330
+ this.timeline.retain(origin.id);
22165
23331
  }
22166
23332
  /**
22167
23333
  * Execute SQL for its side effects. Multiple semicolon-separated statements
@@ -22216,7 +23382,15 @@ var Database = class {
22216
23382
  /** Execute a single-statement query and return all rows keyed by column name. */
22217
23383
  query(sql, params = [], options = {}) {
22218
23384
  this.assertOpen();
22219
- if (options.at) return options.at.open().query(sql, params);
23385
+ const at = options.at;
23386
+ if (typeof at === "string") {
23387
+ try {
23388
+ return this.timeline.get(at).value.open().query(sql, params);
23389
+ } catch (error) {
23390
+ this.historyError(error);
23391
+ }
23392
+ }
23393
+ if (at) return at.open().query(sql, params);
22220
23394
  return this.prepareSingle(sql).all(...params);
22221
23395
  }
22222
23396
  /** Compile a single SQL statement into a reusable {@link Statement}. */
@@ -22264,23 +23438,77 @@ var Database = class {
22264
23438
  * {@link Snapshot.open} for a copy-on-write fork.
22265
23439
  */
22266
23440
  snapshot() {
23441
+ const point = this.record(this.historyBranch);
23442
+ return this.timeline.get(point.id).value;
23443
+ }
23444
+ /** Alias for {@link snapshot}, naming the value as a timeline checkpoint. */
23445
+ checkpoint() {
23446
+ return this.snapshot();
23447
+ }
23448
+ /**
23449
+ * Commit the live state onto `branch` (default: the branch this database follows).
23450
+ * Does not switch the live database. Illegal inside a transaction.
23451
+ */
23452
+ record(branch = this.historyBranch) {
22267
23453
  this.assertOpen();
22268
23454
  if (this.transactions.inTransaction) {
22269
23455
  throw pgError("transaction_state", "cannot snapshot during a transaction", "25P01");
22270
23456
  }
22271
- return captureSnapshot(
22272
- this.state,
22273
- this.prng,
22274
- this.now,
22275
- this.seed,
22276
- this.randomMode,
22277
- this.systemClock,
22278
- this.int8Mode
22279
- );
23457
+ try {
23458
+ return project(this.timeline.commit(this.captureLive(), { branch }));
23459
+ } catch (error) {
23460
+ this.historyError(error);
23461
+ }
22280
23462
  }
22281
- /** Alias for {@link snapshot}, naming the value as a timeline checkpoint. */
22282
- checkpoint() {
22283
- return this.snapshot();
23463
+ /** Point `name` at a checkpoint without copying rows or switching the live database. */
23464
+ fork(name, at) {
23465
+ this.assertOpen();
23466
+ try {
23467
+ const point = this.timeline.fork(name, at !== void 0 ? { from: at } : {});
23468
+ if (!point) throw pgError("misuse", "no checkpoint to fork from", "XX000");
23469
+ return project(point);
23470
+ } catch (error) {
23471
+ if (error instanceof PostgresError) throw error;
23472
+ this.historyError(error);
23473
+ }
23474
+ }
23475
+ /** Move `branch` to `id` and install that checkpoint as the live database. */
23476
+ checkout(id, branch = this.historyBranch) {
23477
+ this.assertOpen();
23478
+ if (this.transactions.inTransaction) {
23479
+ throw pgError("transaction_state", "cannot checkout during a transaction", "25P01");
23480
+ }
23481
+ try {
23482
+ const point = this.timeline.checkout(branch, id);
23483
+ this.historyBranch = branch;
23484
+ this.install(point.value);
23485
+ return project(point);
23486
+ } catch (error) {
23487
+ this.historyError(error);
23488
+ }
23489
+ }
23490
+ /** Return the live database to the origin checkpoint on `main`. */
23491
+ reset() {
23492
+ return this.checkout(this.originId, "main");
23493
+ }
23494
+ /** Checkpoint ids and branch heads. Values stay inside the timeline. */
23495
+ get history() {
23496
+ const timeline = this.timeline;
23497
+ return {
23498
+ get size() {
23499
+ return timeline.size;
23500
+ },
23501
+ head(branch) {
23502
+ const point = timeline.head(branch);
23503
+ return point ? project(point) : void 0;
23504
+ },
23505
+ branches() {
23506
+ return timeline.branches();
23507
+ },
23508
+ checkpoints() {
23509
+ return timeline.checkpoints().map(project);
23510
+ }
23511
+ };
22284
23512
  }
22285
23513
  /** Open a copy-on-write branch from `at`, or from the current state when omitted. */
22286
23514
  branch(at = this.snapshot()) {
@@ -22325,6 +23553,26 @@ var Database = class {
22325
23553
  assertOpen() {
22326
23554
  if (this.closed) throw pgError("misuse", "Database is closed", "XX000");
22327
23555
  }
23556
+ historyError(error) {
23557
+ const message = error instanceof Error ? error.message : String(error);
23558
+ throw pgError("misuse", message, "XX000");
23559
+ }
23560
+ captureLive() {
23561
+ return captureSnapshot(
23562
+ this.state,
23563
+ this.prng,
23564
+ this.now,
23565
+ this.seed,
23566
+ this.randomMode,
23567
+ this.systemClock,
23568
+ this.int8Mode
23569
+ );
23570
+ }
23571
+ install(snapshot) {
23572
+ this.state.restoreFrom(snapshot.state.cloneShallow());
23573
+ this.prng.setState(snapshot.prngState);
23574
+ if (!this.systemClock) this.now = fixedClock(new Date(snapshot.nowMs));
23575
+ }
22328
23576
  prepareSingle(sql) {
22329
23577
  const statements = parse(sql);
22330
23578
  if (statements.length === 0) {