prisma-sql 1.75.5 → 1.75.7

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/generator.js CHANGED
@@ -1,11 +1,4 @@
1
1
  #!/usr/bin/env node
2
- import net from 'net';
3
- import tls from 'tls';
4
- import crypto from 'crypto';
5
- import Stream from 'stream';
6
- import { performance as performance$1 } from 'perf_hooks';
7
- import os from 'os';
8
- import fs from 'fs';
9
2
  import { generatorHandler } from '@prisma/generator-helper';
10
3
  import { convertDMMFToModels, processAllDirectives, isDynamicParameter, extractDynamicName } from '@dee-wan/schema-parser';
11
4
  import { mkdir, writeFile } from 'fs/promises';
@@ -21,30 +14,22 @@ var __propIsEnum = Object.prototype.propertyIsEnumerable;
21
14
  var __typeError = (msg) => {
22
15
  throw TypeError(msg);
23
16
  };
24
- var __pow = Math.pow;
25
17
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
26
- var __spreadValues = (a, b2) => {
27
- for (var prop in b2 || (b2 = {}))
28
- if (__hasOwnProp.call(b2, prop))
29
- __defNormalProp(a, prop, b2[prop]);
18
+ var __spreadValues = (a, b) => {
19
+ for (var prop in b || (b = {}))
20
+ if (__hasOwnProp.call(b, prop))
21
+ __defNormalProp(a, prop, b[prop]);
30
22
  if (__getOwnPropSymbols)
31
- for (var prop of __getOwnPropSymbols(b2)) {
32
- if (__propIsEnum.call(b2, prop))
33
- __defNormalProp(a, prop, b2[prop]);
23
+ for (var prop of __getOwnPropSymbols(b)) {
24
+ if (__propIsEnum.call(b, prop))
25
+ __defNormalProp(a, prop, b[prop]);
34
26
  }
35
27
  return a;
36
28
  };
37
- var __spreadProps = (a, b2) => __defProps(a, __getOwnPropDescs(b2));
38
- var __esm = (fn, res) => function __init() {
39
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
40
- };
29
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
41
30
  var __commonJS = (cb, mod) => function __require() {
42
31
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
43
32
  };
44
- var __export = (target, all) => {
45
- for (var name in all)
46
- __defProp(target, name, { get: all[name], enumerable: true });
47
- };
48
33
  var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
49
34
  var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
50
35
  var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
@@ -78,2247 +63,19 @@ var __async = (__this, __arguments, generator) => {
78
63
  });
79
64
  };
80
65
 
81
- // node_modules/postgres/src/query.js
82
- function cachedError(xs) {
83
- if (originCache.has(xs))
84
- return originCache.get(xs);
85
- const x = Error.stackTraceLimit;
86
- Error.stackTraceLimit = 4;
87
- originCache.set(xs, new Error());
88
- Error.stackTraceLimit = x;
89
- return originCache.get(xs);
90
- }
91
- var originCache, originStackCache, originError, CLOSE, Query;
92
- var init_query = __esm({
93
- "node_modules/postgres/src/query.js"() {
94
- originCache = /* @__PURE__ */ new Map();
95
- originStackCache = /* @__PURE__ */ new Map();
96
- originError = /* @__PURE__ */ Symbol("OriginError");
97
- CLOSE = {};
98
- Query = class extends Promise {
99
- constructor(strings, args, handler, canceller, options = {}) {
100
- let resolve3, reject;
101
- super((a, b2) => {
102
- resolve3 = a;
103
- reject = b2;
104
- });
105
- this.tagged = Array.isArray(strings.raw);
106
- this.strings = strings;
107
- this.args = args;
108
- this.handler = handler;
109
- this.canceller = canceller;
110
- this.options = options;
111
- this.state = null;
112
- this.statement = null;
113
- this.resolve = (x) => (this.active = false, resolve3(x));
114
- this.reject = (x) => (this.active = false, reject(x));
115
- this.active = false;
116
- this.cancelled = null;
117
- this.executed = false;
118
- this.signature = "";
119
- this[originError] = this.handler.debug ? new Error() : this.tagged && cachedError(this.strings);
120
- }
121
- get origin() {
122
- return (this.handler.debug ? this[originError].stack : this.tagged && originStackCache.has(this.strings) ? originStackCache.get(this.strings) : originStackCache.set(this.strings, this[originError].stack).get(this.strings)) || "";
123
- }
124
- static get [Symbol.species]() {
125
- return Promise;
126
- }
127
- cancel() {
128
- return this.canceller && (this.canceller(this), this.canceller = null);
129
- }
130
- simple() {
131
- this.options.simple = true;
132
- this.options.prepare = false;
133
- return this;
134
- }
135
- readable() {
136
- return __async(this, null, function* () {
137
- this.simple();
138
- this.streaming = true;
139
- return this;
140
- });
141
- }
142
- writable() {
143
- return __async(this, null, function* () {
144
- this.simple();
145
- this.streaming = true;
146
- return this;
147
- });
148
- }
149
- cursor(rows = 1, fn) {
150
- this.options.simple = false;
151
- if (typeof rows === "function") {
152
- fn = rows;
153
- rows = 1;
154
- }
155
- this.cursorRows = rows;
156
- if (typeof fn === "function")
157
- return this.cursorFn = fn, this;
158
- let prev;
159
- return {
160
- [Symbol.asyncIterator]: () => ({
161
- next: () => {
162
- if (this.executed && !this.active)
163
- return { done: true };
164
- prev && prev();
165
- const promise = new Promise((resolve3, reject) => {
166
- this.cursorFn = (value) => {
167
- resolve3({ value, done: false });
168
- return new Promise((r) => prev = r);
169
- };
170
- this.resolve = () => (this.active = false, resolve3({ done: true }));
171
- this.reject = (x) => (this.active = false, reject(x));
172
- });
173
- this.execute();
174
- return promise;
175
- },
176
- return() {
177
- prev && prev(CLOSE);
178
- return { done: true };
179
- }
180
- })
181
- };
182
- }
183
- describe() {
184
- this.options.simple = false;
185
- this.onlyDescribe = this.options.prepare = true;
186
- return this;
187
- }
188
- stream() {
189
- throw new Error(".stream has been renamed to .forEach");
190
- }
191
- forEach(fn) {
192
- this.forEachFn = fn;
193
- this.handle();
194
- return this;
195
- }
196
- raw() {
197
- this.isRaw = true;
198
- return this;
199
- }
200
- values() {
201
- this.isRaw = "values";
202
- return this;
203
- }
204
- handle() {
205
- return __async(this, null, function* () {
206
- !this.executed && (this.executed = true) && (yield 1) && this.handler(this);
207
- });
208
- }
209
- execute() {
210
- this.handle();
211
- return this;
212
- }
213
- then() {
214
- this.handle();
215
- return super.then.apply(this, arguments);
216
- }
217
- catch() {
218
- this.handle();
219
- return super.catch.apply(this, arguments);
220
- }
221
- finally() {
222
- this.handle();
223
- return super.finally.apply(this, arguments);
224
- }
225
- };
226
- }
227
- });
228
-
229
- // node_modules/postgres/src/errors.js
230
- function connection(x, options, socket) {
231
- const { host, port } = socket || options;
232
- const error = Object.assign(
233
- new Error("write " + x + " " + (options.path || host + ":" + port)),
234
- {
235
- code: x,
236
- errno: x,
237
- address: options.path || host
238
- },
239
- options.path ? {} : { port }
240
- );
241
- Error.captureStackTrace(error, connection);
242
- return error;
243
- }
244
- function postgres(x) {
245
- const error = new PostgresError(x);
246
- Error.captureStackTrace(error, postgres);
247
- return error;
248
- }
249
- function generic(code, message) {
250
- const error = Object.assign(new Error(code + ": " + message), { code });
251
- Error.captureStackTrace(error, generic);
252
- return error;
253
- }
254
- function notSupported(x) {
255
- const error = Object.assign(
256
- new Error(x + " (B) is not supported"),
257
- {
258
- code: "MESSAGE_NOT_SUPPORTED",
259
- name: x
260
- }
261
- );
262
- Error.captureStackTrace(error, notSupported);
263
- return error;
264
- }
265
- var PostgresError, Errors;
266
- var init_errors = __esm({
267
- "node_modules/postgres/src/errors.js"() {
268
- PostgresError = class extends Error {
269
- constructor(x) {
270
- super(x.message);
271
- this.name = this.constructor.name;
272
- Object.assign(this, x);
273
- }
274
- };
275
- Errors = {
276
- connection,
277
- postgres,
278
- generic,
279
- notSupported
280
- };
281
- }
282
- });
283
-
284
- // node_modules/postgres/src/types.js
285
- function handleValue(x, parameters, types2, options) {
286
- let value = x instanceof Parameter ? x.value : x;
287
- if (value === void 0) {
288
- x instanceof Parameter ? x.value = options.transform.undefined : value = x = options.transform.undefined;
289
- if (value === void 0)
290
- throw Errors.generic("UNDEFINED_VALUE", "Undefined values are not allowed");
291
- }
292
- return "$" + types2.push(
293
- x instanceof Parameter ? (parameters.push(x.value), x.array ? x.array[x.type || inferType(x.value)] || x.type || firstIsString(x.value) : x.type) : (parameters.push(x), inferType(x))
294
- );
295
- }
296
- function stringify(q, string, value, parameters, types2, options) {
297
- for (let i = 1; i < q.strings.length; i++) {
298
- string += stringifyValue(string, value, parameters, types2, options) + q.strings[i];
299
- value = q.args[i];
300
- }
301
- return string;
302
- }
303
- function stringifyValue(string, value, parameters, types2, o) {
304
- return value instanceof Builder ? value.build(string, parameters, types2, o) : value instanceof Query ? fragment(value, parameters, types2, o) : value instanceof Identifier ? value.value : value && value[0] instanceof Query ? value.reduce((acc, x) => acc + " " + fragment(x, parameters, types2, o), "") : handleValue(value, parameters, types2, o);
305
- }
306
- function fragment(q, parameters, types2, options) {
307
- q.fragment = true;
308
- return stringify(q, q.strings[0], q.args[0], parameters, types2, options);
309
- }
310
- function valuesBuilder(first, parameters, types2, columns, options) {
311
- return first.map(
312
- (row) => "(" + columns.map(
313
- (column) => stringifyValue("values", row[column], parameters, types2, options)
314
- ).join(",") + ")"
315
- ).join(",");
316
- }
317
- function values(first, rest, parameters, types2, options) {
318
- const multi = Array.isArray(first[0]);
319
- const columns = rest.length ? rest.flat() : Object.keys(multi ? first[0] : first);
320
- return valuesBuilder(multi ? first : [first], parameters, types2, columns, options);
321
- }
322
- function select(first, rest, parameters, types2, options) {
323
- typeof first === "string" && (first = [first].concat(rest));
324
- if (Array.isArray(first))
325
- return escapeIdentifiers(first, options);
326
- let value;
327
- const columns = rest.length ? rest.flat() : Object.keys(first);
328
- return columns.map((x) => {
329
- value = first[x];
330
- return (value instanceof Query ? fragment(value, parameters, types2, options) : value instanceof Identifier ? value.value : handleValue(value, parameters, types2, options)) + " as " + escapeIdentifier(options.transform.column.to ? options.transform.column.to(x) : x);
331
- }).join(",");
332
- }
333
- function notTagged() {
334
- throw Errors.generic("NOT_TAGGED_CALL", "Query not called as a tagged template literal");
335
- }
336
- function firstIsString(x) {
337
- if (Array.isArray(x))
338
- return firstIsString(x[0]);
339
- return typeof x === "string" ? 1009 : 0;
340
- }
341
- function typeHandlers(types2) {
342
- return Object.keys(types2).reduce((acc, k) => {
343
- types2[k].from && [].concat(types2[k].from).forEach((x) => acc.parsers[x] = types2[k].parse);
344
- if (types2[k].serialize) {
345
- acc.serializers[types2[k].to] = types2[k].serialize;
346
- types2[k].from && [].concat(types2[k].from).forEach((x) => acc.serializers[x] = types2[k].serialize);
347
- }
348
- return acc;
349
- }, { parsers: {}, serializers: {} });
350
- }
351
- function escapeIdentifiers(xs, { transform: { column } }) {
352
- return xs.map((x) => escapeIdentifier(column.to ? column.to(x) : x)).join(",");
353
- }
354
- function arrayEscape(x) {
355
- return x.replace(escapeBackslash, "\\\\").replace(escapeQuote, '\\"');
356
- }
357
- function arrayParserLoop(s, x, parser, typarray) {
358
- const xs = [];
359
- const delimiter = typarray === 1020 ? ";" : ",";
360
- for (; s.i < x.length; s.i++) {
361
- s.char = x[s.i];
362
- if (s.quoted) {
363
- if (s.char === "\\") {
364
- s.str += x[++s.i];
365
- } else if (s.char === '"') {
366
- xs.push(parser ? parser(s.str) : s.str);
367
- s.str = "";
368
- s.quoted = x[s.i + 1] === '"';
369
- s.last = s.i + 2;
370
- } else {
371
- s.str += s.char;
372
- }
373
- } else if (s.char === '"') {
374
- s.quoted = true;
375
- } else if (s.char === "{") {
376
- s.last = ++s.i;
377
- xs.push(arrayParserLoop(s, x, parser, typarray));
378
- } else if (s.char === "}") {
379
- s.quoted = false;
380
- s.last < s.i && xs.push(parser ? parser(x.slice(s.last, s.i)) : x.slice(s.last, s.i));
381
- s.last = s.i + 1;
382
- break;
383
- } else if (s.char === delimiter && s.p !== "}" && s.p !== '"') {
384
- xs.push(parser ? parser(x.slice(s.last, s.i)) : x.slice(s.last, s.i));
385
- s.last = s.i + 1;
386
- }
387
- s.p = s.char;
388
- }
389
- s.last < s.i && xs.push(parser ? parser(x.slice(s.last, s.i + 1)) : x.slice(s.last, s.i + 1));
390
- return xs;
391
- }
392
- function createJsonTransform(fn) {
393
- return function jsonTransform(x, column) {
394
- return typeof x === "object" && x !== null && (column.type === 114 || column.type === 3802) ? Array.isArray(x) ? x.map((x2) => jsonTransform(x2, column)) : Object.entries(x).reduce((acc, [k, v]) => Object.assign(acc, { [fn(k)]: jsonTransform(v, column) }), {}) : x;
395
- };
396
- }
397
- var types, NotTagged, Identifier, Parameter, Builder, defaultHandlers, builders, serializers, parsers, mergeUserTypes, escapeIdentifier, inferType, escapeBackslash, escapeQuote, arraySerializer, arrayParserState, arrayParser, toCamel, toPascal, toKebab, fromCamel, fromPascal, fromKebab, camel, pascal, kebab;
398
- var init_types = __esm({
399
- "node_modules/postgres/src/types.js"() {
400
- init_query();
401
- init_errors();
402
- types = {
403
- string: {
404
- to: 25,
405
- from: null,
406
- // defaults to string
407
- serialize: (x) => "" + x
408
- },
409
- number: {
410
- to: 0,
411
- from: [21, 23, 26, 700, 701],
412
- serialize: (x) => "" + x,
413
- parse: (x) => +x
414
- },
415
- json: {
416
- to: 114,
417
- from: [114, 3802],
418
- serialize: (x) => JSON.stringify(x),
419
- parse: (x) => JSON.parse(x)
420
- },
421
- boolean: {
422
- to: 16,
423
- from: 16,
424
- serialize: (x) => x === true ? "t" : "f",
425
- parse: (x) => x === "t"
426
- },
427
- date: {
428
- to: 1184,
429
- from: [1082, 1114, 1184],
430
- serialize: (x) => (x instanceof Date ? x : new Date(x)).toISOString(),
431
- parse: (x) => new Date(x)
432
- },
433
- bytea: {
434
- to: 17,
435
- from: 17,
436
- serialize: (x) => "\\x" + Buffer.from(x).toString("hex"),
437
- parse: (x) => Buffer.from(x.slice(2), "hex")
438
- }
439
- };
440
- NotTagged = class {
441
- then() {
442
- notTagged();
443
- }
444
- catch() {
445
- notTagged();
446
- }
447
- finally() {
448
- notTagged();
449
- }
450
- };
451
- Identifier = class extends NotTagged {
452
- constructor(value) {
453
- super();
454
- this.value = escapeIdentifier(value);
455
- }
456
- };
457
- Parameter = class extends NotTagged {
458
- constructor(value, type, array) {
459
- super();
460
- this.value = value;
461
- this.type = type;
462
- this.array = array;
463
- }
464
- };
465
- Builder = class extends NotTagged {
466
- constructor(first, rest) {
467
- super();
468
- this.first = first;
469
- this.rest = rest;
470
- }
471
- build(before, parameters, types2, options) {
472
- const keyword = builders.map(([x, fn]) => ({ fn, i: before.search(x) })).sort((a, b2) => a.i - b2.i).pop();
473
- return keyword.i === -1 ? escapeIdentifiers(this.first, options) : keyword.fn(this.first, this.rest, parameters, types2, options);
474
- }
475
- };
476
- defaultHandlers = typeHandlers(types);
477
- builders = Object.entries({
478
- values,
479
- in: (...xs) => {
480
- const x = values(...xs);
481
- return x === "()" ? "(null)" : x;
482
- },
483
- select,
484
- as: select,
485
- returning: select,
486
- "\\(": select,
487
- update(first, rest, parameters, types2, options) {
488
- return (rest.length ? rest.flat() : Object.keys(first)).map(
489
- (x) => escapeIdentifier(options.transform.column.to ? options.transform.column.to(x) : x) + "=" + stringifyValue("values", first[x], parameters, types2, options)
490
- );
491
- },
492
- insert(first, rest, parameters, types2, options) {
493
- const columns = rest.length ? rest.flat() : Object.keys(Array.isArray(first) ? first[0] : first);
494
- return "(" + escapeIdentifiers(columns, options) + ")values" + valuesBuilder(Array.isArray(first) ? first : [first], parameters, types2, columns, options);
495
- }
496
- }).map(([x, fn]) => [new RegExp("((?:^|[\\s(])" + x + "(?:$|[\\s(]))(?![\\s\\S]*\\1)", "i"), fn]);
497
- serializers = defaultHandlers.serializers;
498
- parsers = defaultHandlers.parsers;
499
- mergeUserTypes = function(types2) {
500
- const user = typeHandlers(types2 || {});
501
- return {
502
- serializers: Object.assign({}, serializers, user.serializers),
503
- parsers: Object.assign({}, parsers, user.parsers)
504
- };
505
- };
506
- escapeIdentifier = function escape(str) {
507
- return '"' + str.replace(/"/g, '""').replace(/\./g, '"."') + '"';
508
- };
509
- inferType = function inferType2(x) {
510
- return x instanceof Parameter ? x.type : x instanceof Date ? 1184 : x instanceof Uint8Array ? 17 : x === true || x === false ? 16 : typeof x === "bigint" ? 20 : Array.isArray(x) ? inferType2(x[0]) : 0;
511
- };
512
- escapeBackslash = /\\/g;
513
- escapeQuote = /"/g;
514
- arraySerializer = function arraySerializer2(xs, serializer, options, typarray) {
515
- if (Array.isArray(xs) === false)
516
- return xs;
517
- if (!xs.length)
518
- return "{}";
519
- const first = xs[0];
520
- const delimiter = typarray === 1020 ? ";" : ",";
521
- if (Array.isArray(first) && !first.type)
522
- return "{" + xs.map((x) => arraySerializer2(x, serializer, options, typarray)).join(delimiter) + "}";
523
- return "{" + xs.map((x) => {
524
- if (x === void 0) {
525
- x = options.transform.undefined;
526
- if (x === void 0)
527
- throw Errors.generic("UNDEFINED_VALUE", "Undefined values are not allowed");
528
- }
529
- return x === null ? "null" : '"' + arrayEscape(serializer ? serializer(x.type ? x.value : x) : "" + x) + '"';
530
- }).join(delimiter) + "}";
531
- };
532
- arrayParserState = {
533
- i: 0,
534
- char: null,
535
- str: "",
536
- quoted: false,
537
- last: 0
538
- };
539
- arrayParser = function arrayParser2(x, parser, typarray) {
540
- arrayParserState.i = arrayParserState.last = 0;
541
- return arrayParserLoop(arrayParserState, x, parser, typarray);
542
- };
543
- toCamel = (x) => {
544
- let str = x[0];
545
- for (let i = 1; i < x.length; i++)
546
- str += x[i] === "_" ? x[++i].toUpperCase() : x[i];
547
- return str;
548
- };
549
- toPascal = (x) => {
550
- let str = x[0].toUpperCase();
551
- for (let i = 1; i < x.length; i++)
552
- str += x[i] === "_" ? x[++i].toUpperCase() : x[i];
553
- return str;
554
- };
555
- toKebab = (x) => x.replace(/_/g, "-");
556
- fromCamel = (x) => x.replace(/([A-Z])/g, "_$1").toLowerCase();
557
- fromPascal = (x) => (x.slice(0, 1) + x.slice(1).replace(/([A-Z])/g, "_$1")).toLowerCase();
558
- fromKebab = (x) => x.replace(/-/g, "_");
559
- toCamel.column = { from: toCamel };
560
- toCamel.value = { from: createJsonTransform(toCamel) };
561
- fromCamel.column = { to: fromCamel };
562
- camel = __spreadValues({}, toCamel);
563
- camel.column.to = fromCamel;
564
- toPascal.column = { from: toPascal };
565
- toPascal.value = { from: createJsonTransform(toPascal) };
566
- fromPascal.column = { to: fromPascal };
567
- pascal = __spreadValues({}, toPascal);
568
- pascal.column.to = fromPascal;
569
- toKebab.column = { from: toKebab };
570
- toKebab.value = { from: createJsonTransform(toKebab) };
571
- fromKebab.column = { to: fromKebab };
572
- kebab = __spreadValues({}, toKebab);
573
- kebab.column.to = fromKebab;
574
- }
575
- });
576
-
577
- // node_modules/postgres/src/result.js
578
- var Result;
579
- var init_result = __esm({
580
- "node_modules/postgres/src/result.js"() {
581
- Result = class extends Array {
582
- constructor() {
583
- super();
584
- Object.defineProperties(this, {
585
- count: { value: null, writable: true },
586
- state: { value: null, writable: true },
587
- command: { value: null, writable: true },
588
- columns: { value: null, writable: true },
589
- statement: { value: null, writable: true }
590
- });
591
- }
592
- static get [Symbol.species]() {
593
- return Array;
594
- }
595
- };
596
- }
597
- });
598
-
599
- // node_modules/postgres/src/queue.js
600
- function Queue(initial = []) {
601
- let xs = initial.slice();
602
- let index = 0;
603
- return {
604
- get length() {
605
- return xs.length - index;
606
- },
607
- remove: (x) => {
608
- const index2 = xs.indexOf(x);
609
- return index2 === -1 ? null : (xs.splice(index2, 1), x);
610
- },
611
- push: (x) => (xs.push(x), x),
612
- shift: () => {
613
- const out = xs[index++];
614
- if (index === xs.length) {
615
- index = 0;
616
- xs = [];
617
- } else {
618
- xs[index - 1] = void 0;
619
- }
620
- return out;
621
- }
622
- };
623
- }
624
- var queue_default;
625
- var init_queue = __esm({
626
- "node_modules/postgres/src/queue.js"() {
627
- queue_default = Queue;
628
- }
629
- });
630
-
631
- // node_modules/postgres/src/bytes.js
632
- function fit(x) {
633
- if (buffer.length - b.i < x) {
634
- const prev = buffer, length = prev.length;
635
- buffer = Buffer.allocUnsafe(length + (length >> 1) + x);
636
- prev.copy(buffer);
637
- }
638
- }
639
- function reset() {
640
- b.i = 0;
641
- return b;
642
- }
643
- var size, buffer, messages, b, bytes_default;
644
- var init_bytes = __esm({
645
- "node_modules/postgres/src/bytes.js"() {
646
- size = 256;
647
- buffer = Buffer.allocUnsafe(size);
648
- messages = "BCcDdEFfHPpQSX".split("").reduce((acc, x) => {
649
- const v = x.charCodeAt(0);
650
- acc[x] = () => {
651
- buffer[0] = v;
652
- b.i = 5;
653
- return b;
654
- };
655
- return acc;
656
- }, {});
657
- b = Object.assign(reset, messages, {
658
- N: String.fromCharCode(0),
659
- i: 0,
660
- inc(x) {
661
- b.i += x;
662
- return b;
663
- },
664
- str(x) {
665
- const length = Buffer.byteLength(x);
666
- fit(length);
667
- b.i += buffer.write(x, b.i, length, "utf8");
668
- return b;
669
- },
670
- i16(x) {
671
- fit(2);
672
- buffer.writeUInt16BE(x, b.i);
673
- b.i += 2;
674
- return b;
675
- },
676
- i32(x, i) {
677
- if (i || i === 0) {
678
- buffer.writeUInt32BE(x, i);
679
- return b;
680
- }
681
- fit(4);
682
- buffer.writeUInt32BE(x, b.i);
683
- b.i += 4;
684
- return b;
685
- },
686
- z(x) {
687
- fit(x);
688
- buffer.fill(0, b.i, b.i + x);
689
- b.i += x;
690
- return b;
691
- },
692
- raw(x) {
693
- buffer = Buffer.concat([buffer.subarray(0, b.i), x]);
694
- b.i = buffer.length;
695
- return b;
696
- },
697
- end(at = 1) {
698
- buffer.writeUInt32BE(b.i - at, at);
699
- const out = buffer.subarray(0, b.i);
700
- b.i = 0;
701
- buffer = Buffer.allocUnsafe(size);
702
- return out;
703
- }
704
- });
705
- bytes_default = b;
706
- }
707
- });
708
- function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose = noop } = {}) {
709
- const {
710
- sslnegotiation,
711
- ssl,
712
- max,
713
- user,
714
- host,
715
- port,
716
- database,
717
- parsers: parsers2,
718
- transform,
719
- onnotice,
720
- onnotify,
721
- onparameter,
722
- max_pipeline,
723
- keep_alive,
724
- backoff: backoff2,
725
- target_session_attrs
726
- } = options;
727
- const sent = queue_default(), id = uid++, backend = { pid: null, secret: null }, idleTimer = timer(end, options.idle_timeout), lifeTimer = timer(end, options.max_lifetime), connectTimer = timer(connectTimedOut, options.connect_timeout);
728
- let socket = null, cancelMessage, errorResponse = null, result = new Result(), incoming = Buffer.alloc(0), needsTypes = options.fetch_types, backendParameters = {}, statements = {}, statementId = Math.random().toString(36).slice(2), statementCount = 1, closedTime = 0, remaining = 0, hostIndex = 0, retries = 0, length = 0, delay = 0, rows = 0, serverSignature = null, nextWriteTimer = null, terminated = false, incomings = null, results = null, initial = null, ending = null, stream = null, chunk = null, ended = null, nonce = null, query = null, final = null;
729
- const connection2 = {
730
- queue: queues.closed,
731
- idleTimer,
732
- connect(query2) {
733
- initial = query2;
734
- reconnect();
735
- },
736
- terminate,
737
- execute,
738
- cancel,
739
- end,
740
- count: 0,
741
- id
742
- };
743
- queues.closed && queues.closed.push(connection2);
744
- return connection2;
745
- function createSocket() {
746
- return __async(this, null, function* () {
747
- let x;
748
- try {
749
- x = options.socket ? yield Promise.resolve(options.socket(options)) : new net.Socket();
750
- } catch (e) {
751
- error(e);
752
- return;
753
- }
754
- x.on("error", error);
755
- x.on("close", closed);
756
- x.on("drain", drain);
757
- return x;
758
- });
759
- }
760
- function cancel(_0, _1, _2) {
761
- return __async(this, arguments, function* ({ pid, secret }, resolve3, reject) {
762
- try {
763
- cancelMessage = bytes_default().i32(16).i32(80877102).i32(pid).i32(secret).end(16);
764
- yield connect();
765
- socket.once("error", reject);
766
- socket.once("close", resolve3);
767
- } catch (error2) {
768
- reject(error2);
769
- }
770
- });
771
- }
772
- function execute(q) {
773
- if (terminated)
774
- return queryError(q, Errors.connection("CONNECTION_DESTROYED", options));
775
- if (stream)
776
- return queryError(q, Errors.generic("COPY_IN_PROGRESS", "You cannot execute queries during copy"));
777
- if (q.cancelled)
778
- return;
779
- try {
780
- q.state = backend;
781
- query ? sent.push(q) : (query = q, query.active = true);
782
- build(q);
783
- return write(toBuffer(q)) && !q.describeFirst && !q.cursorFn && sent.length < max_pipeline && (!q.options.onexecute || q.options.onexecute(connection2));
784
- } catch (error2) {
785
- sent.length === 0 && write(Sync);
786
- errored(error2);
787
- return true;
788
- }
789
- }
790
- function toBuffer(q) {
791
- if (q.parameters.length >= 65534)
792
- throw Errors.generic("MAX_PARAMETERS_EXCEEDED", "Max number of parameters (65534) exceeded");
793
- return q.options.simple ? bytes_default().Q().str(q.statement.string + bytes_default.N).end() : q.describeFirst ? Buffer.concat([describe(q), Flush]) : q.prepare ? q.prepared ? prepared(q) : Buffer.concat([describe(q), prepared(q)]) : unnamed(q);
794
- }
795
- function describe(q) {
796
- return Buffer.concat([
797
- Parse(q.statement.string, q.parameters, q.statement.types, q.statement.name),
798
- Describe("S", q.statement.name)
799
- ]);
800
- }
801
- function prepared(q) {
802
- return Buffer.concat([
803
- Bind(q.parameters, q.statement.types, q.statement.name, q.cursorName),
804
- q.cursorFn ? Execute("", q.cursorRows) : ExecuteUnnamed
805
- ]);
806
- }
807
- function unnamed(q) {
808
- return Buffer.concat([
809
- Parse(q.statement.string, q.parameters, q.statement.types),
810
- DescribeUnnamed,
811
- prepared(q)
812
- ]);
813
- }
814
- function build(q) {
815
- const parameters = [], types2 = [];
816
- const string = stringify(q, q.strings[0], q.args[0], parameters, types2, options);
817
- !q.tagged && q.args.forEach((x) => handleValue(x, parameters, types2, options));
818
- q.prepare = options.prepare && ("prepare" in q.options ? q.options.prepare : true);
819
- q.string = string;
820
- q.signature = q.prepare && types2 + string;
821
- q.onlyDescribe && delete statements[q.signature];
822
- q.parameters = q.parameters || parameters;
823
- q.prepared = q.prepare && q.signature in statements;
824
- q.describeFirst = q.onlyDescribe || parameters.length && !q.prepared;
825
- q.statement = q.prepared ? statements[q.signature] : { string, types: types2, name: q.prepare ? statementId + statementCount++ : "" };
826
- typeof options.debug === "function" && options.debug(id, string, parameters, types2);
827
- }
828
- function write(x, fn) {
829
- chunk = chunk ? Buffer.concat([chunk, x]) : Buffer.from(x);
830
- if (chunk.length >= 1024)
831
- return nextWrite(fn);
832
- nextWriteTimer === null && (nextWriteTimer = setImmediate(nextWrite));
833
- return true;
834
- }
835
- function nextWrite(fn) {
836
- const x = socket.write(chunk, fn);
837
- nextWriteTimer !== null && clearImmediate(nextWriteTimer);
838
- chunk = nextWriteTimer = null;
839
- return x;
840
- }
841
- function connectTimedOut() {
842
- errored(Errors.connection("CONNECT_TIMEOUT", options, socket));
843
- socket.destroy();
844
- }
845
- function secure() {
846
- return __async(this, null, function* () {
847
- if (sslnegotiation !== "direct") {
848
- write(SSLRequest);
849
- const canSSL = yield new Promise((r) => socket.once("data", (x) => r(x[0] === 83)));
850
- if (!canSSL && ssl === "prefer")
851
- return connected();
852
- }
853
- const options2 = {
854
- socket,
855
- servername: net.isIP(socket.host) ? void 0 : socket.host
856
- };
857
- if (sslnegotiation === "direct")
858
- options2.ALPNProtocols = ["postgresql"];
859
- if (ssl === "require" || ssl === "allow" || ssl === "prefer")
860
- options2.rejectUnauthorized = false;
861
- else if (typeof ssl === "object")
862
- Object.assign(options2, ssl);
863
- socket.removeAllListeners();
864
- socket = tls.connect(options2);
865
- socket.on("secureConnect", connected);
866
- socket.on("error", error);
867
- socket.on("close", closed);
868
- socket.on("drain", drain);
869
- });
870
- }
871
- function drain() {
872
- !query && onopen(connection2);
873
- }
874
- function data(x) {
875
- if (incomings) {
876
- incomings.push(x);
877
- remaining -= x.length;
878
- if (remaining > 0)
879
- return;
880
- }
881
- incoming = incomings ? Buffer.concat(incomings, length - remaining) : incoming.length === 0 ? x : Buffer.concat([incoming, x], incoming.length + x.length);
882
- while (incoming.length > 4) {
883
- length = incoming.readUInt32BE(1);
884
- if (length >= incoming.length) {
885
- remaining = length - incoming.length;
886
- incomings = [incoming];
887
- break;
888
- }
889
- try {
890
- handle(incoming.subarray(0, length + 1));
891
- } catch (e) {
892
- query && (query.cursorFn || query.describeFirst) && write(Sync);
893
- errored(e);
894
- }
895
- incoming = incoming.subarray(length + 1);
896
- remaining = 0;
897
- incomings = null;
898
- }
899
- }
900
- function connect() {
901
- return __async(this, null, function* () {
902
- terminated = false;
903
- backendParameters = {};
904
- socket || (socket = yield createSocket());
905
- if (!socket)
906
- return;
907
- connectTimer.start();
908
- if (options.socket)
909
- return ssl ? secure() : connected();
910
- socket.on("connect", ssl ? secure : connected);
911
- if (options.path)
912
- return socket.connect(options.path);
913
- socket.ssl = ssl;
914
- socket.connect(port[hostIndex], host[hostIndex]);
915
- socket.host = host[hostIndex];
916
- socket.port = port[hostIndex];
917
- hostIndex = (hostIndex + 1) % port.length;
918
- });
919
- }
920
- function reconnect() {
921
- setTimeout(connect, closedTime ? Math.max(0, closedTime + delay - performance$1.now()) : 0);
922
- }
923
- function connected() {
924
- try {
925
- statements = {};
926
- needsTypes = options.fetch_types;
927
- statementId = Math.random().toString(36).slice(2);
928
- statementCount = 1;
929
- lifeTimer.start();
930
- socket.on("data", data);
931
- keep_alive && socket.setKeepAlive && socket.setKeepAlive(true, 1e3 * keep_alive);
932
- const s = StartupMessage();
933
- write(s);
934
- } catch (err) {
935
- error(err);
936
- }
937
- }
938
- function error(err) {
939
- if (connection2.queue === queues.connecting && options.host[retries + 1])
940
- return;
941
- errored(err);
942
- while (sent.length)
943
- queryError(sent.shift(), err);
944
- }
945
- function errored(err) {
946
- stream && (stream.destroy(err), stream = null);
947
- query && queryError(query, err);
948
- initial && (queryError(initial, err), initial = null);
949
- }
950
- function queryError(query2, err) {
951
- if (query2.reserve)
952
- return query2.reject(err);
953
- if (!err || typeof err !== "object")
954
- err = new Error(err);
955
- "query" in err || "parameters" in err || Object.defineProperties(err, {
956
- stack: { value: err.stack + query2.origin.replace(/.*\n/, "\n"), enumerable: options.debug },
957
- query: { value: query2.string, enumerable: options.debug },
958
- parameters: { value: query2.parameters, enumerable: options.debug },
959
- args: { value: query2.args, enumerable: options.debug },
960
- types: { value: query2.statement && query2.statement.types, enumerable: options.debug }
961
- });
962
- query2.reject(err);
963
- }
964
- function end() {
965
- return ending || (!connection2.reserved && onend(connection2), !connection2.reserved && !initial && !query && sent.length === 0 ? (terminate(), new Promise((r) => socket && socket.readyState !== "closed" ? socket.once("close", r) : r())) : ending = new Promise((r) => ended = r));
966
- }
967
- function terminate() {
968
- terminated = true;
969
- if (stream || query || initial || sent.length)
970
- error(Errors.connection("CONNECTION_DESTROYED", options));
971
- clearImmediate(nextWriteTimer);
972
- if (socket) {
973
- socket.removeListener("data", data);
974
- socket.removeListener("connect", connected);
975
- socket.readyState === "open" && socket.end(bytes_default().X().end());
976
- }
977
- ended && (ended(), ending = ended = null);
978
- }
979
- function closed(hadError) {
980
- return __async(this, null, function* () {
981
- incoming = Buffer.alloc(0);
982
- remaining = 0;
983
- incomings = null;
984
- clearImmediate(nextWriteTimer);
985
- socket.removeListener("data", data);
986
- socket.removeListener("connect", connected);
987
- idleTimer.cancel();
988
- lifeTimer.cancel();
989
- connectTimer.cancel();
990
- socket.removeAllListeners();
991
- socket = null;
992
- if (initial)
993
- return reconnect();
994
- !hadError && (query || sent.length) && error(Errors.connection("CONNECTION_CLOSED", options, socket));
995
- closedTime = performance$1.now();
996
- hadError && options.shared.retries++;
997
- delay = (typeof backoff2 === "function" ? backoff2(options.shared.retries) : backoff2) * 1e3;
998
- onclose(connection2, Errors.connection("CONNECTION_CLOSED", options, socket));
999
- });
1000
- }
1001
- function handle(xs, x = xs[0]) {
1002
- (x === 68 ? DataRow : (
1003
- // D
1004
- x === 100 ? CopyData : (
1005
- // d
1006
- x === 65 ? NotificationResponse : (
1007
- // A
1008
- x === 83 ? ParameterStatus : (
1009
- // S
1010
- x === 90 ? ReadyForQuery : (
1011
- // Z
1012
- x === 67 ? CommandComplete : (
1013
- // C
1014
- x === 50 ? BindComplete : (
1015
- // 2
1016
- x === 49 ? ParseComplete : (
1017
- // 1
1018
- x === 116 ? ParameterDescription : (
1019
- // t
1020
- x === 84 ? RowDescription : (
1021
- // T
1022
- x === 82 ? Authentication : (
1023
- // R
1024
- x === 110 ? NoData : (
1025
- // n
1026
- x === 75 ? BackendKeyData : (
1027
- // K
1028
- x === 69 ? ErrorResponse : (
1029
- // E
1030
- x === 115 ? PortalSuspended : (
1031
- // s
1032
- x === 51 ? CloseComplete : (
1033
- // 3
1034
- x === 71 ? CopyInResponse : (
1035
- // G
1036
- x === 78 ? NoticeResponse : (
1037
- // N
1038
- x === 72 ? CopyOutResponse : (
1039
- // H
1040
- x === 99 ? CopyDone : (
1041
- // c
1042
- x === 73 ? EmptyQueryResponse : (
1043
- // I
1044
- x === 86 ? FunctionCallResponse : (
1045
- // V
1046
- x === 118 ? NegotiateProtocolVersion : (
1047
- // v
1048
- x === 87 ? CopyBothResponse : (
1049
- // W
1050
- /* c8 ignore next */
1051
- UnknownMessage
1052
- )
1053
- )
1054
- )
1055
- )
1056
- )
1057
- )
1058
- )
1059
- )
1060
- )
1061
- )
1062
- )
1063
- )
1064
- )
1065
- )
1066
- )
1067
- )
1068
- )
1069
- )
1070
- )
1071
- )
1072
- )
1073
- )
1074
- )
1075
- ))(xs);
1076
- }
1077
- function DataRow(x) {
1078
- let index = 7;
1079
- let length2;
1080
- let column;
1081
- let value;
1082
- const row = query.isRaw ? new Array(query.statement.columns.length) : {};
1083
- for (let i = 0; i < query.statement.columns.length; i++) {
1084
- column = query.statement.columns[i];
1085
- length2 = x.readInt32BE(index);
1086
- index += 4;
1087
- value = length2 === -1 ? null : query.isRaw === true ? x.subarray(index, index += length2) : column.parser === void 0 ? x.toString("utf8", index, index += length2) : column.parser.array === true ? column.parser(x.toString("utf8", index + 1, index += length2)) : column.parser(x.toString("utf8", index, index += length2));
1088
- query.isRaw ? row[i] = query.isRaw === true ? value : transform.value.from ? transform.value.from(value, column) : value : row[column.name] = transform.value.from ? transform.value.from(value, column) : value;
1089
- }
1090
- query.forEachFn ? query.forEachFn(transform.row.from ? transform.row.from(row) : row, result) : result[rows++] = transform.row.from ? transform.row.from(row) : row;
1091
- }
1092
- function ParameterStatus(x) {
1093
- const [k, v] = x.toString("utf8", 5, x.length - 1).split(bytes_default.N);
1094
- backendParameters[k] = v;
1095
- if (options.parameters[k] !== v) {
1096
- options.parameters[k] = v;
1097
- onparameter && onparameter(k, v);
1098
- }
1099
- }
1100
- function ReadyForQuery(x) {
1101
- if (query) {
1102
- if (errorResponse) {
1103
- query.retried ? errored(query.retried) : query.prepared && retryRoutines.has(errorResponse.routine) ? retry(query, errorResponse) : errored(errorResponse);
1104
- } else {
1105
- query.resolve(results || result);
1106
- }
1107
- } else if (errorResponse) {
1108
- errored(errorResponse);
1109
- }
1110
- query = results = errorResponse = null;
1111
- result = new Result();
1112
- connectTimer.cancel();
1113
- if (initial) {
1114
- if (target_session_attrs) {
1115
- if (!backendParameters.in_hot_standby || !backendParameters.default_transaction_read_only)
1116
- return fetchState();
1117
- else if (tryNext(target_session_attrs, backendParameters))
1118
- return terminate();
1119
- }
1120
- if (needsTypes) {
1121
- initial.reserve && (initial = null);
1122
- return fetchArrayTypes();
1123
- }
1124
- initial && !initial.reserve && execute(initial);
1125
- options.shared.retries = retries = 0;
1126
- initial = null;
1127
- return;
1128
- }
1129
- while (sent.length && (query = sent.shift()) && (query.active = true, query.cancelled))
1130
- Connection(options).cancel(query.state, query.cancelled.resolve, query.cancelled.reject);
1131
- if (query)
1132
- return;
1133
- connection2.reserved ? !connection2.reserved.release && x[5] === 73 ? ending ? terminate() : (connection2.reserved = null, onopen(connection2)) : connection2.reserved() : ending ? terminate() : onopen(connection2);
1134
- }
1135
- function CommandComplete(x) {
1136
- rows = 0;
1137
- for (let i = x.length - 1; i > 0; i--) {
1138
- if (x[i] === 32 && x[i + 1] < 58 && result.count === null)
1139
- result.count = +x.toString("utf8", i + 1, x.length - 1);
1140
- if (x[i - 1] >= 65) {
1141
- result.command = x.toString("utf8", 5, i);
1142
- result.state = backend;
1143
- break;
1144
- }
1145
- }
1146
- final && (final(), final = null);
1147
- if (result.command === "BEGIN" && max !== 1 && !connection2.reserved)
1148
- return errored(Errors.generic("UNSAFE_TRANSACTION", "Only use sql.begin, sql.reserved or max: 1"));
1149
- if (query.options.simple)
1150
- return BindComplete();
1151
- if (query.cursorFn) {
1152
- result.count && query.cursorFn(result);
1153
- write(Sync);
1154
- }
1155
- }
1156
- function ParseComplete() {
1157
- query.parsing = false;
1158
- }
1159
- function BindComplete() {
1160
- !result.statement && (result.statement = query.statement);
1161
- result.columns = query.statement.columns;
1162
- }
1163
- function ParameterDescription(x) {
1164
- const length2 = x.readUInt16BE(5);
1165
- for (let i = 0; i < length2; ++i)
1166
- !query.statement.types[i] && (query.statement.types[i] = x.readUInt32BE(7 + i * 4));
1167
- query.prepare && (statements[query.signature] = query.statement);
1168
- query.describeFirst && !query.onlyDescribe && (write(prepared(query)), query.describeFirst = false);
1169
- }
1170
- function RowDescription(x) {
1171
- if (result.command) {
1172
- results = results || [result];
1173
- results.push(result = new Result());
1174
- result.count = null;
1175
- query.statement.columns = null;
1176
- }
1177
- const length2 = x.readUInt16BE(5);
1178
- let index = 7;
1179
- let start;
1180
- query.statement.columns = Array(length2);
1181
- for (let i = 0; i < length2; ++i) {
1182
- start = index;
1183
- while (x[index++] !== 0) ;
1184
- const table = x.readUInt32BE(index);
1185
- const number = x.readUInt16BE(index + 4);
1186
- const type = x.readUInt32BE(index + 6);
1187
- query.statement.columns[i] = {
1188
- name: transform.column.from ? transform.column.from(x.toString("utf8", start, index - 1)) : x.toString("utf8", start, index - 1),
1189
- parser: parsers2[type],
1190
- table,
1191
- number,
1192
- type
1193
- };
1194
- index += 18;
1195
- }
1196
- result.statement = query.statement;
1197
- if (query.onlyDescribe)
1198
- return query.resolve(query.statement), write(Sync);
1199
- }
1200
- function Authentication(_0) {
1201
- return __async(this, arguments, function* (x, type = x.readUInt32BE(5)) {
1202
- (type === 3 ? AuthenticationCleartextPassword : type === 5 ? AuthenticationMD5Password : type === 10 ? SASL : type === 11 ? SASLContinue : type === 12 ? SASLFinal : type !== 0 ? UnknownAuth : noop)(x, type);
1203
- });
1204
- }
1205
- function AuthenticationCleartextPassword() {
1206
- return __async(this, null, function* () {
1207
- const payload = yield Pass();
1208
- write(
1209
- bytes_default().p().str(payload).z(1).end()
1210
- );
1211
- });
1212
- }
1213
- function AuthenticationMD5Password(x) {
1214
- return __async(this, null, function* () {
1215
- const payload = "md5" + (yield md5(
1216
- Buffer.concat([
1217
- Buffer.from(yield md5((yield Pass()) + user)),
1218
- x.subarray(9)
1219
- ])
1220
- ));
1221
- write(
1222
- bytes_default().p().str(payload).z(1).end()
1223
- );
1224
- });
1225
- }
1226
- function SASL() {
1227
- return __async(this, null, function* () {
1228
- nonce = (yield crypto.randomBytes(18)).toString("base64");
1229
- bytes_default().p().str("SCRAM-SHA-256" + bytes_default.N);
1230
- const i = bytes_default.i;
1231
- write(bytes_default.inc(4).str("n,,n=*,r=" + nonce).i32(bytes_default.i - i - 4, i).end());
1232
- });
1233
- }
1234
- function SASLContinue(x) {
1235
- return __async(this, null, function* () {
1236
- const res = x.toString("utf8", 9).split(",").reduce((acc, x2) => (acc[x2[0]] = x2.slice(2), acc), {});
1237
- const saltedPassword = yield crypto.pbkdf2Sync(
1238
- yield Pass(),
1239
- Buffer.from(res.s, "base64"),
1240
- parseInt(res.i),
1241
- 32,
1242
- "sha256"
1243
- );
1244
- const clientKey = yield hmac(saltedPassword, "Client Key");
1245
- const auth = "n=*,r=" + nonce + ",r=" + res.r + ",s=" + res.s + ",i=" + res.i + ",c=biws,r=" + res.r;
1246
- serverSignature = (yield hmac(yield hmac(saltedPassword, "Server Key"), auth)).toString("base64");
1247
- const payload = "c=biws,r=" + res.r + ",p=" + xor(
1248
- clientKey,
1249
- Buffer.from(yield hmac(yield sha256(clientKey), auth))
1250
- ).toString("base64");
1251
- write(
1252
- bytes_default().p().str(payload).end()
1253
- );
1254
- });
1255
- }
1256
- function SASLFinal(x) {
1257
- if (x.toString("utf8", 9).split(bytes_default.N, 1)[0].slice(2) === serverSignature)
1258
- return;
1259
- errored(Errors.generic("SASL_SIGNATURE_MISMATCH", "The server did not return the correct signature"));
1260
- socket.destroy();
1261
- }
1262
- function Pass() {
1263
- return Promise.resolve(
1264
- typeof options.pass === "function" ? options.pass() : options.pass
1265
- );
1266
- }
1267
- function NoData() {
1268
- result.statement = query.statement;
1269
- result.statement.columns = [];
1270
- if (query.onlyDescribe)
1271
- return query.resolve(query.statement), write(Sync);
1272
- }
1273
- function BackendKeyData(x) {
1274
- backend.pid = x.readUInt32BE(5);
1275
- backend.secret = x.readUInt32BE(9);
1276
- }
1277
- function fetchArrayTypes() {
1278
- return __async(this, null, function* () {
1279
- needsTypes = false;
1280
- const types2 = yield new Query([`
1281
- select b.oid, b.typarray
1282
- from pg_catalog.pg_type a
1283
- left join pg_catalog.pg_type b on b.oid = a.typelem
1284
- where a.typcategory = 'A'
1285
- group by b.oid, b.typarray
1286
- order by b.oid
1287
- `], [], execute);
1288
- types2.forEach(({ oid, typarray }) => addArrayType(oid, typarray));
1289
- });
1290
- }
1291
- function addArrayType(oid, typarray) {
1292
- if (!!options.parsers[typarray] && !!options.serializers[typarray]) return;
1293
- const parser = options.parsers[oid];
1294
- options.shared.typeArrayMap[oid] = typarray;
1295
- options.parsers[typarray] = (xs) => arrayParser(xs, parser, typarray);
1296
- options.parsers[typarray].array = true;
1297
- options.serializers[typarray] = (xs) => arraySerializer(xs, options.serializers[oid], options, typarray);
1298
- }
1299
- function tryNext(x, xs) {
1300
- return x === "read-write" && xs.default_transaction_read_only === "on" || x === "read-only" && xs.default_transaction_read_only === "off" || x === "primary" && xs.in_hot_standby === "on" || x === "standby" && xs.in_hot_standby === "off" || x === "prefer-standby" && xs.in_hot_standby === "off" && options.host[retries];
1301
- }
1302
- function fetchState() {
1303
- const query2 = new Query([`
1304
- show transaction_read_only;
1305
- select pg_catalog.pg_is_in_recovery()
1306
- `], [], execute, null, { simple: true });
1307
- query2.resolve = ([[a], [b2]]) => {
1308
- backendParameters.default_transaction_read_only = a.transaction_read_only;
1309
- backendParameters.in_hot_standby = b2.pg_is_in_recovery ? "on" : "off";
1310
- };
1311
- query2.execute();
1312
- }
1313
- function ErrorResponse(x) {
1314
- if (query) {
1315
- (query.cursorFn || query.describeFirst) && write(Sync);
1316
- errorResponse = Errors.postgres(parseError(x));
1317
- } else {
1318
- errored(Errors.postgres(parseError(x)));
1319
- }
1320
- }
1321
- function retry(q, error2) {
1322
- delete statements[q.signature];
1323
- q.retried = error2;
1324
- execute(q);
1325
- }
1326
- function NotificationResponse(x) {
1327
- if (!onnotify)
1328
- return;
1329
- let index = 9;
1330
- while (x[index++] !== 0) ;
1331
- onnotify(
1332
- x.toString("utf8", 9, index - 1),
1333
- x.toString("utf8", index, x.length - 1)
1334
- );
1335
- }
1336
- function PortalSuspended() {
1337
- return __async(this, null, function* () {
1338
- try {
1339
- const x = yield Promise.resolve(query.cursorFn(result));
1340
- rows = 0;
1341
- x === CLOSE ? write(Close(query.portal)) : (result = new Result(), write(Execute("", query.cursorRows)));
1342
- } catch (err) {
1343
- write(Sync);
1344
- query.reject(err);
1345
- }
1346
- });
1347
- }
1348
- function CloseComplete() {
1349
- result.count && query.cursorFn(result);
1350
- query.resolve(result);
1351
- }
1352
- function CopyInResponse() {
1353
- stream = new Stream.Writable({
1354
- autoDestroy: true,
1355
- write(chunk2, encoding, callback) {
1356
- socket.write(bytes_default().d().raw(chunk2).end(), callback);
1357
- },
1358
- destroy(error2, callback) {
1359
- callback(error2);
1360
- socket.write(bytes_default().f().str(error2 + bytes_default.N).end());
1361
- stream = null;
1362
- },
1363
- final(callback) {
1364
- socket.write(bytes_default().c().end());
1365
- final = callback;
1366
- stream = null;
1367
- }
1368
- });
1369
- query.resolve(stream);
1370
- }
1371
- function CopyOutResponse() {
1372
- stream = new Stream.Readable({
1373
- read() {
1374
- socket.resume();
1375
- }
1376
- });
1377
- query.resolve(stream);
1378
- }
1379
- function CopyBothResponse() {
1380
- stream = new Stream.Duplex({
1381
- autoDestroy: true,
1382
- read() {
1383
- socket.resume();
1384
- },
1385
- /* c8 ignore next 11 */
1386
- write(chunk2, encoding, callback) {
1387
- socket.write(bytes_default().d().raw(chunk2).end(), callback);
1388
- },
1389
- destroy(error2, callback) {
1390
- callback(error2);
1391
- socket.write(bytes_default().f().str(error2 + bytes_default.N).end());
1392
- stream = null;
1393
- },
1394
- final(callback) {
1395
- socket.write(bytes_default().c().end());
1396
- final = callback;
1397
- }
1398
- });
1399
- query.resolve(stream);
1400
- }
1401
- function CopyData(x) {
1402
- stream && (stream.push(x.subarray(5)) || socket.pause());
1403
- }
1404
- function CopyDone() {
1405
- stream && stream.push(null);
1406
- stream = null;
1407
- }
1408
- function NoticeResponse(x) {
1409
- onnotice ? onnotice(parseError(x)) : console.log(parseError(x));
1410
- }
1411
- function EmptyQueryResponse() {
1412
- }
1413
- function FunctionCallResponse() {
1414
- errored(Errors.notSupported("FunctionCallResponse"));
1415
- }
1416
- function NegotiateProtocolVersion() {
1417
- errored(Errors.notSupported("NegotiateProtocolVersion"));
1418
- }
1419
- function UnknownMessage(x) {
1420
- console.error("Postgres.js : Unknown Message:", x[0]);
1421
- }
1422
- function UnknownAuth(x, type) {
1423
- console.error("Postgres.js : Unknown Auth:", type);
1424
- }
1425
- function Bind(parameters, types2, statement = "", portal = "") {
1426
- let prev, type;
1427
- bytes_default().B().str(portal + bytes_default.N).str(statement + bytes_default.N).i16(0).i16(parameters.length);
1428
- parameters.forEach((x, i) => {
1429
- if (x === null)
1430
- return bytes_default.i32(4294967295);
1431
- type = types2[i];
1432
- parameters[i] = x = type in options.serializers ? options.serializers[type](x) : "" + x;
1433
- prev = bytes_default.i;
1434
- bytes_default.inc(4).str(x).i32(bytes_default.i - prev - 4, prev);
1435
- });
1436
- bytes_default.i16(0);
1437
- return bytes_default.end();
1438
- }
1439
- function Parse(str, parameters, types2, name = "") {
1440
- bytes_default().P().str(name + bytes_default.N).str(str + bytes_default.N).i16(parameters.length);
1441
- parameters.forEach((x, i) => bytes_default.i32(types2[i] || 0));
1442
- return bytes_default.end();
1443
- }
1444
- function Describe(x, name = "") {
1445
- return bytes_default().D().str(x).str(name + bytes_default.N).end();
1446
- }
1447
- function Execute(portal = "", rows2 = 0) {
1448
- return Buffer.concat([
1449
- bytes_default().E().str(portal + bytes_default.N).i32(rows2).end(),
1450
- Flush
1451
- ]);
1452
- }
1453
- function Close(portal = "") {
1454
- return Buffer.concat([
1455
- bytes_default().C().str("P").str(portal + bytes_default.N).end(),
1456
- bytes_default().S().end()
1457
- ]);
1458
- }
1459
- function StartupMessage() {
1460
- return cancelMessage || bytes_default().inc(4).i16(3).z(2).str(
1461
- Object.entries(Object.assign(
1462
- {
1463
- user,
1464
- database,
1465
- client_encoding: "UTF8"
1466
- },
1467
- options.connection
1468
- )).filter(([, v]) => v).map(([k, v]) => k + bytes_default.N + v).join(bytes_default.N)
1469
- ).z(2).end(0);
1470
- }
1471
- }
1472
- function parseError(x) {
1473
- const error = {};
1474
- let start = 5;
1475
- for (let i = 5; i < x.length - 1; i++) {
1476
- if (x[i] === 0) {
1477
- error[errorFields[x[start]]] = x.toString("utf8", start + 1, i);
1478
- start = i + 1;
1479
- }
1480
- }
1481
- return error;
1482
- }
1483
- function md5(x) {
1484
- return crypto.createHash("md5").update(x).digest("hex");
1485
- }
1486
- function hmac(key, x) {
1487
- return crypto.createHmac("sha256", key).update(x).digest();
1488
- }
1489
- function sha256(x) {
1490
- return crypto.createHash("sha256").update(x).digest();
1491
- }
1492
- function xor(a, b2) {
1493
- const length = Math.max(a.length, b2.length);
1494
- const buffer2 = Buffer.allocUnsafe(length);
1495
- for (let i = 0; i < length; i++)
1496
- buffer2[i] = a[i] ^ b2[i];
1497
- return buffer2;
1498
- }
1499
- function timer(fn, seconds) {
1500
- seconds = typeof seconds === "function" ? seconds() : seconds;
1501
- if (!seconds)
1502
- return { cancel: noop, start: noop };
1503
- let timer2;
1504
- return {
1505
- cancel() {
1506
- timer2 && (clearTimeout(timer2), timer2 = null);
1507
- },
1508
- start() {
1509
- timer2 && clearTimeout(timer2);
1510
- timer2 = setTimeout(done, seconds * 1e3, arguments);
1511
- }
1512
- };
1513
- function done(args) {
1514
- fn.apply(null, args);
1515
- timer2 = null;
1516
- }
1517
- }
1518
- var connection_default, uid, Sync, Flush, SSLRequest, ExecuteUnnamed, DescribeUnnamed, noop, retryRoutines, errorFields;
1519
- var init_connection = __esm({
1520
- "node_modules/postgres/src/connection.js"() {
1521
- init_types();
1522
- init_errors();
1523
- init_result();
1524
- init_queue();
1525
- init_query();
1526
- init_bytes();
1527
- connection_default = Connection;
1528
- uid = 1;
1529
- Sync = bytes_default().S().end();
1530
- Flush = bytes_default().H().end();
1531
- SSLRequest = bytes_default().i32(8).i32(80877103).end(8);
1532
- ExecuteUnnamed = Buffer.concat([bytes_default().E().str(bytes_default.N).i32(0).end(), Sync]);
1533
- DescribeUnnamed = bytes_default().D().str("S").str(bytes_default.N).end();
1534
- noop = () => {
1535
- };
1536
- retryRoutines = /* @__PURE__ */ new Set([
1537
- "FetchPreparedStatement",
1538
- "RevalidateCachedQuery",
1539
- "transformAssignedExpr"
1540
- ]);
1541
- errorFields = {
1542
- 83: "severity_local",
1543
- // S
1544
- 86: "severity",
1545
- // V
1546
- 67: "code",
1547
- // C
1548
- 77: "message",
1549
- // M
1550
- 68: "detail",
1551
- // D
1552
- 72: "hint",
1553
- // H
1554
- 80: "position",
1555
- // P
1556
- 112: "internal_position",
1557
- // p
1558
- 113: "internal_query",
1559
- // q
1560
- 87: "where",
1561
- // W
1562
- 115: "schema_name",
1563
- // s
1564
- 116: "table_name",
1565
- // t
1566
- 99: "column_name",
1567
- // c
1568
- 100: "data type_name",
1569
- // d
1570
- 110: "constraint_name",
1571
- // n
1572
- 70: "file",
1573
- // F
1574
- 76: "line",
1575
- // L
1576
- 82: "routine"
1577
- // R
1578
- };
1579
- }
1580
- });
1581
-
1582
- // node_modules/postgres/src/subscribe.js
1583
- function Subscribe(postgres2, options) {
1584
- const subscribers = /* @__PURE__ */ new Map(), slot = "postgresjs_" + Math.random().toString(36).slice(2), state = {};
1585
- let connection2, stream, ended = false;
1586
- const sql = subscribe.sql = postgres2(__spreadProps(__spreadValues({}, options), {
1587
- transform: { column: {}, value: {}, row: {} },
1588
- max: 1,
1589
- fetch_types: false,
1590
- idle_timeout: null,
1591
- max_lifetime: null,
1592
- connection: __spreadProps(__spreadValues({}, options.connection), {
1593
- replication: "database"
1594
- }),
1595
- onclose: function() {
1596
- return __async(this, null, function* () {
1597
- if (ended)
1598
- return;
1599
- stream = null;
1600
- state.pid = state.secret = void 0;
1601
- connected(yield init(sql, slot, options.publications));
1602
- subscribers.forEach((event) => event.forEach(({ onsubscribe }) => onsubscribe()));
1603
- });
1604
- },
1605
- no_subscribe: true
1606
- }));
1607
- const end = sql.end, close = sql.close;
1608
- sql.end = () => __async(null, null, function* () {
1609
- ended = true;
1610
- stream && (yield new Promise((r) => (stream.once("close", r), stream.end())));
1611
- return end();
1612
- });
1613
- sql.close = () => __async(null, null, function* () {
1614
- stream && (yield new Promise((r) => (stream.once("close", r), stream.end())));
1615
- return close();
1616
- });
1617
- return subscribe;
1618
- function subscribe(_0, _1) {
1619
- return __async(this, arguments, function* (event, fn, onsubscribe = noop2, onerror = noop2) {
1620
- event = parseEvent(event);
1621
- if (!connection2)
1622
- connection2 = init(sql, slot, options.publications);
1623
- const subscriber = { fn, onsubscribe };
1624
- const fns = subscribers.has(event) ? subscribers.get(event).add(subscriber) : subscribers.set(event, /* @__PURE__ */ new Set([subscriber])).get(event);
1625
- const unsubscribe = () => {
1626
- fns.delete(subscriber);
1627
- fns.size === 0 && subscribers.delete(event);
1628
- };
1629
- return connection2.then((x) => {
1630
- connected(x);
1631
- onsubscribe();
1632
- stream && stream.on("error", onerror);
1633
- return { unsubscribe, state, sql };
1634
- });
1635
- });
1636
- }
1637
- function connected(x) {
1638
- stream = x.stream;
1639
- state.pid = x.state.pid;
1640
- state.secret = x.state.secret;
1641
- }
1642
- function init(sql2, slot2, publications) {
1643
- return __async(this, null, function* () {
1644
- if (!publications)
1645
- throw new Error("Missing publication names");
1646
- const xs = yield sql2.unsafe(
1647
- `CREATE_REPLICATION_SLOT ${slot2} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT`
1648
- );
1649
- const [x] = xs;
1650
- const stream2 = yield sql2.unsafe(
1651
- `START_REPLICATION SLOT ${slot2} LOGICAL ${x.consistent_point} (proto_version '1', publication_names '${publications}')`
1652
- ).writable();
1653
- const state2 = {
1654
- lsn: Buffer.concat(x.consistent_point.split("/").map((x2) => Buffer.from(("00000000" + x2).slice(-8), "hex")))
1655
- };
1656
- stream2.on("data", data);
1657
- stream2.on("error", error);
1658
- stream2.on("close", sql2.close);
1659
- return { stream: stream2, state: xs.state };
1660
- function error(e) {
1661
- console.error("Unexpected error during logical streaming - reconnecting", e);
1662
- }
1663
- function data(x2) {
1664
- if (x2[0] === 119) {
1665
- parse(x2.subarray(25), state2, sql2.options.parsers, handle, options.transform);
1666
- } else if (x2[0] === 107 && x2[17]) {
1667
- state2.lsn = x2.subarray(1, 9);
1668
- pong();
1669
- }
1670
- }
1671
- function handle(a, b2) {
1672
- const path = b2.relation.schema + "." + b2.relation.table;
1673
- call("*", a, b2);
1674
- call("*:" + path, a, b2);
1675
- b2.relation.keys.length && call("*:" + path + "=" + b2.relation.keys.map((x2) => a[x2.name]), a, b2);
1676
- call(b2.command, a, b2);
1677
- call(b2.command + ":" + path, a, b2);
1678
- b2.relation.keys.length && call(b2.command + ":" + path + "=" + b2.relation.keys.map((x2) => a[x2.name]), a, b2);
1679
- }
1680
- function pong() {
1681
- const x2 = Buffer.alloc(34);
1682
- x2[0] = "r".charCodeAt(0);
1683
- x2.fill(state2.lsn, 1);
1684
- x2.writeBigInt64BE(BigInt(Date.now() - Date.UTC(2e3, 0, 1)) * BigInt(1e3), 25);
1685
- stream2.write(x2);
1686
- }
1687
- });
1688
- }
1689
- function call(x, a, b2) {
1690
- subscribers.has(x) && subscribers.get(x).forEach(({ fn }) => fn(a, b2, x));
1691
- }
1692
- }
1693
- function Time(x) {
1694
- return new Date(Date.UTC(2e3, 0, 1) + Number(x / BigInt(1e3)));
1695
- }
1696
- function parse(x, state, parsers2, handle, transform) {
1697
- const char = (acc, [k, v]) => (acc[k.charCodeAt(0)] = v, acc);
1698
- Object.entries({
1699
- R: (x2) => {
1700
- let i = 1;
1701
- const r = state[x2.readUInt32BE(i)] = {
1702
- schema: x2.toString("utf8", i += 4, i = x2.indexOf(0, i)) || "pg_catalog",
1703
- table: x2.toString("utf8", i + 1, i = x2.indexOf(0, i + 1)),
1704
- columns: Array(x2.readUInt16BE(i += 2)),
1705
- keys: []
1706
- };
1707
- i += 2;
1708
- let columnIndex = 0, column;
1709
- while (i < x2.length) {
1710
- column = r.columns[columnIndex++] = {
1711
- key: x2[i++],
1712
- name: transform.column.from ? transform.column.from(x2.toString("utf8", i, i = x2.indexOf(0, i))) : x2.toString("utf8", i, i = x2.indexOf(0, i)),
1713
- type: x2.readUInt32BE(i += 1),
1714
- parser: parsers2[x2.readUInt32BE(i)],
1715
- atttypmod: x2.readUInt32BE(i += 4)
1716
- };
1717
- column.key && r.keys.push(column);
1718
- i += 4;
1719
- }
1720
- },
1721
- Y: () => {
1722
- },
1723
- // Type
1724
- O: () => {
1725
- },
1726
- // Origin
1727
- B: (x2) => {
1728
- state.date = Time(x2.readBigInt64BE(9));
1729
- state.lsn = x2.subarray(1, 9);
1730
- },
1731
- I: (x2) => {
1732
- let i = 1;
1733
- const relation = state[x2.readUInt32BE(i)];
1734
- const { row } = tuples(x2, relation.columns, i += 7, transform);
1735
- handle(row, {
1736
- command: "insert",
1737
- relation
1738
- });
1739
- },
1740
- D: (x2) => {
1741
- let i = 1;
1742
- const relation = state[x2.readUInt32BE(i)];
1743
- i += 4;
1744
- const key = x2[i] === 75;
1745
- handle(
1746
- key || x2[i] === 79 ? tuples(x2, relation.columns, i += 3, transform).row : null,
1747
- {
1748
- command: "delete",
1749
- relation,
1750
- key
1751
- }
1752
- );
1753
- },
1754
- U: (x2) => {
1755
- let i = 1;
1756
- const relation = state[x2.readUInt32BE(i)];
1757
- i += 4;
1758
- const key = x2[i] === 75;
1759
- const xs = key || x2[i] === 79 ? tuples(x2, relation.columns, i += 3, transform) : null;
1760
- xs && (i = xs.i);
1761
- const { row } = tuples(x2, relation.columns, i + 3, transform);
1762
- handle(row, {
1763
- command: "update",
1764
- relation,
1765
- key,
1766
- old: xs && xs.row
1767
- });
1768
- },
1769
- T: () => {
1770
- },
1771
- // Truncate,
1772
- C: () => {
1773
- }
1774
- // Commit
1775
- }).reduce(char, {})[x[0]](x);
1776
- }
1777
- function tuples(x, columns, xi, transform) {
1778
- let type, column, value;
1779
- const row = transform.raw ? new Array(columns.length) : {};
1780
- for (let i = 0; i < columns.length; i++) {
1781
- type = x[xi++];
1782
- column = columns[i];
1783
- value = type === 110 ? null : type === 117 ? void 0 : column.parser === void 0 ? x.toString("utf8", xi + 4, xi += 4 + x.readUInt32BE(xi)) : column.parser.array === true ? column.parser(x.toString("utf8", xi + 5, xi += 4 + x.readUInt32BE(xi))) : column.parser(x.toString("utf8", xi + 4, xi += 4 + x.readUInt32BE(xi)));
1784
- transform.raw ? row[i] = transform.raw === true ? value : transform.value.from ? transform.value.from(value, column) : value : row[column.name] = transform.value.from ? transform.value.from(value, column) : value;
1785
- }
1786
- return { i: xi, row: transform.row.from ? transform.row.from(row) : row };
1787
- }
1788
- function parseEvent(x) {
1789
- const xs = x.match(/^(\*|insert|update|delete)?:?([^.]+?\.?[^=]+)?=?(.+)?/i) || [];
1790
- if (!xs)
1791
- throw new Error("Malformed subscribe pattern: " + x);
1792
- const [, command, path, key] = xs;
1793
- return (command || "*") + (path ? ":" + (path.indexOf(".") === -1 ? "public." + path : path) : "") + (key ? "=" + key : "");
1794
- }
1795
- var noop2;
1796
- var init_subscribe = __esm({
1797
- "node_modules/postgres/src/subscribe.js"() {
1798
- noop2 = () => {
1799
- };
1800
- }
1801
- });
1802
- function largeObject(sql, oid, mode = 131072 | 262144) {
1803
- return new Promise((resolve3, reject) => __async(null, null, function* () {
1804
- yield sql.begin((sql2) => __async(null, null, function* () {
1805
- let finish;
1806
- !oid && ([{ oid }] = yield sql2`select lo_creat(-1) as oid`);
1807
- const [{ fd }] = yield sql2`select lo_open(${oid}, ${mode}) as fd`;
1808
- const lo = {
1809
- writable,
1810
- readable,
1811
- close: () => sql2`select lo_close(${fd})`.then(finish),
1812
- tell: () => sql2`select lo_tell64(${fd})`,
1813
- read: (x) => sql2`select loread(${fd}, ${x}) as data`,
1814
- write: (x) => sql2`select lowrite(${fd}, ${x})`,
1815
- truncate: (x) => sql2`select lo_truncate64(${fd}, ${x})`,
1816
- seek: (x, whence = 0) => sql2`select lo_lseek64(${fd}, ${x}, ${whence})`,
1817
- size: () => sql2`
1818
- select
1819
- lo_lseek64(${fd}, location, 0) as position,
1820
- seek.size
1821
- from (
1822
- select
1823
- lo_lseek64($1, 0, 2) as size,
1824
- tell.location
1825
- from (select lo_tell64($1) as location) tell
1826
- ) seek
1827
- `
1828
- };
1829
- resolve3(lo);
1830
- return new Promise((r) => __async(null, null, function* () {
1831
- return finish = r;
1832
- }));
1833
- function readable() {
1834
- return __async(this, arguments, function* ({
1835
- highWaterMark = 2048 * 8,
1836
- start = 0,
1837
- end = Infinity
1838
- } = {}) {
1839
- let max = end - start;
1840
- start && (yield lo.seek(start));
1841
- return new Stream.Readable({
1842
- highWaterMark,
1843
- read(size2) {
1844
- return __async(this, null, function* () {
1845
- const l = size2 > max ? size2 - max : size2;
1846
- max -= size2;
1847
- const [{ data }] = yield lo.read(l);
1848
- this.push(data);
1849
- if (data.length < size2)
1850
- this.push(null);
1851
- });
1852
- }
1853
- });
1854
- });
1855
- }
1856
- function writable() {
1857
- return __async(this, arguments, function* ({
1858
- highWaterMark = 2048 * 8,
1859
- start = 0
1860
- } = {}) {
1861
- start && (yield lo.seek(start));
1862
- return new Stream.Writable({
1863
- highWaterMark,
1864
- write(chunk, encoding, callback) {
1865
- lo.write(chunk).then(() => callback(), callback);
1866
- }
1867
- });
1868
- });
1869
- }
1870
- })).catch(reject);
1871
- }));
1872
- }
1873
- var init_large = __esm({
1874
- "node_modules/postgres/src/large.js"() {
1875
- }
1876
- });
1877
-
1878
- // node_modules/postgres/src/index.js
1879
- var src_exports = {};
1880
- __export(src_exports, {
1881
- default: () => src_default
1882
- });
1883
- function Postgres(a, b2) {
1884
- const options = parseOptions(a, b2), subscribe = options.no_subscribe || Subscribe(Postgres, __spreadValues({}, options));
1885
- let ending = false;
1886
- const queries = queue_default(), connecting = queue_default(), reserved = queue_default(), closed = queue_default(), ended = queue_default(), open = queue_default(), busy = queue_default(), full = queue_default(), queues = { connecting, reserved, closed, ended, open, busy, full };
1887
- const connections = [...Array(options.max)].map(() => connection_default(options, queues, { onopen, onend, onclose }));
1888
- const sql = Sql(handler);
1889
- Object.assign(sql, {
1890
- get parameters() {
1891
- return options.parameters;
1892
- },
1893
- largeObject: largeObject.bind(null, sql),
1894
- subscribe,
1895
- CLOSE,
1896
- END: CLOSE,
1897
- PostgresError,
1898
- options,
1899
- reserve,
1900
- listen,
1901
- begin,
1902
- close,
1903
- end
1904
- });
1905
- return sql;
1906
- function Sql(handler2) {
1907
- handler2.debug = options.debug;
1908
- Object.entries(options.types).reduce((acc, [name, type]) => {
1909
- acc[name] = (x) => new Parameter(x, type.to);
1910
- return acc;
1911
- }, typed);
1912
- Object.assign(sql2, {
1913
- types: typed,
1914
- typed,
1915
- unsafe,
1916
- notify,
1917
- array,
1918
- json,
1919
- file
1920
- });
1921
- return sql2;
1922
- function typed(value, type) {
1923
- return new Parameter(value, type);
1924
- }
1925
- function sql2(strings, ...args) {
1926
- const query = strings && Array.isArray(strings.raw) ? new Query(strings, args, handler2, cancel) : typeof strings === "string" && !args.length ? new Identifier(options.transform.column.to ? options.transform.column.to(strings) : strings) : new Builder(strings, args);
1927
- return query;
1928
- }
1929
- function unsafe(string, args = [], options2 = {}) {
1930
- arguments.length === 2 && !Array.isArray(args) && (options2 = args, args = []);
1931
- const query = new Query([string], args, handler2, cancel, __spreadProps(__spreadValues({
1932
- prepare: false
1933
- }, options2), {
1934
- simple: "simple" in options2 ? options2.simple : args.length === 0
1935
- }));
1936
- return query;
1937
- }
1938
- function file(path, args = [], options2 = {}) {
1939
- arguments.length === 2 && !Array.isArray(args) && (options2 = args, args = []);
1940
- const query = new Query([], args, (query2) => {
1941
- fs.readFile(path, "utf8", (err, string) => {
1942
- if (err)
1943
- return query2.reject(err);
1944
- query2.strings = [string];
1945
- handler2(query2);
1946
- });
1947
- }, cancel, __spreadProps(__spreadValues({}, options2), {
1948
- simple: "simple" in options2 ? options2.simple : args.length === 0
1949
- }));
1950
- return query;
1951
- }
1952
- }
1953
- function listen(name, fn, onlisten) {
1954
- return __async(this, null, function* () {
1955
- const listener = { fn, onlisten };
1956
- const sql2 = listen.sql || (listen.sql = Postgres(__spreadProps(__spreadValues({}, options), {
1957
- max: 1,
1958
- idle_timeout: null,
1959
- max_lifetime: null,
1960
- fetch_types: false,
1961
- onclose() {
1962
- Object.entries(listen.channels).forEach(([name2, { listeners }]) => {
1963
- delete listen.channels[name2];
1964
- Promise.all(listeners.map((l) => listen(name2, l.fn, l.onlisten).catch(() => {
1965
- })));
1966
- });
1967
- },
1968
- onnotify(c, x) {
1969
- c in listen.channels && listen.channels[c].listeners.forEach((l) => l.fn(x));
1970
- }
1971
- })));
1972
- const channels = listen.channels || (listen.channels = {}), exists = name in channels;
1973
- if (exists) {
1974
- channels[name].listeners.push(listener);
1975
- const result2 = yield channels[name].result;
1976
- listener.onlisten && listener.onlisten();
1977
- return { state: result2.state, unlisten };
1978
- }
1979
- channels[name] = { result: sql2`listen ${sql2.unsafe('"' + name.replace(/"/g, '""') + '"')}`, listeners: [listener] };
1980
- const result = yield channels[name].result;
1981
- listener.onlisten && listener.onlisten();
1982
- return { state: result.state, unlisten };
1983
- function unlisten() {
1984
- return __async(this, null, function* () {
1985
- if (name in channels === false)
1986
- return;
1987
- channels[name].listeners = channels[name].listeners.filter((x) => x !== listener);
1988
- if (channels[name].listeners.length)
1989
- return;
1990
- delete channels[name];
1991
- return sql2`unlisten ${sql2.unsafe('"' + name.replace(/"/g, '""') + '"')}`;
1992
- });
1993
- }
1994
- });
1995
- }
1996
- function notify(channel, payload) {
1997
- return __async(this, null, function* () {
1998
- return yield sql`select pg_notify(${channel}, ${"" + payload})`;
1999
- });
2000
- }
2001
- function reserve() {
2002
- return __async(this, null, function* () {
2003
- const queue = queue_default();
2004
- const c = open.length ? open.shift() : yield new Promise((resolve3, reject) => {
2005
- const query = { reserve: resolve3, reject };
2006
- queries.push(query);
2007
- closed.length && connect(closed.shift(), query);
2008
- });
2009
- move(c, reserved);
2010
- c.reserved = () => queue.length ? c.execute(queue.shift()) : move(c, reserved);
2011
- c.reserved.release = true;
2012
- const sql2 = Sql(handler2);
2013
- sql2.release = () => {
2014
- c.reserved = null;
2015
- onopen(c);
2016
- };
2017
- return sql2;
2018
- function handler2(q) {
2019
- c.queue === full ? queue.push(q) : c.execute(q) || move(c, full);
2020
- }
2021
- });
2022
- }
2023
- function begin(options2, fn) {
2024
- return __async(this, null, function* () {
2025
- !fn && (fn = options2, options2 = "");
2026
- const queries2 = queue_default();
2027
- let savepoints = 0, connection2, prepare = null;
2028
- try {
2029
- yield sql.unsafe("begin " + options2.replace(/[^a-z ]/ig, ""), [], { onexecute }).execute();
2030
- return yield Promise.race([
2031
- scope(connection2, fn),
2032
- new Promise((_, reject) => connection2.onclose = reject)
2033
- ]);
2034
- } catch (error) {
2035
- throw error;
2036
- }
2037
- function scope(c, fn2, name) {
2038
- return __async(this, null, function* () {
2039
- const sql2 = Sql(handler2);
2040
- sql2.savepoint = savepoint;
2041
- sql2.prepare = (x) => prepare = x.replace(/[^a-z0-9$-_. ]/gi);
2042
- let uncaughtError, result;
2043
- name && (yield sql2`savepoint ${sql2(name)}`);
2044
- try {
2045
- result = yield new Promise((resolve3, reject) => {
2046
- const x = fn2(sql2);
2047
- Promise.resolve(Array.isArray(x) ? Promise.all(x) : x).then(resolve3, reject);
2048
- });
2049
- if (uncaughtError)
2050
- throw uncaughtError;
2051
- } catch (e) {
2052
- yield name ? sql2`rollback to ${sql2(name)}` : sql2`rollback`;
2053
- throw e instanceof PostgresError && e.code === "25P02" && uncaughtError || e;
2054
- }
2055
- if (!name) {
2056
- prepare ? yield sql2`prepare transaction '${sql2.unsafe(prepare)}'` : yield sql2`commit`;
2057
- }
2058
- return result;
2059
- function savepoint(name2, fn3) {
2060
- if (name2 && Array.isArray(name2.raw))
2061
- return savepoint((sql3) => sql3.apply(sql3, arguments));
2062
- arguments.length === 1 && (fn3 = name2, name2 = null);
2063
- return scope(c, fn3, "s" + savepoints++ + (name2 ? "_" + name2 : ""));
2064
- }
2065
- function handler2(q) {
2066
- q.catch((e) => uncaughtError || (uncaughtError = e));
2067
- c.queue === full ? queries2.push(q) : c.execute(q) || move(c, full);
2068
- }
2069
- });
2070
- }
2071
- function onexecute(c) {
2072
- connection2 = c;
2073
- move(c, reserved);
2074
- c.reserved = () => queries2.length ? c.execute(queries2.shift()) : move(c, reserved);
2075
- }
2076
- });
2077
- }
2078
- function move(c, queue) {
2079
- c.queue.remove(c);
2080
- queue.push(c);
2081
- c.queue = queue;
2082
- queue === open ? c.idleTimer.start() : c.idleTimer.cancel();
2083
- return c;
2084
- }
2085
- function json(x) {
2086
- return new Parameter(x, 3802);
2087
- }
2088
- function array(x, type) {
2089
- if (!Array.isArray(x))
2090
- return array(Array.from(arguments));
2091
- return new Parameter(x, type || (x.length ? inferType(x) || 25 : 0), options.shared.typeArrayMap);
2092
- }
2093
- function handler(query) {
2094
- if (ending)
2095
- return query.reject(Errors.connection("CONNECTION_ENDED", options, options));
2096
- if (open.length)
2097
- return go(open.shift(), query);
2098
- if (closed.length)
2099
- return connect(closed.shift(), query);
2100
- busy.length ? go(busy.shift(), query) : queries.push(query);
2101
- }
2102
- function go(c, query) {
2103
- return c.execute(query) ? move(c, busy) : move(c, full);
2104
- }
2105
- function cancel(query) {
2106
- return new Promise((resolve3, reject) => {
2107
- query.state ? query.active ? connection_default(options).cancel(query.state, resolve3, reject) : query.cancelled = { resolve: resolve3, reject } : (queries.remove(query), query.cancelled = true, query.reject(Errors.generic("57014", "canceling statement due to user request")), resolve3());
2108
- });
2109
- }
2110
- function end() {
2111
- return __async(this, arguments, function* ({ timeout = null } = {}) {
2112
- if (ending)
2113
- return ending;
2114
- yield 1;
2115
- let timer2;
2116
- return ending = Promise.race([
2117
- new Promise((r) => timeout !== null && (timer2 = setTimeout(destroy, timeout * 1e3, r))),
2118
- Promise.all(connections.map((c) => c.end()).concat(
2119
- listen.sql ? listen.sql.end({ timeout: 0 }) : [],
2120
- subscribe.sql ? subscribe.sql.end({ timeout: 0 }) : []
2121
- ))
2122
- ]).then(() => clearTimeout(timer2));
2123
- });
2124
- }
2125
- function close() {
2126
- return __async(this, null, function* () {
2127
- yield Promise.all(connections.map((c) => c.end()));
2128
- });
2129
- }
2130
- function destroy(resolve3) {
2131
- return __async(this, null, function* () {
2132
- yield Promise.all(connections.map((c) => c.terminate()));
2133
- while (queries.length)
2134
- queries.shift().reject(Errors.connection("CONNECTION_DESTROYED", options));
2135
- resolve3();
2136
- });
2137
- }
2138
- function connect(c, query) {
2139
- move(c, connecting);
2140
- c.connect(query);
2141
- return c;
2142
- }
2143
- function onend(c) {
2144
- move(c, ended);
2145
- }
2146
- function onopen(c) {
2147
- if (queries.length === 0)
2148
- return move(c, open);
2149
- let max = Math.ceil(queries.length / (connecting.length + 1)), ready = true;
2150
- while (ready && queries.length && max-- > 0) {
2151
- const query = queries.shift();
2152
- if (query.reserve)
2153
- return query.reserve(c);
2154
- ready = c.execute(query);
2155
- }
2156
- ready ? move(c, busy) : move(c, full);
2157
- }
2158
- function onclose(c, e) {
2159
- move(c, closed);
2160
- c.reserved = null;
2161
- c.onclose && (c.onclose(e), c.onclose = null);
2162
- options.onclose && options.onclose(c.id);
2163
- queries.length && connect(c, queries.shift());
2164
- }
2165
- }
2166
- function parseOptions(a, b2) {
2167
- if (a && a.shared)
2168
- return a;
2169
- const env = process.env, o = (!a || typeof a === "string" ? b2 : a) || {}, { url, multihost } = parseUrl(a), query = [...url.searchParams].reduce((a2, [b3, c]) => (a2[b3] = c, a2), {}), host = o.hostname || o.host || multihost || url.hostname || env.PGHOST || "localhost", port = o.port || url.port || env.PGPORT || 5432, user = o.user || o.username || url.username || env.PGUSERNAME || env.PGUSER || osUsername();
2170
- o.no_prepare && (o.prepare = false);
2171
- query.sslmode && (query.ssl = query.sslmode, delete query.sslmode);
2172
- "timeout" in o && (console.log("The timeout option is deprecated, use idle_timeout instead"), o.idle_timeout = o.timeout);
2173
- query.sslrootcert === "system" && (query.ssl = "verify-full");
2174
- const ints = ["idle_timeout", "connect_timeout", "max_lifetime", "max_pipeline", "backoff", "keep_alive"];
2175
- const defaults = {
2176
- max: globalThis.Cloudflare ? 3 : 10,
2177
- ssl: false,
2178
- sslnegotiation: null,
2179
- idle_timeout: null,
2180
- connect_timeout: 30,
2181
- max_lifetime,
2182
- max_pipeline: 100,
2183
- backoff,
2184
- keep_alive: 60,
2185
- prepare: true,
2186
- debug: false,
2187
- fetch_types: true,
2188
- publications: "alltables",
2189
- target_session_attrs: null
2190
- };
2191
- return __spreadValues(__spreadProps(__spreadValues({
2192
- host: Array.isArray(host) ? host : host.split(",").map((x) => x.split(":")[0]),
2193
- port: Array.isArray(port) ? port : host.split(",").map((x) => parseInt(x.split(":")[1] || port)),
2194
- path: o.path || host.indexOf("/") > -1 && host + "/.s.PGSQL." + port,
2195
- database: o.database || o.db || (url.pathname || "").slice(1) || env.PGDATABASE || user,
2196
- user,
2197
- pass: o.pass || o.password || url.password || env.PGPASSWORD || ""
2198
- }, Object.entries(defaults).reduce(
2199
- (acc, [k, d]) => {
2200
- const value = k in o ? o[k] : k in query ? query[k] === "disable" || query[k] === "false" ? false : query[k] : env["PG" + k.toUpperCase()] || d;
2201
- acc[k] = typeof value === "string" && ints.includes(k) ? +value : value;
2202
- return acc;
2203
- },
2204
- {}
2205
- )), {
2206
- connection: __spreadValues(__spreadValues({
2207
- application_name: env.PGAPPNAME || "postgres.js"
2208
- }, o.connection), Object.entries(query).reduce((acc, [k, v]) => (k in defaults || (acc[k] = v), acc), {})),
2209
- types: o.types || {},
2210
- target_session_attrs: tsa(o, url, env),
2211
- onnotice: o.onnotice,
2212
- onnotify: o.onnotify,
2213
- onclose: o.onclose,
2214
- onparameter: o.onparameter,
2215
- socket: o.socket,
2216
- transform: parseTransform(o.transform || { undefined: void 0 }),
2217
- parameters: {},
2218
- shared: { retries: 0, typeArrayMap: {} }
2219
- }), mergeUserTypes(o.types));
2220
- }
2221
- function tsa(o, url, env) {
2222
- const x = o.target_session_attrs || url.searchParams.get("target_session_attrs") || env.PGTARGETSESSIONATTRS;
2223
- if (!x || ["read-write", "read-only", "primary", "standby", "prefer-standby"].includes(x))
2224
- return x;
2225
- throw new Error("target_session_attrs " + x + " is not supported");
2226
- }
2227
- function backoff(retries) {
2228
- return (0.5 + Math.random() / 2) * Math.min(__pow(3, retries) / 100, 20);
2229
- }
2230
- function max_lifetime() {
2231
- return 60 * (30 + Math.random() * 30);
2232
- }
2233
- function parseTransform(x) {
2234
- return {
2235
- undefined: x.undefined,
2236
- column: {
2237
- from: typeof x.column === "function" ? x.column : x.column && x.column.from,
2238
- to: x.column && x.column.to
2239
- },
2240
- value: {
2241
- from: typeof x.value === "function" ? x.value : x.value && x.value.from,
2242
- to: x.value && x.value.to
2243
- },
2244
- row: {
2245
- from: typeof x.row === "function" ? x.row : x.row && x.row.from,
2246
- to: x.row && x.row.to
2247
- }
2248
- };
2249
- }
2250
- function parseUrl(url) {
2251
- if (!url || typeof url !== "string")
2252
- return { url: { searchParams: /* @__PURE__ */ new Map() } };
2253
- let host = url;
2254
- host = host.slice(host.indexOf("://") + 3).split(/[?/]/)[0];
2255
- host = decodeURIComponent(host.slice(host.indexOf("@") + 1));
2256
- const urlObj = new URL(url.replace(host, host.split(",")[0]));
2257
- return {
2258
- url: {
2259
- username: decodeURIComponent(urlObj.username),
2260
- password: decodeURIComponent(urlObj.password),
2261
- host: urlObj.host,
2262
- hostname: urlObj.hostname,
2263
- port: urlObj.port,
2264
- pathname: urlObj.pathname,
2265
- searchParams: urlObj.searchParams
2266
- },
2267
- multihost: host.indexOf(",") > -1 && host
2268
- };
2269
- }
2270
- function osUsername() {
2271
- try {
2272
- return os.userInfo().username;
2273
- } catch (_) {
2274
- return process.env.USERNAME || process.env.USER || process.env.LOGNAME;
2275
- }
2276
- }
2277
- var src_default;
2278
- var init_src = __esm({
2279
- "node_modules/postgres/src/index.js"() {
2280
- init_types();
2281
- init_connection();
2282
- init_query();
2283
- init_queue();
2284
- init_errors();
2285
- init_subscribe();
2286
- init_large();
2287
- Object.assign(Postgres, {
2288
- PostgresError,
2289
- toPascal,
2290
- pascal,
2291
- toCamel,
2292
- camel,
2293
- toKebab,
2294
- kebab,
2295
- fromPascal,
2296
- fromCamel,
2297
- fromKebab,
2298
- BigInt: {
2299
- to: 20,
2300
- from: [20],
2301
- parse: (x) => BigInt(x),
2302
- // eslint-disable-line
2303
- serialize: (x) => x.toString()
2304
- }
2305
- });
2306
- src_default = Postgres;
2307
- }
2308
- });
2309
-
2310
66
  // package.json
2311
67
  var require_package = __commonJS({
2312
68
  "package.json"(exports$1, module) {
2313
69
  module.exports = {
2314
70
  name: "prisma-sql",
2315
- version: "1.75.5",
71
+ version: "1.75.7",
2316
72
  description: "Convert Prisma queries to optimized SQL with type safety. 2-7x faster than Prisma Client.",
2317
73
  main: "dist/index.cjs",
2318
74
  module: "dist/index.js",
2319
75
  types: "dist/index.d.ts",
2320
76
  bin: {
2321
- "prisma-sql-generator": "./dist/generator.cjs"
77
+ "prisma-sql-generator": "./dist/generator.cjs",
78
+ "prisma-sql-collect-stats": "./dist/collect-planner-stats.cjs"
2322
79
  },
2323
80
  exports: {
2324
81
  ".": {
@@ -2379,7 +136,8 @@ var require_package = __commonJS({
2379
136
  dependencies: {
2380
137
  "@dee-wan/schema-parser": "1.4.0",
2381
138
  "@prisma/generator-helper": "^7.4.0",
2382
- "@prisma/internals": "^7.4.0"
139
+ "@prisma/internals": "^7.4.0",
140
+ postgres: "^3.4.8"
2383
141
  },
2384
142
  devDependencies: {
2385
143
  "@faker-js/faker": "^10.2.0",
@@ -2393,7 +151,6 @@ var require_package = __commonJS({
2393
151
  "better-sqlite3": "^12.6.2",
2394
152
  "drizzle-kit": "^0.31.8",
2395
153
  "drizzle-orm": "^0.45.1",
2396
- postgres: "^3.4.8",
2397
154
  tsup: "^8.5.1",
2398
155
  tsx: "^4.21.0",
2399
156
  typescript: "^5.9.3",
@@ -3679,9 +1436,9 @@ function findTiebreakerField(model) {
3679
1436
  if (scalarSet.has("id")) return "id";
3680
1437
  return null;
3681
1438
  }
3682
- function hasTiebreaker(orderBy, parse2, field) {
1439
+ function hasTiebreaker(orderBy, parse, field) {
3683
1440
  if (!isNotNullish(orderBy)) return false;
3684
- const normalized = normalizeOrderByInput(orderBy, parse2);
1441
+ const normalized = normalizeOrderByInput(orderBy, parse);
3685
1442
  return normalized.some(
3686
1443
  (obj) => Object.prototype.hasOwnProperty.call(obj, field)
3687
1444
  );
@@ -4989,7 +2746,7 @@ function extractReferencedParams(whereClause, specParams) {
4989
2746
  return { cleanWhere: whereClause, params: [] };
4990
2747
  }
4991
2748
  const allParams = Array.isArray(specParams) ? specParams : typeof specParams.snapshot === "function" ? specParams.snapshot().params : [];
4992
- const refs = Array.from(refSet).sort((a, b2) => a - b2);
2749
+ const refs = Array.from(refSet).sort((a, b) => a - b);
4993
2750
  const params = [];
4994
2751
  const indexMap = /* @__PURE__ */ new Map();
4995
2752
  for (const oldIdx of refs) {
@@ -4997,7 +2754,7 @@ function extractReferencedParams(whereClause, specParams) {
4997
2754
  indexMap.set(oldIdx, params.length);
4998
2755
  }
4999
2756
  let cleanWhere = whereClause;
5000
- const sorted = Array.from(indexMap.entries()).sort((a, b2) => b2[0] - a[0]);
2757
+ const sorted = Array.from(indexMap.entries()).sort((a, b) => b[0] - a[0]);
5001
2758
  for (const [oldIdx, newIdx] of sorted) {
5002
2759
  cleanWhere = cleanWhere.split(`$${oldIdx}`).join(`$${newIdx}`);
5003
2760
  }
@@ -5005,7 +2762,7 @@ function extractReferencedParams(whereClause, specParams) {
5005
2762
  }
5006
2763
  function buildFlatJoinSql(spec) {
5007
2764
  const {
5008
- select: select2,
2765
+ select,
5009
2766
  from,
5010
2767
  whereClause,
5011
2768
  whereJoins,
@@ -5073,7 +2830,7 @@ function buildFlatJoinSql(spec) {
5073
2830
  if (built.joins.length === 0) {
5074
2831
  return emptyResult;
5075
2832
  }
5076
- const baseSelect = (select2 != null ? select2 : "").trim();
2833
+ const baseSelect = (select != null ? select : "").trim();
5077
2834
  const allSelects = [baseSelect, ...built.selects].filter((s) => s && s.trim().length > 0).join(SQL_SEPARATORS.FIELD_LIST);
5078
2835
  if (!allSelects) {
5079
2836
  throw new Error("Flat-join SELECT requires at least one selected field");
@@ -6333,12 +4090,12 @@ function maybeReverseNegativeTake(takeVal, hasOrderBy, orderByInput) {
6333
4090
 
6334
4091
  // src/builder/select/lateral-join.ts
6335
4092
  function createParamCollector() {
6336
- const values2 = [];
4093
+ const values = [];
6337
4094
  return {
6338
- values: values2,
4095
+ values,
6339
4096
  add(value) {
6340
- values2.push(value);
6341
- return `$${values2.length}`;
4097
+ values.push(value);
4098
+ return `$${values.length}`;
6342
4099
  }
6343
4100
  };
6344
4101
  }
@@ -6365,14 +4122,14 @@ function reindexWhereParams(whereClause, specParams, collector) {
6365
4122
  }
6366
4123
  if (refSet.size === 0) return whereClause;
6367
4124
  const allParams = Array.isArray(specParams) ? specParams : typeof specParams.snapshot === "function" ? specParams.snapshot().params : [];
6368
- const refs = Array.from(refSet).sort((a, b2) => a - b2);
4125
+ const refs = Array.from(refSet).sort((a, b) => a - b);
6369
4126
  const indexMap = /* @__PURE__ */ new Map();
6370
4127
  for (const oldIdx of refs) {
6371
4128
  collector.values.push(allParams[oldIdx - 1]);
6372
4129
  indexMap.set(oldIdx, collector.values.length);
6373
4130
  }
6374
4131
  let clean = whereClause;
6375
- const sorted = Array.from(indexMap.entries()).sort((a, b2) => b2[0] - a[0]);
4132
+ const sorted = Array.from(indexMap.entries()).sort((a, b) => b[0] - a[0]);
6376
4133
  for (const [oldIdx, newIdx] of sorted) {
6377
4134
  clean = clean.split(`$${oldIdx}`).join(`$${newIdx}`);
6378
4135
  }
@@ -6703,8 +4460,8 @@ Hint: When using distinct with SQLite:
6703
4460
  }
6704
4461
  return unquoteIdent(column);
6705
4462
  }
6706
- function parseSimpleScalarSelect(select2, fromAlias) {
6707
- const raw = select2.trim();
4463
+ function parseSimpleScalarSelect(select, fromAlias) {
4464
+ const raw = select.trim();
6708
4465
  if (raw.length === 0) return [];
6709
4466
  const parts = raw.split(SQL_SEPARATORS.FIELD_LIST);
6710
4467
  const names = [];
@@ -6917,8 +4674,8 @@ function resolveCountSelect(countSelectRaw, model) {
6917
4674
  }
6918
4675
  function buildIncludeColumns(spec) {
6919
4676
  var _a3, _b, _c, _d, _e;
6920
- const { select: select2, includes, dialect, model, schemas, from, params } = spec;
6921
- const baseSelect = (select2 != null ? select2 : "").trim();
4677
+ const { select, includes, dialect, model, schemas, from, params } = spec;
4678
+ const baseSelect = (select != null ? select : "").trim();
6922
4679
  let countCols = "";
6923
4680
  let countJoins = [];
6924
4681
  const countSelectRaw = (_e = (_b = (_a3 = spec.args) == null ? void 0 : _a3.select) == null ? void 0 : _b[COUNT_SELECT_KEY]) != null ? _e : (_d = (_c = spec.args) == null ? void 0 : _c.include) == null ? void 0 : _d[COUNT_SELECT_KEY];
@@ -7078,7 +4835,7 @@ function hasNestedIncludes(includeSpec) {
7078
4835
  }
7079
4836
  function constructFinalSql(spec) {
7080
4837
  const {
7081
- select: select2,
4838
+ select,
7082
4839
  from,
7083
4840
  whereClause,
7084
4841
  whereJoins,
@@ -7161,7 +4918,7 @@ function constructFinalSql(spec) {
7161
4918
  parts.push(SQL_TEMPLATES.SELECT);
7162
4919
  const distinctOn = dialect === "postgres" ? buildPostgresDistinctOnClause(from.alias, distinct, model) : null;
7163
4920
  if (distinctOn) parts.push(distinctOn);
7164
- const baseSelect = (select2 != null ? select2 : "").trim();
4921
+ const baseSelect = (select != null ? select : "").trim();
7165
4922
  const fullSelectList = buildSelectList(baseSelect, includeCols);
7166
4923
  if (!isNonEmptyString(fullSelectList)) {
7167
4924
  throw new Error("SELECT requires at least one selected field or include");
@@ -7197,9 +4954,9 @@ function constructFinalSql(spec) {
7197
4954
 
7198
4955
  // src/builder/select/fields.ts
7199
4956
  var DEFAULT_SELECT_CACHE = /* @__PURE__ */ new WeakMap();
7200
- function toSelectEntries(select2) {
4957
+ function toSelectEntries(select) {
7201
4958
  const out = [];
7202
- for (const [k, v] of Object.entries(select2)) {
4959
+ for (const [k, v] of Object.entries(select)) {
7203
4960
  if (v !== false && v !== void 0) out.push([k, v]);
7204
4961
  }
7205
4962
  return out;
@@ -7922,7 +5679,7 @@ function resolveRelationOrderByChain(relationFieldName, value, currentModel, cur
7922
5679
  `Relation orderBy nesting too deep (max ${MAX_RELATION_ORDER_BY_DEPTH} levels)`
7923
5680
  );
7924
5681
  }
7925
- if ("_count" in value) {
5682
+ if ("_count" in value && value._count !== void 0) {
7926
5683
  throw new Error(
7927
5684
  `Relation orderBy with _count on '${relationFieldName}' is not yet supported by prisma-sql`
7928
5685
  );
@@ -7951,7 +5708,7 @@ function resolveRelationOrderByChain(relationFieldName, value, currentModel, cur
7951
5708
  ctx.joins.push(`LEFT JOIN ${tableRef} ${joinAlias} ON ${cond}`);
7952
5709
  const relScalarSet = getScalarFieldSet(relatedModel);
7953
5710
  const relRelationSet = getRelationFieldSet(relatedModel);
7954
- const nestedEntries = Object.entries(value);
5711
+ const nestedEntries = Object.entries(value).filter(([, v]) => v !== void 0);
7955
5712
  const orderFragments = [];
7956
5713
  for (const [nestedField, nestedValue] of nestedEntries) {
7957
5714
  if (relScalarSet.has(nestedField)) {
@@ -8810,11 +6567,11 @@ function buildCountSql(whereResult, tableName, alias, argsOrSkip, dialect, model
8810
6567
  if (selectFields.length === 0) {
8811
6568
  return buildSimpleCountSql(whereResult, tableName, alias, d);
8812
6569
  }
8813
- const select2 = {};
8814
- for (const f of selectFields) select2[f] = true;
6570
+ const select = {};
6571
+ for (const f of selectFields) select[f] = true;
8815
6572
  const subArgs = __spreadProps(__spreadValues({}, args), {
8816
6573
  include: void 0,
8817
- select: select2
6574
+ select
8818
6575
  });
8819
6576
  const subSchemas = Array.isArray(schemas) && schemas.length > 0 ? schemas : [model];
8820
6577
  const sub = buildSelectSql({
@@ -9037,7 +6794,7 @@ function normalizeSqlAndMappingsForDialect(sql, paramMappings, dialect) {
9037
6794
  return { sql: normalizedSql, paramMappings: expandedMappings };
9038
6795
  }
9039
6796
  function buildParamsFromMappings(mappings) {
9040
- const sorted = [...mappings].sort((a, b2) => a.index - b2.index);
6797
+ const sorted = [...mappings].sort((a, b) => a.index - b.index);
9041
6798
  const staticParams = [];
9042
6799
  const dynamicKeys = [];
9043
6800
  let paramOrder = "";
@@ -9579,9 +7336,9 @@ function createDatabaseExecutor(params) {
9579
7336
  return __async(this, null, function* () {
9580
7337
  const { databaseUrl, dialect } = params;
9581
7338
  if (dialect === "postgres") {
9582
- const postgres2 = yield Promise.resolve().then(() => (init_src(), src_exports));
7339
+ const postgres = yield import('postgres');
9583
7340
  cleanDatabaseUrl(databaseUrl);
9584
- const sql = postgres2.default(databaseUrl, { max: 1 });
7341
+ const sql = postgres.default(databaseUrl, { max: 1 });
9585
7342
  return {
9586
7343
  executor: {
9587
7344
  query: (sqlStr, params2) => __async(null, null, function* () {
@@ -9753,7 +7510,7 @@ function measureRoundtripCost(params) {
9753
7510
  yield executor.query("SELECT 1");
9754
7511
  roundtripTimes.push(performance.now() - start);
9755
7512
  }
9756
- roundtripTimes.sort((a, b2) => a - b2);
7513
+ roundtripTimes.sort((a, b) => a - b);
9757
7514
  const medianRoundtrip = roundtripTimes[Math.floor(SAMPLES / 2)];
9758
7515
  console.log(
9759
7516
  ` [roundtrip] SELECT 1 times (ms): min=${roundtripTimes[0].toFixed(3)} median=${medianRoundtrip.toFixed(3)} max=${roundtripTimes[SAMPLES - 1].toFixed(3)}`
@@ -9791,7 +7548,7 @@ function estimateFromQueryPairRatio(params) {
9791
7548
  yield executor.query(`SELECT * FROM ${tableName} LIMIT ${smallLimit}`);
9792
7549
  smallTimes.push(performance.now() - start);
9793
7550
  }
9794
- smallTimes.sort((a, b2) => a - b2);
7551
+ smallTimes.sort((a, b) => a - b);
9795
7552
  const medianSmall = smallTimes[Math.floor(SAMPLES / 2)];
9796
7553
  const largeTimes = [];
9797
7554
  let actualLargeRows = 0;
@@ -9803,7 +7560,7 @@ function estimateFromQueryPairRatio(params) {
9803
7560
  largeTimes.push(performance.now() - start);
9804
7561
  actualLargeRows = rows.length;
9805
7562
  }
9806
- largeTimes.sort((a, b2) => a - b2);
7563
+ largeTimes.sort((a, b) => a - b);
9807
7564
  const medianLarge = largeTimes[Math.floor(SAMPLES / 2)];
9808
7565
  const rowDiff = actualLargeRows - smallLimit;
9809
7566
  const timeDiff = medianLarge - medianSmall;
@@ -9831,7 +7588,7 @@ function estimateFromQueryPairRatio(params) {
9831
7588
  yield executor.query(`SELECT * FROM ${tableName} LIMIT ${smallLimit}`);
9832
7589
  sequentialTimes.push(performance.now() - start);
9833
7590
  }
9834
- sequentialTimes.sort((a, b2) => a - b2);
7591
+ sequentialTimes.sort((a, b) => a - b);
9835
7592
  const median3Sequential = sequentialTimes[Math.floor(SAMPLES / 2)];
9836
7593
  const marginalQueryCost = (median3Sequential - medianSmall) / 2;
9837
7594
  console.log(
@@ -9878,7 +7635,7 @@ function measureJsonOverhead(params) {
9878
7635
  yield executor.query(rawSql);
9879
7636
  rawTimes.push(performance.now() - start);
9880
7637
  }
9881
- rawTimes.sort((a, b2) => a - b2);
7638
+ rawTimes.sort((a, b) => a - b);
9882
7639
  const medianRaw = rawTimes[Math.floor(SAMPLES / 2)];
9883
7640
  const aggTimes = [];
9884
7641
  for (let i = 0; i < SAMPLES; i++) {
@@ -9886,7 +7643,7 @@ function measureJsonOverhead(params) {
9886
7643
  yield executor.query(aggSql);
9887
7644
  aggTimes.push(performance.now() - start);
9888
7645
  }
9889
- aggTimes.sort((a, b2) => a - b2);
7646
+ aggTimes.sort((a, b) => a - b);
9890
7647
  const medianAgg = aggTimes[Math.floor(SAMPLES / 2)];
9891
7648
  const factor = medianRaw > 0.01 ? medianAgg / medianRaw : 3;
9892
7649
  console.log(` [json] Raw ${limit} rows: ${medianRaw.toFixed(3)}ms`);
@@ -10134,6 +7891,7 @@ function processAllModelDirectives(directiveResults, config) {
10134
7891
  }
10135
7892
  return { queries, skippedCount };
10136
7893
  }
7894
+ var DB_CONNECT_TIMEOUT_MS = 5e3;
10137
7895
  function generateClient(options) {
10138
7896
  return __async(this, null, function* () {
10139
7897
  var _a3;
@@ -10144,9 +7902,7 @@ function generateClient(options) {
10144
7902
  const directiveResults = processAllDirectives(
10145
7903
  datamodel.models,
10146
7904
  datamodel,
10147
- {
10148
- skipInvalid: config.skipInvalid
10149
- }
7905
+ { skipInvalid: config.skipInvalid }
10150
7906
  );
10151
7907
  const { queries, skippedCount } = processAllModelDirectives(
10152
7908
  directiveResults,
@@ -10159,13 +7915,31 @@ function generateClient(options) {
10159
7915
  let executor = options.executor;
10160
7916
  let cleanup;
10161
7917
  if (!executor && datasourceUrl) {
7918
+ let timedOut = false;
7919
+ const timeoutHandle = new Promise((_, reject) => {
7920
+ var _a4;
7921
+ const id = setTimeout(() => {
7922
+ timedOut = true;
7923
+ reject(
7924
+ new Error(
7925
+ `DB connection timed out after ${DB_CONNECT_TIMEOUT_MS}ms`
7926
+ )
7927
+ );
7928
+ }, DB_CONNECT_TIMEOUT_MS);
7929
+ (_a4 = id.unref) == null ? void 0 : _a4.call(id);
7930
+ });
10162
7931
  try {
10163
- const dbConn = yield createDatabaseExecutor({
10164
- databaseUrl: datasourceUrl,
10165
- dialect: config.dialect
10166
- });
10167
- executor = dbConn.executor;
10168
- cleanup = dbConn.cleanup;
7932
+ const dbConn = yield Promise.race([
7933
+ createDatabaseExecutor({
7934
+ databaseUrl: datasourceUrl,
7935
+ dialect: config.dialect
7936
+ }),
7937
+ timeoutHandle
7938
+ ]);
7939
+ if (!timedOut) {
7940
+ executor = dbConn.executor;
7941
+ cleanup = dbConn.cleanup;
7942
+ }
10169
7943
  } catch (error) {
10170
7944
  console.warn(
10171
7945
  "\u26A0 Failed to connect:",