@crvouga/mockingbird-service-postgres 3.3.0 → 3.4.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/dist/wire/cli.js CHANGED
@@ -200,17 +200,27 @@ var createClock = (source = Date.now) => {
200
200
  offsetMs = 0;
201
201
  frozenAt = void 0;
202
202
  },
203
- state: () => ({ now: now(), frozen: frozenAt !== void 0, offsetMs })
203
+ // A frozen clock does not follow its source, so it has no offset to report.
204
+ state: () => ({
205
+ now: now(),
206
+ frozen: frozenAt !== void 0,
207
+ offsetMs: frozenAt !== void 0 ? 0 : offsetMs
208
+ })
204
209
  };
205
210
  };
211
+ var restoreClock = (clock, state) => {
212
+ clock.freeze();
213
+ clock.set(state.now);
214
+ if (!state.frozen)
215
+ clock.unfreeze();
216
+ };
206
217
 
207
- // ../core/dist/control.js
208
- var ADMIN_PREFIX = "/__admin";
209
- var resolveAdminPrefix = (prefix = ADMIN_PREFIX) => {
210
- if (!/^\/[A-Za-z0-9_-]+(?:\/[A-Za-z0-9_-]+)*$/.test(prefix)) {
211
- throw new Error("adminPrefix must be an absolute non-root path of literal segments, without a trailing slash");
218
+ // ../core/dist/controls.js
219
+ var ControlError = class extends RangeError {
220
+ constructor(message2) {
221
+ super(message2);
222
+ this.name = "ControlError";
212
223
  }
213
- return prefix;
214
224
  };
215
225
  var UNITS = {
216
226
  ms: 1,
@@ -220,15 +230,439 @@ var UNITS = {
220
230
  d: 864e5
221
231
  };
222
232
  var parseDuration = (value) => {
223
- if (typeof value === "number" && Number.isFinite(value))
224
- return value;
233
+ if (typeof value === "number")
234
+ return Number.isFinite(value) ? value : void 0;
225
235
  if (typeof value !== "string")
226
236
  return void 0;
227
- const match = /^(-?\d+(?:\.\d+)?)\s*(ms|s|m|h|d)$/.exec(value.trim());
237
+ const match = /^(-?\d+(?:\.\d+)?)\s*(ms|s|m|h|d)?$/.exec(value.trim());
228
238
  if (!match)
229
239
  return void 0;
230
- return Number(match[1]) * UNITS[match[2]];
240
+ return Number(match[1]) * UNITS[match[2] ?? "ms"];
241
+ };
242
+ var parseInstant = (value) => {
243
+ if (typeof value === "number")
244
+ return Number.isFinite(value) ? value : void 0;
245
+ if (typeof value !== "string")
246
+ return void 0;
247
+ const text = value.trim();
248
+ if (/^-?\d+$/.test(text))
249
+ return Number(text);
250
+ const parsed = Date.parse(text);
251
+ return Number.isNaN(parsed) ? void 0 : parsed;
252
+ };
253
+ var durationMs = (value, label, negative = false) => {
254
+ const parsed = parseDuration(value);
255
+ if (parsed === void 0)
256
+ throw new ControlError(`${label}: expected milliseconds or a duration like "250ms" or "15m"`);
257
+ if (!negative && parsed < 0)
258
+ throw new ControlError(`${label}: must not be negative`);
259
+ return parsed;
260
+ };
261
+ var instantMs = (value, label) => {
262
+ const parsed = parseInstant(value);
263
+ if (parsed === void 0)
264
+ throw new ControlError(`${label}: expected epoch ms or ISO-8601`);
265
+ return parsed;
266
+ };
267
+ var normalizeSeed = (seed, label = "seed") => {
268
+ if (typeof seed === "number" && Number.isFinite(seed))
269
+ return seed;
270
+ if (typeof seed === "string" && seed !== "")
271
+ return /^\d+$/.test(seed) ? Number(seed) : seed;
272
+ throw new ControlError(`${label}: expected a number or a non-empty string`);
273
+ };
274
+ var SNAPSHOT_FORMAT = "mockingbird.snapshot/v1";
275
+ var NAMESPACE_KEYS = /* @__PURE__ */ new Set(["seed", "clock", "virtualTime", "latency", "faults", "snapshot"]);
276
+ var MOCK_KEYS = /* @__PURE__ */ new Set([...NAMESPACE_KEYS, "credentials", "namespaces"]);
277
+ var REPORTED_KEYS = /* @__PURE__ */ new Set(["namespace", "snapshots"]);
278
+ var REPORTED_CLOCK_KEYS = /* @__PURE__ */ new Set(["iso", "offsetMs"]);
279
+ var KEY_PATTERN = /^[A-Za-z0-9_.-]{1,64}$/;
280
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
281
+ var unknownKeys = (value, known, label, reported) => {
282
+ for (const key of Object.keys(value)) {
283
+ if (!known.has(key) && !reported?.has(key))
284
+ throw new ControlError(`${label}: unknown control ${JSON.stringify(key)}; expected ${[...known].join(", ")}`);
285
+ }
286
+ };
287
+ var latencyRule = (value, label) => {
288
+ if (!isRecord(value))
289
+ return { delayMs: durationMs(value, label), jitterMs: 0 };
290
+ unknownKeys(value, /* @__PURE__ */ new Set(["delay", "jitter", "delayMs", "jitterMs", "operations"]), label);
291
+ return {
292
+ delayMs: durationMs(value.delay ?? value.delayMs ?? 0, `${label}.delay`),
293
+ jitterMs: durationMs(value.jitter ?? value.jitterMs ?? 0, `${label}.jitter`)
294
+ };
295
+ };
296
+ var normalizeLatency = (value, label = "latency") => {
297
+ const base = latencyRule(value, label);
298
+ const operations = {};
299
+ if (isRecord(value) && value.operations !== void 0) {
300
+ if (!isRecord(value.operations))
301
+ throw new ControlError(`${label}.operations: expected an object keyed by operationId`);
302
+ for (const [operationId, rule] of Object.entries(value.operations)) {
303
+ if (isRecord(rule) && rule.operations !== void 0)
304
+ throw new ControlError(`${label}.operations.${operationId}: cannot nest operations`);
305
+ operations[operationId] = latencyRule(rule, `${label}.operations.${operationId}`);
306
+ }
307
+ }
308
+ return { ...base, operations };
309
+ };
310
+ var normalizeClock = (value, label = "clock") => {
311
+ if (!isRecord(value))
312
+ throw new ControlError(`${label}: expected an object`);
313
+ unknownKeys(value, /* @__PURE__ */ new Set(["now", "set", "frozen", "freeze", "autoAdvance", "autoAdvanceMs"]), label, REPORTED_CLOCK_KEYS);
314
+ const plan = {};
315
+ const now = value.now ?? value.set;
316
+ if (now !== void 0)
317
+ plan.now = instantMs(now, `${label}.now`);
318
+ const frozen = value.frozen ?? value.freeze;
319
+ if (frozen !== void 0) {
320
+ if (typeof frozen !== "boolean")
321
+ throw new ControlError(`${label}.frozen: expected a boolean`);
322
+ plan.frozen = frozen;
323
+ }
324
+ const auto = value.autoAdvance ?? value.autoAdvanceMs;
325
+ if (auto !== void 0)
326
+ plan.autoAdvanceMs = durationMs(auto, `${label}.autoAdvance`);
327
+ return plan;
328
+ };
329
+ var assertSnapshotDocument = (value, label = "snapshot") => {
330
+ if (!isRecord(value))
331
+ throw new ControlError(`${label}: expected a snapshot document`);
332
+ if (value.format !== SNAPSHOT_FORMAT)
333
+ throw new ControlError(`${label}.format: expected ${JSON.stringify(SNAPSHOT_FORMAT)}`);
334
+ if (!Array.isArray(value.records))
335
+ throw new ControlError(`${label}.records: expected a list`);
336
+ value.records.forEach((row, index) => {
337
+ if (!isRecord(row) || typeof row.collection !== "string" || typeof row.id !== "string" || row.value === void 0 && typeof row.raw !== "string" || row.seq !== void 0 && !Number.isSafeInteger(row.seq))
338
+ throw new ControlError(`${label}.records[${index}]: expected {collection, id, value, seq?}`);
339
+ });
340
+ if (value.sequences !== void 0) {
341
+ if (!Array.isArray(value.sequences))
342
+ throw new ControlError(`${label}.sequences: expected a list`);
343
+ value.sequences.forEach((row, index) => {
344
+ if (!isRecord(row) || typeof row.name !== "string" || typeof row.kind !== "string" || !Number.isSafeInteger(row.value))
345
+ throw new ControlError(`${label}.sequences[${index}]: expected {name, kind, value}`);
346
+ });
347
+ }
348
+ if (value.clock !== void 0) {
349
+ if (!isRecord(value.clock) || typeof value.clock.now !== "number" || typeof value.clock.frozen !== "boolean")
350
+ throw new ControlError(`${label}.clock: expected {now, frozen}`);
351
+ }
352
+ return value;
353
+ };
354
+ var normalizeControls = (value, label = "controls") => {
355
+ if (!isRecord(value))
356
+ throw new ControlError(`${label}: expected an object`);
357
+ unknownKeys(value, NAMESPACE_KEYS, label, REPORTED_KEYS);
358
+ const plan = {};
359
+ if (value.seed !== void 0)
360
+ plan.seed = normalizeSeed(value.seed, `${label}.seed`);
361
+ if (value.clock !== void 0)
362
+ plan.clock = normalizeClock(value.clock, `${label}.clock`);
363
+ if (value.virtualTime !== void 0) {
364
+ if (typeof value.virtualTime !== "boolean")
365
+ throw new ControlError(`${label}.virtualTime: expected a boolean`);
366
+ plan.virtualTime = value.virtualTime;
367
+ }
368
+ if (value.latency !== void 0)
369
+ plan.latency = normalizeLatency(value.latency, `${label}.latency`);
370
+ if (value.faults !== void 0) {
371
+ if (!Array.isArray(value.faults) || !value.faults.every(isRecord))
372
+ throw new ControlError(`${label}.faults: expected a list of fault rules`);
373
+ plan.faults = value.faults;
374
+ }
375
+ if (value.snapshot !== void 0)
376
+ plan.snapshot = assertSnapshotDocument(value.snapshot, `${label}.snapshot`);
377
+ return plan;
378
+ };
379
+ var normalizeBootControls = (value, label = "controls") => {
380
+ if (value === void 0)
381
+ return { shared: {}, namespaces: {}, credentials: {} };
382
+ if (!isRecord(value))
383
+ throw new ControlError(`${label}: expected an object`);
384
+ unknownKeys(value, MOCK_KEYS, label);
385
+ const { credentials, namespaces, ...shared } = value;
386
+ const plan = {
387
+ shared: normalizeControls(shared, label),
388
+ namespaces: {},
389
+ credentials: {}
390
+ };
391
+ if (namespaces !== void 0) {
392
+ if (!isRecord(namespaces))
393
+ throw new ControlError(`${label}.namespaces: expected an object`);
394
+ for (const [name2, each] of Object.entries(namespaces)) {
395
+ if (!KEY_PATTERN.test(name2))
396
+ throw new ControlError(`${label}.namespaces: bad namespace ${JSON.stringify(name2)}`);
397
+ plan.namespaces[name2] = normalizeControls(each, `${label}.namespaces.${name2}`);
398
+ }
399
+ }
400
+ if (credentials !== void 0) {
401
+ if (!isRecord(credentials))
402
+ throw new ControlError(`${label}.credentials: expected an object`);
403
+ for (const [credential, namespace] of Object.entries(credentials)) {
404
+ if (typeof namespace !== "string" || !KEY_PATTERN.test(namespace))
405
+ throw new ControlError(`${label}.credentials: bad namespace for a credential`);
406
+ plan.credentials[credential] = namespace;
407
+ }
408
+ }
409
+ return plan;
410
+ };
411
+ var CONTROL_HEADERS = {
412
+ namespace: "x-mockingbird-namespace",
413
+ adminKey: "x-mockingbird-admin-key",
414
+ branch: "x-mockingbird-branch",
415
+ at: "x-mockingbird-at",
416
+ reset: "x-mockingbird-reset",
417
+ restore: "x-mockingbird-restore",
418
+ seed: "x-mockingbird-seed",
419
+ time: "x-mockingbird-time",
420
+ advance: "x-mockingbird-advance",
421
+ virtualTime: "x-mockingbird-virtual-time",
422
+ fault: "x-mockingbird-fault",
423
+ delay: "x-mockingbird-delay",
424
+ timeout: "x-mockingbird-timeout",
425
+ snapshot: "x-mockingbird-snapshot"
426
+ };
427
+ var CONTROL_HEADER_REFERENCE = [
428
+ {
429
+ header: CONTROL_HEADERS.namespace,
430
+ value: "<key>",
431
+ scope: "select",
432
+ guarded: false,
433
+ summary: "Isolation key. Each key has its own records, clock, random streams, faults, latency, journal and snapshots."
434
+ },
435
+ {
436
+ header: CONTROL_HEADERS.branch,
437
+ value: "<name>",
438
+ scope: "select",
439
+ guarded: false,
440
+ summary: "Read and write a named copy-on-write branch of the namespace's history."
441
+ },
442
+ {
443
+ header: CONTROL_HEADERS.at,
444
+ value: "<checkpoint>",
445
+ scope: "select",
446
+ guarded: false,
447
+ summary: "Read the namespace as it was at a checkpoint. With a branch, start the branch there."
448
+ },
449
+ {
450
+ header: CONTROL_HEADERS.reset,
451
+ value: "true",
452
+ scope: "namespace",
453
+ guarded: true,
454
+ summary: "Reset the namespace to its boot state before the request is handled."
455
+ },
456
+ {
457
+ header: CONTROL_HEADERS.restore,
458
+ value: "<snapshot>",
459
+ scope: "namespace",
460
+ guarded: true,
461
+ summary: "Restore a snapshot before the request is handled."
462
+ },
463
+ {
464
+ header: CONTROL_HEADERS.seed,
465
+ value: "<seed>",
466
+ scope: "namespace",
467
+ guarded: true,
468
+ summary: "Restart the namespace's random streams from this seed."
469
+ },
470
+ {
471
+ header: CONTROL_HEADERS.time,
472
+ value: "<epoch ms | ISO-8601>",
473
+ scope: "namespace",
474
+ guarded: true,
475
+ summary: "Freeze the namespace clock at this instant."
476
+ },
477
+ {
478
+ header: CONTROL_HEADERS.advance,
479
+ value: "<duration>",
480
+ scope: "namespace",
481
+ guarded: true,
482
+ summary: "Move the namespace clock by this much, forward or (negative) back."
483
+ },
484
+ {
485
+ header: CONTROL_HEADERS.virtualTime,
486
+ value: "true | false",
487
+ scope: "namespace",
488
+ guarded: true,
489
+ summary: "Spend injected waits on the mock clock (true) or the wall clock (false)."
490
+ },
491
+ {
492
+ header: CONTROL_HEADERS.delay,
493
+ value: "<duration>",
494
+ scope: "request",
495
+ guarded: true,
496
+ summary: "Hold this response back this long, on top of the namespace's latency."
497
+ },
498
+ {
499
+ header: CONTROL_HEADERS.timeout,
500
+ value: "<duration>",
501
+ scope: "request",
502
+ guarded: true,
503
+ summary: "Never answer this request: hold it this long, then drop the connection."
504
+ },
505
+ {
506
+ header: CONTROL_HEADERS.fault,
507
+ value: '<status> | drop | <preset> | key=value; \u2026 | {"status": 503, \u2026}',
508
+ scope: "request",
509
+ guarded: true,
510
+ summary: "Fault this request only. Stored fault rules are not consulted when it answers."
511
+ },
512
+ {
513
+ header: CONTROL_HEADERS.snapshot,
514
+ value: "<name>",
515
+ scope: "namespace",
516
+ guarded: true,
517
+ summary: "Snapshot the namespace after the request is handled. Echoed on the response."
518
+ }
519
+ ];
520
+ var flag = (value, header) => {
521
+ const text = value.trim().toLowerCase();
522
+ if (text === "true" || text === "1")
523
+ return true;
524
+ if (text === "false" || text === "0")
525
+ return false;
526
+ throw new ControlError(`${header}: expected true or false`);
527
+ };
528
+ var name = (value, header) => {
529
+ const text = value.trim();
530
+ if (!KEY_PATTERN.test(text))
531
+ throw new ControlError(`${header}: must match ${KEY_PATTERN}`);
532
+ return text;
533
+ };
534
+ var FAULT_PAIRS = /* @__PURE__ */ new Set([
535
+ "status",
536
+ "delay",
537
+ "jitter",
538
+ "timeout",
539
+ "drop",
540
+ "truncate",
541
+ "effect",
542
+ "preset",
543
+ "body"
544
+ ]);
545
+ var parseFaultHeader = (value, header = CONTROL_HEADERS.fault) => {
546
+ const text = value.trim();
547
+ if (text === "")
548
+ throw new ControlError(`${header}: expected a fault`);
549
+ if (text.startsWith("{")) {
550
+ let parsed;
551
+ try {
552
+ parsed = JSON.parse(text);
553
+ } catch {
554
+ throw new ControlError(`${header}: not valid JSON`);
555
+ }
556
+ if (!isRecord(parsed))
557
+ throw new ControlError(`${header}: expected a JSON object`);
558
+ return parsed;
559
+ }
560
+ const rule = {};
561
+ const headers = {};
562
+ for (const [index, raw] of text.split(";").entries()) {
563
+ const part = raw.trim();
564
+ if (part === "")
565
+ continue;
566
+ const equals = part.indexOf("=");
567
+ if (equals < 0) {
568
+ if (index > 0 && part !== "drop")
569
+ throw new ControlError(`${header}: expected key=value, got ${JSON.stringify(part)}`);
570
+ if (/^\d{3}$/.test(part))
571
+ rule.status = Number(part);
572
+ else if (part === "drop")
573
+ rule.drop = true;
574
+ else
575
+ rule.preset = name(part, header);
576
+ continue;
577
+ }
578
+ const key = part.slice(0, equals).trim().toLowerCase();
579
+ const item = part.slice(equals + 1).trim();
580
+ if (key.startsWith("header."))
581
+ headers[key.slice("header.".length)] = item;
582
+ else if (!FAULT_PAIRS.has(key))
583
+ throw new ControlError(`${header}: unknown key ${JSON.stringify(key)}; expected ${[...FAULT_PAIRS].join(", ")} or header.<name>`);
584
+ else if (key === "status" || key === "truncate") {
585
+ if (!/^\d+$/.test(item))
586
+ throw new ControlError(`${header}: ${key} must be a number`);
587
+ rule[key] = Number(item);
588
+ } else if (key === "drop")
589
+ rule.drop = flag(item, `${header} drop`);
590
+ else
591
+ rule[key] = item;
592
+ }
593
+ if (Object.keys(headers).length > 0)
594
+ rule.headers = headers;
595
+ if (Object.keys(rule).length === 0)
596
+ throw new ControlError(`${header}: expected a fault`);
597
+ return rule;
231
598
  };
599
+ var GUARDED = CONTROL_HEADER_REFERENCE.filter((each) => each.guarded).map((each) => each.header);
600
+
601
+ // ../core/dist/control.js
602
+ var ADMIN_PREFIX = "/__admin";
603
+ var resolveAdminPrefix = (prefix = ADMIN_PREFIX) => {
604
+ if (!/^\/[A-Za-z0-9_-]+(?:\/[A-Za-z0-9_-]+)*$/.test(prefix)) {
605
+ throw new Error("adminPrefix must be an absolute non-root path of literal segments, without a trailing slash");
606
+ }
607
+ return prefix;
608
+ };
609
+ var ADMIN_KEY_HEADER = CONTROL_HEADERS.adminKey;
610
+ var NAMESPACE_HEADER = CONTROL_HEADERS.namespace;
611
+ var ADMIN_CONTROL_PAGES = [
612
+ {
613
+ page: "namespaces",
614
+ title: "Namespaces",
615
+ routes: ["/namespaces", "/credentials"],
616
+ headers: [CONTROL_HEADERS.namespace]
617
+ },
618
+ { page: "reset", title: "Reset", routes: ["/reset"], headers: [CONTROL_HEADERS.reset] },
619
+ {
620
+ page: "snapshot-and-restore",
621
+ title: "Snapshot and restore",
622
+ routes: ["/snapshots"],
623
+ headers: [CONTROL_HEADERS.restore, CONTROL_HEADERS.snapshot]
624
+ },
625
+ {
626
+ page: "clock",
627
+ title: "Clock",
628
+ routes: ["/clock"],
629
+ headers: [CONTROL_HEADERS.time, CONTROL_HEADERS.advance]
630
+ },
631
+ {
632
+ page: "checkpoints-and-branches",
633
+ title: "Checkpoints and branches",
634
+ routes: ["/timeline", "/checkpoints", "/branches"],
635
+ headers: [CONTROL_HEADERS.branch, CONTROL_HEADERS.at]
636
+ },
637
+ { page: "faults", title: "Faults", routes: ["/faults"], headers: [CONTROL_HEADERS.fault] },
638
+ {
639
+ page: "latency-and-timeouts",
640
+ title: "Latency and timeouts",
641
+ routes: ["/latency"],
642
+ headers: [CONTROL_HEADERS.delay, CONTROL_HEADERS.timeout, CONTROL_HEADERS.virtualTime]
643
+ },
644
+ {
645
+ page: "seed-and-determinism",
646
+ title: "Seed and determinism",
647
+ routes: [],
648
+ headers: [CONTROL_HEADERS.seed]
649
+ },
650
+ { page: "control-document", title: "The control document", routes: ["/controls"], headers: [] },
651
+ { page: "boot", title: "Boot", routes: [], headers: [] },
652
+ { page: "request-headers", title: "Request headers", routes: [], headers: [] },
653
+ {
654
+ page: "journal-and-state",
655
+ title: "Journal, metrics and state",
656
+ routes: ["/requests", "/metrics", "/state", "/ui"],
657
+ headers: []
658
+ },
659
+ {
660
+ page: "reference",
661
+ title: "Reference",
662
+ routes: ["/", "/health"],
663
+ headers: [CONTROL_HEADERS.adminKey]
664
+ }
665
+ ];
232
666
 
233
667
  // ../../adapters/node/dist/fleet.js
234
668
  import { randomUUID } from "node:crypto";
@@ -268,6 +702,8 @@ var serve = async (api, options2 = {}) => {
268
702
  req.socket.destroy();
269
703
  return;
270
704
  }
705
+ if (aborted.signal.aborted)
706
+ return;
271
707
  res.writeHead(500, { "content-type": "application/json" });
272
708
  res.end(JSON.stringify({
273
709
  error: {
@@ -299,6 +735,7 @@ var serve = async (api, options2 = {}) => {
299
735
  }
300
736
  res.end();
301
737
  } catch {
738
+ await new Promise((resolve2) => setImmediate(resolve2));
302
739
  res.destroy();
303
740
  } finally {
304
741
  reader.releaseLock();
@@ -382,11 +819,11 @@ var httpChild = async (target, entry, options2) => {
382
819
  adminKey: entry.adminKey,
383
820
  seed: entry.seed,
384
821
  onLog: options2.onLog,
822
+ ...entry.adminControls !== void 0 ? { adminControls: entry.adminControls } : {},
385
823
  ...entry.fixtures !== void 0 ? { fixtures: entry.fixtures } : {},
386
824
  ...entry.baseUrl !== void 0 ? { baseUrl: entry.baseUrl } : {}
387
825
  });
388
826
  const adminPrefix = resolveAdminPrefix(entry.adminPrefix);
389
- runtime.isolateNamespaces();
390
827
  const locked = /* @__PURE__ */ new Set();
391
828
  const active = /* @__PURE__ */ new Map();
392
829
  const api = {
@@ -500,14 +937,14 @@ async function startFleet(config, options2) {
500
937
  if (!Array.isArray(body.services) || body.services.length === 0)
501
938
  throw new Error("services must be a nonempty list");
502
939
  const selected = /* @__PURE__ */ new Map();
503
- for (const name of body.services) {
504
- if (typeof name !== "string" || !children.has(name))
940
+ for (const name2 of body.services) {
941
+ if (typeof name2 !== "string" || !children.has(name2))
505
942
  throw new Error("unknown service in selection");
506
- selected.set(name, children.get(name));
943
+ selected.set(name2, children.get(name2));
507
944
  }
508
945
  return selected;
509
946
  };
510
- const diagnostics = (namespace) => Object.fromEntries([...children].map(([name, child]) => [name, child.diagnostics(namespace)]));
947
+ const diagnostics = (namespace) => Object.fromEntries([...children].map(([name2, child]) => [name2, child.diagnostics(namespace)]));
511
948
  const transaction = async (namespace, selected, run) => {
512
949
  if (controlling)
513
950
  return json(409, { error: "another fleet operation is in progress" });
@@ -517,33 +954,33 @@ async function startFleet(config, options2) {
517
954
  const results = {};
518
955
  let failure;
519
956
  try {
520
- for (const [name, child] of selected) {
521
- failure = name;
957
+ for (const [name2, child] of selected) {
958
+ failure = name2;
522
959
  release.push(child.lock(namespace));
523
960
  }
524
961
  const busy = Object.fromEntries([...selected].filter(([, child]) => {
525
962
  const state = child.diagnostics(namespace);
526
963
  return state.activeRequests + state.blockedCommands + state.pendingWebhooks + (state.activeJobs ?? 0) > 0;
527
- }).map(([name, child]) => [name, child.diagnostics(namespace)]));
964
+ }).map(([name2, child]) => [name2, child.diagnostics(namespace)]));
528
965
  if (Object.keys(busy).length)
529
966
  return json(409, { error: "namespace is not quiescent", services: busy });
530
- for (const [name, child] of selected) {
531
- failure = name;
532
- before.set(name, await child.checkpoint(namespace));
967
+ for (const [name2, child] of selected) {
968
+ failure = name2;
969
+ before.set(name2, await child.checkpoint(namespace));
533
970
  }
534
- for (const [name, child] of selected) {
535
- failure = name;
536
- results[name] = { status: "ok", result: await run(name, child) };
971
+ for (const [name2, child] of selected) {
972
+ failure = name2;
973
+ results[name2] = { status: "ok", result: await run(name2, child) };
537
974
  }
538
975
  return json(200, { status: "ok", namespace, services: results });
539
976
  } catch {
540
977
  const rollback = {};
541
- for (const [name, point] of before) {
978
+ for (const [name2, point] of before) {
542
979
  try {
543
- await selected.get(name)?.restore(namespace, point);
544
- rollback[name] = "restored";
980
+ await selected.get(name2)?.restore(namespace, point);
981
+ rollback[name2] = "restored";
545
982
  } catch {
546
- rollback[name] = "failed";
983
+ rollback[name2] = "failed";
547
984
  }
548
985
  }
549
986
  return json(500, {
@@ -566,14 +1003,14 @@ async function startFleet(config, options2) {
566
1003
  const adminPrefix = resolveAdminPrefix(config.adminPrefix);
567
1004
  const path = url.pathname.startsWith(`${adminPrefix}/`) ? url.pathname.slice(adminPrefix.length) : "";
568
1005
  if (path === "/health" && request.method === "GET") {
569
- const states = await Promise.all([...children].map(async ([name, child]) => {
1006
+ const states = await Promise.all([...children].map(async ([name2, child]) => {
570
1007
  let protocolReady = false;
571
1008
  try {
572
1009
  protocolReady = await child.ready();
573
1010
  } catch {
574
1011
  }
575
1012
  return [
576
- name,
1013
+ name2,
577
1014
  {
578
1015
  processReady: !stopped,
579
1016
  protocolReady,
@@ -604,7 +1041,7 @@ async function startFleet(config, options2) {
604
1041
  return json(200, {
605
1042
  namespace,
606
1043
  ...clock(namespace).state(),
607
- services: Object.fromEntries([...children].map(([name, child]) => [name, child.clock(namespace).state()]))
1044
+ services: Object.fromEntries([...children].map(([name2, child]) => [name2, child.clock(namespace).state()]))
608
1045
  });
609
1046
  if (request.method !== "POST")
610
1047
  return json(405, { error: "method not allowed" });
@@ -648,19 +1085,12 @@ async function startFleet(config, options2) {
648
1085
  return json(400, { error: "freeze must be boolean" });
649
1086
  const response2 = await transaction(namespace, selected, async (_name, child) => {
650
1087
  const childClock = child.clock(namespace);
651
- childClock.freeze();
652
- childClock.set(target);
653
- if (!frozen)
654
- childClock.unfreeze();
1088
+ restoreClock(childClock, { now: target, frozen });
655
1089
  await child.settle?.(namespace);
656
1090
  return childClock.state();
657
1091
  });
658
- if (response2.ok) {
659
- current.freeze();
660
- current.set(target);
661
- if (!frozen)
662
- current.unfreeze();
663
- }
1092
+ if (response2.ok)
1093
+ restoreClock(current, { now: target, frozen });
664
1094
  return response2;
665
1095
  }
666
1096
  if (!route)
@@ -677,22 +1107,17 @@ async function startFleet(config, options2) {
677
1107
  const point = checkpoints.get(route[3]);
678
1108
  if (!point || point.namespace !== namespace)
679
1109
  return json(404, { error: "no snapshot in this namespace" });
680
- const restored = new Map([...point.values].map(([name]) => [name, children.get(name)]));
681
- const response2 = await transaction(namespace, restored, async (name, child) => child.restore(namespace, point.values.get(name)));
682
- if (response2.ok) {
683
- const current = clock(namespace);
684
- current.freeze();
685
- current.set(point.clock.now);
686
- if (!point.clock.frozen)
687
- current.unfreeze();
688
- }
1110
+ const restored = new Map([...point.values].map(([name2]) => [name2, children.get(name2)]));
1111
+ const response2 = await transaction(namespace, restored, async (name2, child) => child.restore(namespace, point.values.get(name2)));
1112
+ if (response2.ok)
1113
+ restoreClock(clock(namespace), point.clock);
689
1114
  return response2;
690
1115
  }
691
1116
  const snapshotId = randomUUID();
692
1117
  const values = /* @__PURE__ */ new Map();
693
- const response = await transaction(namespace, selected, async (name, child) => {
694
- values.set(name, await child.checkpoint(namespace));
695
- return { checkpoint: `${snapshotId}:${name}` };
1118
+ const response = await transaction(namespace, selected, async (name2, child) => {
1119
+ values.set(name2, await child.checkpoint(namespace));
1120
+ return { checkpoint: `${snapshotId}:${name2}` };
696
1121
  });
697
1122
  if (!response.ok)
698
1123
  return response;
@@ -708,24 +1133,28 @@ async function startFleet(config, options2) {
708
1133
  const adminPrefix = resolveAdminPrefix(config.adminPrefix);
709
1134
  if (!isObject(config.services) || Object.keys(config.services).length === 0)
710
1135
  throw new Error("config must contain at least one service");
711
- for (const [name, entry] of Object.entries(config.services)) {
712
- if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(name))
1136
+ for (const [name2, entry] of Object.entries(config.services)) {
1137
+ if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(name2))
713
1138
  throw new Error("invalid service name");
1139
+ if (config.adminControls !== void 0 || entry.adminControls !== void 0)
1140
+ normalizeBootControls({ ...config.adminControls, ...entry.adminControls }, `services.${name2}.adminControls`);
714
1141
  try {
715
- const target = await options2.load(name);
1142
+ const target = await options2.load(name2);
716
1143
  if (entry.protocol && entry.protocol !== ("protocol" in target ? target.protocol : "http"))
717
1144
  throw new Error("configured protocol does not match target");
718
1145
  const adminKey = entry.adminKey ?? config.adminKey ?? process.env.MOCKINGBIRD_ADMIN_KEY;
719
1146
  const child = "start" in target ? await target.start(entry) : await httpChild(target, {
720
1147
  ...entry,
721
1148
  adminPrefix: resolveAdminPrefix(entry.adminPrefix ?? adminPrefix),
722
- ...adminKey !== void 0 ? { adminKey } : {}
1149
+ ...adminKey !== void 0 ? { adminKey } : {},
1150
+ // Fleet-wide controls, with the service's own keys replacing them.
1151
+ ...config.adminControls !== void 0 || entry.adminControls !== void 0 ? { adminControls: { ...config.adminControls, ...entry.adminControls } } : {}
723
1152
  }, options2);
724
- children.set(name, child);
1153
+ children.set(name2, child);
725
1154
  if (!await child.ready())
726
1155
  throw new Error("protocol readiness failed");
727
1156
  } catch {
728
- throw new Error(`service ${name} failed to start; all started listeners were closed`);
1157
+ throw new Error(`service ${name2} failed to start; all started listeners were closed`);
729
1158
  }
730
1159
  }
731
1160
  supervisor = await listen(api, {
@@ -740,8 +1169,8 @@ async function startFleet(config, options2) {
740
1169
  startedAt,
741
1170
  adminBase: `${supervisor.url}${adminPrefix}/fleet`,
742
1171
  healthUrl: `${supervisor.url}${adminPrefix}/health`,
743
- services: Object.fromEntries([...children].map(([name, child]) => [
744
- name,
1172
+ services: Object.fromEntries([...children].map(([name2, child]) => [
1173
+ name2,
745
1174
  {
746
1175
  protocol: child.protocol,
747
1176
  url: publicUrl(child.url),
@@ -758,8 +1187,8 @@ async function startFleet(config, options2) {
758
1187
  version: 1,
759
1188
  id,
760
1189
  pid: process.pid,
761
- services: Object.fromEntries([...children].map(([name, child]) => [
762
- name,
1190
+ services: Object.fromEntries([...children].map(([name2, child]) => [
1191
+ name2,
763
1192
  { url: child.connection ?? child.url, namespaces: child.connections }
764
1193
  ]))
765
1194
  });
@@ -774,10 +1203,10 @@ async function startFleet(config, options2) {
774
1203
  }
775
1204
 
776
1205
  // ../../adapters/node/dist/cli.js
777
- var optionHelp = (options2) => Object.entries(options2).map(([name, option]) => {
778
- const flag = `--${name}${option.type === "string" ? ` ${option.value ?? "<value>"}` : ""}`;
1206
+ var optionHelp = (options2) => Object.entries(options2).map(([name2, option]) => {
1207
+ const flag2 = `--${name2}${option.type === "string" ? ` ${option.value ?? "<value>"}` : ""}`;
779
1208
  const fallback2 = option.default !== void 0 ? ` (default: ${String(option.default)})` : "";
780
- return ` ${flag.padEnd(30)} ${option.description}${fallback2}`;
1209
+ return ` ${flag2.padEnd(30)} ${option.description}${fallback2}`;
781
1210
  });
782
1211
  var help = (spec) => [
783
1212
  `${spec.bin} \u2014 ${spec.description}`,
@@ -786,35 +1215,35 @@ var help = (spec) => [
786
1215
  ` ${spec.bin} <command> [options]`,
787
1216
  "",
788
1217
  "Commands:",
789
- ...Object.entries(spec.commands).map(([name, c]) => ` ${name.padEnd(30)} ${c.summary}`),
1218
+ ...Object.entries(spec.commands).map(([name2, c]) => ` ${name2.padEnd(30)} ${c.summary}`),
790
1219
  "",
791
1220
  `Run \`${spec.bin} <command> --help\` for a command's options.`
792
1221
  ].join("\n");
793
- var commandHelp = (spec, name, command2) => [
794
- `${spec.bin} ${name} \u2014 ${command2.summary}`,
1222
+ var commandHelp = (spec, name2, command2) => [
1223
+ `${spec.bin} ${name2} \u2014 ${command2.summary}`,
795
1224
  "",
796
1225
  "Usage:",
797
- ` ${command2.usage ?? `${spec.bin} ${name} [options]`}`,
1226
+ ` ${command2.usage ?? `${spec.bin} ${name2} [options]`}`,
798
1227
  ...command2.options ? ["", "Options:", ...optionHelp(command2.options)] : []
799
1228
  ].join("\n");
800
1229
  var runCli = async (spec, argv) => {
801
1230
  const pair = argv.length >= 2 ? `${argv[0]} ${argv[1]}` : void 0;
802
1231
  const words = pair !== void 0 && spec.commands[pair] ? 2 : 1;
803
- const name = words === 2 ? pair : argv[0];
1232
+ const name2 = words === 2 ? pair : argv[0];
804
1233
  const rest = argv.slice(words);
805
- if (name === void 0 || name === "--help" || name === "-h" || name === "help") {
1234
+ if (name2 === void 0 || name2 === "--help" || name2 === "-h" || name2 === "help") {
806
1235
  console.log(help(spec));
807
1236
  return 0;
808
1237
  }
809
- const command2 = spec.commands[name];
1238
+ const command2 = spec.commands[name2];
810
1239
  if (!command2) {
811
- console.error(`${spec.bin}: unknown command ${JSON.stringify(name)}
1240
+ console.error(`${spec.bin}: unknown command ${JSON.stringify(name2)}
812
1241
 
813
1242
  ${help(spec)}`);
814
1243
  return 2;
815
1244
  }
816
1245
  if (rest.includes("--help") || rest.includes("-h")) {
817
- console.log(commandHelp(spec, name, command2));
1246
+ console.log(commandHelp(spec, name2, command2));
818
1247
  return 0;
819
1248
  }
820
1249
  let parsed;
@@ -832,9 +1261,9 @@ ${help(spec)}`);
832
1261
  ]))
833
1262
  });
834
1263
  } catch (error) {
835
- console.error(`${spec.bin} ${name}: ${error instanceof Error ? error.message : String(error)}
1264
+ console.error(`${spec.bin} ${name2}: ${error instanceof Error ? error.message : String(error)}
836
1265
 
837
- ${commandHelp(spec, name, command2)}`);
1266
+ ${commandHelp(spec, name2, command2)}`);
838
1267
  return 2;
839
1268
  }
840
1269
  return command2.run(parsed.values, parsed.positionals);
@@ -852,7 +1281,51 @@ var COMMON_SERVE_OPTIONS = {
852
1281
  value: "<key>",
853
1282
  description: "Require x-mockingbird-admin-key on /__admin/* (env MOCKINGBIRD_ADMIN_KEY)"
854
1283
  },
855
- seed: { type: "string", value: "<seed>", description: "Seed for every random choice" },
1284
+ seed: {
1285
+ type: "string",
1286
+ value: "<seed>",
1287
+ description: "Seed for every random choice (env MOCKINGBIRD_SEED)"
1288
+ },
1289
+ "admin-controls": {
1290
+ type: "string",
1291
+ value: "<json|file>",
1292
+ description: "Admin controls to boot with, as JSON or a JSON file: clock, latency, faults, snapshot, namespaces (env MOCKINGBIRD_ADMIN_CONTROLS)"
1293
+ },
1294
+ clock: {
1295
+ type: "string",
1296
+ value: "<instant>",
1297
+ description: "Start the clock at this instant (epoch ms or ISO-8601)"
1298
+ },
1299
+ freeze: { type: "boolean", description: "Freeze the clock: it moves only when told to" },
1300
+ "auto-advance": {
1301
+ type: "string",
1302
+ value: "<duration>",
1303
+ description: "Step the clock this much before every request (e.g. 1s)"
1304
+ },
1305
+ latency: {
1306
+ type: "string",
1307
+ value: "<duration>",
1308
+ description: "Baseline response time for every request (e.g. 250ms)"
1309
+ },
1310
+ jitter: {
1311
+ type: "string",
1312
+ value: "<duration>",
1313
+ description: "Seeded extra latency between 0 and this"
1314
+ },
1315
+ "virtual-time": {
1316
+ type: "boolean",
1317
+ description: "Spend latency, delays and timeouts on the mock clock instead of really waiting"
1318
+ },
1319
+ fault: {
1320
+ type: "string",
1321
+ value: "<fault>",
1322
+ description: 'A fault to boot with, as in x-mockingbird-fault: 503, rate_limited, "status=503; delay=2s"'
1323
+ },
1324
+ snapshot: {
1325
+ type: "string",
1326
+ value: "<file>",
1327
+ description: "Start from a snapshot document (GET /__admin/snapshots/:id)"
1328
+ },
856
1329
  log: {
857
1330
  type: "string",
858
1331
  value: "<pretty|json|off>",
@@ -899,10 +1372,72 @@ var formatLog = (format) => {
899
1372
  };
900
1373
  };
901
1374
  var asString = (value) => typeof value === "string" ? value : void 0;
902
- var loadTarget = async (name, own2) => {
903
- if (name === own2.name)
1375
+ var readJsonFile = async (path, label) => {
1376
+ try {
1377
+ return JSON.parse(await readFile2(path, "utf8"));
1378
+ } catch (error) {
1379
+ throw new Error(`${label}: cannot read ${path}: ${error instanceof Error ? error.message : error}`);
1380
+ }
1381
+ };
1382
+ var isObject2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1383
+ var resolveServeControls = async (values, env = process.env, base) => {
1384
+ const source = asString(values["admin-controls"]) ?? env.MOCKINGBIRD_ADMIN_CONTROLS;
1385
+ let document = isObject2(base) ? { ...base } : {};
1386
+ if (source !== void 0 && source.trim() !== "") {
1387
+ let parsed;
1388
+ if (source.trim().startsWith("{")) {
1389
+ try {
1390
+ parsed = JSON.parse(source);
1391
+ } catch {
1392
+ throw new Error("--admin-controls: not valid JSON");
1393
+ }
1394
+ } else
1395
+ parsed = await readJsonFile(source, "--admin-controls");
1396
+ if (!isObject2(parsed))
1397
+ throw new Error("--admin-controls: expected a JSON object");
1398
+ document = { ...document, ...parsed };
1399
+ }
1400
+ const clock = isObject2(document.clock) ? { ...document.clock } : {};
1401
+ const now = asString(values.clock);
1402
+ if (now !== void 0)
1403
+ clock.now = now;
1404
+ if (values.freeze === true)
1405
+ clock.frozen = true;
1406
+ const autoAdvance = asString(values["auto-advance"]);
1407
+ if (autoAdvance !== void 0)
1408
+ clock.autoAdvance = autoAdvance;
1409
+ if (Object.keys(clock).length > 0)
1410
+ document.clock = clock;
1411
+ const delay = asString(values.latency);
1412
+ const jitter = asString(values.jitter);
1413
+ if (delay !== void 0 || jitter !== void 0) {
1414
+ const latency = isObject2(document.latency) ? { ...document.latency } : document.latency !== void 0 ? { delay: document.latency } : {};
1415
+ if (delay !== void 0)
1416
+ latency.delay = delay;
1417
+ if (jitter !== void 0)
1418
+ latency.jitter = jitter;
1419
+ document.latency = latency;
1420
+ }
1421
+ if (values["virtual-time"] === true)
1422
+ document.virtualTime = true;
1423
+ const fault = asString(values.fault);
1424
+ if (fault !== void 0)
1425
+ document.faults = [
1426
+ ...Array.isArray(document.faults) ? document.faults : [],
1427
+ parseFaultHeader(fault, "--fault")
1428
+ ];
1429
+ const snapshot = asString(values.snapshot);
1430
+ if (snapshot !== void 0)
1431
+ document.snapshot = await readJsonFile(snapshot, "--snapshot");
1432
+ if (Object.keys(document).length === 0)
1433
+ return void 0;
1434
+ normalizeBootControls(document, "adminControls");
1435
+ return document;
1436
+ };
1437
+ var loadTarget = async (name2, own2) => {
1438
+ if (name2 === own2.name)
904
1439
  return own2;
905
- const specifier = `@crvouga/mockingbird-service-${name}/server`;
1440
+ const specifier = `@crvouga/mockingbird-service-${name2}/server`;
906
1441
  try {
907
1442
  let mod;
908
1443
  try {
@@ -916,7 +1451,7 @@ var loadTarget = async (name, own2) => {
916
1451
  return mod.serveTarget;
917
1452
  } catch (error) {
918
1453
  const reason = error instanceof Error ? error.message : String(error);
919
- throw new Error(`cannot load service "${name}": ${reason}. Install @crvouga/mockingbird-service-${name}.`);
1454
+ throw new Error(`cannot load service "${name2}": ${reason}. Install @crvouga/mockingbird-service-${name2}.`);
920
1455
  }
921
1456
  };
922
1457
  var start = async (target, values, config) => {
@@ -925,7 +1460,8 @@ var start = async (target, values, config) => {
925
1460
  adminPrefix,
926
1461
  adminKey: config.adminKey,
927
1462
  seed: config.seed,
928
- onLog: formatLog(config.log)
1463
+ onLog: formatLog(config.log),
1464
+ ...config.adminControls !== void 0 ? { adminControls: config.adminControls } : {}
929
1465
  });
930
1466
  const listening = await listen(runtime, { port: config.port, host: config.host });
931
1467
  target.listening?.(listening);
@@ -965,8 +1501,11 @@ var serveCommand = (target) => ({
965
1501
  const adminKey2 = config.adminKey ?? asString(values["admin-key"]) ?? process.env.MOCKINGBIRD_ADMIN_KEY;
966
1502
  if (adminKey2 !== void 0)
967
1503
  config.adminKey = adminKey2;
1504
+ const adminControls = await resolveServeControls(values, process.env, config.adminControls);
1505
+ if (adminControls !== void 0)
1506
+ config.adminControls = adminControls;
968
1507
  const fleet = await startFleet(config, {
969
- load: (name) => loadTarget(name, target),
1508
+ load: (name2) => loadTarget(name2, target),
970
1509
  onLog: formatLog(config.log ?? log2),
971
1510
  ...asString(values["ready-file"]) ? { readyFile: asString(values["ready-file"]) } : {},
972
1511
  ...asString(values["connections-file"]) ? { connectionsFile: asString(values["connections-file"]) } : {},
@@ -974,8 +1513,8 @@ var serveCommand = (target) => ({
974
1513
  if (values["ready-json"])
975
1514
  console.log(JSON.stringify(manifest));
976
1515
  else
977
- for (const [name, endpoint] of Object.entries(manifest.services))
978
- console.log(`${name} emulator listening on ${endpoint.url}`);
1516
+ for (const [name2, endpoint] of Object.entries(manifest.services))
1517
+ console.log(`${name2} emulator listening on ${endpoint.url}`);
979
1518
  }
980
1519
  });
981
1520
  return untilSignal([fleet]);
@@ -990,10 +1529,12 @@ var serveCommand = (target) => ({
990
1529
  }
991
1530
  const port = asString(values.port);
992
1531
  const adminKey = asString(values["admin-key"]) ?? process.env.MOCKINGBIRD_ADMIN_KEY;
993
- const seed = asString(values.seed);
1532
+ const seed = asString(values.seed) ?? process.env.MOCKINGBIRD_SEED;
994
1533
  let listening;
995
1534
  try {
1535
+ const adminControls = await resolveServeControls(values);
996
1536
  listening = await start(target, values, {
1537
+ ...adminControls !== void 0 ? { adminControls } : {},
997
1538
  adminPrefix: resolveAdminPrefix(asString(values["admin-prefix"]) ?? process.env.MOCKINGBIRD_ADMIN_PREFIX),
998
1539
  port: port === void 0 ? target.defaultPort : Number.parseInt(port, 10),
999
1540
  host: asString(values.host) ?? "127.0.0.1",
@@ -1213,9 +1754,9 @@ var builder = null;
1213
1754
  function setCatalogBuilder(b) {
1214
1755
  builder = b;
1215
1756
  }
1216
- function catalogRelation(ctx, schema, name) {
1757
+ function catalogRelation(ctx, schema, name2) {
1217
1758
  if (schema !== "pg_catalog" && schema !== "information_schema") return null;
1218
- return builder ? builder(ctx, schema, name) : null;
1759
+ return builder ? builder(ctx, schema, name2) : null;
1219
1760
  }
1220
1761
  var PG_CATALOG_RELATIONS = /* @__PURE__ */ new Set([
1221
1762
  "pg_namespace",
@@ -3396,19 +3937,19 @@ function parseJsonpath(text) {
3396
3937
  i++;
3397
3938
  if (s[i] === '"') {
3398
3939
  i++;
3399
- let name = "";
3940
+ let name2 = "";
3400
3941
  while (i < s.length && s[i] !== '"') {
3401
3942
  if (s[i] === "\\" && i + 1 < s.length) {
3402
- name += s[i + 1];
3943
+ name2 += s[i + 1];
3403
3944
  i += 2;
3404
3945
  } else {
3405
- name += s[i];
3946
+ name2 += s[i];
3406
3947
  i++;
3407
3948
  }
3408
3949
  }
3409
3950
  if (s[i] !== '"') invalidJsonpath();
3410
3951
  i++;
3411
- steps.push({ kind: "member", name });
3952
+ steps.push({ kind: "member", name: name2 });
3412
3953
  continue;
3413
3954
  }
3414
3955
  const m = /^[A-Za-z_][A-Za-z0-9_]*/.exec(s.slice(i));
@@ -3612,9 +4153,9 @@ var QUOTED_KEYWORDS = /* @__PURE__ */ new Set([
3612
4153
  "xmlserialize",
3613
4154
  "xmltable"
3614
4155
  ]);
3615
- function quoteIdentifier(name) {
3616
- if (/^[a-z_][a-z0-9_]*$/.test(name) && !QUOTED_KEYWORDS.has(name)) return name;
3617
- return `"${name.replaceAll('"', '""')}"`;
4156
+ function quoteIdentifier(name2) {
4157
+ if (/^[a-z_][a-z0-9_]*$/.test(name2) && !QUOTED_KEYWORDS.has(name2)) return name2;
4158
+ return `"${name2.replaceAll('"', '""')}"`;
3618
4159
  }
3619
4160
 
3620
4161
  // src/types/regnamespace.ts
@@ -3623,7 +4164,7 @@ var BUILTIN_NAMESPACES = [
3623
4164
  ["pg_catalog", 11],
3624
4165
  ["information_schema", 13212]
3625
4166
  ];
3626
- var builtinNamespaceOid = (name) => BUILTIN_NAMESPACES.find(([builtin]) => builtin === name)?.[1];
4167
+ var builtinNamespaceOid = (name2) => BUILTIN_NAMESPACES.find(([builtin]) => builtin === name2)?.[1];
3627
4168
  var builtinNamespaceName = (oid) => BUILTIN_NAMESPACES.find(([, builtin]) => builtin === oid)?.[0];
3628
4169
  var OID_MAX = 4294967295n;
3629
4170
  function parseOidText(text) {
@@ -3656,18 +4197,18 @@ function parseNamespaceInput(text) {
3656
4197
  skipSpace();
3657
4198
  while (at < text.length) {
3658
4199
  if (text[at] === '"') {
3659
- let name = "";
4200
+ let name2 = "";
3660
4201
  at++;
3661
4202
  for (; ; ) {
3662
4203
  const close = text.indexOf('"', at);
3663
4204
  if (close === -1) invalidName();
3664
- name += text.slice(at, close);
4205
+ name2 += text.slice(at, close);
3665
4206
  at = close + 1;
3666
4207
  if (text[at] !== '"') break;
3667
- name += '"';
4208
+ name2 += '"';
3668
4209
  at++;
3669
4210
  }
3670
- names.push(name);
4211
+ names.push(name2);
3671
4212
  } else {
3672
4213
  const start3 = at;
3673
4214
  while (at < text.length && text[at] !== "." && !/\s/.test(text[at])) at++;
@@ -3684,9 +4225,9 @@ function parseNamespaceInput(text) {
3684
4225
  if (names.length !== 1) invalidName();
3685
4226
  return { name: names[0] };
3686
4227
  }
3687
- function namespaceText(oid, name) {
4228
+ function namespaceText(oid, name2) {
3688
4229
  if (oid === 0) return "-";
3689
- return name === null || name === void 0 ? String(oid) : quoteIdentifier(name);
4230
+ return name2 === null || name2 === void 0 ? String(oid) : quoteIdentifier(name2);
3690
4231
  }
3691
4232
 
3692
4233
  // src/types/value.ts
@@ -3770,8 +4311,8 @@ var TYPE_ALIASES = {
3770
4311
  smallserial: "int2",
3771
4312
  serial2: "int2"
3772
4313
  };
3773
- function normalizeTypeName(name) {
3774
- const lower = name.trim().toLowerCase().replace(/\s+/g, " ");
4314
+ function normalizeTypeName(name2) {
4315
+ const lower = name2.trim().toLowerCase().replace(/\s+/g, " ");
3775
4316
  return TYPE_ALIASES[lower] ?? null;
3776
4317
  }
3777
4318
  function isArrayType(t) {
@@ -4414,9 +4955,9 @@ var TableData = class _TableData {
4414
4955
  shareCount = 0;
4415
4956
  /** Derived unique/btree index maps; null until built or invalidated. */
4416
4957
  indexStores = null;
4417
- constructor(schema, name, columns, oid, temp = false) {
4958
+ constructor(schema, name2, columns, oid, temp = false) {
4418
4959
  this.schema = schema;
4419
- this.name = name;
4960
+ this.name = name2;
4420
4961
  this.columns = columns;
4421
4962
  this.rows = [];
4422
4963
  this.constraints = [];
@@ -4460,8 +5001,8 @@ var TableData = class _TableData {
4460
5001
  thaw() {
4461
5002
  if (this.shareCount > 0) this.shareCount--;
4462
5003
  }
4463
- columnIndex(name) {
4464
- return this.columns.findIndex((c) => c.name === name);
5004
+ columnIndex(name2) {
5005
+ return this.columns.findIndex((c) => c.name === name2);
4465
5006
  }
4466
5007
  clone() {
4467
5008
  const t = new _TableData(
@@ -4499,13 +5040,13 @@ var SchemaData = class _SchemaData {
4499
5040
  functions = /* @__PURE__ */ new Map();
4500
5041
  indexes = /* @__PURE__ */ new Map();
4501
5042
  oid;
4502
- constructor(name, oid) {
4503
- this.name = name;
5043
+ constructor(name2, oid) {
5044
+ this.name = name2;
4504
5045
  this.oid = oid;
4505
5046
  }
4506
5047
  /** all relation names (tables, views, sequences, indexes share pg_class namespace) */
4507
- hasRelation(name) {
4508
- return this.tables.has(name) || this.views.has(name) || this.sequences.has(name) || this.indexes.has(name);
5048
+ hasRelation(name2) {
5049
+ return this.tables.has(name2) || this.views.has(name2) || this.sequences.has(name2) || this.indexes.has(name2);
4509
5050
  }
4510
5051
  clone() {
4511
5052
  const s = new _SchemaData(this.name, this.oid);
@@ -4608,8 +5149,8 @@ var DatabaseState = class _DatabaseState {
4608
5149
  nextOid() {
4609
5150
  return this.oidCounter++;
4610
5151
  }
4611
- getSetting(name) {
4612
- return this.localSettings.get(name) ?? this.settings.get(name);
5152
+ getSetting(name2) {
5153
+ return this.localSettings.get(name2) ?? this.settings.get(name2);
4613
5154
  }
4614
5155
  /** effective search path: existing schemas from search_path setting */
4615
5156
  effectiveSearchPath() {
@@ -4617,8 +5158,8 @@ var DatabaseState = class _DatabaseState {
4617
5158
  const parts = raw.split(",").map((p) => p.trim()).map((p) => p.startsWith('"') && p.endsWith('"') ? p.slice(1, -1) : p).filter((p) => p.length > 0);
4618
5159
  const out = [];
4619
5160
  for (const p of parts) {
4620
- const name = p === "$user" ? "postgres" : p;
4621
- if (this.schemas.has(name)) out.push(name);
5161
+ const name2 = p === "$user" ? "postgres" : p;
5162
+ if (this.schemas.has(name2)) out.push(name2);
4622
5163
  }
4623
5164
  return out;
4624
5165
  }
@@ -4626,38 +5167,38 @@ var DatabaseState = class _DatabaseState {
4626
5167
  const path = this.effectiveSearchPath();
4627
5168
  return path[0] ?? "public";
4628
5169
  }
4629
- getSchema(name) {
4630
- const s = this.schemas.get(name);
4631
- if (!s) throw pgError("undefined_object", `schema "${name}" does not exist`, "3F000");
5170
+ getSchema(name2) {
5171
+ const s = this.schemas.get(name2);
5172
+ if (!s) throw pgError("undefined_object", `schema "${name2}" does not exist`, "3F000");
4632
5173
  return s;
4633
5174
  }
4634
5175
  /** Resolve a possibly-qualified relation name to its schema. */
4635
5176
  resolveRelationSchema(parts) {
4636
5177
  if (parts.length === 2) {
4637
- const [schema, name2] = parts;
4638
- return { schema, name: name2 };
5178
+ const [schema, name3] = parts;
5179
+ return { schema, name: name3 };
4639
5180
  }
4640
5181
  if (parts.length === 3) {
4641
- const [, schema, name2] = parts;
4642
- return { schema, name: name2 };
5182
+ const [, schema, name3] = parts;
5183
+ return { schema, name: name3 };
4643
5184
  }
4644
- const name = parts[0];
5185
+ const name2 = parts[0];
4645
5186
  for (const schema of ["pg_catalog", ...this.effectiveSearchPath()]) {
4646
- if (schema === "pg_catalog" && PG_CATALOG_RELATIONS.has(name)) return { schema, name };
5187
+ if (schema === "pg_catalog" && PG_CATALOG_RELATIONS.has(name2)) return { schema, name: name2 };
4647
5188
  const s = this.schemas.get(schema);
4648
- if (s?.hasRelation(name)) return { schema, name };
5189
+ if (s?.hasRelation(name2)) return { schema, name: name2 };
4649
5190
  }
4650
5191
  return null;
4651
5192
  }
4652
5193
  findTable(parts) {
4653
5194
  if (parts.length >= 2) {
4654
5195
  const schema = parts[parts.length - 2];
4655
- const name2 = parts[parts.length - 1];
4656
- return this.schemas.get(schema)?.tables.get(name2) ?? null;
5196
+ const name3 = parts[parts.length - 1];
5197
+ return this.schemas.get(schema)?.tables.get(name3) ?? null;
4657
5198
  }
4658
- const name = parts[0];
5199
+ const name2 = parts[0];
4659
5200
  for (const schema of this.effectiveSearchPath()) {
4660
- const t = this.schemas.get(schema)?.tables.get(name);
5201
+ const t = this.schemas.get(schema)?.tables.get(name2);
4661
5202
  if (t) return t;
4662
5203
  }
4663
5204
  return null;
@@ -4672,12 +5213,12 @@ var DatabaseState = class _DatabaseState {
4672
5213
  findView(parts) {
4673
5214
  if (parts.length >= 2) {
4674
5215
  const schema = parts[parts.length - 2];
4675
- const name2 = parts[parts.length - 1];
4676
- return this.schemas.get(schema)?.views.get(name2) ?? null;
5216
+ const name3 = parts[parts.length - 1];
5217
+ return this.schemas.get(schema)?.views.get(name3) ?? null;
4677
5218
  }
4678
- const name = parts[0];
5219
+ const name2 = parts[0];
4679
5220
  for (const schema of this.effectiveSearchPath()) {
4680
- const v = this.schemas.get(schema)?.views.get(name);
5221
+ const v = this.schemas.get(schema)?.views.get(name2);
4681
5222
  if (v) return v;
4682
5223
  }
4683
5224
  return null;
@@ -4685,12 +5226,12 @@ var DatabaseState = class _DatabaseState {
4685
5226
  findSequence(parts) {
4686
5227
  if (parts.length >= 2) {
4687
5228
  const schema = parts[parts.length - 2];
4688
- const name2 = parts[parts.length - 1];
4689
- return this.schemas.get(schema)?.sequences.get(name2) ?? null;
5229
+ const name3 = parts[parts.length - 1];
5230
+ return this.schemas.get(schema)?.sequences.get(name3) ?? null;
4690
5231
  }
4691
- const name = parts[0];
5232
+ const name2 = parts[0];
4692
5233
  for (const schema of this.effectiveSearchPath()) {
4693
- const s = this.schemas.get(schema)?.sequences.get(name);
5234
+ const s = this.schemas.get(schema)?.sequences.get(name2);
4694
5235
  if (s) return s;
4695
5236
  }
4696
5237
  return null;
@@ -4698,12 +5239,12 @@ var DatabaseState = class _DatabaseState {
4698
5239
  findEnum(parts) {
4699
5240
  if (parts.length >= 2) {
4700
5241
  const schema = parts[parts.length - 2];
4701
- const name2 = parts[parts.length - 1];
4702
- return this.schemas.get(schema)?.enums.get(name2) ?? null;
5242
+ const name3 = parts[parts.length - 1];
5243
+ return this.schemas.get(schema)?.enums.get(name3) ?? null;
4703
5244
  }
4704
- const name = parts[0];
5245
+ const name2 = parts[0];
4705
5246
  for (const schema of ["pg_catalog", ...this.effectiveSearchPath()]) {
4706
- const e = this.schemas.get(schema)?.enums.get(name);
5247
+ const e = this.schemas.get(schema)?.enums.get(name2);
4707
5248
  if (e) return e;
4708
5249
  }
4709
5250
  return null;
@@ -4711,12 +5252,12 @@ var DatabaseState = class _DatabaseState {
4711
5252
  findDomain(parts) {
4712
5253
  if (parts.length >= 2) {
4713
5254
  const schema = parts[parts.length - 2];
4714
- const name2 = parts[parts.length - 1];
4715
- return this.schemas.get(schema)?.domains.get(name2) ?? null;
5255
+ const name3 = parts[parts.length - 1];
5256
+ return this.schemas.get(schema)?.domains.get(name3) ?? null;
4716
5257
  }
4717
- const name = parts[0];
5258
+ const name2 = parts[0];
4718
5259
  for (const schema of ["pg_catalog", ...this.effectiveSearchPath()]) {
4719
- const d = this.schemas.get(schema)?.domains.get(name);
5260
+ const d = this.schemas.get(schema)?.domains.get(name2);
4720
5261
  if (d) return d;
4721
5262
  }
4722
5263
  return null;
@@ -4724,14 +5265,14 @@ var DatabaseState = class _DatabaseState {
4724
5265
  findFunctions(parts) {
4725
5266
  if (parts.length >= 2) {
4726
5267
  const schema = parts[parts.length - 2];
4727
- const name2 = parts[parts.length - 1];
4728
- if (schema === "pg_catalog") return this.systemFunctions.get(name2) ?? [];
4729
- return this.schemas.get(schema)?.functions.get(name2) ?? [];
5268
+ const name3 = parts[parts.length - 1];
5269
+ if (schema === "pg_catalog") return this.systemFunctions.get(name3) ?? [];
5270
+ return this.schemas.get(schema)?.functions.get(name3) ?? [];
4730
5271
  }
4731
- const name = parts[0];
4732
- const out = [...this.systemFunctions.get(name) ?? []];
5272
+ const name2 = parts[0];
5273
+ const out = [...this.systemFunctions.get(name2) ?? []];
4733
5274
  for (const schema of this.effectiveSearchPath()) {
4734
- const fns = this.schemas.get(schema)?.functions.get(name);
5275
+ const fns = this.schemas.get(schema)?.functions.get(name2);
4735
5276
  if (fns) out.push(...fns);
4736
5277
  }
4737
5278
  return out;
@@ -4743,8 +5284,8 @@ var DatabaseState = class _DatabaseState {
4743
5284
  }
4744
5285
  /** format_type()-style display name for a type OID (builtin or enum). */
4745
5286
  typeNameForOid(oid) {
4746
- for (const [name, o] of Object.entries(TYPE_OIDS)) {
4747
- if (o === oid) return typeDisplayName(name);
5287
+ for (const [name2, o] of Object.entries(TYPE_OIDS)) {
5288
+ if (o === oid) return typeDisplayName(name2);
4748
5289
  }
4749
5290
  for (const schema of this.schemas.values()) {
4750
5291
  for (const e of schema.enums.values()) {
@@ -4767,7 +5308,7 @@ var DatabaseState = class _DatabaseState {
4767
5308
  s.sequenceCurrval = new Map(this.sequenceCurrval);
4768
5309
  s.tableStats = new Map(this.tableStats);
4769
5310
  s.oidCounter = this.oidCounter;
4770
- for (const [name, overloads] of this.systemFunctions) s.systemFunctions.set(name, overloads.slice());
5311
+ for (const [name2, overloads] of this.systemFunctions) s.systemFunctions.set(name2, overloads.slice());
4771
5312
  return s;
4772
5313
  }
4773
5314
  /** Share frozen catalog objects; copy maps so CREATE/DROP is isolated. */
@@ -4784,7 +5325,7 @@ var DatabaseState = class _DatabaseState {
4784
5325
  s.sequenceCurrval = new Map(this.sequenceCurrval);
4785
5326
  s.tableStats = new Map(this.tableStats);
4786
5327
  s.oidCounter = this.oidCounter;
4787
- for (const [name, overloads] of this.systemFunctions) s.systemFunctions.set(name, overloads.slice());
5328
+ for (const [name2, overloads] of this.systemFunctions) s.systemFunctions.set(name2, overloads.slice());
4788
5329
  return s;
4789
5330
  }
4790
5331
  freezeShared() {
@@ -4920,30 +5461,30 @@ var TransactionManager = class {
4920
5461
  this.state.localSettings.clear();
4921
5462
  while (this.freezeDepth > 0) this.thawOnce();
4922
5463
  }
4923
- savepoint(name) {
5464
+ savepoint(name2) {
4924
5465
  if (this.base === null) {
4925
5466
  throw pgError("transaction_state", "SAVEPOINT can only be used in transaction blocks", "25P01");
4926
5467
  }
4927
- this.savepoints.push({ name, snap: this.takeSnapshot() });
5468
+ this.savepoints.push({ name: name2, snap: this.takeSnapshot() });
4928
5469
  }
4929
- releaseSavepoint(name) {
4930
- const idx = this.findSavepoint(name);
5470
+ releaseSavepoint(name2) {
5471
+ const idx = this.findSavepoint(name2);
4931
5472
  this.savepoints.splice(idx);
4932
5473
  }
4933
- rollbackToSavepoint(name) {
4934
- const idx = this.findSavepoint(name);
5474
+ rollbackToSavepoint(name2) {
5475
+ const idx = this.findSavepoint(name2);
4935
5476
  const sp = this.savepoints[idx];
4936
5477
  this.restore(sp.snap);
4937
5478
  this.savepoints.splice(idx + 1);
4938
5479
  }
4939
- findSavepoint(name) {
5480
+ findSavepoint(name2) {
4940
5481
  if (this.base === null) {
4941
5482
  throw pgError("transaction_state", `SAVEPOINT can only be used in transaction blocks`, "25P01");
4942
5483
  }
4943
5484
  for (let i = this.savepoints.length - 1; i >= 0; i--) {
4944
- if (this.savepoints[i].name === name) return i;
5485
+ if (this.savepoints[i].name === name2) return i;
4945
5486
  }
4946
- throw pgError("invalid_savepoint_specification", `savepoint "${name}" does not exist`, "3B001");
5487
+ throw pgError("invalid_savepoint_specification", `savepoint "${name2}" does not exist`, "3B001");
4947
5488
  }
4948
5489
  reset() {
4949
5490
  this.base = null;
@@ -5493,35 +6034,35 @@ var RowScope = class {
5493
6034
  /** Resolve a (possibly qualified) column reference. undefined = not found. */
5494
6035
  lookup(parts) {
5495
6036
  if (parts.length === 1) {
5496
- const name2 = parts[0];
6037
+ const name3 = parts[0];
5497
6038
  let found2;
5498
6039
  let count2 = 0;
5499
6040
  for (let i = 0; i < this.columns.length; i++) {
5500
6041
  const c = this.columns[i];
5501
- if (c.name === name2 && !c.hidden) {
6042
+ if (c.name === name3 && !c.hidden) {
5502
6043
  count2++;
5503
6044
  if (count2 > 1) {
5504
- throw pgError("ambiguous_column", `column reference "${name2}" is ambiguous`);
6045
+ throw pgError("ambiguous_column", `column reference "${name3}" is ambiguous`);
5505
6046
  }
5506
6047
  found2 = tv(c.type, this.row[i] ?? null);
5507
6048
  }
5508
6049
  }
5509
6050
  if (found2 !== void 0) return found2;
5510
- if (this.rangeVars.has(name2)) {
5511
- return this.wholeRow(name2);
6051
+ if (this.rangeVars.has(name3)) {
6052
+ return this.wholeRow(name3);
5512
6053
  }
5513
6054
  return this.parent?.lookup(parts);
5514
6055
  }
5515
6056
  const table = parts[parts.length - 2];
5516
- const name = parts[parts.length - 1];
6057
+ const name2 = parts[parts.length - 1];
5517
6058
  let found;
5518
6059
  let count = 0;
5519
6060
  for (let i = 0; i < this.columns.length; i++) {
5520
6061
  const c = this.columns[i];
5521
- if (c.table === table && c.name === name) {
6062
+ if (c.table === table && c.name === name2) {
5522
6063
  count++;
5523
6064
  if (count > 1) {
5524
- throw pgError("ambiguous_column", `column reference "${name}" is ambiguous`);
6065
+ throw pgError("ambiguous_column", `column reference "${name2}" is ambiguous`);
5525
6066
  }
5526
6067
  found = tv(c.type, this.row[i] ?? null);
5527
6068
  }
@@ -5545,9 +6086,9 @@ var RowScope = class {
5545
6086
  if (types.length === 0) return void 0;
5546
6087
  return tv("record", { kind: "pgrecord", types, values, names });
5547
6088
  }
5548
- hasRangeVar(name) {
5549
- if (this.rangeVars.has(name)) return true;
5550
- return this.parent?.hasRangeVar(name) ?? false;
6089
+ hasRangeVar(name2) {
6090
+ if (this.rangeVars.has(name2)) return true;
6091
+ return this.parent?.hasRangeVar(name2) ?? false;
5551
6092
  }
5552
6093
  };
5553
6094
  function childEnv(env, outer) {
@@ -8002,17 +8543,17 @@ function getMathFunctions() {
8002
8543
  acosh: Math.acosh,
8003
8544
  atanh: Math.atanh
8004
8545
  };
8005
- for (const [name, fn] of Object.entries(trig)) {
8546
+ for (const [name2, fn] of Object.entries(trig)) {
8006
8547
  m.set(
8007
- name,
8548
+ name2,
8008
8549
  strict("float8", (ctx, args2) => {
8009
8550
  const x = argFloat(ctx, args2[0]);
8010
- if ((name === "asin" || name === "acos") && (x < -1 || x > 1)) {
8551
+ if ((name2 === "asin" || name2 === "acos") && (x < -1 || x > 1)) {
8011
8552
  throw pgError("numeric_value_out_of_range", "input is out of range");
8012
8553
  }
8013
- if (name === "acosh" && x < 1) throw pgError("numeric_value_out_of_range", "input is out of range");
8014
- if (name === "atanh" && (x < -1 || x > 1)) throw pgError("numeric_value_out_of_range", "input is out of range");
8015
- return tv("float8", checkFloat(fn(x), name));
8554
+ if (name2 === "acosh" && x < 1) throw pgError("numeric_value_out_of_range", "input is out of range");
8555
+ if (name2 === "atanh" && (x < -1 || x > 1)) throw pgError("numeric_value_out_of_range", "input is out of range");
8556
+ return tv("float8", checkFloat(fn(x), name2));
8016
8557
  })
8017
8558
  );
8018
8559
  }
@@ -8029,12 +8570,12 @@ function getMathFunctions() {
8029
8570
  acosd: (x) => Math.acos(x) * 180 / Math.PI,
8030
8571
  atand: (x) => Math.atan(x) * 180 / Math.PI
8031
8572
  };
8032
- for (const [name, fn] of Object.entries(degTrig)) {
8573
+ for (const [name2, fn] of Object.entries(degTrig)) {
8033
8574
  m.set(
8034
- name,
8575
+ name2,
8035
8576
  strict("float8", (ctx, args2) => {
8036
8577
  const x = argFloat(ctx, args2[0]);
8037
- if ((name === "asind" || name === "acosd") && (x < -1 || x > 1)) {
8578
+ if ((name2 === "asind" || name2 === "acosd") && (x < -1 || x > 1)) {
8038
8579
  throw pgError("numeric_value_out_of_range", "input is out of range");
8039
8580
  }
8040
8581
  return tv("float8", fn(x));
@@ -8279,9 +8820,9 @@ function keyColumns(constraint) {
8279
8820
  function sameKeyColumns(index, constraint) {
8280
8821
  return index.columns.length === constraint.columns.length && index.columns.every((column, position) => column.column === constraint.columns[position]);
8281
8822
  }
8282
- function nameTaken(schema, name, self) {
8283
- if (schema.tables.has(name) || schema.views.has(name) || schema.sequences.has(name)) return true;
8284
- const other = schema.indexes.get(name);
8823
+ function nameTaken(schema, name2, self) {
8824
+ if (schema.tables.has(name2) || schema.views.has(name2) || schema.sequences.has(name2)) return true;
8825
+ const other = schema.indexes.get(name2);
8285
8826
  return other !== void 0 && other !== self;
8286
8827
  }
8287
8828
  function syncIndexCatalog(state) {
@@ -8306,18 +8847,18 @@ function syncIndexCatalog(state) {
8306
8847
  schema.indexes.delete(key);
8307
8848
  continue;
8308
8849
  }
8309
- const name = owner ? owner.constraint.name : index.name;
8310
- const stale = index.oid === void 0 || index.tableOid !== home.table.oid || index.schema !== home.schema.name || index.table !== home.table.name || index.name !== name || key !== name || owner !== void 0 && !sameKeyColumns(index, owner.constraint);
8850
+ const name2 = owner ? owner.constraint.name : index.name;
8851
+ const stale = index.oid === void 0 || index.tableOid !== home.table.oid || index.schema !== home.schema.name || index.table !== home.table.name || index.name !== name2 || key !== name2 || owner !== void 0 && !sameKeyColumns(index, owner.constraint);
8311
8852
  if (!stale) {
8312
8853
  if (owner) linked.add(index.oid);
8313
8854
  continue;
8314
8855
  }
8315
8856
  schema.indexes.delete(key);
8316
- if (nameTaken(home.schema, name)) continue;
8857
+ if (nameTaken(home.schema, name2)) continue;
8317
8858
  const next = {
8318
8859
  ...index,
8319
8860
  oid: index.oid ?? state.nextOid(),
8320
- name,
8861
+ name: name2,
8321
8862
  schema: home.schema.name,
8322
8863
  table: home.table.name,
8323
8864
  tableOid: home.table.oid,
@@ -8327,7 +8868,7 @@ function syncIndexCatalog(state) {
8327
8868
  next.nullsNotDistinct = owner.constraint.kind === "unique" && owner.constraint.nullsNotDistinct;
8328
8869
  linked.add(next.oid);
8329
8870
  }
8330
- home.schema.indexes.set(name, next);
8871
+ home.schema.indexes.set(name2, next);
8331
8872
  }
8332
8873
  }
8333
8874
  for (const { schema, table } of [...tables.values()]) {
@@ -8361,7 +8902,7 @@ function syncIndexCatalog(state) {
8361
8902
  }
8362
8903
  }
8363
8904
  function claimConstraintIndexName(schema, constraint, explicit, reserved = /* @__PURE__ */ new Set()) {
8364
- const used = (name) => schema.hasRelation(name) || reserved.has(name);
8905
+ const used = (name2) => schema.hasRelation(name2) || reserved.has(name2);
8365
8906
  if (used(constraint.name)) {
8366
8907
  if (explicit) throw pgError("duplicate_table", `relation "${constraint.name}" already exists`, "42P07");
8367
8908
  const base = constraint.name;
@@ -8370,11 +8911,11 @@ function claimConstraintIndexName(schema, constraint, explicit, reserved = /* @_
8370
8911
  reserved.add(constraint.name);
8371
8912
  }
8372
8913
  function findIndex(state, parts) {
8373
- const name = parts[parts.length - 1];
8914
+ const name2 = parts[parts.length - 1];
8374
8915
  const schemas = parts.length >= 2 ? [parts[parts.length - 2]] : state.effectiveSearchPath();
8375
8916
  for (const schemaName of schemas) {
8376
8917
  const schema = state.schemas.get(schemaName);
8377
- const index = schema?.indexes.get(name);
8918
+ const index = schema?.indexes.get(name2);
8378
8919
  if (schema && index) return { schema, index };
8379
8920
  }
8380
8921
  return null;
@@ -8394,14 +8935,14 @@ function constraintOfIndex(state, index) {
8394
8935
  return table && constraint && isKeyConstraint(constraint) ? { table, constraint } : null;
8395
8936
  }
8396
8937
  function otherRelationKind(state, parts) {
8397
- const name = parts[parts.length - 1];
8938
+ const name2 = parts[parts.length - 1];
8398
8939
  const schemas = parts.length >= 2 ? [parts[parts.length - 2]] : state.effectiveSearchPath();
8399
8940
  for (const schemaName of schemas) {
8400
8941
  const schema = state.schemas.get(schemaName);
8401
8942
  if (!schema) continue;
8402
- if (schema.tables.has(name)) return "table";
8403
- if (schema.views.has(name)) return "view";
8404
- if (schema.sequences.has(name)) return "sequence";
8943
+ if (schema.tables.has(name2)) return "table";
8944
+ if (schema.views.has(name2)) return "view";
8945
+ if (schema.sequences.has(name2)) return "sequence";
8405
8946
  }
8406
8947
  return null;
8407
8948
  }
@@ -8438,14 +8979,14 @@ function deparseSelectCore(body) {
8438
8979
  }
8439
8980
  function deparseFrom(item) {
8440
8981
  if (item.type === "from_table") {
8441
- const name = item.name.join(".");
8442
- return item.alias ? `${name} ${quoteIdent(item.alias)}` : name;
8982
+ const name2 = item.name.join(".");
8983
+ return item.alias ? `${name2} ${quoteIdent(item.alias)}` : name2;
8443
8984
  }
8444
8985
  return "(subquery)";
8445
8986
  }
8446
- function quoteIdent(name) {
8447
- if (/^[a-z_][a-z0-9_$]*$/.test(name)) return name;
8448
- return `"${name.replaceAll('"', '""')}"`;
8987
+ function quoteIdent(name2) {
8988
+ if (/^[a-z_][a-z0-9_$]*$/.test(name2)) return name2;
8989
+ return `"${name2.replaceAll('"', '""')}"`;
8449
8990
  }
8450
8991
  function deparseExpr(e) {
8451
8992
  switch (e.type) {
@@ -8497,10 +9038,10 @@ var PATTERN_OPS = /* @__PURE__ */ new Set(["~~", "~~*", "!~~", "!~~*", "~", "~*"
8497
9038
  function formatType(scope, type, mod = null) {
8498
9039
  if (isArrayType(type)) return `${formatType(scope, arrayElemType(type), mod)}[]`;
8499
9040
  if (isEnumType(type)) {
8500
- const [schema, name] = type.slice(5).split(".");
8501
- if (name === void 0) return quoteIdentifier(schema);
9041
+ const [schema, name2] = type.slice(5).split(".");
9042
+ if (name2 === void 0) return quoteIdentifier(schema);
8502
9043
  const visible = scope.ctx.state.effectiveSearchPath().includes(schema);
8503
- return visible ? quoteIdentifier(name) : `${quoteIdentifier(schema)}.${quoteIdentifier(name)}`;
9044
+ return visible ? quoteIdentifier(name2) : `${quoteIdentifier(schema)}.${quoteIdentifier(name2)}`;
8504
9045
  }
8505
9046
  const base = typeDisplayName(type);
8506
9047
  if (!mod || mod.a === void 0) return type === "bpchar" ? "bpchar" : base;
@@ -8642,13 +9183,13 @@ var Analyzer = class {
8642
9183
  }
8643
9184
  }
8644
9185
  functionName(parts) {
8645
- const name = parts[parts.length - 1];
9186
+ const name2 = parts[parts.length - 1];
8646
9187
  const state = this.scope.ctx.state;
8647
9188
  const schema = parts.length >= 2 ? parts[parts.length - 2] : state.findFunctions([...parts])[0]?.schema;
8648
9189
  if (schema === void 0 || schema === "pg_catalog" || state.effectiveSearchPath().includes(schema)) {
8649
- return quoteIdentifier(name);
9190
+ return quoteIdentifier(name2);
8650
9191
  }
8651
- return `${quoteIdentifier(schema)}.${quoteIdentifier(name)}`;
9192
+ return `${quoteIdentifier(schema)}.${quoteIdentifier(name2)}`;
8652
9193
  }
8653
9194
  /** Arguments of a function call: untyped literals become text, varchar and char values are cast to it. */
8654
9195
  argument(node, literal2 = TEXT) {
@@ -8676,9 +9217,9 @@ var Analyzer = class {
8676
9217
  analyze(e) {
8677
9218
  switch (e.type) {
8678
9219
  case "colref": {
8679
- const name = e.parts[e.parts.length - 1];
8680
- const column = this.scope.table?.columns.find((c) => c.name === name);
8681
- return { k: "var", name, type: column?.type.id ?? null };
9220
+ const name2 = e.parts[e.parts.length - 1];
9221
+ const column = this.scope.table?.columns.find((c) => c.name === name2);
9222
+ return { k: "var", name: name2, type: column?.type.id ?? null };
8682
9223
  }
8683
9224
  case "string_lit":
8684
9225
  return { k: "const", type: null, mod: null, text: e.value };
@@ -8788,28 +9329,28 @@ var Analyzer = class {
8788
9329
  }
8789
9330
  case "func": {
8790
9331
  if (e.star || e.distinct || e.over || e.filter || e.orderBy || e.withinGroupOrderBy) break;
8791
- const name = e.name[e.name.length - 1];
9332
+ const name2 = e.name[e.name.length - 1];
8792
9333
  const args2 = e.args.map((arg) => this.analyze(arg));
8793
- if ((name === "__any_array" || name === "__all_array") && args2.length === 3 && isUntyped(args2[2])) {
9334
+ if ((name2 === "__any_array" || name2 === "__all_array") && args2.length === 3 && isUntyped(args2[2])) {
8794
9335
  const array = args2[1];
8795
9336
  const elementType = typeOf(array);
8796
9337
  const element = elementType && isArrayType(elementType) ? arrayElemType(elementType) : null;
8797
9338
  const left = element ? this.coerce(args2[0], element) : args2[0];
8798
- return { k: "saop", op: args2[2].text ?? "=", any: name === "__any_array", left, right: array };
9339
+ return { k: "saop", op: args2[2].text ?? "=", any: name2 === "__any_array", left, right: array };
8799
9340
  }
8800
- if (e.name.length === 1 && (name === "coalesce" || name === "greatest" || name === "least")) {
8801
- const parts = [`${name.toUpperCase()}(`];
9341
+ if (e.name.length === 1 && (name2 === "coalesce" || name2 === "greatest" || name2 === "least")) {
9342
+ const parts = [`${name2.toUpperCase()}(`];
8802
9343
  this.unify(args2).forEach((arg, position) => {
8803
9344
  if (position > 0) parts.push(", ");
8804
9345
  parts.push(arg);
8805
9346
  });
8806
9347
  return this.form([...parts, ")"], e);
8807
9348
  }
8808
- if (e.name.length === 1 && name === "nullif" && args2.length === 2) {
9349
+ if (e.name.length === 1 && name2 === "nullif" && args2.length === 2) {
8809
9350
  const [left, right] = this.operator("=", args2[0], args2[1], e).args;
8810
9351
  return this.form(["NULLIF(", left, ", ", right, ")"], e);
8811
9352
  }
8812
- const literals = LITERAL_ARGUMENTS[name] ?? [];
9353
+ const literals = LITERAL_ARGUMENTS[name2] ?? [];
8813
9354
  return {
8814
9355
  k: "func",
8815
9356
  name: this.functionName(e.name),
@@ -9076,9 +9617,9 @@ function tableName(scope, index, pretty) {
9076
9617
  return found?.schema === index.schema ? quoteIdentifier(index.table) : qualified;
9077
9618
  }
9078
9619
  function storageParameters(index) {
9079
- return (index.options ?? []).map(({ name, value }) => {
9620
+ return (index.options ?? []).map(({ name: name2, value }) => {
9080
9621
  const bare = quoteIdentifier(value) === value;
9081
- return `${quoteIdentifier(name)}=${bare ? value : `'${value.replaceAll("'", "''")}'`}`;
9622
+ return `${quoteIdentifier(name2)}=${bare ? value : `'${value.replaceAll("'", "''")}'`}`;
9082
9623
  }).join(", ");
9083
9624
  }
9084
9625
  function deparseIndexPredicate(ctx, index, pretty = false) {
@@ -9119,23 +9660,23 @@ function setDatabaseCatalogContext(state, context) {
9119
9660
 
9120
9661
  // src/functions/misc-fns.ts
9121
9662
  var PG_VERSION_TEXT = "PostgreSQL 18.3 (postgres-mem) on TypeScript, in-memory engine";
9122
- function findSequenceForCall(ctx, name) {
9123
- const parts = parseQualifiedName(name);
9663
+ function findSequenceForCall(ctx, name2) {
9664
+ const parts = parseQualifiedName(name2);
9124
9665
  const seq = ctx.state.findSequence(parts);
9125
9666
  if (!seq) {
9126
- throw pgError("undefined_table", `relation "${name}" does not exist`, "42P01");
9667
+ throw pgError("undefined_table", `relation "${name2}" does not exist`, "42P01");
9127
9668
  }
9128
9669
  return seq;
9129
9670
  }
9130
- function parseQualifiedName(name) {
9671
+ function parseQualifiedName(name2) {
9131
9672
  const parts = [];
9132
9673
  let current = "";
9133
9674
  let inQuote = false;
9134
- for (let i = 0; i < name.length; i++) {
9135
- const c = name[i];
9675
+ for (let i = 0; i < name2.length; i++) {
9676
+ const c = name2[i];
9136
9677
  if (inQuote) {
9137
9678
  if (c === '"') {
9138
- if (name[i + 1] === '"') {
9679
+ if (name2[i + 1] === '"') {
9139
9680
  current += '"';
9140
9681
  i++;
9141
9682
  } else inQuote = false;
@@ -9267,12 +9808,12 @@ function getMiscFunctions() {
9267
9808
  );
9268
9809
  m.set("current_setting", (ctx, args2) => {
9269
9810
  if (args2[0].v === null) return tv("text", null);
9270
- const name = argText(ctx, args2[0]).toLowerCase();
9811
+ const name2 = argText(ctx, args2[0]).toLowerCase();
9271
9812
  const missingOk = args2.length > 1 && args2[1].v === true;
9272
- const value = ctx.state.getSetting(name);
9813
+ const value = ctx.state.getSetting(name2);
9273
9814
  if (value === void 0) {
9274
9815
  if (missingOk) return tv("text", null);
9275
- throw pgError("undefined_object", `unrecognized configuration parameter "${name}"`, "42704");
9816
+ throw pgError("undefined_object", `unrecognized configuration parameter "${name2}"`, "42704");
9276
9817
  }
9277
9818
  return tv("text", value);
9278
9819
  });
@@ -9280,9 +9821,9 @@ function getMiscFunctions() {
9280
9821
  if (args2[0].v === null) {
9281
9822
  throw pgError("null_value_not_allowed", "NULL value not allowed for parameter name", "22004");
9282
9823
  }
9283
- const name = argText(ctx, args2[0]).toLowerCase();
9824
+ const name2 = argText(ctx, args2[0]).toLowerCase();
9284
9825
  const value = args2[1].v === null ? "" : argText(ctx, args2[1]);
9285
- ctx.state.settings.set(name, value);
9826
+ ctx.state.settings.set(name2, value);
9286
9827
  return tv("text", value);
9287
9828
  });
9288
9829
  m.set(
@@ -9357,8 +9898,8 @@ function getMiscFunctions() {
9357
9898
  m.set("format_type", (ctx, args2) => {
9358
9899
  if (args2[0].v === null) return tv("text", null);
9359
9900
  const oid = argInt(ctx, args2[0]);
9360
- const name = ctx.state.typeNameForOid(oid);
9361
- return tv("text", name ?? "???");
9901
+ const name2 = ctx.state.typeNameForOid(oid);
9902
+ return tv("text", name2 ?? "???");
9362
9903
  });
9363
9904
  m.set("pg_get_expr", (_ctx, args2) => {
9364
9905
  const expr = args2[0];
@@ -9543,8 +10084,8 @@ function pgRegexToJs(pattern) {
9543
10084
  "invalid regular expression: brackets [] not balanced",
9544
10085
  "2201B"
9545
10086
  );
9546
- const name = pattern.slice(j + 2, end);
9547
- cls += posixClass(name);
10087
+ const name2 = pattern.slice(j + 2, end);
10088
+ cls += posixClass(name2);
9548
10089
  j = end + 1;
9549
10090
  continue;
9550
10091
  }
@@ -9574,8 +10115,8 @@ function pgRegexToJs(pattern) {
9574
10115
  }
9575
10116
  return out;
9576
10117
  }
9577
- function posixClass(name) {
9578
- switch (name) {
10118
+ function posixClass(name2) {
10119
+ switch (name2) {
9579
10120
  case "alpha":
9580
10121
  return "a-zA-Z";
9581
10122
  case "digit":
@@ -10769,8 +11310,8 @@ function getScalarFunctions() {
10769
11310
  getTsearchFunctions(),
10770
11311
  getMiscFunctions()
10771
11312
  ]) {
10772
- for (const [name, fn] of source) {
10773
- registry.set(name, fn);
11313
+ for (const [name2, fn] of source) {
11314
+ registry.set(name2, fn);
10774
11315
  }
10775
11316
  }
10776
11317
  const stringLength = registry.get("length");
@@ -10782,13 +11323,13 @@ function getScalarFunctions() {
10782
11323
  REGISTRY = registry;
10783
11324
  return registry;
10784
11325
  }
10785
- function hasScalarFunction(name) {
10786
- return getScalarFunctions().has(name);
11326
+ function hasScalarFunction(name2) {
11327
+ return getScalarFunctions().has(name2);
10787
11328
  }
10788
- function callScalarFunction(ctx, name, args2) {
10789
- const fn = getScalarFunctions().get(name);
11329
+ function callScalarFunction(ctx, name2, args2) {
11330
+ const fn = getScalarFunctions().get(name2);
10790
11331
  if (!fn) {
10791
- throw pgError("undefined_function", `function ${name}(${args2.map((a) => a.t).join(", ")}) does not exist`, "42883");
11332
+ throw pgError("undefined_function", `function ${name2}(${args2.map((a) => a.t).join(", ")}) does not exist`, "42883");
10792
11333
  }
10793
11334
  return fn(ctx, args2);
10794
11335
  }
@@ -10833,12 +11374,12 @@ function installPgTrgm(state, schemaName) {
10833
11374
  function uninstallPgTrgm(state) {
10834
11375
  let removed = false;
10835
11376
  for (const schema of state.schemas.values()) {
10836
- for (const [name, fns] of [...schema.functions.entries()]) {
11377
+ for (const [name2, fns] of [...schema.functions.entries()]) {
10837
11378
  const keep = fns.filter((fn) => fn.language !== "internal" || fn.rawBody !== PGTRGM_BODY);
10838
11379
  if (keep.length === fns.length) continue;
10839
11380
  removed = true;
10840
- if (keep.length === 0) schema.functions.delete(name);
10841
- else schema.functions.set(name, keep);
11381
+ if (keep.length === 0) schema.functions.delete(name2);
11382
+ else schema.functions.set(name2, keep);
10842
11383
  }
10843
11384
  }
10844
11385
  return removed;
@@ -12162,8 +12703,8 @@ function evalExpr(ctx, scope, e) {
12162
12703
  case "trim": {
12163
12704
  const src = evalExpr(ctx, scope, e.source);
12164
12705
  const chars2 = e.chars ? evalExpr(ctx, scope, e.chars) : tv("text", " ");
12165
- const name = e.side === "leading" ? "ltrim" : e.side === "trailing" ? "rtrim" : "btrim";
12166
- return callScalarFunction(ctx, name, [src, chars2]);
12706
+ const name2 = e.side === "leading" ? "ltrim" : e.side === "trailing" ? "rtrim" : "btrim";
12707
+ return callScalarFunction(ctx, name2, [src, chars2]);
12167
12708
  }
12168
12709
  case "extract": {
12169
12710
  const src = evalExpr(ctx, scope, e.source);
@@ -12755,15 +13296,15 @@ var NAMED_ARG_SIGNATURES = /* @__PURE__ */ new Map([
12755
13296
  }
12756
13297
  ]
12757
13298
  ]);
12758
- function reorderNamedArgs(name, args2, argNames) {
12759
- const sig = NAMED_ARG_SIGNATURES.get(name);
13299
+ function reorderNamedArgs(name2, args2, argNames) {
13300
+ const sig = NAMED_ARG_SIGNATURES.get(name2);
12760
13301
  if (!sig) return args2;
12761
13302
  const out = sig.defaults.slice();
12762
13303
  let pos = 0;
12763
13304
  for (let i = 0; i < args2.length; i++) {
12764
13305
  const n = argNames[i];
12765
13306
  const idx = n === null || n === void 0 ? pos++ : sig.params.indexOf(n);
12766
- if (idx < 0) throw pgError("undefined_function", `function ${name} has no parameter named "${n}"`);
13307
+ if (idx < 0) throw pgError("undefined_function", `function ${name2} has no parameter named "${n}"`);
12767
13308
  out[idx] = args2[i];
12768
13309
  }
12769
13310
  return out;
@@ -12807,8 +13348,8 @@ function evalAnyAllArray(ctx, scope, kind, args2) {
12807
13348
  const rights = arr.v.items.map((item) => tv(elemType, item));
12808
13349
  return anyAllCompare(ctx, op, left, rights, kind);
12809
13350
  }
12810
- function evalLazyFunc(ctx, scope, name, argExprs) {
12811
- switch (name) {
13351
+ function evalLazyFunc(ctx, scope, name2, argExprs) {
13352
+ switch (name2) {
12812
13353
  case "coalesce": {
12813
13354
  let t = UNKNOWN;
12814
13355
  for (const a of argExprs) {
@@ -12828,7 +13369,7 @@ function evalLazyFunc(ctx, scope, name, argExprs) {
12828
13369
  }
12829
13370
  case "greatest":
12830
13371
  case "least": {
12831
- const op = name === "greatest" ? ">" : "<";
13372
+ const op = name2 === "greatest" ? ">" : "<";
12832
13373
  let best = null;
12833
13374
  let t = UNKNOWN;
12834
13375
  const vals = argExprs.map((a) => evalExpr(ctx, scope, a));
@@ -12844,7 +13385,7 @@ function evalLazyFunc(ctx, scope, name, argExprs) {
12844
13385
  return best ?? tv(finalT, null);
12845
13386
  }
12846
13387
  default:
12847
- throw pgError("internal", `lazy function ${name} not handled`);
13388
+ throw pgError("internal", `lazy function ${name2} not handled`);
12848
13389
  }
12849
13390
  }
12850
13391
 
@@ -13369,16 +13910,16 @@ var FACTORIES = /* @__PURE__ */ new Map([
13369
13910
  function getAggregateFactories() {
13370
13911
  return FACTORIES;
13371
13912
  }
13372
- function isAggregateName(name) {
13373
- return FACTORIES.has(name);
13913
+ function isAggregateName(name2) {
13914
+ return FACTORIES.has(name2);
13374
13915
  }
13375
- function createAggregate(ctx, name, argTypes) {
13376
- const f = FACTORIES.get(name);
13377
- if (!f) throw pgError("undefined_function", `aggregate ${name} does not exist`, "42883");
13916
+ function createAggregate(ctx, name2, argTypes) {
13917
+ const f = FACTORIES.get(name2);
13918
+ if (!f) throw pgError("undefined_function", `aggregate ${name2} does not exist`, "42883");
13378
13919
  return f(ctx, argTypes);
13379
13920
  }
13380
- function isOrderedSetAggregate(name) {
13381
- return name === "percentile_cont" || name === "percentile_disc" || name === "mode";
13921
+ function isOrderedSetAggregate(name2) {
13922
+ return name2 === "percentile_cont" || name2 === "percentile_disc" || name2 === "mode";
13382
13923
  }
13383
13924
  function unifyAggType(a, b) {
13384
13925
  if (a === UNKNOWN) return b;
@@ -13983,12 +14524,12 @@ function installPgcrypto(state, schemaName) {
13983
14524
  function uninstallPgcrypto(state) {
13984
14525
  let removed = false;
13985
14526
  for (const schema of state.schemas.values()) {
13986
- for (const [name, fns] of [...schema.functions.entries()]) {
14527
+ for (const [name2, fns] of [...schema.functions.entries()]) {
13987
14528
  const keep = fns.filter((fn) => fn.language !== "internal" || fn.rawBody !== PGCRYPTO_BODY);
13988
14529
  if (keep.length === fns.length) continue;
13989
14530
  removed = true;
13990
- if (keep.length === 0) schema.functions.delete(name);
13991
- else schema.functions.set(name, keep);
14531
+ if (keep.length === 0) schema.functions.delete(name2);
14532
+ else schema.functions.set(name2, keep);
13992
14533
  }
13993
14534
  }
13994
14535
  return removed;
@@ -14271,8 +14812,8 @@ SRFS.set("jsonb_object_keys", jsonKeysSrf());
14271
14812
  function getSrfFunctions() {
14272
14813
  return SRFS;
14273
14814
  }
14274
- function isSrfName(name) {
14275
- return SRFS.has(name);
14815
+ function isSrfName(name2) {
14816
+ return SRFS.has(name2);
14276
14817
  }
14277
14818
 
14278
14819
  // src/indexes/index.ts
@@ -14280,8 +14821,8 @@ var IndexStore = class _IndexStore {
14280
14821
  name;
14281
14822
  unique;
14282
14823
  entries = /* @__PURE__ */ new Map();
14283
- constructor(name, unique = false) {
14284
- this.name = name;
14824
+ constructor(name2, unique = false) {
14825
+ this.name = name2;
14285
14826
  this.unique = unique;
14286
14827
  }
14287
14828
  get size() {
@@ -15055,12 +15596,12 @@ var Parser = class {
15055
15596
  return this.parseWithableStatement();
15056
15597
  case "table": {
15057
15598
  this.pos++;
15058
- const name = this.qualifiedName();
15599
+ const name2 = this.qualifiedName();
15059
15600
  const core = {
15060
15601
  type: "select_core",
15061
15602
  distinct: null,
15062
15603
  targets: [{ expr: { type: "star" }, alias: null }],
15063
- from: [{ type: "from_table", name, only: false, alias: null, colAliases: null }],
15604
+ from: [{ type: "from_table", name: name2, only: false, alias: null, colAliases: null }],
15064
15605
  where: null,
15065
15606
  groupBy: null,
15066
15607
  groupDistinct: false,
@@ -15092,13 +15633,13 @@ var Parser = class {
15092
15633
  this.expectKw("materialized");
15093
15634
  this.expectKw("view");
15094
15635
  this.eatKw("concurrently");
15095
- const name = this.qualifiedName();
15636
+ const name2 = this.qualifiedName();
15096
15637
  let withData = true;
15097
15638
  if (this.eatKw("with")) {
15098
15639
  if (this.eatKw("no")) withData = false;
15099
15640
  this.expectKw("data");
15100
15641
  }
15101
- return { type: "refresh_materialized_view", name, withData };
15642
+ return { type: "refresh_materialized_view", name: name2, withData };
15102
15643
  }
15103
15644
  case "begin":
15104
15645
  case "start": {
@@ -15154,8 +15695,8 @@ var Parser = class {
15154
15695
  this.eatKw("work") || this.eatKw("transaction");
15155
15696
  if (this.eatKw("to")) {
15156
15697
  this.eatKw("savepoint");
15157
- const name = this.ident();
15158
- return { type: "transaction", action: "rollback_to", savepointName: name };
15698
+ const name2 = this.ident();
15699
+ return { type: "transaction", action: "rollback_to", savepointName: name2 };
15159
15700
  }
15160
15701
  let chain = false;
15161
15702
  if (this.eatKw("and")) {
@@ -15170,14 +15711,14 @@ var Parser = class {
15170
15711
  }
15171
15712
  case "savepoint": {
15172
15713
  this.pos++;
15173
- const name = this.ident();
15174
- return { type: "transaction", action: "savepoint", savepointName: name };
15714
+ const name2 = this.ident();
15715
+ return { type: "transaction", action: "savepoint", savepointName: name2 };
15175
15716
  }
15176
15717
  case "release": {
15177
15718
  this.pos++;
15178
15719
  this.eatKw("savepoint");
15179
- const name = this.ident();
15180
- return { type: "transaction", action: "release", savepointName: name };
15720
+ const name2 = this.ident();
15721
+ return { type: "transaction", action: "release", savepointName: name2 };
15181
15722
  }
15182
15723
  case "set":
15183
15724
  return this.parseSet();
@@ -15216,7 +15757,7 @@ var Parser = class {
15216
15757
  }
15217
15758
  case "prepare": {
15218
15759
  this.pos++;
15219
- const name = this.ident();
15760
+ const name2 = this.ident();
15220
15761
  let argTypes = null;
15221
15762
  if (this.eatPunct("(")) {
15222
15763
  argTypes = [];
@@ -15229,11 +15770,11 @@ var Parser = class {
15229
15770
  }
15230
15771
  this.expectKw("as");
15231
15772
  const query = this.parseStatement();
15232
- return { type: "prepare", name, argTypes, query };
15773
+ return { type: "prepare", name: name2, argTypes, query };
15233
15774
  }
15234
15775
  case "execute": {
15235
15776
  this.pos++;
15236
- const name = this.ident();
15777
+ const name2 = this.ident();
15237
15778
  const params = [];
15238
15779
  if (this.eatPunct("(")) {
15239
15780
  if (!this.atPunct(")")) {
@@ -15243,7 +15784,7 @@ var Parser = class {
15243
15784
  }
15244
15785
  this.expectPunct(")");
15245
15786
  }
15246
- return { type: "execute", name, params };
15787
+ return { type: "execute", name: name2, params };
15247
15788
  }
15248
15789
  case "deallocate": {
15249
15790
  this.pos++;
@@ -15444,7 +15985,7 @@ var Parser = class {
15444
15985
  const recursive = this.eatKw("recursive");
15445
15986
  const ctes = [];
15446
15987
  do {
15447
- const name = this.ident();
15988
+ const name2 = this.ident();
15448
15989
  let columns = null;
15449
15990
  if (this.eatPunct("(")) {
15450
15991
  columns = [];
@@ -15464,7 +16005,7 @@ var Parser = class {
15464
16005
  const query = this.parseWithableStatement();
15465
16006
  this.expectPunct(")");
15466
16007
  if (this.atKw("search") || this.atKw("cycle")) throw unsupported("WITH ... SEARCH/CYCLE");
15467
- ctes.push({ name, columns, query, materialized });
16008
+ ctes.push({ name: name2, columns, query, materialized });
15468
16009
  } while (this.eatPunct(","));
15469
16010
  return { recursive, ctes };
15470
16011
  }
@@ -15612,12 +16153,12 @@ var Parser = class {
15612
16153
  const windows = [];
15613
16154
  if (this.eatKw("window")) {
15614
16155
  do {
15615
- const name = this.ident();
16156
+ const name2 = this.ident();
15616
16157
  this.expectKw("as");
15617
16158
  this.expectPunct("(");
15618
16159
  const spec = this.parseWindowSpec();
15619
16160
  this.expectPunct(")");
15620
- windows.push({ name, spec });
16161
+ windows.push({ name: name2, spec });
15621
16162
  } while (this.eatPunct(","));
15622
16163
  }
15623
16164
  return { type: "select_core", distinct, targets, from, where, groupBy, groupDistinct, having, windows };
@@ -15860,7 +16401,7 @@ var Parser = class {
15860
16401
  }
15861
16402
  const only = this.eatKw("only");
15862
16403
  const save = this.pos;
15863
- const name = this.qualifiedName();
16404
+ const name2 = this.qualifiedName();
15864
16405
  if (this.atPunct("(")) {
15865
16406
  this.pos = save;
15866
16407
  const call = this.parseExpr();
@@ -15872,7 +16413,7 @@ var Parser = class {
15872
16413
  }
15873
16414
  const { alias, colAliases } = this.parseAliasClause();
15874
16415
  if (this.atKw("tablesample")) throw unsupported("TABLESAMPLE");
15875
- return { type: "from_table", name, only, alias, colAliases };
16416
+ return { type: "from_table", name: name2, only, alias, colAliases };
15876
16417
  }
15877
16418
  parseWithOrdinality() {
15878
16419
  if (this.atKw("with") && this.atKw("ordinality", 1)) {
@@ -16074,7 +16615,7 @@ var Parser = class {
16074
16615
  return sets;
16075
16616
  }
16076
16617
  parseSetColumn() {
16077
- const name = this.ident();
16618
+ const name2 = this.ident();
16078
16619
  let subscripts = null;
16079
16620
  const fields = [];
16080
16621
  while (this.atPunct("[") || this.atPunct(".")) {
@@ -16095,7 +16636,7 @@ var Parser = class {
16095
16636
  fields.push(this.ident(true));
16096
16637
  }
16097
16638
  }
16098
- return { name, subscripts, fields };
16639
+ return { name: name2, subscripts, fields };
16099
16640
  }
16100
16641
  parseUpdate(withClause) {
16101
16642
  this.expectKw("update");
@@ -16199,21 +16740,21 @@ var Parser = class {
16199
16740
  if (this.atKw("sequence")) {
16200
16741
  this.pos++;
16201
16742
  const ifNotExists = this.parseIfNotExists();
16202
- const name = this.qualifiedName();
16743
+ const name2 = this.qualifiedName();
16203
16744
  const options2 = this.parseSequenceOptions();
16204
- return { type: "create_sequence", name, ifNotExists, temp, unlogged, options: options2 };
16745
+ return { type: "create_sequence", name: name2, ifNotExists, temp, unlogged, options: options2 };
16205
16746
  }
16206
16747
  if (this.atKw("schema")) {
16207
16748
  this.pos++;
16208
16749
  const ifNotExists = this.parseIfNotExists();
16209
16750
  if (this.atKw("authorization")) throw unsupported("CREATE SCHEMA AUTHORIZATION");
16210
- const name = this.ident();
16751
+ const name2 = this.ident();
16211
16752
  if (!this.atPunct(";") && this.peek().type !== "eof") throw unsupported("CREATE SCHEMA with elements");
16212
- return { type: "create_schema", name, ifNotExists };
16753
+ return { type: "create_schema", name: name2, ifNotExists };
16213
16754
  }
16214
16755
  if (this.atKw("type")) {
16215
16756
  this.pos++;
16216
- const name = this.qualifiedName();
16757
+ const name2 = this.qualifiedName();
16217
16758
  this.expectKw("as");
16218
16759
  if (this.eatKw("enum")) {
16219
16760
  this.expectPunct("(");
@@ -16226,13 +16767,13 @@ var Parser = class {
16226
16767
  } while (this.eatPunct(","));
16227
16768
  }
16228
16769
  this.expectPunct(")");
16229
- return { type: "create_enum", name, labels };
16770
+ return { type: "create_enum", name: name2, labels };
16230
16771
  }
16231
16772
  throw unsupported("CREATE TYPE (non-enum)");
16232
16773
  }
16233
16774
  if (this.atKw("domain")) {
16234
16775
  this.pos++;
16235
- const name = this.qualifiedName();
16776
+ const name2 = this.qualifiedName();
16236
16777
  this.eatKw("as");
16237
16778
  const baseType = this.parseTypeName();
16238
16779
  let notNull = false;
@@ -16260,7 +16801,7 @@ var Parser = class {
16260
16801
  break;
16261
16802
  }
16262
16803
  }
16263
- return { type: "create_domain", name, baseType, notNull, defaultExpr, checks, collate };
16804
+ return { type: "create_domain", name: name2, baseType, notNull, defaultExpr, checks, collate };
16264
16805
  }
16265
16806
  if (this.atKw("function") || this.atKw("procedure")) {
16266
16807
  const isProc = this.atKw("procedure");
@@ -16277,7 +16818,7 @@ var Parser = class {
16277
16818
  if (this.atKw("extension")) {
16278
16819
  this.pos++;
16279
16820
  const ifNotExists = this.parseIfNotExists();
16280
- const name = this.ident(true);
16821
+ const name2 = this.ident(true);
16281
16822
  let schema = null;
16282
16823
  let version = null;
16283
16824
  let cascade = false;
@@ -16301,7 +16842,7 @@ var Parser = class {
16301
16842
  }
16302
16843
  throw unsupported("CREATE EXTENSION option");
16303
16844
  }
16304
- return { type: "create_extension", name, ifNotExists, schema, version, cascade };
16845
+ return { type: "create_extension", name: name2, ifNotExists, schema, version, cascade };
16305
16846
  }
16306
16847
  if (this.atKw("database")) throw unsupported("CREATE DATABASE");
16307
16848
  if (this.atKw("role") || this.atKw("user") || this.atKw("group")) throw unsupported("roles");
@@ -16333,7 +16874,7 @@ var Parser = class {
16333
16874
  }
16334
16875
  parseCreateTable(temp, unlogged) {
16335
16876
  const ifNotExists = this.parseIfNotExists();
16336
- const name = this.qualifiedName();
16877
+ const name2 = this.qualifiedName();
16337
16878
  if (this.atKw("as") || this.atPunct("(") === false && this.atKw("as")) {
16338
16879
  this.pos++;
16339
16880
  const query = this.parseSelectStmt();
@@ -16344,7 +16885,7 @@ var Parser = class {
16344
16885
  }
16345
16886
  return {
16346
16887
  type: "create_table_as",
16347
- name,
16888
+ name: name2,
16348
16889
  ifNotExists,
16349
16890
  temp,
16350
16891
  unlogged,
@@ -16384,7 +16925,7 @@ var Parser = class {
16384
16925
  }
16385
16926
  return {
16386
16927
  type: "create_table_as",
16387
- name,
16928
+ name: name2,
16388
16929
  ifNotExists,
16389
16930
  temp,
16390
16931
  unlogged,
@@ -16441,12 +16982,12 @@ var Parser = class {
16441
16982
  if (this.peek(-1).value === "delete") this.expectKw("rows");
16442
16983
  }
16443
16984
  if (this.eatKw("tablespace")) this.ident(true);
16444
- return { type: "create_table", name, ifNotExists, temp, unlogged, columns, constraints, likeClauses };
16985
+ return { type: "create_table", name: name2, ifNotExists, temp, unlogged, columns, constraints, likeClauses };
16445
16986
  }
16446
16987
  tryParseTableConstraint() {
16447
- let name = null;
16988
+ let name2 = null;
16448
16989
  const save = this.pos;
16449
- if (this.eatKw("constraint")) name = this.ident();
16990
+ if (this.eatKw("constraint")) name2 = this.ident();
16450
16991
  if (this.atKw("primary") && this.atKw("key", 1)) {
16451
16992
  this.pos += 2;
16452
16993
  this.expectPunct("(");
@@ -16456,7 +16997,7 @@ var Parser = class {
16456
16997
  } while (this.eatPunct(","));
16457
16998
  this.expectPunct(")");
16458
16999
  this.skipConstraintTail();
16459
- return { kind: "primary_key", name, columns };
17000
+ return { kind: "primary_key", name: name2, columns };
16460
17001
  }
16461
17002
  if (this.atKw("unique") && (this.atPunct("(", 1) || this.atKw("nulls", 1))) {
16462
17003
  this.pos++;
@@ -16473,7 +17014,7 @@ var Parser = class {
16473
17014
  } while (this.eatPunct(","));
16474
17015
  this.expectPunct(")");
16475
17016
  this.skipConstraintTail();
16476
- return { kind: "unique", name, columns, nullsNotDistinct };
17017
+ return { kind: "unique", name: name2, columns, nullsNotDistinct };
16477
17018
  }
16478
17019
  if (this.atKw("check") && this.atPunct("(", 1)) {
16479
17020
  this.pos++;
@@ -16486,7 +17027,7 @@ var Parser = class {
16486
17027
  noInherit = true;
16487
17028
  }
16488
17029
  this.skipConstraintTail();
16489
- return { kind: "check", name, expr, noInherit };
17030
+ return { kind: "check", name: name2, expr, noInherit };
16490
17031
  }
16491
17032
  if (this.atKw("foreign") && this.atKw("key", 1)) {
16492
17033
  this.pos += 2;
@@ -16508,7 +17049,7 @@ var Parser = class {
16508
17049
  }
16509
17050
  const { onDelete, onUpdate, match } = this.parseRefActions();
16510
17051
  this.skipConstraintTail();
16511
- return { kind: "foreign_key", name, columns, refTable, refColumns, onDelete, onUpdate, match };
17052
+ return { kind: "foreign_key", name: name2, columns, refTable, refColumns, onDelete, onUpdate, match };
16512
17053
  }
16513
17054
  if (this.atKw("exclude")) throw unsupported("EXCLUDE constraints");
16514
17055
  this.pos = save;
@@ -16578,7 +17119,7 @@ var Parser = class {
16578
17119
  this.errorAt(this.peek(), "expected referential action");
16579
17120
  }
16580
17121
  parseColumnDef() {
16581
- const name = this.ident();
17122
+ const name2 = this.ident();
16582
17123
  const typeName = this.parseTypeName();
16583
17124
  const constraints = [];
16584
17125
  for (; ; ) {
@@ -16683,7 +17224,7 @@ var Parser = class {
16683
17224
  if (cname !== null) this.errorAt(this.peek(), "expected column constraint");
16684
17225
  break;
16685
17226
  }
16686
- return { name, typeName, constraints };
17227
+ return { name: name2, typeName, constraints };
16687
17228
  }
16688
17229
  /** `STORAGE { PLAIN | EXTERNAL | EXTENDED | MAIN | DEFAULT }`: an identifier (not a string) or DEFAULT. */
16689
17230
  parseStorageMode() {
@@ -16781,11 +17322,11 @@ var Parser = class {
16781
17322
  }
16782
17323
  parseCreateIndex(unique) {
16783
17324
  const concurrently = this.eatKw("concurrently");
16784
- let name = null;
17325
+ let name2 = null;
16785
17326
  let ifNotExists = false;
16786
17327
  if (!this.atKw("on")) {
16787
17328
  ifNotExists = this.parseIfNotExists();
16788
- if (!this.atKw("on")) name = this.ident();
17329
+ if (!this.atKw("on")) name2 = this.ident();
16789
17330
  }
16790
17331
  this.expectKw("on");
16791
17332
  this.eatKw("only");
@@ -16846,7 +17387,7 @@ var Parser = class {
16846
17387
  return {
16847
17388
  type: "create_index",
16848
17389
  unique,
16849
- name,
17390
+ name: name2,
16850
17391
  ifNotExists,
16851
17392
  table,
16852
17393
  using,
@@ -16861,7 +17402,7 @@ var Parser = class {
16861
17402
  parseCreateView(orReplace, temp, materialized) {
16862
17403
  const ifNotExists = materialized ? this.parseIfNotExists() : false;
16863
17404
  void ifNotExists;
16864
- const name = this.qualifiedName();
17405
+ const name2 = this.qualifiedName();
16865
17406
  let columns = null;
16866
17407
  if (this.eatPunct("(")) {
16867
17408
  columns = [];
@@ -16896,10 +17437,10 @@ var Parser = class {
16896
17437
  this.expectKw("option");
16897
17438
  }
16898
17439
  }
16899
- return { type: "create_view", name, orReplace, temp, columns, query, materialized, withData };
17440
+ return { type: "create_view", name: name2, orReplace, temp, columns, query, materialized, withData };
16900
17441
  }
16901
17442
  parseCreateFunction(orReplace) {
16902
- const name = this.qualifiedName();
17443
+ const name2 = this.qualifiedName();
16903
17444
  this.expectPunct("(");
16904
17445
  const args2 = [];
16905
17446
  if (!this.atPunct(")")) {
@@ -17082,7 +17623,7 @@ var Parser = class {
17082
17623
  return {
17083
17624
  type: "create_function",
17084
17625
  orReplace,
17085
- name,
17626
+ name: name2,
17086
17627
  args: args2,
17087
17628
  returns,
17088
17629
  returnsTable,
@@ -17094,7 +17635,7 @@ var Parser = class {
17094
17635
  };
17095
17636
  }
17096
17637
  parseCreateTrigger(orReplace) {
17097
- const name = this.ident();
17638
+ const name2 = this.ident();
17098
17639
  let timing;
17099
17640
  if (this.eatKw("before")) timing = "before";
17100
17641
  else if (this.eatKw("after")) timing = "after";
@@ -17150,7 +17691,7 @@ var Parser = class {
17150
17691
  } while (this.eatPunct(","));
17151
17692
  }
17152
17693
  this.expectPunct(")");
17153
- return { type: "create_trigger", orReplace, name, timing, events, table, forEachRow, when, funcName, funcArgs };
17694
+ return { type: "create_trigger", orReplace, name: name2, timing, events, table, forEachRow, when, funcName, funcArgs };
17154
17695
  }
17155
17696
  // --- ALTER --------------------------------------------------------------------
17156
17697
  parseAlter() {
@@ -17167,14 +17708,14 @@ var Parser = class {
17167
17708
  }
17168
17709
  if (this.eatKw("sequence")) {
17169
17710
  const ifExists = this.parseIfExists();
17170
- const name = this.qualifiedName();
17711
+ const name2 = this.qualifiedName();
17171
17712
  if (this.atKw("rename")) {
17172
17713
  this.pos++;
17173
17714
  this.expectKw("to");
17174
17715
  const to = this.ident();
17175
17716
  return {
17176
17717
  type: "alter_sequence",
17177
- name,
17718
+ name: name2,
17178
17719
  ifExists,
17179
17720
  options: { ownedBy: void 0 },
17180
17721
  ...{ renameTo: to }
@@ -17182,10 +17723,10 @@ var Parser = class {
17182
17723
  }
17183
17724
  if (this.atKw("set") && (this.atKw("logged", 1) || this.atKw("unlogged", 1))) {
17184
17725
  this.pos++;
17185
- return { type: "alter_sequence", name, ifExists, options: { logged: this.next().value === "logged" } };
17726
+ return { type: "alter_sequence", name: name2, ifExists, options: { logged: this.next().value === "logged" } };
17186
17727
  }
17187
17728
  const options2 = this.parseSequenceOptions();
17188
- return { type: "alter_sequence", name, ifExists, options: options2 };
17729
+ return { type: "alter_sequence", name: name2, ifExists, options: options2 };
17189
17730
  }
17190
17731
  let isMatView = false;
17191
17732
  if (!this.atKw("view") && this.atKw("materialized") && this.atKw("view", 1)) {
@@ -17194,14 +17735,14 @@ var Parser = class {
17194
17735
  }
17195
17736
  if (isMatView || this.eatKw("view")) {
17196
17737
  const ifExists = this.parseIfExists();
17197
- const name = this.qualifiedName();
17738
+ const name2 = this.qualifiedName();
17198
17739
  if (this.eatKw("rename")) {
17199
17740
  this.expectKw("to");
17200
- return { type: "alter_view", name, ifExists, action: { kind: "rename_table", to: this.ident() } };
17741
+ return { type: "alter_view", name: name2, ifExists, action: { kind: "rename_table", to: this.ident() } };
17201
17742
  }
17202
17743
  if (this.eatKw("set")) {
17203
17744
  this.expectKw("schema");
17204
- return { type: "alter_view", name, ifExists, action: { kind: "set_schema", to: this.ident() } };
17745
+ return { type: "alter_view", name: name2, ifExists, action: { kind: "set_schema", to: this.ident() } };
17205
17746
  }
17206
17747
  if (this.eatKw("owner")) {
17207
17748
  this.expectKw("to");
@@ -17212,23 +17753,23 @@ var Parser = class {
17212
17753
  }
17213
17754
  if (this.eatKw("index")) {
17214
17755
  const ifExists = this.parseIfExists();
17215
- const name = this.qualifiedName();
17756
+ const name2 = this.qualifiedName();
17216
17757
  if (this.eatKw("rename")) {
17217
17758
  this.expectKw("to");
17218
- return { type: "alter_index", name, ifExists, action: { kind: "rename_table", to: this.ident() } };
17759
+ return { type: "alter_index", name: name2, ifExists, action: { kind: "rename_table", to: this.ident() } };
17219
17760
  }
17220
17761
  throw unsupported("this ALTER INDEX form");
17221
17762
  }
17222
17763
  if (this.eatKw("schema")) {
17223
- const name = this.ident();
17764
+ const name2 = this.ident();
17224
17765
  if (this.eatKw("rename")) {
17225
17766
  this.expectKw("to");
17226
- return { type: "alter_schema", name, action: { kind: "rename", to: this.ident() } };
17767
+ return { type: "alter_schema", name: name2, action: { kind: "rename", to: this.ident() } };
17227
17768
  }
17228
17769
  throw unsupported("this ALTER SCHEMA form");
17229
17770
  }
17230
17771
  if (this.eatKw("type")) {
17231
- const name = this.qualifiedName();
17772
+ const name2 = this.qualifiedName();
17232
17773
  if (this.eatKw("add")) {
17233
17774
  this.expectKw("value");
17234
17775
  const ifNotExists = this.parseIfNotExists();
@@ -17245,7 +17786,7 @@ var Parser = class {
17245
17786
  }
17246
17787
  return {
17247
17788
  type: "alter_enum",
17248
- name,
17789
+ name: name2,
17249
17790
  action: { kind: "add_value", label: t.value, ifNotExists, before, after }
17250
17791
  };
17251
17792
  }
@@ -17254,7 +17795,7 @@ var Parser = class {
17254
17795
  const from = this.next();
17255
17796
  this.expectKw("to");
17256
17797
  const to = this.next();
17257
- return { type: "alter_enum", name, action: { kind: "rename_value", from: from.value, to: to.value } };
17798
+ return { type: "alter_enum", name: name2, action: { kind: "rename_value", from: from.value, to: to.value } };
17258
17799
  }
17259
17800
  throw unsupported("this ALTER TYPE form");
17260
17801
  }
@@ -17289,17 +17830,17 @@ var Parser = class {
17289
17830
  if (this.eatKw("drop")) {
17290
17831
  if (this.eatKw("constraint")) {
17291
17832
  const ifExists2 = this.parseIfExists();
17292
- const name2 = this.ident();
17833
+ const name3 = this.ident();
17293
17834
  const cascade2 = this.eatKw("cascade");
17294
17835
  if (!cascade2) this.eatKw("restrict");
17295
- return { kind: "drop_constraint", name: name2, ifExists: ifExists2, cascade: cascade2 };
17836
+ return { kind: "drop_constraint", name: name3, ifExists: ifExists2, cascade: cascade2 };
17296
17837
  }
17297
17838
  this.eatKw("column");
17298
17839
  const ifExists = this.parseIfExists();
17299
- const name = this.ident();
17840
+ const name2 = this.ident();
17300
17841
  const cascade = this.eatKw("cascade");
17301
17842
  if (!cascade) this.eatKw("restrict");
17302
- return { kind: "drop_column", name, ifExists, cascade };
17843
+ return { kind: "drop_column", name: name2, ifExists, cascade };
17303
17844
  }
17304
17845
  if (this.eatKw("alter")) {
17305
17846
  this.eatKw("column");
@@ -17523,9 +18064,9 @@ var Parser = class {
17523
18064
  this.pos++;
17524
18065
  parts.push(this.ident(true));
17525
18066
  }
17526
- const name = parts.join(".");
18067
+ const name2 = parts.join(".");
17527
18068
  if (!this.eatKw("to") && !this.eatOp("=")) this.errorAt(this.peek(), "expected TO or =");
17528
- if (this.eatKw("default")) return { type: "set", name, value: null, local };
18069
+ if (this.eatKw("default")) return { type: "set", name: name2, value: null, local };
17529
18070
  const values = [];
17530
18071
  do {
17531
18072
  const t = this.next();
@@ -17537,7 +18078,7 @@ var Parser = class {
17537
18078
  this.errorAt(t, "expected value");
17538
18079
  }
17539
18080
  } while (this.eatPunct(","));
17540
- return { type: "set", name, value: values.join(", "), local };
18081
+ return { type: "set", name: name2, value: values.join(", "), local };
17541
18082
  }
17542
18083
  parseExplain() {
17543
18084
  this.expectKw("explain");
@@ -18458,7 +18999,7 @@ var Parser = class {
18458
18999
  this.expectPunct("]");
18459
19000
  return { type: "array_ctor", items };
18460
19001
  }
18461
- parseFuncCall(name) {
19002
+ parseFuncCall(name2) {
18462
19003
  this.expectPunct("(");
18463
19004
  let star = false;
18464
19005
  let distinct = false;
@@ -18528,7 +19069,7 @@ var Parser = class {
18528
19069
  const names = Object.keys(argNames).length > 0 ? args2.map((_, i) => argNames[i] ?? null) : void 0;
18529
19070
  return {
18530
19071
  type: "func",
18531
- name,
19072
+ name: name2,
18532
19073
  args: args2,
18533
19074
  star,
18534
19075
  distinct,
@@ -18541,10 +19082,10 @@ var Parser = class {
18541
19082
  };
18542
19083
  }
18543
19084
  parseWindowSpec() {
18544
- let name;
19085
+ let name2;
18545
19086
  const t = this.peek();
18546
19087
  if (t.type === "ident" && !RESERVED.has(t.value) && !["partition", "order", "range", "rows", "groups"].includes(t.value) || t.type === "quoted_ident") {
18547
- name = this.ident();
19088
+ name2 = this.ident();
18548
19089
  }
18549
19090
  const partitionBy = [];
18550
19091
  if (this.eatKw("partition")) {
@@ -18583,7 +19124,7 @@ var Parser = class {
18583
19124
  }
18584
19125
  frame = { mode, start: start3, end, exclusion };
18585
19126
  }
18586
- return { name, partitionBy, orderBy, frame };
19127
+ return { name: name2, partitionBy, orderBy, frame };
18587
19128
  }
18588
19129
  parseFrameBound() {
18589
19130
  if (this.eatKw("unbounded")) {
@@ -18658,7 +19199,7 @@ var PlParser = class {
18658
19199
  if (nameTok.type !== "ident" && nameTok.type !== "quoted_ident") {
18659
19200
  throw unsupported(`plpgsql DECLARE near "${nameTok.value}"`);
18660
19201
  }
18661
- const name = nameTok.value;
19202
+ const name2 = nameTok.value;
18662
19203
  const typeStart = this.peek().pos;
18663
19204
  while (!(this.peek().type === "punct" && this.peek().value === ";") && !(this.peek().type === "op" && (this.peek().value === ":=" || this.peek().value === "=")) && this.peek().type !== "eof") {
18664
19205
  this.pos++;
@@ -18672,7 +19213,7 @@ var PlParser = class {
18672
19213
  } else {
18673
19214
  this.expectSemi();
18674
19215
  }
18675
- return { name, typeName, init };
19216
+ return { name: name2, typeName, init };
18676
19217
  }
18677
19218
  parseBlock() {
18678
19219
  this.expectKw("begin");
@@ -18943,10 +19484,10 @@ var PlVars = class {
18943
19484
  names = [];
18944
19485
  types = [];
18945
19486
  values = [];
18946
- declare(name, type, value) {
18947
- const i = this.names.indexOf(name);
19487
+ declare(name2, type, value) {
19488
+ const i = this.names.indexOf(name2);
18948
19489
  if (i === -1) {
18949
- this.names.push(name);
19490
+ this.names.push(name2);
18950
19491
  this.types.push(type);
18951
19492
  this.values.push(value);
18952
19493
  } else {
@@ -18954,14 +19495,14 @@ var PlVars = class {
18954
19495
  this.values[i] = value;
18955
19496
  }
18956
19497
  }
18957
- set(name, v, env) {
18958
- const i = this.names.indexOf(name);
18959
- if (i === -1) throw pgError("undefined_column", `"${name}" is not a known variable`, "42703");
19498
+ set(name2, v, env) {
19499
+ const i = this.names.indexOf(name2);
19500
+ if (i === -1) throw pgError("undefined_column", `"${name2}" is not a known variable`, "42703");
18960
19501
  const casted = v.v === null ? tv(this.types[i], null) : castTo(env.ctx, v, this.types[i], { assignment: true });
18961
19502
  this.values[i] = casted.v;
18962
19503
  }
18963
- get(name) {
18964
- const i = this.names.indexOf(name);
19504
+ get(name2) {
19505
+ const i = this.names.indexOf(name2);
18965
19506
  if (i === -1) return void 0;
18966
19507
  return tv(this.types[i], this.values[i] ?? null);
18967
19508
  }
@@ -19190,8 +19731,8 @@ var WINDOW_FUNCTION_NAMES = /* @__PURE__ */ new Set([
19190
19731
  "last_value",
19191
19732
  "nth_value"
19192
19733
  ]);
19193
- function isWindowFunctionName(name) {
19194
- return WINDOW_FUNCTION_NAMES.has(name);
19734
+ function isWindowFunctionName(name2) {
19735
+ return WINDOW_FUNCTION_NAMES.has(name2);
19195
19736
  }
19196
19737
 
19197
19738
  // src/executor/window.ts
@@ -19272,17 +19813,17 @@ function computePartition(ctx, call, spec, rowIdxs, evalAt, results) {
19272
19813
  peerGroup[pos] = group;
19273
19814
  }
19274
19815
  const groupCount = n === 0 ? 0 : peerGroup[n - 1] + 1;
19275
- const name = call.name[call.name.length - 1];
19276
- if (isWindowFunctionName(name)) {
19277
- computeRankingFunction(ctx, name, call, rowIdxs, peerGroup, groupCount, evalAt, results, spec);
19816
+ const name2 = call.name[call.name.length - 1];
19817
+ if (isWindowFunctionName(name2)) {
19818
+ computeRankingFunction(ctx, name2, call, rowIdxs, peerGroup, groupCount, evalAt, results, spec);
19278
19819
  return;
19279
19820
  }
19280
- if (!isAggregateName(name)) {
19281
- throw pgError("undefined_function", `function ${name} does not exist as a window function`, "42883");
19821
+ if (!isAggregateName(name2)) {
19822
+ throw pgError("undefined_function", `function ${name2} does not exist as a window function`, "42883");
19282
19823
  }
19283
19824
  const frame = spec.frame ?? defaultFrame(spec);
19284
- if (!call.filter && (name === "sum" || name === "count") && isRunningRowsFrame(frame, spec)) {
19285
- computeRunningAgg(ctx, call, name, rowIdxs, evalAt, results);
19825
+ if (!call.filter && (name2 === "sum" || name2 === "count") && isRunningRowsFrame(frame, spec)) {
19826
+ computeRunningAgg(ctx, call, name2, rowIdxs, evalAt, results);
19286
19827
  return;
19287
19828
  }
19288
19829
  for (let pos = 0; pos < n; pos++) {
@@ -19307,7 +19848,7 @@ function computePartition(ctx, call, spec, rowIdxs, evalAt, results) {
19307
19848
  }
19308
19849
  return UNKNOWN;
19309
19850
  });
19310
- const acc = createAggregate(ctx, name, argTypes);
19851
+ const acc = createAggregate(ctx, name2, argTypes);
19311
19852
  for (const r of argRows) acc.step(r);
19312
19853
  results[rowIdxs[pos]] = acc.result();
19313
19854
  }
@@ -19342,7 +19883,7 @@ function isRunningRowsFrame(frame, spec) {
19342
19883
  const end = frame.end ?? (spec.orderBy.length > 0 ? { kind: "current_row" } : { kind: "unbounded_following" });
19343
19884
  return end.kind === "current_row";
19344
19885
  }
19345
- function computeRunningAgg(ctx, call, name, rowIdxs, evalAt, results) {
19886
+ function computeRunningAgg(ctx, call, name2, rowIdxs, evalAt, results) {
19346
19887
  const argTypes = call.args.map((_, ai) => {
19347
19888
  for (const rowIdx of rowIdxs) {
19348
19889
  const v = evalAt(rowIdx, call.args[ai]);
@@ -19350,7 +19891,7 @@ function computeRunningAgg(ctx, call, name, rowIdxs, evalAt, results) {
19350
19891
  }
19351
19892
  return UNKNOWN;
19352
19893
  });
19353
- const acc = createAggregate(ctx, name, argTypes);
19894
+ const acc = createAggregate(ctx, name2, argTypes);
19354
19895
  for (const rowIdx of rowIdxs) {
19355
19896
  const argRows = call.star ? [] : call.args.map((a) => evalAt(rowIdx, a));
19356
19897
  acc.step(argRows);
@@ -19466,9 +20007,9 @@ function boundPos(ctx, mode, bound, isStart, pos, rowIdxs, peerGroup, _keys, spe
19466
20007
  }
19467
20008
  }
19468
20009
  }
19469
- function computeRankingFunction(ctx, name, call, rowIdxs, peerGroup, _groupCount, evalAt, results, spec) {
20010
+ function computeRankingFunction(ctx, name2, call, rowIdxs, peerGroup, _groupCount, evalAt, results, spec) {
19470
20011
  const n = rowIdxs.length;
19471
- switch (name) {
20012
+ switch (name2) {
19472
20013
  case "row_number": {
19473
20014
  for (let pos = 0; pos < n; pos++) results[rowIdxs[pos]] = tv("int8", BigInt(pos + 1));
19474
20015
  return;
@@ -19534,7 +20075,7 @@ function computeRankingFunction(ctx, name, call, rowIdxs, peerGroup, _groupCount
19534
20075
  }
19535
20076
  case "lag":
19536
20077
  case "lead": {
19537
- const dir = name === "lag" ? -1 : 1;
20078
+ const dir = name2 === "lag" ? -1 : 1;
19538
20079
  for (let pos = 0; pos < n; pos++) {
19539
20080
  const cur = evalAt(rowIdxs[pos], call.args[0]);
19540
20081
  const offset = call.args[1] ? Number(castTo(ctx, evalAt(rowIdxs[pos], call.args[1]), "int4", {}).v) : 1;
@@ -19571,8 +20112,8 @@ function computeRankingFunction(ctx, name, call, rowIdxs, peerGroup, _groupCount
19571
20112
  continue;
19572
20113
  }
19573
20114
  let targetPos;
19574
- if (name === "first_value") targetPos = included[0];
19575
- else if (name === "last_value") targetPos = included[included.length - 1];
20115
+ if (name2 === "first_value") targetPos = included[0];
20116
+ else if (name2 === "last_value") targetPos = included[included.length - 1];
19576
20117
  else {
19577
20118
  const nth = Number(castTo(ctx, evalAt(rowIdxs[pos], call.args[1]), "int4", {}).v);
19578
20119
  if (nth <= 0)
@@ -19584,7 +20125,7 @@ function computeRankingFunction(ctx, name, call, rowIdxs, peerGroup, _groupCount
19584
20125
  return;
19585
20126
  }
19586
20127
  default:
19587
- throw pgError("undefined_function", `window function ${name} is not implemented`, "42883");
20128
+ throw pgError("undefined_function", `window function ${name2} is not implemented`, "42883");
19588
20129
  }
19589
20130
  }
19590
20131
 
@@ -19677,9 +20218,9 @@ function makeEvalScope(env, scope, extras) {
19677
20218
  groupingValue(node) {
19678
20219
  return extras?.groupingValue?.(node);
19679
20220
  },
19680
- callUserFunction(name, args2, node) {
20221
+ callUserFunction(name2, args2, node) {
19681
20222
  void node;
19682
- const fn = resolveUserFunctionForArgs(env, name, args2);
20223
+ const fn = resolveUserFunctionForArgs(env, name2, args2);
19683
20224
  if (!fn) return void 0;
19684
20225
  return callSqlFunctionScalar(env, fn, args2);
19685
20226
  },
@@ -19693,8 +20234,8 @@ function evalPredicate(env, scope, e, extras, kind = "WHERE") {
19693
20234
  const v = evalScalar(env, scope, e, extras);
19694
20235
  return evalAsPredicate(env.ctx, kind, v);
19695
20236
  }
19696
- function resolveUserFunctionForArgs(env, name, args2) {
19697
- const candidates = env.ctx.state.findFunctions(name);
20237
+ function resolveUserFunctionForArgs(env, name2, args2) {
20238
+ const candidates = env.ctx.state.findFunctions(name2);
19698
20239
  for (const fn of candidates) {
19699
20240
  const required = fn.argDefaults.filter((d) => d === null).length;
19700
20241
  if (args2.length < required || args2.length > fn.argTypes.length) continue;
@@ -19803,13 +20344,13 @@ function callSqlFunctionSet(env, fn, args2) {
19803
20344
  });
19804
20345
  return { columns: [{ name: fn.name, type: retT, table: null }], rows };
19805
20346
  }
19806
- function referencesRelation(node, name) {
20347
+ function referencesRelation(node, name2) {
19807
20348
  if (!node || typeof node !== "object") return false;
19808
- if (Array.isArray(node)) return node.some((n) => referencesRelation(n, name));
20349
+ if (Array.isArray(node)) return node.some((n) => referencesRelation(n, name2));
19809
20350
  const o = node;
19810
- if (o.type === "from_table" && Array.isArray(o.name) && o.name.length === 1 && o.name[0] === name) return true;
20351
+ if (o.type === "from_table" && Array.isArray(o.name) && o.name.length === 1 && o.name[0] === name2) return true;
19811
20352
  for (const k of Object.keys(o)) {
19812
- if (referencesRelation(o[k], name)) return true;
20353
+ if (referencesRelation(o[k], name2)) return true;
19813
20354
  }
19814
20355
  return false;
19815
20356
  }
@@ -20178,9 +20719,9 @@ function joinSideOf(expr, left, right) {
20178
20719
  };
20179
20720
  for (const ref of refs) {
20180
20721
  const alias = ref.parts.length >= 2 ? ref.parts[ref.parts.length - 2] : null;
20181
- const name = ref.parts[ref.parts.length - 1];
20182
- const inLeft = alias ? left.columns.some((c) => c.table === alias) : left.columns.some((c) => !c.hidden && c.name === name);
20183
- const inRight = alias ? right.columns.some((c) => c.table === alias) : right.columns.some((c) => !c.hidden && c.name === name);
20722
+ const name2 = ref.parts[ref.parts.length - 1];
20723
+ const inLeft = alias ? left.columns.some((c) => c.table === alias) : left.columns.some((c) => !c.hidden && c.name === name2);
20724
+ const inRight = alias ? right.columns.some((c) => c.table === alias) : right.columns.some((c) => !c.hidden && c.name === name2);
20184
20725
  if (inLeft && !inRight) fold("left");
20185
20726
  else if (inRight && !inLeft) fold("right");
20186
20727
  else fold("mixed");
@@ -20475,7 +21016,7 @@ function collectCalls(e, out) {
20475
21016
  if (!e || typeof e !== "object") return;
20476
21017
  if (e.type === "subquery_expr") return;
20477
21018
  if (e.type === "func") {
20478
- const name = e.name[e.name.length - 1];
21019
+ const name2 = e.name[e.name.length - 1];
20479
21020
  if (e.over) {
20480
21021
  if (!out.windows.includes(e)) out.windows.push(e);
20481
21022
  for (const a of e.args) collectCalls(a, out);
@@ -20484,7 +21025,7 @@ function collectCalls(e, out) {
20484
21025
  for (const ob of e.over.orderBy ?? []) collectCalls(ob.expr, out);
20485
21026
  return;
20486
21027
  }
20487
- if (isAggregateName(name)) {
21028
+ if (isAggregateName(name2)) {
20488
21029
  if (!out.aggs.includes(e)) out.aggs.push(e);
20489
21030
  if (e.filter) collectCalls(e.filter, out);
20490
21031
  return;
@@ -20587,11 +21128,11 @@ function expandGroupItems(items, targets, canResolve) {
20587
21128
  }
20588
21129
  function resolveColIdx(columns, parts) {
20589
21130
  if (parts.length === 1) {
20590
- const name2 = parts[0];
21131
+ const name3 = parts[0];
20591
21132
  let found = -1;
20592
21133
  for (let i = 0; i < columns.length; i++) {
20593
21134
  const c = columns[i];
20594
- if (!c.hidden && c.name === name2) {
21135
+ if (!c.hidden && c.name === name3) {
20595
21136
  if (found !== -1) return null;
20596
21137
  found = i;
20597
21138
  }
@@ -20599,10 +21140,10 @@ function resolveColIdx(columns, parts) {
20599
21140
  return found === -1 ? null : found;
20600
21141
  }
20601
21142
  const table = parts[parts.length - 2];
20602
- const name = parts[parts.length - 1];
21143
+ const name2 = parts[parts.length - 1];
20603
21144
  for (let i = 0; i < columns.length; i++) {
20604
21145
  const c = columns[i];
20605
- if (c.table === table && c.name === name) return i;
21146
+ if (c.table === table && c.name === name2) return i;
20606
21147
  }
20607
21148
  return null;
20608
21149
  }
@@ -20653,7 +21194,7 @@ function validateGroupedExpr(e, groupDefs, columns, inAgg) {
20653
21194
  for (const a of e.args) validateGroupedExpr(a, groupDefs, columns, inAgg);
20654
21195
  return;
20655
21196
  case "func": {
20656
- const name = e.name[e.name.length - 1];
21197
+ const name2 = e.name[e.name.length - 1];
20657
21198
  if (e.over) {
20658
21199
  for (const a of e.args) validateGroupedExpr(a, groupDefs, columns, false);
20659
21200
  if (e.filter) validateGroupedExpr(e.filter, groupDefs, columns, false);
@@ -20661,7 +21202,7 @@ function validateGroupedExpr(e, groupDefs, columns, inAgg) {
20661
21202
  for (const ob of e.over.orderBy ?? []) validateGroupedExpr(ob.expr, groupDefs, columns, false);
20662
21203
  return;
20663
21204
  }
20664
- if (isAggregateName(name)) {
21205
+ if (isAggregateName(name2)) {
20665
21206
  for (const a of e.args) validateGroupedExpr(a, groupDefs, columns, true);
20666
21207
  if (e.filter) validateGroupedExpr(e.filter, groupDefs, columns, true);
20667
21208
  for (const ob of e.orderBy ?? []) validateGroupedExpr(ob.expr, groupDefs, columns, true);
@@ -20799,8 +21340,8 @@ function validateGroupedQuery(core, groupDefs, columns, orderBy = []) {
20799
21340
  }
20800
21341
  function computeAggregate(env, call, rows, probeScope) {
20801
21342
  const ctx = env.ctx;
20802
- const name = call.name[call.name.length - 1];
20803
- const orderedSet = isOrderedSetAggregate(name);
21343
+ const name2 = call.name[call.name.length - 1];
21344
+ const orderedSet = isOrderedSetAggregate(name2);
20804
21345
  const orderBy = orderedSet ? call.withinGroupOrderBy ?? [] : call.orderBy ?? [];
20805
21346
  const tuples = [];
20806
21347
  for (const rscope of rows) {
@@ -20895,7 +21436,7 @@ function computeAggregate(env, call, rows, probeScope) {
20895
21436
  argTypes[i] = v.t === UNKNOWN ? "text" : v.t;
20896
21437
  }
20897
21438
  }
20898
- const acc = createAggregate(ctx, name, argTypes);
21439
+ const acc = createAggregate(ctx, name2, argTypes);
20899
21440
  for (const t of effective) acc.step(t.args);
20900
21441
  return acc.result();
20901
21442
  }
@@ -20971,11 +21512,11 @@ function orderPosition(e, rel3) {
20971
21512
  return v.i;
20972
21513
  }
20973
21514
  if (e.type === "colref" && e.parts.length === 1) {
20974
- const name = e.parts[0];
20975
- const matches2 = visible.filter(({ c }) => c.name === name);
21515
+ const name2 = e.parts[0];
21516
+ const matches2 = visible.filter(({ c }) => c.name === name2);
20976
21517
  if (matches2.length === 1) return matches2[0].i;
20977
21518
  if (matches2.length > 1) {
20978
- throw pgError("ambiguous_column", `ORDER BY "${name}" is ambiguous`, "42702");
21519
+ throw pgError("ambiguous_column", `ORDER BY "${name2}" is ambiguous`, "42702");
20979
21520
  }
20980
21521
  }
20981
21522
  return null;
@@ -21193,9 +21734,9 @@ function expandTargets(core, columns) {
21193
21734
  }
21194
21735
  continue;
21195
21736
  }
21196
- const name = t.alias ?? inferColumnName(t.expr);
21737
+ const name2 = t.alias ?? inferColumnName(t.expr);
21197
21738
  const isSrf = t.expr.type === "func" && !t.expr.over && t.expr.name.length === 1 && isSrfName(t.expr.name[0]) && !isAggregateName(t.expr.name[0]);
21198
- items.push({ name, kind: isSrf ? "srf" : "expr", colIdx: -1, expr: t.expr, hidden: false });
21739
+ items.push({ name: name2, kind: isSrf ? "srf" : "expr", colIdx: -1, expr: t.expr, hidden: false });
21199
21740
  }
21200
21741
  return items;
21201
21742
  }
@@ -21386,8 +21927,8 @@ function executeCore(env0, core, orderBy, opts) {
21386
21927
  continue;
21387
21928
  }
21388
21929
  if (ob.expr.type === "colref" && ob.expr.parts.length === 1) {
21389
- const name = ob.expr.parts[0];
21390
- const matches2 = projItems.map((p, i) => ({ p, i })).filter(({ p }) => !p.hidden && p.name === name);
21930
+ const name2 = ob.expr.parts[0];
21931
+ const matches2 = projItems.map((p, i) => ({ p, i })).filter(({ p }) => !p.hidden && p.name === name2);
21391
21932
  if (matches2.length === 1) {
21392
21933
  sortSpecs.push({ colIdx: matches2[0].i, dir, nullsFirst });
21393
21934
  continue;
@@ -21395,7 +21936,7 @@ function executeCore(env0, core, orderBy, opts) {
21395
21936
  if (matches2.length > 1) {
21396
21937
  const idx = resolveColIdx(srcCols, ob.expr.parts);
21397
21938
  if (idx === null) {
21398
- throw pgError("ambiguous_column", `ORDER BY "${name}" is ambiguous`, "42702");
21939
+ throw pgError("ambiguous_column", `ORDER BY "${name2}" is ambiguous`, "42702");
21399
21940
  }
21400
21941
  }
21401
21942
  }
@@ -21531,10 +22072,10 @@ function executeCore(env0, core, orderBy, opts) {
21531
22072
  return resolveTypeName(ctx.state, expr.target).column.id;
21532
22073
  }
21533
22074
  if (expr.type === "func") {
21534
- const name = expr.name[expr.name.length - 1];
21535
- if (isAggregateName(name)) {
22075
+ const name2 = expr.name[expr.name.length - 1];
22076
+ if (isAggregateName(name2)) {
21536
22077
  const argTypes = expr.args.map((a) => probeType(a));
21537
- return createAggregate(ctx, name, argTypes).result().t;
22078
+ return createAggregate(ctx, name2, argTypes).result().t;
21538
22079
  }
21539
22080
  }
21540
22081
  return evalScalar(env, probeScope, expr, probeExtras).t;
@@ -21910,18 +22451,18 @@ function evalReturning(env, table, label, targets, rows, command2) {
21910
22451
  function insertTargetColumns(env, table, stmt) {
21911
22452
  if (stmt.columns) {
21912
22453
  const seen = /* @__PURE__ */ new Set();
21913
- return stmt.columns.map((name) => {
21914
- const i = table.columnIndex(name);
22454
+ return stmt.columns.map((name2) => {
22455
+ const i = table.columnIndex(name2);
21915
22456
  if (i === -1) {
21916
- throw pgError("undefined_column", `column "${name}" of relation "${table.name}" does not exist`, "42703");
22457
+ throw pgError("undefined_column", `column "${name2}" of relation "${table.name}" does not exist`, "42703");
21917
22458
  }
21918
- if (seen.has(name)) {
21919
- throw pgError("duplicate_column", `column "${name}" specified more than once`, "42701");
22459
+ if (seen.has(name2)) {
22460
+ throw pgError("duplicate_column", `column "${name2}" specified more than once`, "42701");
21920
22461
  }
21921
- seen.add(name);
22462
+ seen.add(name2);
21922
22463
  const col = table.columns[i];
21923
22464
  if (col.generated) {
21924
- throw pgError("generated_always", `cannot insert a non-DEFAULT value into column "${name}"`, "428C9");
22465
+ throw pgError("generated_always", `cannot insert a non-DEFAULT value into column "${name2}"`, "428C9");
21925
22466
  }
21926
22467
  return i;
21927
22468
  });
@@ -21972,10 +22513,10 @@ function resolveArbiters(env, table, clause) {
21972
22513
  throw pgError("syntax", "ON CONFLICT DO UPDATE requires inference specification or constraint name", "42601");
21973
22514
  }
21974
22515
  if ("constraint" in clause.target) {
21975
- const name = clause.target.constraint;
21976
- const spec = specs.find((s) => s.name === name);
22516
+ const name2 = clause.target.constraint;
22517
+ const spec = specs.find((s) => s.name === name2);
21977
22518
  if (!spec) {
21978
- throw pgError("undefined_object", `constraint "${name}" for table "${table.name}" does not exist`, "42704");
22519
+ throw pgError("undefined_object", `constraint "${name2}" for table "${table.name}" does not exist`, "42704");
21979
22520
  }
21980
22521
  return [{ spec }];
21981
22522
  }
@@ -22458,11 +22999,11 @@ function getDefaultSettings() {
22458
22999
  }
22459
23000
  return defaultSettings;
22460
23001
  }
22461
- function resetValue(state, name) {
22462
- return state.settingDefaults?.get(name) ?? getDefaultSettings().get(name);
23002
+ function resetValue(state, name2) {
23003
+ return state.settingDefaults?.get(name2) ?? getDefaultSettings().get(name2);
22463
23004
  }
22464
- function canonicalGucName(name) {
22465
- const n = name.toLowerCase();
23005
+ function canonicalGucName(name2) {
23006
+ const n = name2.toLowerCase();
22466
23007
  if (n === "time zone" || n === "timezone") return "timezone";
22467
23008
  if (n === "session characteristics as transaction isolation level") return "transaction_isolation";
22468
23009
  return n;
@@ -22479,13 +23020,13 @@ function showColumnName(guc) {
22479
23020
  return guc;
22480
23021
  }
22481
23022
  }
22482
- function isKnownGuc(name) {
22483
- return getDefaultSettings().has(name) || name.includes(".");
23023
+ function isKnownGuc(name2) {
23024
+ return getDefaultSettings().has(name2) || name2.includes(".");
22484
23025
  }
22485
23026
  function executeSet(env, stmt) {
22486
23027
  const state = env.ctx.state;
22487
- const name = canonicalGucName(stmt.name);
22488
- if (!isKnownGuc(name) && !state.settings.has(name)) {
23028
+ const name2 = canonicalGucName(stmt.name);
23029
+ if (!isKnownGuc(name2) && !state.settings.has(name2)) {
22489
23030
  throw pgError("undefined_object", `unrecognized configuration parameter "${stmt.name}"`, "42704");
22490
23031
  }
22491
23032
  const target = stmt.local ? state.localSettings : state.settings;
@@ -22493,18 +23034,18 @@ function executeSet(env, stmt) {
22493
23034
  return commandResult("SET", 0);
22494
23035
  }
22495
23036
  if (stmt.value === null) {
22496
- const dflt = resetValue(state, name);
22497
- if (dflt !== void 0) target.set(name, dflt);
22498
- else target.delete(name);
23037
+ const dflt = resetValue(state, name2);
23038
+ if (dflt !== void 0) target.set(name2, dflt);
23039
+ else target.delete(name2);
22499
23040
  return commandResult("SET", 0);
22500
23041
  }
22501
- target.set(name, stmt.value);
23042
+ target.set(name2, stmt.value);
22502
23043
  return commandResult("SET", 0);
22503
23044
  }
22504
23045
  function executeShow(env, stmt) {
22505
23046
  const state = env.ctx.state;
22506
- const name = canonicalGucName(stmt.name);
22507
- if (name === "all") {
23047
+ const name2 = canonicalGucName(stmt.name);
23048
+ if (name2 === "all") {
22508
23049
  const rows = [...state.settings.entries()].sort((a, b) => a[0] < b[0] ? -1 : 1).map(([k, v]) => [k, state.localSettings.get(k) ?? v, ""]);
22509
23050
  return {
22510
23051
  columns: [
@@ -22517,12 +23058,12 @@ function executeShow(env, stmt) {
22517
23058
  rowCount: rows.length
22518
23059
  };
22519
23060
  }
22520
- const value = state.getSetting(name);
23061
+ const value = state.getSetting(name2);
22521
23062
  if (value === void 0) {
22522
23063
  throw pgError("undefined_object", `unrecognized configuration parameter "${stmt.name}"`, "42704");
22523
23064
  }
22524
23065
  return {
22525
- columns: [{ name: showColumnName(name), type: "text" }],
23066
+ columns: [{ name: showColumnName(name2), type: "text" }],
22526
23067
  rows: [[value]],
22527
23068
  command: "SHOW",
22528
23069
  rowCount: 1
@@ -22530,19 +23071,19 @@ function executeShow(env, stmt) {
22530
23071
  }
22531
23072
  function executeReset(env, stmt) {
22532
23073
  const state = env.ctx.state;
22533
- const name = canonicalGucName(stmt.name);
22534
- if (name === "all") {
23074
+ const name2 = canonicalGucName(stmt.name);
23075
+ if (name2 === "all") {
22535
23076
  state.settings = new Map([...getDefaultSettings(), ...state.settingDefaults ?? []]);
22536
23077
  state.localSettings.clear();
22537
23078
  return commandResult("RESET", 0);
22538
23079
  }
22539
- if (!isKnownGuc(name) && !state.settings.has(name)) {
23080
+ if (!isKnownGuc(name2) && !state.settings.has(name2)) {
22540
23081
  throw pgError("undefined_object", `unrecognized configuration parameter "${stmt.name}"`, "42704");
22541
23082
  }
22542
- const dflt = resetValue(state, name);
22543
- if (dflt !== void 0) state.settings.set(name, dflt);
22544
- else state.settings.delete(name);
22545
- state.localSettings.delete(name);
23083
+ const dflt = resetValue(state, name2);
23084
+ if (dflt !== void 0) state.settings.set(name2, dflt);
23085
+ else state.settings.delete(name2);
23086
+ state.localSettings.delete(name2);
22546
23087
  return commandResult("RESET", 0);
22547
23088
  }
22548
23089
  function executePrepare(env, stmt) {
@@ -22820,9 +23361,9 @@ var EngineCtx = class {
22820
23361
  timezone() {
22821
23362
  return this.state.getSetting("timezone") ?? "UTC";
22822
23363
  }
22823
- namespaceOid(name) {
22824
- const oid = builtinNamespaceOid(name) ?? this.state.schemas.get(name)?.oid;
22825
- if (oid === void 0) throw pgError("undefined_object", `schema "${name}" does not exist`, "3F000");
23364
+ namespaceOid(name2) {
23365
+ const oid = builtinNamespaceOid(name2) ?? this.state.schemas.get(name2)?.oid;
23366
+ if (oid === void 0) throw pgError("undefined_object", `schema "${name2}" does not exist`, "3F000");
22826
23367
  return oid;
22827
23368
  }
22828
23369
  namespaceName(oid) {
@@ -23002,8 +23543,8 @@ function formatType2(ctx, id, mod) {
23002
23543
  if (isArrayType(id)) return `${formatType2(ctx, arrayElemType(id), mod)}[]`;
23003
23544
  if (isEnumType(id)) {
23004
23545
  const [schema, ...rest] = enumTypeName(id).split(".");
23005
- const name = quoteIdent(rest.join("."));
23006
- return ctx.state.effectiveSearchPath().includes(schema ?? "") ? name : `${quoteIdent(schema ?? "")}.${name}`;
23546
+ const name2 = quoteIdent(rest.join("."));
23547
+ return ctx.state.effectiveSearchPath().includes(schema ?? "") ? name2 : `${quoteIdent(schema ?? "")}.${name2}`;
23007
23548
  }
23008
23549
  const a = mod?.a;
23009
23550
  switch (id) {
@@ -23048,10 +23589,10 @@ function typedConst(ctx, type, value) {
23048
23589
  }
23049
23590
  function regclassConst(ctx, raw) {
23050
23591
  const parts = raw.split(".").map((p) => p.startsWith('"') && p.endsWith('"') ? p.slice(1, -1) : p.toLowerCase());
23051
- const name = parts[parts.length - 1] ?? raw;
23592
+ const name2 = parts[parts.length - 1] ?? raw;
23052
23593
  const schema = parts.length > 1 ? parts[parts.length - 2] : null;
23053
- const visible = ctx.state.resolveRelationSchema([name])?.schema;
23054
- const shown = schema === null || visible === schema ? quoteIdent(name) : `${quoteIdent(schema)}.${quoteIdent(name)}`;
23594
+ const visible = ctx.state.resolveRelationSchema([name2])?.schema;
23595
+ const shown = schema === null || visible === schema ? quoteIdent(name2) : `${quoteIdent(schema)}.${quoteIdent(name2)}`;
23055
23596
  return { sql: `${quoteLiteral2(shown)}::regclass`, type: "regclass" };
23056
23597
  }
23057
23598
  function resolveUnknown(ctx, node, type) {
@@ -23150,8 +23691,8 @@ function bareFunctionName(e) {
23150
23691
  if (e.name.length === 1) return e.name[0];
23151
23692
  return e.name.length === 2 && e.name[0] === "pg_catalog" ? e.name[1] : null;
23152
23693
  }
23153
- function findSignature(name, argc) {
23154
- for (const spec of SIGNATURES[name] ?? []) {
23694
+ function findSignature(name2, argc) {
23695
+ for (const spec of SIGNATURES[name2] ?? []) {
23155
23696
  const [left, result] = spec.split("->");
23156
23697
  const params = left === "" ? [] : left.split(",");
23157
23698
  const variadic = params[params.length - 1] === "*any";
@@ -23164,22 +23705,22 @@ function unify(ctx, nodes) {
23164
23705
  return { nodes: nodes.map((n) => resolveUnknown(ctx, n, type)), type };
23165
23706
  }
23166
23707
  function analyzeFunc(ctx, e) {
23167
- const name = bareFunctionName(e);
23168
- if (name === null || e.star || e.distinct || e.over || e.filter || (e.orderBy?.length ?? 0) > 0) {
23708
+ const name2 = bareFunctionName(e);
23709
+ if (name2 === null || e.star || e.distinct || e.over || e.filter || (e.orderBy?.length ?? 0) > 0) {
23169
23710
  return { sql: deparseExpr(e), type: null };
23170
23711
  }
23171
- const sqlValueType = e.name.length === 2 ? SQL_VALUE_FUNCTIONS[name] : void 0;
23712
+ const sqlValueType = e.name.length === 2 ? SQL_VALUE_FUNCTIONS[name2] : void 0;
23172
23713
  if (sqlValueType !== void 0 && e.args.every((a) => a.type === "number_lit")) {
23173
23714
  const precision = e.args.length > 0 ? `(${e.args.map(deparseExpr).join(", ")})` : "";
23174
- return { sql: `${name.toUpperCase()}${precision}`, type: sqlValueType };
23715
+ return { sql: `${name2.toUpperCase()}${precision}`, type: sqlValueType };
23175
23716
  }
23176
23717
  const args2 = e.args.map((a) => analyze(ctx, a));
23177
- if (CONDITIONAL_FUNCTIONS.has(name)) {
23718
+ if (CONDITIONAL_FUNCTIONS.has(name2)) {
23178
23719
  const unified = unify(ctx, args2);
23179
- return { sql: `${name.toUpperCase()}(${unified.nodes.map((n) => n.sql).join(", ")})`, type: unified.type };
23720
+ return { sql: `${name2.toUpperCase()}(${unified.nodes.map((n) => n.sql).join(", ")})`, type: unified.type };
23180
23721
  }
23181
- const shown = KEYWORD_FUNCTION_NAMES.has(name) ? `"${name}"` : name;
23182
- const signature = findSignature(name, args2.length);
23722
+ const shown = KEYWORD_FUNCTION_NAMES.has(name2) ? `"${name2}"` : name2;
23723
+ const signature = findSignature(name2, args2.length);
23183
23724
  if (!signature) {
23184
23725
  const rendered = args2.map((n) => resolveUnknown(ctx, n, "text").sql);
23185
23726
  return { sql: `${shown}(${rendered.join(", ")})`, type: null };
@@ -23191,7 +23732,7 @@ function analyzeFunc(ctx, e) {
23191
23732
  let type = signature.result;
23192
23733
  if (type === "?") type = null;
23193
23734
  else if (type.startsWith("=")) type = coerced[Number(type.slice(1))]?.type ?? null;
23194
- if (name === "timezone") {
23735
+ if (name2 === "timezone") {
23195
23736
  const source = coerced[1]?.type;
23196
23737
  type = source === "timestamptz" ? "timestamp" : source === "timestamp" ? "timestamptz" : null;
23197
23738
  }
@@ -23450,15 +23991,15 @@ var AVAILABLE_EXTENSIONS = [
23450
23991
  }
23451
23992
  ];
23452
23993
  var PLPGSQL_EXTENSION_OID = 13563;
23453
- function findExtensionSpec(name) {
23454
- return AVAILABLE_EXTENSIONS.find((spec) => spec.name === name) ?? null;
23994
+ function findExtensionSpec(name2) {
23995
+ return AVAILABLE_EXTENSIONS.find((spec) => spec.name === name2) ?? null;
23455
23996
  }
23456
- function extensionMembers(state, name) {
23997
+ function extensionMembers(state, name2) {
23457
23998
  const members = [];
23458
23999
  for (const schema of state.schemas.values()) {
23459
24000
  for (const overloads of schema.functions.values()) {
23460
24001
  for (const fn of overloads) {
23461
- if (fn.language === "internal" && fn.rawBody === name) members.push(fn);
24002
+ if (fn.language === "internal" && fn.rawBody === name2) members.push(fn);
23462
24003
  }
23463
24004
  }
23464
24005
  }
@@ -23483,7 +24024,7 @@ function installedExtensions(state) {
23483
24024
 
23484
24025
  // src/schema/catalog-extensions.ts
23485
24026
  function rel(specs, rows, table) {
23486
- const columns = specs.map(([name, type]) => ({ name, type, table }));
24027
+ const columns = specs.map(([name2, type]) => ({ name: name2, type, table }));
23487
24028
  return { columns, rows };
23488
24029
  }
23489
24030
  function pgExtension(state, namespaceOid2) {
@@ -23564,8 +24105,8 @@ function pgAvailableExtensionVersions(state) {
23564
24105
  "pg_available_extension_versions"
23565
24106
  );
23566
24107
  }
23567
- function extensionCatalogRelation(state, name, namespaceOid2) {
23568
- switch (name) {
24108
+ function extensionCatalogRelation(state, name2, namespaceOid2) {
24109
+ switch (name2) {
23569
24110
  case "pg_extension":
23570
24111
  return pgExtension(state, namespaceOid2);
23571
24112
  case "pg_available_extensions":
@@ -23734,7 +24275,7 @@ function resolveStorage(type, mode) {
23734
24275
 
23735
24276
  // src/schema/catalog-tables.ts
23736
24277
  function rel2(specs, rows, table) {
23737
- const columns = specs.map(([name, type]) => ({ name, type, table }));
24278
+ const columns = specs.map(([name2, type]) => ({ name: name2, type, table }));
23738
24279
  return { columns, rows };
23739
24280
  }
23740
24281
  var OWNER = "postgres";
@@ -23749,8 +24290,8 @@ function* allSequences(state) {
23749
24290
  }
23750
24291
  }
23751
24292
  var NS_PG_CATALOG = 11;
23752
- function namespaceOid(state, name) {
23753
- return builtinNamespaceOid(name) ?? state.schemas.get(name)?.oid ?? 0;
24293
+ function namespaceOid(state, name2) {
24294
+ return builtinNamespaceOid(name2) ?? state.schemas.get(name2)?.oid ?? 0;
23754
24295
  }
23755
24296
  function attTypmod(mod, type) {
23756
24297
  if (!mod || mod.a === void 0) return -1;
@@ -23764,7 +24305,7 @@ function enumOid(ctx, t) {
23764
24305
  return e ? e.oid : 0;
23765
24306
  }
23766
24307
  function pgNamespace(state) {
23767
- const rows = BUILTIN_NAMESPACES.map(([name, oid]) => [oid, name, 10, null]);
24308
+ const rows = BUILTIN_NAMESPACES.map(([name2, oid]) => [oid, name2, 10, null]);
23768
24309
  for (const s of state.schemas.values()) rows.push([s.oid, s.name, 10, null]);
23769
24310
  return rel2(
23770
24311
  [
@@ -23781,10 +24322,10 @@ var RELAM = 5;
23781
24322
  function pgClass(ctx) {
23782
24323
  const state = ctx.state;
23783
24324
  const rows = [];
23784
- const push = (oid, name, schema, kind, natts, tuples, hasindex, populated, persistence) => {
24325
+ const push = (oid, name2, schema, kind, natts, tuples, hasindex, populated, persistence) => {
23785
24326
  rows.push([
23786
24327
  oid,
23787
- name,
24328
+ name2,
23788
24329
  namespaceOid(state, schema),
23789
24330
  0,
23790
24331
  10,
@@ -23932,16 +24473,16 @@ function pgAttribute(ctx) {
23932
24473
  }
23933
24474
  function pgType(ctx) {
23934
24475
  const rows = [];
23935
- for (const [name, oid] of Object.entries(TYPE_OIDS)) {
23936
- const isArr = name.startsWith("_");
24476
+ for (const [name2, oid] of Object.entries(TYPE_OIDS)) {
24477
+ const isArr = name2.startsWith("_");
23937
24478
  rows.push([
23938
24479
  oid,
23939
- name,
24480
+ name2,
23940
24481
  NS_PG_CATALOG,
23941
24482
  "b",
23942
24483
  isArr ? "A" : "U",
23943
- isArr ? TYPE_OIDS[name.slice(1)] ?? 0 : 0,
23944
- isArr ? 0 : TYPE_OIDS[`_${name}`] ?? 0,
24484
+ isArr ? TYPE_OIDS[name2.slice(1)] ?? 0 : 0,
24485
+ isArr ? 0 : TYPE_OIDS[`_${name2}`] ?? 0,
23945
24486
  0,
23946
24487
  0,
23947
24488
  -1
@@ -23976,23 +24517,23 @@ function pgProc(ctx) {
23976
24517
  const rows = [];
23977
24518
  let oid = 1e3;
23978
24519
  const seen = /* @__PURE__ */ new Set();
23979
- const push = (name, ns, kind, retset, nargs, realOid) => {
23980
- rows.push([realOid ?? oid++, name, ns, kind, retset, nargs]);
24520
+ const push = (name2, ns, kind, retset, nargs, realOid) => {
24521
+ rows.push([realOid ?? oid++, name2, ns, kind, retset, nargs]);
23981
24522
  };
23982
- for (const name of getScalarFunctions().keys()) {
23983
- if (!seen.has(name)) {
23984
- seen.add(name);
23985
- push(name, NS_PG_CATALOG, "f", false, -1);
24523
+ for (const name2 of getScalarFunctions().keys()) {
24524
+ if (!seen.has(name2)) {
24525
+ seen.add(name2);
24526
+ push(name2, NS_PG_CATALOG, "f", false, -1);
23986
24527
  }
23987
24528
  }
23988
- for (const name of Object.keys(getAggregateFactories())) {
23989
- if (!seen.has(`agg:${name}`)) {
23990
- seen.add(`agg:${name}`);
23991
- push(name, NS_PG_CATALOG, "a", false, -1);
24529
+ for (const name2 of Object.keys(getAggregateFactories())) {
24530
+ if (!seen.has(`agg:${name2}`)) {
24531
+ seen.add(`agg:${name2}`);
24532
+ push(name2, NS_PG_CATALOG, "a", false, -1);
23992
24533
  }
23993
24534
  }
23994
- for (const name of WINDOW_FUNCTION_NAMES) push(name, NS_PG_CATALOG, "w", false, -1);
23995
- for (const name of getSrfFunctions().keys()) push(name, NS_PG_CATALOG, "f", true, -1);
24535
+ for (const name2 of WINDOW_FUNCTION_NAMES) push(name2, NS_PG_CATALOG, "w", false, -1);
24536
+ for (const name2 of getSrfFunctions().keys()) push(name2, NS_PG_CATALOG, "f", true, -1);
23996
24537
  for (const schema of ctx.state.schemas.values()) {
23997
24538
  for (const fns of schema.functions.values()) {
23998
24539
  for (const f of fns) {
@@ -24145,7 +24686,7 @@ function pgAm() {
24145
24686
  ["amname", "name"],
24146
24687
  ["amtype", "bpchar"]
24147
24688
  ],
24148
- [...ACCESS_METHODS].map(([name, [oid, type]]) => [oid, name, type]),
24689
+ [...ACCESS_METHODS].map(([name2, [oid, type]]) => [oid, name2, type]),
24149
24690
  "pg_am"
24150
24691
  );
24151
24692
  }
@@ -24153,13 +24694,13 @@ var timestamptz = (ms) => ms === void 0 ? null : BigInt(Math.round(ms)) * 1000n
24153
24694
  function pgStatUserTables(ctx) {
24154
24695
  const state = ctx.state;
24155
24696
  const rows = [];
24156
- const push = (oid, schema, name, live, indexes) => {
24697
+ const push = (oid, schema, name2, live, indexes) => {
24157
24698
  const stats = state.tableStats.get(oid);
24158
24699
  const scanned = indexes.filter((index) => index.lastScan !== void 0).map((index) => index.lastScan);
24159
24700
  rows.push([
24160
24701
  oid,
24161
24702
  schema,
24162
- name,
24703
+ name2,
24163
24704
  0n,
24164
24705
  null,
24165
24706
  0n,
@@ -24426,8 +24967,8 @@ function pgIndexesView(ctx) {
24426
24967
  function pgSettings(ctx) {
24427
24968
  const rows = [];
24428
24969
  const keys = /* @__PURE__ */ new Set([...ctx.state.settings.keys(), ...ctx.state.localSettings.keys()]);
24429
- for (const name of [...keys].sort()) {
24430
- rows.push([name, ctx.state.getSetting(name) ?? null]);
24970
+ for (const name2 of [...keys].sort()) {
24971
+ rows.push([name2, ctx.state.getSetting(name2) ?? null]);
24431
24972
  }
24432
24973
  return rel2(
24433
24974
  [
@@ -24448,7 +24989,7 @@ function pgDatabase(ctx) {
24448
24989
  ["datistemplate", "bool"],
24449
24990
  ["datallowconn", "bool"]
24450
24991
  ],
24451
- names.map((name, index) => [5 + index, name, 6, false, true]),
24992
+ names.map((name2, index) => [5 + index, name2, 6, false, true]),
24452
24993
  "pg_database"
24453
24994
  );
24454
24995
  }
@@ -24710,9 +25251,9 @@ function infoRoutines(ctx) {
24710
25251
  "routines"
24711
25252
  );
24712
25253
  }
24713
- function buildCatalogRelation(ctx, schema, name) {
25254
+ function buildCatalogRelation(ctx, schema, name2) {
24714
25255
  if (schema === "pg_catalog") {
24715
- switch (name) {
25256
+ switch (name2) {
24716
25257
  case "pg_namespace":
24717
25258
  return pgNamespace(ctx.state);
24718
25259
  case "pg_class":
@@ -24759,10 +25300,10 @@ function buildCatalogRelation(ctx, schema, name) {
24759
25300
  case "pg_trigger":
24760
25301
  return pgTrigger(ctx);
24761
25302
  default:
24762
- return extensionCatalogRelation(ctx.state, name, (ns) => namespaceOid(ctx.state, ns));
25303
+ return extensionCatalogRelation(ctx.state, name2, (ns) => namespaceOid(ctx.state, ns));
24763
25304
  }
24764
25305
  }
24765
- switch (name) {
25306
+ switch (name2) {
24766
25307
  case "schemata":
24767
25308
  return infoSchemata(ctx.state);
24768
25309
  case "tables":
@@ -24928,14 +25469,14 @@ function takeConcurrentBuildFault(state) {
24928
25469
  state.faults.concurrentIndexBuild = void 0;
24929
25470
  return new PostgresError("internal", FAULT_MESSAGES[code] ?? "concurrent index build interrupted", code);
24930
25471
  }
24931
- function assertUniqueIndexBuildable(env, table, index, name = index.name) {
25472
+ function assertUniqueIndexBuildable(env, table, index, name2 = index.name) {
24932
25473
  if (!index.unique) return;
24933
25474
  const spec = uniqueSpecOfIndex(table, index);
24934
25475
  const seen = /* @__PURE__ */ new Set();
24935
25476
  for (let i = 0; i < table.rowCount(); i++) {
24936
25477
  const key = uniqueKeyOf(env, table, spec, table.rowAt(i));
24937
25478
  if (key === null) continue;
24938
- if (seen.has(key)) throw pgError("constraint_unique", `could not create unique index "${name}"`, "23505");
25479
+ if (seen.has(key)) throw pgError("constraint_unique", `could not create unique index "${name2}"`, "23505");
24939
25480
  seen.add(key);
24940
25481
  }
24941
25482
  }
@@ -24943,8 +25484,8 @@ function relationMissing(state, parts) {
24943
25484
  if (parts.length >= 2) state.getSchema(parts[parts.length - 2]);
24944
25485
  throw pgError("undefined_table", `relation "${parts.join(".")}" does not exist`, "42P01");
24945
25486
  }
24946
- function transientName(schema, name) {
24947
- const base = `${name}_ccnew`;
25487
+ function transientName(schema, name2) {
25488
+ const base = `${name2}_ccnew`;
24948
25489
  if (!schema.hasRelation(base)) return base;
24949
25490
  for (let i = 1; ; i++) {
24950
25491
  if (!schema.hasRelation(`${base}${i}`)) return `${base}${i}`;
@@ -25111,13 +25652,13 @@ function executeAnalyze(env, stmt) {
25111
25652
 
25112
25653
  // src/executor/alter-column.ts
25113
25654
  var SYSTEM_COLUMNS = /* @__PURE__ */ new Set(["tableoid", "cmax", "xmax", "cmin", "xmin", "ctid"]);
25114
- function alterableColumn(table, name) {
25115
- const column = table.columns[table.columnIndex(name)];
25655
+ function alterableColumn(table, name2) {
25656
+ const column = table.columns[table.columnIndex(name2)];
25116
25657
  if (column) return column;
25117
- if (SYSTEM_COLUMNS.has(name)) {
25118
- throw pgError("feature_not_supported", `cannot alter system column "${name}"`, "0A000");
25658
+ if (SYSTEM_COLUMNS.has(name2)) {
25659
+ throw pgError("feature_not_supported", `cannot alter system column "${name2}"`, "0A000");
25119
25660
  }
25120
- throw pgError("undefined_column", `column "${name}" of relation "${table.name}" does not exist`, "42703");
25661
+ throw pgError("undefined_column", `column "${name2}" of relation "${table.name}" does not exist`, "42703");
25121
25662
  }
25122
25663
  function actionLabel(action) {
25123
25664
  switch (action.kind) {
@@ -25218,9 +25759,9 @@ function assertDefaultShape(table, node) {
25218
25759
  if (node === null || typeof node !== "object") return;
25219
25760
  const expr = node;
25220
25761
  if (expr.type === "colref") {
25221
- const name = expr.parts?.[expr.parts.length - 1] ?? "";
25222
- if (expr.parts?.length === 1 && table.columnIndex(name) === -1) {
25223
- throw pgError("undefined_column", `column "${name}" does not exist`, "42703");
25762
+ const name2 = expr.parts?.[expr.parts.length - 1] ?? "";
25763
+ if (expr.parts?.length === 1 && table.columnIndex(name2) === -1) {
25764
+ throw pgError("undefined_column", `column "${name2}" does not exist`, "42703");
25224
25765
  }
25225
25766
  throw pgError("feature_not_supported", "cannot use column reference in DEFAULT expression", "0A000");
25226
25767
  }
@@ -25231,8 +25772,8 @@ function assertDefaultShape(table, node) {
25231
25772
  if (expr.over) {
25232
25773
  throw pgError("windowing_error", "window functions are not allowed in DEFAULT expressions", "42P20");
25233
25774
  }
25234
- const name = expr.name?.length === 1 ? expr.name[0] : null;
25235
- if (name !== null && isAggregateName(name) && !hasScalarFunction(name)) {
25775
+ const name2 = expr.name?.length === 1 ? expr.name[0] : null;
25776
+ if (name2 !== null && isAggregateName(name2) && !hasScalarFunction(name2)) {
25236
25777
  throw pgError("grouping_error", "aggregate functions are not allowed in DEFAULT expressions", "42803");
25237
25778
  }
25238
25779
  }
@@ -25402,15 +25943,15 @@ function executeDropExtension(env, stmt) {
25402
25943
  const state = env.ctx.state;
25403
25944
  const targets = [];
25404
25945
  for (const parts of stmt.names) {
25405
- const name = parts[parts.length - 1];
25406
- const spec = findExtensionSpec(name);
25946
+ const name2 = parts[parts.length - 1];
25947
+ const spec = findExtensionSpec(name2);
25407
25948
  if (spec && installedExtension(state, spec)) {
25408
25949
  if (spec.builtinSchema !== void 0) throw unsupported(`DROP EXTENSION ${spec.name}`);
25409
25950
  targets.push(spec);
25410
25951
  continue;
25411
25952
  }
25412
25953
  if (stmt.ifExists) continue;
25413
- throw pgError("undefined_object", `extension "${name}" does not exist`, "42704");
25954
+ throw pgError("undefined_object", `extension "${name2}" does not exist`, "42704");
25414
25955
  }
25415
25956
  const dependents = targets.map((spec) => ({ spec, drops: extensionDependents(env, spec) }));
25416
25957
  if (!stmt.cascade) {
@@ -25468,7 +26009,7 @@ var SEQ_LIMITS = {
25468
26009
  int4: { min: -2147483648n, max: 2147483647n },
25469
26010
  int8: { min: -9223372036854775808n, max: 9223372036854775807n }
25470
26011
  };
25471
- function buildSequence(env, schema, name, options2, temp) {
26012
+ function buildSequence(env, schema, name2, options2, temp) {
25472
26013
  const state = env.ctx.state;
25473
26014
  let dataType = "int8";
25474
26015
  if (options2.as) {
@@ -25495,7 +26036,7 @@ function buildSequence(env, schema, name, options2, temp) {
25495
26036
  );
25496
26037
  }
25497
26038
  return {
25498
- name,
26039
+ name: name2,
25499
26040
  schema: schema.name,
25500
26041
  increment,
25501
26042
  minValue,
@@ -25515,14 +26056,14 @@ function buildSequence(env, schema, name, options2, temp) {
25515
26056
  };
25516
26057
  }
25517
26058
  function executeCreateSequence(env, stmt) {
25518
- const { schema, name } = targetSchema(env, stmt.name);
25519
- if (schema.hasRelation(name)) {
26059
+ const { schema, name: name2 } = targetSchema(env, stmt.name);
26060
+ if (schema.hasRelation(name2)) {
25520
26061
  if (stmt.ifNotExists) return commandResult("CREATE SEQUENCE", 0);
25521
- throw pgError("duplicate_table", `relation "${name}" already exists`, "42P07");
26062
+ throw pgError("duplicate_table", `relation "${name2}" already exists`, "42P07");
25522
26063
  }
25523
- const seq = buildSequence(env, schema, name, stmt.options, stmt.temp);
26064
+ const seq = buildSequence(env, schema, name2, stmt.options, stmt.temp);
25524
26065
  if (stmt.unlogged) seq.unlogged = true;
25525
- schema.sequences.set(name, seq);
26066
+ schema.sequences.set(name2, seq);
25526
26067
  return commandResult("CREATE SEQUENCE", 0);
25527
26068
  }
25528
26069
  function executeAlterSequence(env, stmt) {
@@ -25605,21 +26146,21 @@ function buildColumn(env, schema, tableName2, def, out, taken) {
25605
26146
  break;
25606
26147
  case "primary_key": {
25607
26148
  col.notNull = true;
25608
- const name = makeName(truncIdent(`${tableName2}_pkey`), taken);
25609
- taken.add(name);
25610
- out.constraints.push({ kind: "primary_key", name, columns: [def.name] });
26149
+ const name2 = makeName(truncIdent(`${tableName2}_pkey`), taken);
26150
+ taken.add(name2);
26151
+ out.constraints.push({ kind: "primary_key", name: name2, columns: [def.name] });
25611
26152
  break;
25612
26153
  }
25613
26154
  case "unique": {
25614
- const name = c.name ?? makeName(truncIdent(`${tableName2}_${def.name}_key`), taken);
25615
- taken.add(name);
25616
- out.constraints.push({ kind: "unique", name, columns: [def.name], nullsNotDistinct: c.nullsNotDistinct });
26155
+ const name2 = c.name ?? makeName(truncIdent(`${tableName2}_${def.name}_key`), taken);
26156
+ taken.add(name2);
26157
+ out.constraints.push({ kind: "unique", name: name2, columns: [def.name], nullsNotDistinct: c.nullsNotDistinct });
25617
26158
  break;
25618
26159
  }
25619
26160
  case "check": {
25620
- const name = c.name ?? makeName(truncIdent(`${tableName2}_${def.name}_check`), taken);
25621
- taken.add(name);
25622
- out.constraints.push({ kind: "check", name, expr: c.expr });
26161
+ const name2 = c.name ?? makeName(truncIdent(`${tableName2}_${def.name}_check`), taken);
26162
+ taken.add(name2);
26163
+ out.constraints.push({ kind: "check", name: name2, expr: c.expr });
25623
26164
  break;
25624
26165
  }
25625
26166
  case "references": {
@@ -25629,11 +26170,11 @@ function buildColumn(env, schema, tableName2, def, out, taken) {
25629
26170
  throw pgError("undefined_table", `relation "${refParts.join(".")}" does not exist`, "42P01");
25630
26171
  }
25631
26172
  const refColumns = c.columns ?? primaryKeyColumns(refTable);
25632
- const name = c.name ?? makeName(truncIdent(`${tableName2}_${def.name}_fkey`), taken);
25633
- taken.add(name);
26173
+ const name2 = c.name ?? makeName(truncIdent(`${tableName2}_${def.name}_fkey`), taken);
26174
+ taken.add(name2);
25634
26175
  out.constraints.push({
25635
26176
  kind: "foreign_key",
25636
- name,
26177
+ name: name2,
25637
26178
  columns: [def.name],
25638
26179
  refSchema: refTable.schema,
25639
26180
  refTable: refTable.name,
@@ -25697,20 +26238,20 @@ function buildTableConstraint(env, tableName2, columns, con, taken) {
25697
26238
  switch (con.kind) {
25698
26239
  case "primary_key": {
25699
26240
  checkCols(con.columns);
25700
- const name = con.name ?? makeName(truncIdent(`${tableName2}_pkey`), taken);
25701
- taken.add(name);
25702
- return { kind: "primary_key", name, columns: con.columns };
26241
+ const name2 = con.name ?? makeName(truncIdent(`${tableName2}_pkey`), taken);
26242
+ taken.add(name2);
26243
+ return { kind: "primary_key", name: name2, columns: con.columns };
25703
26244
  }
25704
26245
  case "unique": {
25705
26246
  checkCols(con.columns);
25706
- const name = con.name ?? makeName(truncIdent(`${tableName2}_${con.columns.join("_")}_key`), taken);
25707
- taken.add(name);
25708
- return { kind: "unique", name, columns: con.columns, nullsNotDistinct: con.nullsNotDistinct };
26247
+ const name2 = con.name ?? makeName(truncIdent(`${tableName2}_${con.columns.join("_")}_key`), taken);
26248
+ taken.add(name2);
26249
+ return { kind: "unique", name: name2, columns: con.columns, nullsNotDistinct: con.nullsNotDistinct };
25709
26250
  }
25710
26251
  case "check": {
25711
- const name = con.name ?? makeName(truncIdent(`${tableName2}_check`), taken);
25712
- taken.add(name);
25713
- return { kind: "check", name, expr: con.expr };
26252
+ const name2 = con.name ?? makeName(truncIdent(`${tableName2}_check`), taken);
26253
+ taken.add(name2);
26254
+ return { kind: "check", name: name2, expr: con.expr };
25714
26255
  }
25715
26256
  case "foreign_key": {
25716
26257
  checkCols(con.columns);
@@ -25719,11 +26260,11 @@ function buildTableConstraint(env, tableName2, columns, con, taken) {
25719
26260
  throw pgError("undefined_table", `relation "${con.refTable.join(".")}" does not exist`, "42P01");
25720
26261
  }
25721
26262
  const refColumns = con.refColumns ?? primaryKeyColumns(refTable);
25722
- const name = con.name ?? makeName(truncIdent(`${tableName2}_${con.columns.join("_")}_fkey`), taken);
25723
- taken.add(name);
26263
+ const name2 = con.name ?? makeName(truncIdent(`${tableName2}_${con.columns.join("_")}_fkey`), taken);
26264
+ taken.add(name2);
25724
26265
  return {
25725
26266
  kind: "foreign_key",
25726
- name,
26267
+ name: name2,
25727
26268
  columns: con.columns,
25728
26269
  refSchema: refTable.schema,
25729
26270
  refTable: refTable.name,
@@ -25739,10 +26280,10 @@ function buildTableConstraint(env, tableName2, columns, con, taken) {
25739
26280
  }
25740
26281
  function executeCreateTable(env, stmt) {
25741
26282
  const state = env.ctx.state;
25742
- const { schema, name } = targetSchema(env, stmt.name);
25743
- if (schema.hasRelation(name)) {
26283
+ const { schema, name: name2 } = targetSchema(env, stmt.name);
26284
+ if (schema.hasRelation(name2)) {
25744
26285
  if (stmt.ifNotExists) return commandResult("CREATE TABLE", 0);
25745
- throw pgError("duplicate_table", `relation "${name}" already exists`, "42P07");
26286
+ throw pgError("duplicate_table", `relation "${name2}" already exists`, "42P07");
25746
26287
  }
25747
26288
  const built = { columns: [], constraints: [], sequences: [] };
25748
26289
  const taken = /* @__PURE__ */ new Set();
@@ -25781,16 +26322,16 @@ function executeCreateTable(env, stmt) {
25781
26322
  throw pgError("duplicate_column", `column "${def.name}" specified more than once`, "42701");
25782
26323
  }
25783
26324
  seen.add(def.name);
25784
- built.columns.push(buildColumn(env, schema, name, def, built, taken));
26325
+ built.columns.push(buildColumn(env, schema, name2, def, built, taken));
25785
26326
  }
25786
26327
  for (const con of stmt.constraints) {
25787
- built.constraints.push(buildTableConstraint(env, name, built.columns, con, taken));
26328
+ built.constraints.push(buildTableConstraint(env, name2, built.columns, con, taken));
25788
26329
  }
25789
26330
  const written = new Set(stmt.constraints.map((con) => con.name));
25790
26331
  for (const def of stmt.columns) {
25791
26332
  for (const con of def.constraints) if (con.kind === "unique") written.add(con.name);
25792
26333
  }
25793
- const claimed = /* @__PURE__ */ new Set([name]);
26334
+ const claimed = /* @__PURE__ */ new Set([name2]);
25794
26335
  for (const con of built.constraints) {
25795
26336
  if (isKeyConstraint(con)) claimConstraintIndexName(schema, con, written.has(con.name), claimed);
25796
26337
  }
@@ -25804,7 +26345,7 @@ function executeCreateTable(env, stmt) {
25804
26345
  }
25805
26346
  const pkCount = built.constraints.filter((c) => c.kind === "primary_key").length;
25806
26347
  if (pkCount > 1) {
25807
- throw pgError("invalid_table_definition", `multiple primary keys for table "${name}" are not allowed`, "42P16");
26348
+ throw pgError("invalid_table_definition", `multiple primary keys for table "${name2}" are not allowed`, "42P16");
25808
26349
  }
25809
26350
  checkForeignKeyPersistence(state, relPersistence(stmt), built.constraints);
25810
26351
  for (const seq of built.sequences) {
@@ -25815,18 +26356,18 @@ function executeCreateTable(env, stmt) {
25815
26356
  if (stmt.unlogged) seq.unlogged = true;
25816
26357
  seqSchema.sequences.set(seq.name, seq);
25817
26358
  }
25818
- const table = new TableData(schema.name, name, built.columns, state.nextOid(), stmt.temp);
26359
+ const table = new TableData(schema.name, name2, built.columns, state.nextOid(), stmt.temp);
25819
26360
  table.unlogged = stmt.unlogged;
25820
26361
  table.constraints = built.constraints;
25821
- schema.tables.set(name, table);
26362
+ schema.tables.set(name2, table);
25822
26363
  return commandResult("CREATE TABLE", 0);
25823
26364
  }
25824
26365
  function executeCreateTableAs(env, stmt) {
25825
26366
  const state = env.ctx.state;
25826
- const { schema, name } = targetSchema(env, stmt.name);
25827
- if (schema.hasRelation(name)) {
26367
+ const { schema, name: name2 } = targetSchema(env, stmt.name);
26368
+ if (schema.hasRelation(name2)) {
25828
26369
  if (stmt.ifNotExists) return commandResult("CREATE TABLE AS", 0);
25829
- throw pgError("duplicate_table", `relation "${name}" already exists`, "42P07");
26370
+ throw pgError("duplicate_table", `relation "${name2}" already exists`, "42P07");
25830
26371
  }
25831
26372
  const rel3 = executeSelectStmt(env, stmt.query);
25832
26373
  const columns = rel3.columns.map((c, i) => ({
@@ -25839,12 +26380,12 @@ function executeCreateTableAs(env, stmt) {
25839
26380
  collate: null,
25840
26381
  domain: null
25841
26382
  }));
25842
- const table = new TableData(schema.name, name, columns, state.nextOid(), stmt.temp);
26383
+ const table = new TableData(schema.name, name2, columns, state.nextOid(), stmt.temp);
25843
26384
  table.unlogged = stmt.unlogged === true;
25844
26385
  if (stmt.withData) {
25845
26386
  for (const row of rel3.rows) table.mutableRows().push(row.slice());
25846
26387
  }
25847
- schema.tables.set(name, table);
26388
+ schema.tables.set(name2, table);
25848
26389
  const count = stmt.withData ? table.rowCount() : 0;
25849
26390
  return { columns: [], rows: [], command: `SELECT ${count}`, rowCount: count };
25850
26391
  }
@@ -25857,10 +26398,10 @@ function executeCreateIndex(env, stmt) {
25857
26398
  const schema = state.getSchema(table.schema);
25858
26399
  const taken = /* @__PURE__ */ new Set([...schema.indexes.keys(), ...constraintNames(table)]);
25859
26400
  const colPart = stmt.columns.map((c) => inferColumnName(c.expr)).map((part) => part === "?column?" ? "expr" : part).join("_");
25860
- const name = stmt.name ?? makeName(truncIdent(`${table.name}_${colPart}_idx`), taken);
25861
- if (schema.indexes.has(name) || schema.hasRelation(name)) {
26401
+ const name2 = stmt.name ?? makeName(truncIdent(`${table.name}_${colPart}_idx`), taken);
26402
+ if (schema.indexes.has(name2) || schema.hasRelation(name2)) {
25862
26403
  if (stmt.ifNotExists) return commandResult("CREATE INDEX", 0);
25863
- throw pgError("duplicate_table", `relation "${name}" already exists`, "42P07");
26404
+ throw pgError("duplicate_table", `relation "${name2}" already exists`, "42P07");
25864
26405
  }
25865
26406
  for (const c of stmt.columns) {
25866
26407
  if (c.expr.type === "colref" && c.expr.parts.length === 1) {
@@ -25884,7 +26425,7 @@ function executeCreateIndex(env, stmt) {
25884
26425
  }
25885
26426
  const index = {
25886
26427
  oid: state.nextOid(),
25887
- name,
26428
+ name: name2,
25888
26429
  schema: schema.name,
25889
26430
  table: table.name,
25890
26431
  tableOid: table.oid,
@@ -25913,19 +26454,19 @@ function executeCreateIndex(env, stmt) {
25913
26454
  }
25914
26455
  }
25915
26456
  if (failure) {
25916
- if (stmt.concurrently) schema.indexes.set(name, { ...index, valid: false });
26457
+ if (stmt.concurrently) schema.indexes.set(name2, { ...index, valid: false });
25917
26458
  throw failure;
25918
26459
  }
25919
- schema.indexes.set(name, index);
26460
+ schema.indexes.set(name2, index);
25920
26461
  table.indexStores = null;
25921
26462
  return commandResult("CREATE INDEX", 0);
25922
26463
  }
25923
26464
  function executeCreateView(env, stmt) {
25924
26465
  const state = env.ctx.state;
25925
- const { schema, name } = targetSchema(env, stmt.name);
25926
- const existing = schema.views.get(name);
25927
- if (schema.hasRelation(name) && !(existing && stmt.orReplace && !stmt.materialized)) {
25928
- throw pgError("duplicate_table", `relation "${name}" already exists`, "42P07");
26466
+ const { schema, name: name2 } = targetSchema(env, stmt.name);
26467
+ const existing = schema.views.get(name2);
26468
+ if (schema.hasRelation(name2) && !(existing && stmt.orReplace && !stmt.materialized)) {
26469
+ throw pgError("duplicate_table", `relation "${name2}" already exists`, "42P07");
25929
26470
  }
25930
26471
  if (existing && stmt.orReplace) {
25931
26472
  const oldRel = executeSelectStmt({ ctx: env.ctx, params: null, ctes: /* @__PURE__ */ new Map(), outer: null }, existing.query);
@@ -25944,8 +26485,8 @@ function executeCreateView(env, stmt) {
25944
26485
  }));
25945
26486
  matRows = stmt.withData ? rel3.rows : null;
25946
26487
  }
25947
- schema.views.set(name, {
25948
- name,
26488
+ schema.views.set(name2, {
26489
+ name: name2,
25949
26490
  schema: schema.name,
25950
26491
  query: stmt.query,
25951
26492
  columns: stmt.columns,
@@ -25982,11 +26523,11 @@ function executeCreateSchema(env, stmt) {
25982
26523
  }
25983
26524
  function executeCreateEnum(env, stmt) {
25984
26525
  const state = env.ctx.state;
25985
- const { schema, name } = targetSchema(env, stmt.name);
25986
- if (schema.enums.has(name) || schema.domains.has(name)) {
25987
- throw pgError("duplicate_object", `type "${name}" already exists`, "42710");
26526
+ const { schema, name: name2 } = targetSchema(env, stmt.name);
26527
+ if (schema.enums.has(name2) || schema.domains.has(name2)) {
26528
+ throw pgError("duplicate_object", `type "${name2}" already exists`, "42710");
25988
26529
  }
25989
- schema.enums.set(name, { name, schema: schema.name, labels: [...stmt.labels], oid: state.nextOid() });
26530
+ schema.enums.set(name2, { name: name2, schema: schema.name, labels: [...stmt.labels], oid: state.nextOid() });
25990
26531
  return commandResult("CREATE TYPE", 0);
25991
26532
  }
25992
26533
  function executeAlterEnum(env, stmt) {
@@ -26024,20 +26565,20 @@ function executeAlterEnum(env, stmt) {
26024
26565
  }
26025
26566
  function executeCreateDomain(env, stmt) {
26026
26567
  const state = env.ctx.state;
26027
- const { schema, name } = targetSchema(env, stmt.name);
26028
- if (schema.domains.has(name) || schema.enums.has(name)) {
26029
- throw pgError("duplicate_object", `type "${name}" already exists`, "42710");
26568
+ const { schema, name: name2 } = targetSchema(env, stmt.name);
26569
+ if (schema.domains.has(name2) || schema.enums.has(name2)) {
26570
+ throw pgError("duplicate_object", `type "${name2}" already exists`, "42710");
26030
26571
  }
26031
26572
  const resolved = resolveTypeName(state, stmt.baseType);
26032
26573
  let checkIdx = 0;
26033
- schema.domains.set(name, {
26034
- name,
26574
+ schema.domains.set(name2, {
26575
+ name: name2,
26035
26576
  schema: schema.name,
26036
26577
  baseType: resolved.column,
26037
26578
  notNull: stmt.notNull,
26038
26579
  defaultExpr: stmt.defaultExpr,
26039
26580
  checks: stmt.checks.map((c) => ({
26040
- name: c.name ?? `${name}_check${checkIdx++ === 0 ? "" : checkIdx - 1}`,
26581
+ name: c.name ?? `${name2}_check${checkIdx++ === 0 ? "" : checkIdx - 1}`,
26041
26582
  expr: c.expr
26042
26583
  })),
26043
26584
  oid: state.nextOid()
@@ -26046,7 +26587,7 @@ function executeCreateDomain(env, stmt) {
26046
26587
  }
26047
26588
  function executeCreateFunction(env, stmt) {
26048
26589
  const state = env.ctx.state;
26049
- const { schema, name } = targetSchema(env, stmt.name);
26590
+ const { schema, name: name2 } = targetSchema(env, stmt.name);
26050
26591
  const lang = stmt.language.toLowerCase();
26051
26592
  if (lang !== "sql" && lang !== "plpgsql") {
26052
26593
  throw unsupported(`LANGUAGE ${stmt.language} functions`);
@@ -26084,13 +26625,13 @@ function executeCreateFunction(env, stmt) {
26084
26625
  if (body === null && stmt.body !== null && lang === "sql") {
26085
26626
  body = parse(stmt.body);
26086
26627
  }
26087
- const existing = schema.functions.get(name) ?? [];
26628
+ const existing = schema.functions.get(name2) ?? [];
26088
26629
  const sameSig = existing.findIndex((f) => f.argTypes.length === argTypes.length);
26089
26630
  if (sameSig !== -1 && !stmt.orReplace) {
26090
- throw pgError("duplicate_function", `function "${name}" already exists with same argument types`, "42723");
26631
+ throw pgError("duplicate_function", `function "${name2}" already exists with same argument types`, "42723");
26091
26632
  }
26092
26633
  const fn = {
26093
- name,
26634
+ name: name2,
26094
26635
  schema: schema.name,
26095
26636
  argNames,
26096
26637
  argTypes,
@@ -26106,7 +26647,7 @@ function executeCreateFunction(env, stmt) {
26106
26647
  };
26107
26648
  if (sameSig !== -1) existing[sameSig] = fn;
26108
26649
  else existing.push(fn);
26109
- schema.functions.set(name, existing);
26650
+ schema.functions.set(name2, existing);
26110
26651
  return commandResult("CREATE FUNCTION", 0);
26111
26652
  }
26112
26653
  function executeCreateTrigger(env, stmt) {
@@ -26388,7 +26929,7 @@ function executeAlterTable(env, stmt) {
26388
26929
  }
26389
26930
  for (const idxMeta of [...schema.indexes.values()]) {
26390
26931
  if (idxMeta.table !== table.name) continue;
26391
- const renames = (name) => name === action.from ? action.to : name;
26932
+ const renames = (name2) => name2 === action.from ? action.to : name2;
26392
26933
  schema.indexes.set(idxMeta.name, {
26393
26934
  ...idxMeta,
26394
26935
  columns: idxMeta.columns.map((c) => c.column === null ? c : { ...c, column: renames(c.column) }),
@@ -26732,17 +27273,17 @@ function executeDrop(env, stmt) {
26732
27273
  break;
26733
27274
  }
26734
27275
  case "schema": {
26735
- const name = parts[parts.length - 1];
26736
- const schema = state.schemas.get(name);
27276
+ const name2 = parts[parts.length - 1];
27277
+ const schema = state.schemas.get(name2);
26737
27278
  if (!schema) {
26738
27279
  if (stmt.ifExists) break;
26739
- throw pgError("undefined_object", `schema "${name}" does not exist`, "3F000");
27280
+ throw pgError("undefined_object", `schema "${name2}" does not exist`, "3F000");
26740
27281
  }
26741
27282
  const nonEmpty = schema.tables.size > 0 || schema.views.size > 0 || schema.sequences.size > 0 || schema.enums.size > 0 || schema.domains.size > 0 || schema.functions.size > 0;
26742
27283
  if (nonEmpty && !stmt.cascade) {
26743
- throw pgError("dependent_objects", `cannot drop schema ${name} because other objects depend on it`, "2BP01");
27284
+ throw pgError("dependent_objects", `cannot drop schema ${name2} because other objects depend on it`, "2BP01");
26744
27285
  }
26745
- state.schemas.delete(name);
27286
+ state.schemas.delete(name2);
26746
27287
  break;
26747
27288
  }
26748
27289
  case "type": {
@@ -27169,12 +27710,12 @@ var Database = class {
27169
27710
  const parts = spec.name.split(".").map((p) => p.trim()).filter((p) => p.length > 0);
27170
27711
  if (parts.length === 0) throw pgError("syntax", "function name is required", "42601");
27171
27712
  const schemaName = (parts.length >= 2 ? parts[0] : this.state.currentSchema()).toLowerCase();
27172
- const name = parts[parts.length - 1].toLowerCase();
27713
+ const name2 = parts[parts.length - 1].toLowerCase();
27173
27714
  const functions = schemaName === "pg_catalog" ? this.state.systemFunctions : this.state.getSchema(schemaName).functions;
27174
27715
  const argTypes = spec.args.map((a) => resolveTypeName(this.state, parseTypeName(a)).column.id);
27175
27716
  const returns = resolveTypeName(this.state, parseTypeName(spec.returns)).column.id;
27176
27717
  const fn = {
27177
- name,
27718
+ name: name2,
27178
27719
  schema: schemaName,
27179
27720
  argNames: spec.args.map(() => null),
27180
27721
  argTypes,
@@ -27189,13 +27730,13 @@ var Database = class {
27189
27730
  oid: this.state.nextOid(),
27190
27731
  jsImpl: spec.fn
27191
27732
  };
27192
- const existing = functions.get(name) ?? [];
27733
+ const existing = functions.get(name2) ?? [];
27193
27734
  const sameSig = existing.findIndex(
27194
27735
  (f) => f.argTypes.length === argTypes.length && f.argTypes.every((t, i) => t === argTypes[i])
27195
27736
  );
27196
27737
  if (sameSig !== -1) existing[sameSig] = fn;
27197
27738
  else existing.push(fn);
27198
- functions.set(name, existing);
27739
+ functions.set(name2, existing);
27199
27740
  }
27200
27741
  /** Execute a single-statement query and return all rows keyed by column name. */
27201
27742
  query(sql, params = [], options2 = {}) {
@@ -27235,15 +27776,15 @@ var Database = class {
27235
27776
  throw error;
27236
27777
  }
27237
27778
  }
27238
- const name = `__api_transaction_${++this.transactionSequence}`;
27239
- this.transactions.savepoint(name);
27779
+ const name2 = `__api_transaction_${++this.transactionSequence}`;
27780
+ this.transactions.savepoint(name2);
27240
27781
  try {
27241
27782
  const value = fn();
27242
- this.transactions.releaseSavepoint(name);
27783
+ this.transactions.releaseSavepoint(name2);
27243
27784
  return value;
27244
27785
  } catch (error) {
27245
- this.transactions.rollbackToSavepoint(name);
27246
- this.transactions.releaseSavepoint(name);
27786
+ this.transactions.rollbackToSavepoint(name2);
27787
+ this.transactions.releaseSavepoint(name2);
27247
27788
  throw error;
27248
27789
  }
27249
27790
  } finally {
@@ -27279,10 +27820,10 @@ var Database = class {
27279
27820
  }
27280
27821
  }
27281
27822
  /** Point `name` at a checkpoint without copying rows or switching the live database. */
27282
- fork(name, at) {
27823
+ fork(name2, at) {
27283
27824
  this.assertOpen();
27284
27825
  try {
27285
- const point = this.timeline.fork(name, at !== void 0 ? { from: at } : {});
27826
+ const point = this.timeline.fork(name2, at !== void 0 ? { from: at } : {});
27286
27827
  if (!point) throw pgError("misuse", "no checkpoint to fork from", "XX000");
27287
27828
  return project(point);
27288
27829
  } catch (error) {
@@ -27476,21 +28017,21 @@ var Cluster = class {
27476
28017
  return [...this.databases.keys()].sort();
27477
28018
  }
27478
28019
  snapshotAll() {
27479
- return new Map([...this.databases].map(([name, db]) => [name, db.snapshot()]));
28020
+ return new Map([...this.databases].map(([name2, db]) => [name2, db.snapshot()]));
27480
28021
  }
27481
28022
  restoreAll(points) {
27482
28023
  if (this.sessions.size > 0) throw new Error("cannot restore a catalog with active sessions");
27483
28024
  if (!points.has(this.defaultDatabaseName)) throw new Error("snapshot lacks default database");
27484
28025
  for (const db of this.databases.values()) db.close();
27485
28026
  this.databases.clear();
27486
- for (const [name, point] of points) this.installDatabase(name, point.open());
28027
+ for (const [name2, point] of points) this.installDatabase(name2, point.open());
27487
28028
  }
27488
- getDatabase(name) {
27489
- return this.databases.get(name);
28029
+ getDatabase(name2) {
28030
+ return this.databases.get(name2);
27490
28031
  }
27491
28032
  /** Add a database that already exists (restored from durable storage) to the catalog. */
27492
- attach(name, db) {
27493
- this.installDatabase(name, db);
28033
+ attach(name2, db) {
28034
+ this.installDatabase(name2, db);
27494
28035
  }
27495
28036
  /** The catalog as it stands, to put back with {@link restoreCatalog} if a change cannot be persisted. */
27496
28037
  catalog() {
@@ -27498,33 +28039,33 @@ var Cluster = class {
27498
28039
  }
27499
28040
  restoreCatalog(entries) {
27500
28041
  this.databases.clear();
27501
- for (const [name, db] of entries) {
27502
- setDatabaseCatalogContext(db.state, { name, names: () => this.databaseNames() });
27503
- this.databases.set(name, db);
28042
+ for (const [name2, db] of entries) {
28043
+ setDatabaseCatalogContext(db.state, { name: name2, names: () => this.databaseNames() });
28044
+ this.databases.set(name2, db);
27504
28045
  }
27505
28046
  }
27506
- requireDatabase(name) {
27507
- const db = this.databases.get(name);
27508
- if (!db) throw new PostgresError("undefined_object", `database "${name}" does not exist`, "3D000");
28047
+ requireDatabase(name2) {
28048
+ const db = this.databases.get(name2);
28049
+ if (!db) throw new PostgresError("undefined_object", `database "${name2}" does not exist`, "3D000");
27509
28050
  return db;
27510
28051
  }
27511
- createDatabase(name, template) {
27512
- if (this.databases.has(name)) {
27513
- throw new PostgresError("duplicate_object", `database "${name}" already exists`, "42P04");
28052
+ createDatabase(name2, template) {
28053
+ if (this.databases.has(name2)) {
28054
+ throw new PostgresError("duplicate_object", `database "${name2}" already exists`, "42P04");
27514
28055
  }
27515
28056
  const db = template === void 0 ? new Database({ now: this.db.now, seed: this.db.seed }) : this.requireTemplate(template).snapshot().open();
27516
- this.installDatabase(name, db);
28057
+ this.installDatabase(name2, db);
27517
28058
  }
27518
- dropDatabase(name, requester) {
27519
- if (name === requester.databaseName || this.activeConnections(name) > 0) {
28059
+ dropDatabase(name2, requester) {
28060
+ if (name2 === requester.databaseName || this.activeConnections(name2) > 0) {
27520
28061
  throw new PostgresError(
27521
28062
  "object_not_in_prerequisite_state",
27522
- `database "${name}" is being accessed by other users`,
28063
+ `database "${name2}" is being accessed by other users`,
27523
28064
  "55006"
27524
28065
  );
27525
28066
  }
27526
- if (!this.databases.delete(name)) {
27527
- throw new PostgresError("undefined_object", `database "${name}" does not exist`, "3D000");
28067
+ if (!this.databases.delete(name2)) {
28068
+ throw new PostgresError("undefined_object", `database "${name2}" does not exist`, "3D000");
27528
28069
  }
27529
28070
  }
27530
28071
  renameDatabase(from, to, requester) {
@@ -27542,25 +28083,25 @@ var Cluster = class {
27542
28083
  this.databases.delete(from);
27543
28084
  this.installDatabase(to, db);
27544
28085
  }
27545
- requireTemplate(name) {
27546
- if (this.activeConnections(name) > 0) {
28086
+ requireTemplate(name2) {
28087
+ if (this.activeConnections(name2) > 0) {
27547
28088
  throw new PostgresError(
27548
28089
  "object_not_in_prerequisite_state",
27549
- `source database "${name}" is being accessed by other users`,
28090
+ `source database "${name2}" is being accessed by other users`,
27550
28091
  "55006"
27551
28092
  );
27552
28093
  }
27553
- return this.requireDatabase(name);
28094
+ return this.requireDatabase(name2);
27554
28095
  }
27555
- activeConnections(name) {
28096
+ activeConnections(name2) {
27556
28097
  let count = 0;
27557
- for (const session of this.sessions.values()) if (session.databaseName === name) count++;
28098
+ for (const session of this.sessions.values()) if (session.databaseName === name2) count++;
27558
28099
  return count;
27559
28100
  }
27560
- installDatabase(name, db) {
27561
- const context = { name, names: () => this.databaseNames() };
28101
+ installDatabase(name2, db) {
28102
+ const context = { name: name2, names: () => this.databaseNames() };
27562
28103
  setDatabaseCatalogContext(db.state, context);
27563
- this.databases.set(name, db);
28104
+ this.databases.set(name2, db);
27564
28105
  registerSessionFunctions(this, db);
27565
28106
  }
27566
28107
  newPid() {
@@ -27817,7 +28358,7 @@ function readSlabCell(column, rowIndex, intern, rowCount) {
27817
28358
  }
27818
28359
  if (pack === PACK_INT) {
27819
28360
  const integer2 = view.getBigInt64(nonNullIndex * 8, true);
27820
- return integer2 <= BigInt(Number.MAX_SAFE_INTEGER) && integer2 >= BigInt(Number.MIN_SAFE_INTEGER) ? Number(integer2) : integer2;
28361
+ return !column.integerBigInt && integer2 <= BigInt(Number.MAX_SAFE_INTEGER) && integer2 >= BigInt(Number.MIN_SAFE_INTEGER) ? Number(integer2) : integer2;
27821
28362
  }
27822
28363
  if (pack === PACK_TEXT_INTERN) {
27823
28364
  const id = view.getUint32(nonNullIndex * 4, true);
@@ -28378,7 +28919,8 @@ function decodeInner(snapshot, prng, clock) {
28378
28919
  if (meta.stats) state.tableStats.set(table.oid, meta.stats);
28379
28920
  const rowCount = readVarintU32(r);
28380
28921
  const slabColumns = [];
28381
- for (let c = 0; c < meta.columns.length; c++) slabColumns.push(readPackedColumn(r, rowCount, intern));
28922
+ for (let c = 0; c < meta.columns.length; c++)
28923
+ slabColumns.push(readPackedColumn(r, rowCount, intern, meta.columns[c].type.id));
28382
28924
  table.attachSlab(new ColumnarSlab(snapshot, rowCount, slabColumns, intern));
28383
28925
  schema.tables.set(table.name, table);
28384
28926
  }
@@ -28391,7 +28933,7 @@ function decodeInner(snapshot, prng, clock) {
28391
28933
  const matRowCount = readVarintU32(r);
28392
28934
  const width = readVarintU32(r);
28393
28935
  const cols = [];
28394
- for (let c = 0; c < width; c++) cols.push(readPackedColumn(r, matRowCount, intern));
28936
+ for (let c = 0; c < width; c++) cols.push(readPackedColumn(r, matRowCount, intern, meta.matColumns?.[c]?.type));
28395
28937
  const slab = new ColumnarSlab(snapshot, matRowCount, cols, intern);
28396
28938
  matRows = slab.materialize();
28397
28939
  }
@@ -28663,7 +29205,7 @@ function writePackedColumn(w, rows, col, internId, forceId) {
28663
29205
  writeTaggedDatum(w, rows[i][col], internId, forceId);
28664
29206
  }
28665
29207
  }
28666
- function readPackedColumn(r, n, intern) {
29208
+ function readPackedColumn(r, n, intern, type) {
28667
29209
  const pack = r.u8();
28668
29210
  if (pack === PACK_NULL) return { pack, nullBitmap: null, payload: new Uint8Array(0) };
28669
29211
  const bits = r.raw(n + 7 >> 3);
@@ -28676,7 +29218,8 @@ function readPackedColumn(r, n, intern) {
28676
29218
  r.skipAlign4();
28677
29219
  const width = 8;
28678
29220
  const payload = r.raw(nonNull * width);
28679
- return { pack, nullBitmap: bits, payload };
29221
+ const integerBigInt = type !== void 0 && ["int8", "money", "time", "timestamp", "timestamptz"].includes(type);
29222
+ return { pack, nullBitmap: bits, payload, integerBigInt };
28680
29223
  }
28681
29224
  if (pack === PACK_TEXT_INTERN) {
28682
29225
  r.skipAlign4();
@@ -28804,27 +29347,27 @@ function readSchemaCatalog(r, schema, intern, str) {
28804
29347
  schema.indexes.set(idx.name, idx);
28805
29348
  }
28806
29349
  }
28807
- function isRecord(value) {
29350
+ function isRecord2(value) {
28808
29351
  return value !== null && typeof value === "object" && !Array.isArray(value);
28809
29352
  }
28810
29353
  function validateColumnType(value) {
28811
- if (!isRecord(value) || typeof value.id !== "string") throw snapshotError();
29354
+ if (!isRecord2(value) || typeof value.id !== "string") throw snapshotError();
28812
29355
  }
28813
29356
  function validateColumnMeta(value) {
28814
- if (!isRecord(value) || typeof value.name !== "string") throw snapshotError();
29357
+ if (!isRecord2(value) || typeof value.name !== "string") throw snapshotError();
28815
29358
  validateColumnType(value.type);
28816
29359
  }
28817
29360
  function validateTableMetaBjv(value) {
28818
- if (!isRecord(value) || typeof value.name !== "string" || typeof value.schema !== "string") throw snapshotError();
29361
+ if (!isRecord2(value) || typeof value.name !== "string" || typeof value.schema !== "string") throw snapshotError();
28819
29362
  if (!Array.isArray(value.columns)) throw snapshotError();
28820
29363
  for (const col of value.columns) validateColumnMeta(col);
28821
29364
  }
28822
29365
  function validateViewMetaBjv(value) {
28823
- if (!isRecord(value) || typeof value.name !== "string" || typeof value.schema !== "string") throw snapshotError();
29366
+ if (!isRecord2(value) || typeof value.name !== "string" || typeof value.schema !== "string") throw snapshotError();
28824
29367
  if (value.matColumns === null || value.matColumns === void 0) return;
28825
29368
  if (!Array.isArray(value.matColumns)) throw snapshotError();
28826
29369
  for (const col of value.matColumns) {
28827
- if (!isRecord(col) || typeof col.name !== "string" || typeof col.type !== "string") throw snapshotError();
29370
+ if (!isRecord2(col) || typeof col.name !== "string" || typeof col.type !== "string") throw snapshotError();
28828
29371
  }
28829
29372
  }
28830
29373
  function snapshotError() {
@@ -29011,7 +29554,7 @@ var encodeLive = (database) => requireCodec().encodeDatabaseState(database.state
29011
29554
  });
29012
29555
  var openImage = (image, template) => {
29013
29556
  const databases = /* @__PURE__ */ new Map();
29014
- for (const [name, bytes] of image) {
29557
+ for (const [name2, bytes] of image) {
29015
29558
  const database = Snapshot.decode(bytes).open({
29016
29559
  seed: template.seed,
29017
29560
  random: template.randomMode,
@@ -29019,7 +29562,7 @@ var openImage = (image, template) => {
29019
29562
  ...template.systemClock ? { now: "system" } : {}
29020
29563
  });
29021
29564
  if (!template.systemClock) database.now = template.now;
29022
- databases.set(name, database);
29565
+ databases.set(name2, database);
29023
29566
  }
29024
29567
  return databases;
29025
29568
  };
@@ -29039,8 +29582,8 @@ var Durability = class {
29039
29582
  /** Record that storage already holds `image` for the cluster's databases (after a restart). */
29040
29583
  adopt(image) {
29041
29584
  this.image = image;
29042
- for (const [name, bytes] of image) {
29043
- const database = this.cluster.getDatabase(name);
29585
+ for (const [name2, bytes] of image) {
29586
+ const database = this.cluster.getDatabase(name2);
29044
29587
  if (database) this.persisted.set(database, bytes);
29045
29588
  }
29046
29589
  }
@@ -29062,16 +29605,16 @@ var Durability = class {
29062
29605
  const image = /* @__PURE__ */ new Map();
29063
29606
  const databases = /* @__PURE__ */ new Map();
29064
29607
  let same = this.image !== null && this.image.size === this.cluster.databaseNames().length;
29065
- for (const name of this.cluster.databaseNames()) {
29066
- const database = this.cluster.requireDatabase(name);
29608
+ for (const name2 of this.cluster.databaseNames()) {
29609
+ const database = this.cluster.requireDatabase(name2);
29067
29610
  const previous = this.persisted.get(database);
29068
29611
  let bytes = previous;
29069
29612
  if (bytes === void 0 || changed === "all" || changed.includes(database)) {
29070
29613
  const encoded = encodeLive(database);
29071
29614
  bytes = previous !== void 0 && sameBytes(previous, encoded) ? previous : encoded;
29072
29615
  }
29073
- same &&= this.image?.get(name) === bytes;
29074
- image.set(name, bytes);
29616
+ same &&= this.image?.get(name2) === bytes;
29617
+ image.set(name2, bytes);
29075
29618
  databases.set(database, bytes);
29076
29619
  }
29077
29620
  if (same) return false;
@@ -29177,7 +29720,7 @@ var backend = {
29177
29720
  }),
29178
29721
  authenticationSASLContinue: (data) => message("R", (w) => w.i32(11).bytes(encoder2.encode(data))),
29179
29722
  authenticationSASLFinal: (data) => message("R", (w) => w.i32(12).bytes(encoder2.encode(data))),
29180
- parameterStatus: (name, value) => message("S", (w) => w.cstring(name).cstring(value)),
29723
+ parameterStatus: (name2, value) => message("S", (w) => w.cstring(name2).cstring(value)),
29181
29724
  backendKeyData: (pid, key) => message("K", (w) => w.i32(pid).i32(key)),
29182
29725
  readyForQuery: (status) => message("Z", (w) => w.u8(status.charCodeAt(0))),
29183
29726
  rowDescription: (fields) => message("T", (w) => {
@@ -29494,10 +30037,10 @@ var SWITCHES = "B:bC:c:D:d:EeFf:h:ijk:lN:nOPp:r:S:sTt:v:W:-:";
29494
30037
  var invalidArgument = (arg) => fail("42601", `invalid command-line argument for server process: ${arg}`, {
29495
30038
  hint: 'Try "postgres --help" for more information.'
29496
30039
  });
29497
- var longOption = (flag, arg) => {
30040
+ var longOption = (flag2, arg) => {
29498
30041
  const equals = arg.indexOf("=");
29499
30042
  if (equals === -1) {
29500
- throw fail("42601", flag === "-" ? `--${arg} requires a value` : `-c ${arg} requires a value`);
30043
+ throw fail("42601", flag2 === "-" ? `--${arg} requires a value` : `-c ${arg} requires a value`);
29501
30044
  }
29502
30045
  return { name: arg.slice(0, equals).replaceAll("-", "_"), value: arg.slice(equals + 1) };
29503
30046
  };
@@ -29511,14 +30054,14 @@ var switchSettings = (args2) => {
29511
30054
  break;
29512
30055
  }
29513
30056
  if (arg === "-" || !arg.startsWith("-")) break;
29514
- const flag = arg[1];
29515
- if (flag === ":" || !SWITCHES.includes(flag)) throw invalidArgument(arg);
29516
- if (flag !== "c" && flag !== "-") {
29517
- throw fail("0A000", `startup option -${flag} is not supported: only -c name=value and --name=value are`);
30057
+ const flag2 = arg[1];
30058
+ if (flag2 === ":" || !SWITCHES.includes(flag2)) throw invalidArgument(arg);
30059
+ if (flag2 !== "c" && flag2 !== "-") {
30060
+ throw fail("0A000", `startup option -${flag2} is not supported: only -c name=value and --name=value are`);
29518
30061
  }
29519
30062
  const value = arg.length > 2 ? arg.slice(2) : args2[++at];
29520
30063
  if (value === void 0) throw invalidArgument(arg);
29521
- settings.push(longOption(flag, value));
30064
+ settings.push(longOption(flag2, value));
29522
30065
  }
29523
30066
  if (at < args2.length) throw invalidArgument(args2[at]);
29524
30067
  return settings;
@@ -29526,9 +30069,9 @@ var switchSettings = (args2) => {
29526
30069
  var NOT_SETTINGS = /* @__PURE__ */ new Set(["user", "database", "options", "replication"]);
29527
30070
  var startupSettings = (parameters) => {
29528
30071
  const settings = switchSettings(splitOptions(parameters.options ?? ""));
29529
- for (const [name, value] of Object.entries(parameters)) {
29530
- if (NOT_SETTINGS.has(name) || name.startsWith("_pq_.")) continue;
29531
- settings.push({ name, value });
30072
+ for (const [name2, value] of Object.entries(parameters)) {
30073
+ if (NOT_SETTINGS.has(name2) || name2.startsWith("_pq_.")) continue;
30074
+ settings.push({ name: name2, value });
29532
30075
  }
29533
30076
  return settings;
29534
30077
  };
@@ -29543,15 +30086,15 @@ var splitIdentifierList = (raw) => {
29543
30086
  if (at >= raw.length) return names;
29544
30087
  for (; ; ) {
29545
30088
  if (raw[at] === '"') {
29546
- let name = "";
30089
+ let name2 = "";
29547
30090
  for (at++; ; at++) {
29548
30091
  if (at >= raw.length) return null;
29549
- if (raw[at] !== '"') name += raw[at];
29550
- else if (raw[at + 1] === '"') name += raw[at++];
30092
+ if (raw[at] !== '"') name2 += raw[at];
30093
+ else if (raw[at + 1] === '"') name2 += raw[at++];
29551
30094
  else break;
29552
30095
  }
29553
30096
  at++;
29554
- names.push(name);
30097
+ names.push(name2);
29555
30098
  } else {
29556
30099
  const start3 = at;
29557
30100
  while (at < raw.length && raw[at] !== "," && !isListSpace(raw[at])) at++;
@@ -29565,12 +30108,12 @@ var splitIdentifierList = (raw) => {
29565
30108
  skipSpace();
29566
30109
  }
29567
30110
  };
29568
- var invalidValue = (name, value, extra = {}) => fail("22023", `invalid value for parameter "${name}": "${value}"`, extra);
29569
- var bool = (value, name) => {
30111
+ var invalidValue = (name2, value, extra = {}) => fail("22023", `invalid value for parameter "${name2}": "${value}"`, extra);
30112
+ var bool = (value, name2) => {
29570
30113
  const text = value.toLowerCase();
29571
30114
  const truthy = text !== "" && ("true".startsWith(text) || "yes".startsWith(text) || text === "on" || text === "1");
29572
30115
  const falsy = text !== "" && ("false".startsWith(text) || "no".startsWith(text) || text === "of" || text === "off" || text === "0");
29573
- if (!truthy && !falsy) throw fail("22023", `parameter "${name}" requires a Boolean value`);
30116
+ if (!truthy && !falsy) throw fail("22023", `parameter "${name2}" requires a Boolean value`);
29574
30117
  return truthy ? "on" : "off";
29575
30118
  };
29576
30119
  var INT_MAX = 2147483647;
@@ -29589,13 +30132,13 @@ var rint2 = (value) => {
29589
30132
  if (diff !== 0.5) return Math.round(value);
29590
30133
  return floor % 2 === 0 ? floor : floor + 1;
29591
30134
  };
29592
- var integer = (min, max) => (value, name) => {
30135
+ var integer = (min, max) => (value, name2) => {
29593
30136
  const parsed = parseNumber(value);
29594
30137
  const result = parsed?.rest.trim() === "" ? rint2(parsed.value) : Number.NaN;
29595
- if (Number.isNaN(result)) throw invalidValue(name, value);
29596
- if (Math.abs(result) > INT_MAX) throw invalidValue(name, value, { hint: "Value exceeds integer range." });
30138
+ if (Number.isNaN(result)) throw invalidValue(name2, value);
30139
+ if (Math.abs(result) > INT_MAX) throw invalidValue(name2, value, { hint: "Value exceeds integer range." });
29597
30140
  if (result < min || result > max) {
29598
- throw fail("22023", `${result} is outside the valid range for parameter "${name}" (${min} .. ${max})`);
30141
+ throw fail("22023", `${result} is outside the valid range for parameter "${name2}" (${min} .. ${max})`);
29599
30142
  }
29600
30143
  return String(result);
29601
30144
  };
@@ -29607,37 +30150,37 @@ var TIME_UNITS = [
29607
30150
  ["ms", 1e3],
29608
30151
  ["us", 1]
29609
30152
  ];
29610
- var milliseconds = (value, name) => {
30153
+ var milliseconds = (value, name2) => {
29611
30154
  const hint = 'Valid units for this parameter are "us", "ms", "s", "min", "h", and "d".';
29612
30155
  const parsed = parseNumber(value);
29613
- if (!parsed) throw invalidValue(name, value);
30156
+ if (!parsed) throw invalidValue(name2, value);
29614
30157
  const unit = parsed.rest.trim();
29615
30158
  const micros = TIME_UNITS.find(([known]) => known === (unit === "" ? "ms" : unit))?.[1];
29616
- if (micros === void 0) throw invalidValue(name, value, { hint });
30159
+ if (micros === void 0) throw invalidValue(name2, value, { hint });
29617
30160
  const ms = rint2(parsed.value * micros / 1e3);
29618
- if (Math.abs(ms) > INT_MAX) throw invalidValue(name, value, { hint: "Value exceeds integer range." });
30161
+ if (Math.abs(ms) > INT_MAX) throw invalidValue(name2, value, { hint: "Value exceeds integer range." });
29619
30162
  if (ms < 0) {
29620
- throw fail("22023", `${ms} ms is outside the valid range for parameter "${name}" (0 ms .. ${INT_MAX} ms)`);
30163
+ throw fail("22023", `${ms} ms is outside the valid range for parameter "${name2}" (0 ms .. ${INT_MAX} ms)`);
29621
30164
  }
29622
30165
  if (ms === 0) return "0";
29623
30166
  const [shown, each] = TIME_UNITS.find(([, size]) => size >= 1e3 && ms * 1e3 % size === 0);
29624
30167
  return `${ms * 1e3 / each}${shown}`;
29625
30168
  };
29626
- var oneOf = (options2, hidden = {}) => (value, name) => {
30169
+ var oneOf = (options2, hidden = {}) => (value, name2) => {
29627
30170
  const text = value.toLowerCase();
29628
30171
  const found = options2.includes(text) ? text : hidden[text];
29629
- if (found === void 0) throw invalidValue(name, value, { hint: `Available values: ${options2.join(", ")}.` });
30172
+ if (found === void 0) throw invalidValue(name2, value, { hint: `Available values: ${options2.join(", ")}.` });
29630
30173
  return found;
29631
30174
  };
29632
30175
  var ISOLATION_LEVELS = ["serializable", "repeatable read", "read committed", "read uncommitted"];
29633
- var searchPath = (value, name) => {
29634
- if (splitIdentifierList(value) === null) throw invalidValue(name, value, { detail: "List syntax is invalid." });
30176
+ var searchPath = (value, name2) => {
30177
+ if (splitIdentifierList(value) === null) throw invalidValue(name2, value, { detail: "List syntax is invalid." });
29635
30178
  return value.replace(/"(?:[^"]|"")*"|[^"]+/g, (part) => part.startsWith('"') ? part : part.toLowerCase());
29636
30179
  };
29637
30180
  var DATE_STYLES = { iso: "ISO", sql: "SQL", postgres: "Postgres", german: "German" };
29638
- var dateStyle = (value, name, current) => {
30181
+ var dateStyle = (value, name2, current) => {
29639
30182
  const words = splitIdentifierList(value);
29640
- if (words === null) throw invalidValue(name, value, { detail: "List syntax is invalid." });
30183
+ if (words === null) throw invalidValue(name2, value, { detail: "List syntax is invalid." });
29641
30184
  let style;
29642
30185
  let order;
29643
30186
  let conflict = false;
@@ -29651,20 +30194,20 @@ var dateStyle = (value, name, current) => {
29651
30194
  conflict ||= order !== void 0 && order !== nextOrder;
29652
30195
  order = nextOrder;
29653
30196
  } else if (word !== "default") {
29654
- throw invalidValue(name, value, { detail: `Unrecognized key word: "${word}".` });
30197
+ throw invalidValue(name2, value, { detail: `Unrecognized key word: "${word}".` });
29655
30198
  }
29656
30199
  }
29657
- if (conflict) throw invalidValue(name, value, { detail: 'Conflicting "DateStyle" specifications.' });
30200
+ if (conflict) throw invalidValue(name2, value, { detail: 'Conflicting "DateStyle" specifications.' });
29658
30201
  const [currentStyle, currentOrder] = (current.get("datestyle") ?? "ISO, MDY").split(", ");
29659
30202
  const useDefault = words.includes("default");
29660
30203
  order ??= style === "German" ? "DMY" : void 0;
29661
30204
  return `${style ?? (useDefault ? "ISO" : currentStyle)}, ${order ?? (useDefault ? "MDY" : currentOrder)}`;
29662
30205
  };
29663
- var timeZone = (value, name) => {
30206
+ var timeZone = (value, name2) => {
29664
30207
  try {
29665
30208
  validateZone(value);
29666
30209
  } catch {
29667
- throw invalidValue(name, value);
30210
+ throw invalidValue(name2, value);
29668
30211
  }
29669
30212
  return value;
29670
30213
  };
@@ -29672,8 +30215,8 @@ var clientEncoding = (value) => {
29672
30215
  const normalized = value.replace(/[^A-Za-z0-9]/g, "").toUpperCase();
29673
30216
  return normalized === "UTF8" || normalized === "UNICODE" ? "UTF8" : value;
29674
30217
  };
29675
- var readOnly = (_value, name) => {
29676
- throw fail("55P02", `parameter "${name}" cannot be changed`);
30218
+ var readOnly = (_value, name2) => {
30219
+ throw fail("55P02", `parameter "${name2}" cannot be changed`);
29677
30220
  };
29678
30221
  var PARAMETERS = {
29679
30222
  search_path: { check: searchPath },
@@ -29715,10 +30258,10 @@ var PARAMETERS = {
29715
30258
  };
29716
30259
  var applyStartupSettings = (settings, session) => {
29717
30260
  const applied = /* @__PURE__ */ new Map();
29718
- for (const { name, value } of settings) {
29719
- const key = name.toLowerCase();
30261
+ for (const { name: name2, value } of settings) {
30262
+ const key = name2.toLowerCase();
29720
30263
  if (!session.has(key) && !key.includes(".")) {
29721
- throw fail("42704", `unrecognized configuration parameter "${name}"`);
30264
+ throw fail("42704", `unrecognized configuration parameter "${name2}"`);
29722
30265
  }
29723
30266
  const parameter = PARAMETERS[key];
29724
30267
  const checked = parameter ? parameter.check(value, parameter.display ?? key, session) : value;
@@ -29890,10 +30433,10 @@ var WRITE_NODES = /* @__PURE__ */ new Set(["insert", "update", "delete"]);
29890
30433
  var containsWrite = (db, node) => {
29891
30434
  if (Array.isArray(node)) return node.some((item) => containsWrite(db, item));
29892
30435
  if (typeof node !== "object" || node === null) return false;
29893
- const { type, name } = node;
30436
+ const { type, name: name2 } = node;
29894
30437
  if (typeof type === "string" && WRITE_NODES.has(type)) return true;
29895
- if (Array.isArray(name)) {
29896
- const named = String(name.at(-1)).toLowerCase();
30438
+ if (Array.isArray(name2)) {
30439
+ const named = String(name2.at(-1)).toLowerCase();
29897
30440
  if (named === "nextval" || named === "setval") return true;
29898
30441
  for (const schema of db.state.schemas.values()) {
29899
30442
  if (schema.functions.has(named) || schema.views.has(named)) return true;
@@ -29984,9 +30527,9 @@ function returningShape(db, sql) {
29984
30527
  continue;
29985
30528
  }
29986
30529
  if (target.expr.type === "colref") {
29987
- const name = target.expr.parts.at(-1) ?? "?column?";
29988
- const column = table.columns.find((item) => item.name === name);
29989
- columns.push(target.alias ?? name);
30530
+ const name2 = target.expr.parts.at(-1) ?? "?column?";
30531
+ const column = table.columns.find((item) => item.name === name2);
30532
+ columns.push(target.alias ?? name2);
29990
30533
  columnTypes.push(column?.type.id ?? "text");
29991
30534
  continue;
29992
30535
  }
@@ -30271,7 +30814,7 @@ var Connection = class {
30271
30814
  }
30272
30815
  this.settings = settings;
30273
30816
  this.started = true;
30274
- const setting = (name, fallback2) => settings.get(name) ?? fallback2;
30817
+ const setting = (name2, fallback2) => settings.get(name2) ?? fallback2;
30275
30818
  const status = {
30276
30819
  server_version: this.options.serverVersion,
30277
30820
  server_encoding: "UTF8",
@@ -30289,7 +30832,7 @@ var Connection = class {
30289
30832
  scram_iterations: "4096",
30290
30833
  ...this.options.parameters
30291
30834
  };
30292
- for (const [name, value] of Object.entries(status)) this.write(backend.parameterStatus(name, value));
30835
+ for (const [name2, value] of Object.entries(status)) this.write(backend.parameterStatus(name2, value));
30293
30836
  this.write(backend.backendKeyData(this.pid, this.secret));
30294
30837
  this.write(backend.readyForQuery("I"));
30295
30838
  }
@@ -30567,12 +31110,12 @@ var Connection = class {
30567
31110
  }
30568
31111
  }
30569
31112
  }
30570
- findSavepoint(name) {
31113
+ findSavepoint(name2) {
30571
31114
  if (!this.transaction) throw pgError2("internal", "SAVEPOINT can only be used in transaction blocks", "25P01");
30572
31115
  for (let i = this.transaction.savepoints.length - 1; i >= 0; i--) {
30573
- if (this.transaction.savepoints[i]?.name === name) return i;
31116
+ if (this.transaction.savepoints[i]?.name === name2) return i;
30574
31117
  }
30575
- throw pgError2("internal", `savepoint "${name}" does not exist`, "3B001");
31118
+ throw pgError2("internal", `savepoint "${name2}" does not exist`, "3B001");
30576
31119
  }
30577
31120
  /** Rebase this transaction's successful writes onto the latest committed state. */
30578
31121
  openWorkspace() {
@@ -30684,16 +31227,16 @@ var Connection = class {
30684
31227
  }
30685
31228
  const create = CREATE_DATABASE.exec(text);
30686
31229
  if (create) {
30687
- const name = identifier(create[1], create[2]);
31230
+ const name2 = identifier(create[1], create[2]);
30688
31231
  const template = create[3] === void 0 && create[4] === void 0 ? void 0 : identifier(create[3], create[4]);
30689
- this.cluster.createDatabase(name, template);
31232
+ this.cluster.createDatabase(name2, template);
30690
31233
  return command("CREATE DATABASE");
30691
31234
  }
30692
31235
  const drop = DROP_DATABASE.exec(text);
30693
31236
  if (drop) {
30694
- const name = identifier(drop[2], drop[3]);
30695
- if (drop[1] && !this.cluster.getDatabase(name)) return command("DROP DATABASE");
30696
- this.cluster.dropDatabase(name, this);
31237
+ const name2 = identifier(drop[2], drop[3]);
31238
+ if (drop[1] && !this.cluster.getDatabase(name2)) return command("DROP DATABASE");
31239
+ this.cluster.dropDatabase(name2, this);
30697
31240
  return command("DROP DATABASE");
30698
31241
  }
30699
31242
  const rename3 = RENAME_DATABASE.exec(text);
@@ -30948,14 +31491,14 @@ var Connection = class {
30948
31491
  }
30949
31492
  fields(result, requested) {
30950
31493
  const formats = this.columnFormats(result, requested);
30951
- return result.columns.map((name, i) => {
31494
+ return result.columns.map((name2, i) => {
30952
31495
  const type = result.columnTypes[i];
30953
- return { name, typeOid: typeOid(type), typeLen: TYPLEN[type] ?? -1, format: formats[i] };
31496
+ return { name: name2, typeOid: typeOid(type), typeLen: TYPLEN[type] ?? -1, format: formats[i] };
30954
31497
  });
30955
31498
  }
30956
31499
  // --- extended query -----------------------------------------------------------------------
30957
31500
  async parse(body) {
30958
- const name = body.cstring();
31501
+ const name2 = body.cstring();
30959
31502
  const sql = body.cstring();
30960
31503
  const count = body.i16();
30961
31504
  const paramOids = [];
@@ -30964,10 +31507,10 @@ var Connection = class {
30964
31507
  if (text !== "" && !LISTEN.test(text) && !UNLISTEN.test(text) && !NOTIFY.test(text) && !TX_CONTROL.test(text)) {
30965
31508
  if (!CLUSTER_DDL.test(text)) this.database.prepare(text);
30966
31509
  }
30967
- if (name !== "" && this.prepared.has(name)) {
30968
- throw pgError2("internal", `prepared statement "${name}" already exists`, "42P05");
31510
+ if (name2 !== "" && this.prepared.has(name2)) {
31511
+ throw pgError2("internal", `prepared statement "${name2}" already exists`, "42P05");
30969
31512
  }
30970
- this.prepared.set(name, { name, sql: text, paramOids });
31513
+ this.prepared.set(name2, { name: name2, sql: text, paramOids });
30971
31514
  this.write(backend.parseComplete());
30972
31515
  }
30973
31516
  bind(body) {
@@ -30997,17 +31540,17 @@ var Connection = class {
30997
31540
  }
30998
31541
  async describe(body) {
30999
31542
  const kind = String.fromCharCode(body.u8());
31000
- const name = body.cstring();
31543
+ const name2 = body.cstring();
31001
31544
  if (kind === "S") {
31002
- const prepared = this.prepared.get(name);
31003
- if (!prepared) throw pgError2("internal", `prepared statement "${name}" does not exist`, "26000");
31545
+ const prepared = this.prepared.get(name2);
31546
+ if (!prepared) throw pgError2("internal", `prepared statement "${name2}" does not exist`, "26000");
31004
31547
  this.write(backend.parameterDescription(prepared.paramOids.map((oid) => oid === 0 ? 25 : oid)));
31005
31548
  const shape = await this.shapeOf(prepared);
31006
31549
  this.write(shape ? backend.rowDescription(this.fields(shape, [])) : backend.noData());
31007
31550
  return;
31008
31551
  }
31009
- const portal = this.portals.get(name);
31010
- if (!portal) throw pgError2("internal", `portal "${name}" does not exist`, "34000");
31552
+ const portal = this.portals.get(name2);
31553
+ if (!portal) throw pgError2("internal", `portal "${name2}" does not exist`, "34000");
31011
31554
  this.busy = true;
31012
31555
  portal.outcome ??= await this.execute(portal.prepared.sql, portal.params);
31013
31556
  const outcome = portal.outcome;
@@ -31032,13 +31575,13 @@ var Connection = class {
31032
31575
  const params = prepared.paramOids.map(() => null);
31033
31576
  return this.inSession(db, () => {
31034
31577
  if (db.transactions.inTransaction) {
31035
- const name = `__describe_${this.pid}`;
31036
- db.transactions.savepoint(name);
31578
+ const name2 = `__describe_${this.pid}`;
31579
+ db.transactions.savepoint(name2);
31037
31580
  try {
31038
31581
  return this.cluster.as(this, () => db.prepare(prepared.sql).textResult(...params));
31039
31582
  } finally {
31040
- db.transactions.rollbackToSavepoint(name);
31041
- db.transactions.releaseSavepoint(name);
31583
+ db.transactions.rollbackToSavepoint(name2);
31584
+ db.transactions.releaseSavepoint(name2);
31042
31585
  }
31043
31586
  }
31044
31587
  db.transactions.begin();
@@ -31055,10 +31598,10 @@ var Connection = class {
31055
31598
  }
31056
31599
  }
31057
31600
  async executePortal(body) {
31058
- const name = body.cstring();
31601
+ const name2 = body.cstring();
31059
31602
  const maxRows = body.i32();
31060
- const portal = this.portals.get(name);
31061
- if (!portal) throw pgError2("internal", `portal "${name}" does not exist`, "34000");
31603
+ const portal = this.portals.get(name2);
31604
+ if (!portal) throw pgError2("internal", `portal "${name2}" does not exist`, "34000");
31062
31605
  this.busy = true;
31063
31606
  try {
31064
31607
  portal.outcome ??= await this.execute(portal.prepared.sql, portal.params);
@@ -31079,12 +31622,12 @@ var Connection = class {
31079
31622
  }
31080
31623
  close(body) {
31081
31624
  const kind = String.fromCharCode(body.u8());
31082
- const name = body.cstring();
31625
+ const name2 = body.cstring();
31083
31626
  if (kind === "S") {
31084
- this.prepared.delete(name);
31627
+ this.prepared.delete(name2);
31085
31628
  for (const [portalName, portal] of [...this.portals])
31086
- if (portal.prepared.name === name) this.portals.delete(portalName);
31087
- } else this.portals.delete(name);
31629
+ if (portal.prepared.name === name2) this.portals.delete(portalName);
31630
+ } else this.portals.delete(name2);
31088
31631
  this.write(backend.closeComplete());
31089
31632
  }
31090
31633
  sync() {
@@ -31149,8 +31692,8 @@ var fileStorage = (root) => {
31149
31692
  }
31150
31693
  return `${digest}.pgmm`;
31151
31694
  };
31152
- const writeAtomic = async (name, bytes) => {
31153
- const pending2 = join(root, `${name}.${process.pid}.${temporary++}.tmp`);
31695
+ const writeAtomic = async (name2, bytes) => {
31696
+ const pending2 = join(root, `${name2}.${process.pid}.${temporary++}.tmp`);
31154
31697
  const handle = await open(pending2, "w");
31155
31698
  try {
31156
31699
  await handle.writeFile(bytes);
@@ -31158,7 +31701,7 @@ var fileStorage = (root) => {
31158
31701
  } finally {
31159
31702
  await handle.close();
31160
31703
  }
31161
- await rename2(pending2, join(root, name));
31704
+ await rename2(pending2, join(root, name2));
31162
31705
  };
31163
31706
  const syncDirectory = async () => {
31164
31707
  if (process.platform === "win32") return;
@@ -31169,13 +31712,13 @@ var fileStorage = (root) => {
31169
31712
  await handle.close();
31170
31713
  }
31171
31714
  };
31172
- const remove = (name) => unlink(join(root, name)).catch(() => void 0);
31715
+ const remove = (name2) => unlink(join(root, name2)).catch(() => void 0);
31173
31716
  return {
31174
31717
  async read() {
31175
31718
  await mkdir(root, { recursive: true });
31176
31719
  const entries = await readdir(root);
31177
- await Promise.all(entries.filter((name) => name.endsWith(".tmp")).map(remove));
31178
- const snapshots = entries.filter((name) => SNAPSHOT_FILE.test(name));
31720
+ await Promise.all(entries.filter((name2) => name2.endsWith(".tmp")).map(remove));
31721
+ const snapshots = entries.filter((name2) => SNAPSHOT_FILE.test(name2));
31179
31722
  present.clear();
31180
31723
  if (!entries.includes(MANIFEST)) {
31181
31724
  await Promise.all(snapshots.map(remove));
@@ -31183,30 +31726,30 @@ var fileStorage = (root) => {
31183
31726
  }
31184
31727
  const manifest = parseManifest(root, await readFile3(join(root, MANIFEST), "utf8"));
31185
31728
  const image = /* @__PURE__ */ new Map();
31186
- for (const { name, file, bytes: length } of manifest.databases) {
31729
+ for (const { name: name2, file, bytes: length } of manifest.databases) {
31187
31730
  let bytes;
31188
31731
  try {
31189
31732
  bytes = new Uint8Array(await readFile3(join(root, file)));
31190
31733
  } catch {
31191
- throw corrupt(root, `the snapshot of database "${name}" is missing`);
31734
+ throw corrupt(root, `the snapshot of database "${name2}" is missing`);
31192
31735
  }
31193
31736
  if (bytes.byteLength !== length || `${sha2562(bytes)}.pgmm` !== file) {
31194
- throw corrupt(root, `the snapshot of database "${name}" does not match its manifest entry`);
31737
+ throw corrupt(root, `the snapshot of database "${name2}" does not match its manifest entry`);
31195
31738
  }
31196
31739
  digests.set(bytes, file.slice(0, 64));
31197
31740
  present.add(file);
31198
- image.set(name, bytes);
31741
+ image.set(name2, bytes);
31199
31742
  }
31200
- await Promise.all(snapshots.filter((name) => !present.has(name)).map(remove));
31743
+ await Promise.all(snapshots.filter((name2) => !present.has(name2)).map(remove));
31201
31744
  return image;
31202
31745
  },
31203
31746
  async write(image) {
31204
31747
  await mkdir(root, { recursive: true });
31205
31748
  const manifest = { format: FORMAT, version: VERSION2, databases: [] };
31206
31749
  let added = false;
31207
- for (const [name, bytes] of image) {
31750
+ for (const [name2, bytes] of image) {
31208
31751
  const file = fileOf(bytes);
31209
- manifest.databases.push({ name, file, bytes: bytes.byteLength });
31752
+ manifest.databases.push({ name: name2, file, bytes: bytes.byteLength });
31210
31753
  if (present.has(file)) continue;
31211
31754
  await writeAtomic(file, bytes);
31212
31755
  present.add(file);
@@ -31294,7 +31837,7 @@ var start2 = async (options2) => {
31294
31837
  );
31295
31838
  }
31296
31839
  const cluster = new Cluster(restored?.get(initialName) ?? seed, initialName);
31297
- for (const [name, database] of restored ?? []) if (name !== initialName) cluster.attach(name, database);
31840
+ for (const [name2, database] of restored ?? []) if (name2 !== initialName) cluster.attach(name2, database);
31298
31841
  let durability = null;
31299
31842
  if (durable) {
31300
31843
  durability = new Durability(cluster, durable.storage, durable);
@@ -31325,12 +31868,12 @@ var start2 = async (options2) => {
31325
31868
  server2.removeListener("error", reject);
31326
31869
  const address = server2.address();
31327
31870
  const port = typeof address === "object" && address !== null ? address.port : 0;
31328
- const name = initialName;
31871
+ const name2 = initialName;
31329
31872
  const auth = options2.password ? `${encodeURIComponent(user)}:${encodeURIComponent(options2.password)}@` : `${encodeURIComponent(user)}@`;
31330
31873
  resolve2({
31331
31874
  port,
31332
31875
  host,
31333
- connectionString: `postgres://${auth}${host}:${port}/${encodeURIComponent(name)}`,
31876
+ connectionString: `postgres://${auth}${host}:${port}/${encodeURIComponent(name2)}`,
31334
31877
  get database() {
31335
31878
  return cluster.db;
31336
31879
  },
@@ -31486,8 +32029,8 @@ async function startProtocol(entry) {
31486
32029
  const namespaces = /* @__PURE__ */ new Map();
31487
32030
  const selectors = { default: entry.database ?? "postgres", ...entry.namespaces };
31488
32031
  try {
31489
- for (const [name, databaseName] of Object.entries(selectors)) {
31490
- if (!/^[A-Za-z0-9_.-]{1,64}$/.test(name) || typeof databaseName !== "string")
32032
+ for (const [name2, databaseName] of Object.entries(selectors)) {
32033
+ if (!/^[A-Za-z0-9_.-]{1,64}$/.test(name2) || typeof databaseName !== "string")
31491
32034
  throw new Error("invalid Postgres namespace/database name");
31492
32035
  const clock = createClock();
31493
32036
  const database = new Database({
@@ -31499,37 +32042,37 @@ async function startProtocol(entry) {
31499
32042
  databaseName,
31500
32043
  allowDatabaseSelection: true,
31501
32044
  host: entry.host ?? "127.0.0.1",
31502
- port: name === "default" ? entry.port ?? 0 : 0,
32045
+ port: name2 === "default" ? entry.port ?? 0 : 0,
31503
32046
  ...entry.password !== void 0 ? { password: entry.password } : {},
31504
32047
  ...entry.user !== void 0 ? { user: entry.user } : {}
31505
32048
  });
31506
- namespaces.set(name, { server: server2, clock });
32049
+ namespaces.set(name2, { server: server2, clock });
31507
32050
  }
31508
32051
  } catch (error) {
31509
32052
  await Promise.allSettled([...namespaces.values()].map(({ server: server2 }) => server2.close()));
31510
32053
  throw error;
31511
32054
  }
31512
- const get = (name) => {
31513
- const found = namespaces.get(name);
31514
- if (!found) throw new Error(`Postgres namespace ${name} is not configured`);
32055
+ const get = (name2) => {
32056
+ const found = namespaces.get(name2);
32057
+ if (!found) throw new Error(`Postgres namespace ${name2} is not configured`);
31515
32058
  return found;
31516
32059
  };
31517
- const publicUrl2 = (name) => {
31518
- const url = new URL(get(name).server.connectionString);
32060
+ const publicUrl2 = (name2) => {
32061
+ const url = new URL(get(name2).server.connectionString);
31519
32062
  url.password = "";
31520
32063
  return url.href;
31521
32064
  };
31522
32065
  const locked = /* @__PURE__ */ new Set();
31523
32066
  const snapshots = /* @__PURE__ */ new WeakMap();
31524
- const origins = new Map([...namespaces].map(([name, { server: server2 }]) => [name, server2.snapshotAll()]));
32067
+ const origins = new Map([...namespaces].map(([name2, { server: server2 }]) => [name2, server2.snapshotAll()]));
31525
32068
  return {
31526
32069
  protocol: "postgres",
31527
32070
  url: publicUrl2("default"),
31528
32071
  connection: get("default").server.connectionString,
31529
- connections: Object.fromEntries([...namespaces].map(([name, { server: server2 }]) => [name, server2.connectionString])),
32072
+ connections: Object.fromEntries([...namespaces].map(([name2, { server: server2 }]) => [name2, server2.connectionString])),
31530
32073
  namespaces: {
31531
32074
  mechanism: "endpoint",
31532
- endpoints: Object.fromEntries([...namespaces.keys()].map((name) => [name, publicUrl2(name)]))
32075
+ endpoints: Object.fromEntries([...namespaces.keys()].map((name2) => [name2, publicUrl2(name2)]))
31533
32076
  },
31534
32077
  async ready() {
31535
32078
  const results = await Promise.all(
@@ -31543,7 +32086,7 @@ async function startProtocol(entry) {
31543
32086
  await Promise.all(
31544
32087
  [...namespaces.values()].map(async ({ server: server2 }) => {
31545
32088
  await server2.close();
31546
- for (const name of server2.databaseNames()) server2.getDatabase(name).close();
32089
+ for (const name2 of server2.databaseNames()) server2.getDatabase(name2).close();
31547
32090
  })
31548
32091
  );
31549
32092
  },
@@ -31585,7 +32128,7 @@ async function startProtocol(entry) {
31585
32128
  if (!point || point.namespace !== namespace) throw new Error("invalid Postgres checkpoint");
31586
32129
  const { server: server2, clock } = get(namespace);
31587
32130
  server2.restoreAll(point.databases);
31588
- for (const name of server2.databaseNames()) server2.getDatabase(name).now = () => new Date(clock.now());
32131
+ for (const name2 of server2.databaseNames()) server2.getDatabase(name2).now = () => new Date(clock.now());
31589
32132
  server2.clearFaults();
31590
32133
  server2.fault(point.faults);
31591
32134
  clock.freeze();
@@ -31595,7 +32138,7 @@ async function startProtocol(entry) {
31595
32138
  async reset(namespace) {
31596
32139
  const { server: server2, clock } = get(namespace);
31597
32140
  server2.restoreAll(origins.get(namespace));
31598
- for (const name of server2.databaseNames()) server2.getDatabase(name).now = () => new Date(clock.now());
32141
+ for (const name2 of server2.databaseNames()) server2.getDatabase(name2).now = () => new Date(clock.now());
31599
32142
  server2.clearFaults();
31600
32143
  clock.reset();
31601
32144
  },
@@ -31633,21 +32176,21 @@ if (args[0] !== "serve") {
31633
32176
  var options = {};
31634
32177
  var log = false;
31635
32178
  for (let i = 1; i < args.length; i++) {
31636
- const flag = args[i];
31637
- if (flag !== void 0 && (flag.startsWith("postgres://") || flag.startsWith("postgresql://"))) {
31638
- options.url = flag;
32179
+ const flag2 = args[i];
32180
+ if (flag2 !== void 0 && (flag2.startsWith("postgres://") || flag2.startsWith("postgresql://"))) {
32181
+ options.url = flag2;
31639
32182
  continue;
31640
32183
  }
31641
32184
  const value = args[i + 1];
31642
32185
  const need = () => {
31643
32186
  if (value === void 0) {
31644
- console.error(`${flag} requires a value`);
32187
+ console.error(`${flag2} requires a value`);
31645
32188
  process.exit(2);
31646
32189
  }
31647
32190
  i++;
31648
32191
  return value;
31649
32192
  };
31650
- switch (flag) {
32193
+ switch (flag2) {
31651
32194
  case "--port":
31652
32195
  options.port = Number(need());
31653
32196
  break;
@@ -31667,7 +32210,7 @@ for (let i = 1; i < args.length; i++) {
31667
32210
  log = true;
31668
32211
  break;
31669
32212
  default:
31670
- console.error(`unknown option ${flag}
32213
+ console.error(`unknown option ${flag2}
31671
32214
  ${usage}`);
31672
32215
  process.exit(2);
31673
32216
  }