pqb 0.7.13 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/index.d.ts +618 -563
  3. package/dist/index.esm.js +1011 -402
  4. package/dist/index.esm.js.map +1 -1
  5. package/dist/index.js +1014 -401
  6. package/dist/index.js.map +1 -1
  7. package/package.json +1 -1
  8. package/src/columnSchema/array.test.ts +67 -0
  9. package/src/columnSchema/array.ts +39 -13
  10. package/src/columnSchema/boolean.test.ts +17 -0
  11. package/src/columnSchema/boolean.ts +5 -1
  12. package/src/columnSchema/columnType.test.ts +230 -107
  13. package/src/columnSchema/columnType.ts +198 -28
  14. package/src/columnSchema/columnTypes.ts +28 -15
  15. package/src/columnSchema/columnsSchema.ts +6 -4
  16. package/src/columnSchema/commonMethods.ts +11 -4
  17. package/src/columnSchema/dateTime.test.ts +298 -0
  18. package/src/columnSchema/dateTime.ts +59 -2
  19. package/src/columnSchema/enum.test.ts +33 -0
  20. package/src/columnSchema/enum.ts +11 -1
  21. package/src/columnSchema/json/array.test.ts +21 -0
  22. package/src/columnSchema/json/array.ts +27 -13
  23. package/src/columnSchema/json/discriminatedUnion.test.ts +32 -0
  24. package/src/columnSchema/json/discriminatedUnion.ts +17 -2
  25. package/src/columnSchema/json/enum.test.ts +9 -0
  26. package/src/columnSchema/json/enum.ts +9 -1
  27. package/src/columnSchema/json/index.ts +19 -19
  28. package/src/columnSchema/json/instanceOf.test.ts +8 -0
  29. package/src/columnSchema/json/instanceOf.ts +4 -1
  30. package/src/columnSchema/json/intersection.test.ts +19 -0
  31. package/src/columnSchema/json/intersection.ts +9 -1
  32. package/src/columnSchema/json/lazy.test.ts +22 -0
  33. package/src/columnSchema/json/lazy.ts +22 -1
  34. package/src/columnSchema/json/literal.test.ts +7 -0
  35. package/src/columnSchema/json/literal.ts +12 -1
  36. package/src/columnSchema/json/map.test.ts +10 -0
  37. package/src/columnSchema/json/map.ts +21 -1
  38. package/src/columnSchema/json/nativeEnum.test.ts +10 -0
  39. package/src/columnSchema/json/nativeEnum.ts +4 -1
  40. package/src/columnSchema/json/nullable.test.ts +18 -0
  41. package/src/columnSchema/json/nullish.test.ts +18 -0
  42. package/src/columnSchema/json/object.test.ts +77 -0
  43. package/src/columnSchema/json/object.ts +31 -3
  44. package/src/columnSchema/json/optional.test.ts +18 -0
  45. package/src/columnSchema/json/record.test.ts +14 -0
  46. package/src/columnSchema/json/record.ts +12 -1
  47. package/src/columnSchema/json/scalarTypes.test.ts +133 -0
  48. package/src/columnSchema/json/scalarTypes.ts +90 -1
  49. package/src/columnSchema/json/set.test.ts +29 -0
  50. package/src/columnSchema/json/set.ts +26 -7
  51. package/src/columnSchema/json/tuple.test.ts +17 -0
  52. package/src/columnSchema/json/tuple.ts +16 -1
  53. package/src/columnSchema/json/typeBase.test.ts +123 -0
  54. package/src/columnSchema/json/typeBase.ts +52 -13
  55. package/src/columnSchema/json/union.test.ts +10 -0
  56. package/src/columnSchema/json/union.ts +18 -1
  57. package/src/columnSchema/json.test.ts +17 -0
  58. package/src/columnSchema/json.ts +10 -2
  59. package/src/columnSchema/number.test.ts +176 -0
  60. package/src/columnSchema/number.ts +48 -1
  61. package/src/columnSchema/string.test.ts +412 -0
  62. package/src/columnSchema/string.ts +126 -15
  63. package/src/columnSchema/timestamps.test.ts +6 -6
  64. package/src/columnSchema/virtual.ts +4 -0
  65. package/src/db.ts +1 -1
  66. package/src/query.ts +1 -1
  67. package/src/queryMethods/create.ts +6 -6
  68. package/src/queryMethods/for.ts +3 -3
  69. package/src/queryMethods/having.ts +1 -1
  70. package/src/queryMethods/join.ts +4 -4
  71. package/src/queryMethods/json.ts +1 -1
  72. package/src/queryMethods/queryMethods.ts +2 -2
  73. package/src/queryMethods/select.ts +3 -3
  74. package/src/queryMethods/update.ts +17 -17
  75. package/src/queryMethods/where.test.ts +1 -1
  76. package/src/queryMethods/where.ts +4 -4
  77. package/src/relations.ts +1 -1
  78. package/src/sql/aggregate.ts +2 -2
  79. package/src/sql/copy.ts +3 -3
  80. package/src/sql/delete.ts +5 -5
  81. package/src/sql/fromAndAs.ts +4 -4
  82. package/src/sql/having.ts +7 -7
  83. package/src/sql/insert.ts +5 -5
  84. package/src/sql/join.ts +16 -16
  85. package/src/sql/select.ts +6 -6
  86. package/src/sql/toSql.ts +24 -24
  87. package/src/sql/update.ts +4 -4
  88. package/src/sql/where.ts +18 -18
  89. package/src/utils.test.ts +9 -0
  90. package/src/utils.ts +3 -0
  91. package/src/columnSchema/columnTypes.test.ts +0 -527
package/dist/index.js CHANGED
@@ -4,168 +4,77 @@ Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  var pg = require('pg');
6
6
 
7
- var __defProp$q = Object.defineProperty;
8
- var __defProps$k = Object.defineProperties;
9
- var __getOwnPropDescs$k = Object.getOwnPropertyDescriptors;
10
- var __getOwnPropSymbols$r = Object.getOwnPropertySymbols;
11
- var __hasOwnProp$r = Object.prototype.hasOwnProperty;
12
- var __propIsEnum$r = Object.prototype.propertyIsEnumerable;
13
- var __defNormalProp$q = (obj, key, value) => key in obj ? __defProp$q(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
14
- var __spreadValues$q = (a, b) => {
15
- for (var prop in b || (b = {}))
16
- if (__hasOwnProp$r.call(b, prop))
17
- __defNormalProp$q(a, prop, b[prop]);
18
- if (__getOwnPropSymbols$r)
19
- for (var prop of __getOwnPropSymbols$r(b)) {
20
- if (__propIsEnum$r.call(b, prop))
21
- __defNormalProp$q(a, prop, b[prop]);
22
- }
23
- return a;
24
- };
25
- var __spreadProps$k = (a, b) => __defProps$k(a, __getOwnPropDescs$k(b));
26
- const addColumnData = (q, key, value) => {
27
- const cloned = Object.create(q);
28
- cloned.data = __spreadProps$k(__spreadValues$q({}, q.data), { [key]: value });
29
- return cloned;
7
+ const defaultsKey = Symbol("defaults");
8
+ const queryTypeWithLimitOne = {
9
+ one: true,
10
+ oneOrThrow: true
30
11
  };
31
- class ColumnType {
32
- constructor() {
33
- this.data = {};
34
- this.isPrimaryKey = false;
35
- this.isHidden = false;
36
- this.isNullable = false;
37
- this.hasDefault = false;
38
- this.chain = [];
12
+ const isQueryReturnsAll = (q) => !q.query.returnType || q.query.returnType === "all";
13
+
14
+ const raw = (sql, values) => ({
15
+ __raw: sql,
16
+ __values: values
17
+ });
18
+ const isRaw = (obj) => "__raw" in obj;
19
+ const keys = [];
20
+ const getRaw = (raw2, valuesArray) => {
21
+ if (raw2.__values === false) {
22
+ return raw2.__raw;
39
23
  }
40
- primaryKey() {
41
- return Object.assign(this, { isPrimaryKey: true });
24
+ const arr = raw2.__raw.split("'");
25
+ const values = raw2.__values || emptyObject;
26
+ const len = arr.length;
27
+ keys.length = 0;
28
+ for (let i = 0; i < len; i += 2) {
29
+ arr[i] = arr[i].replace(/\$(\w+)/g, (_, key) => {
30
+ const value = values[key];
31
+ if (value === void 0) {
32
+ throw new Error(`Query variable \`${key}\` is not provided`);
33
+ }
34
+ keys.push(key);
35
+ valuesArray.push(value);
36
+ return `$${valuesArray.length}`;
37
+ });
42
38
  }
43
- foreignKey(fnOrTable, column, options = {}) {
44
- const cloned = Object.create(this);
45
- if (typeof fnOrTable === "string") {
46
- cloned.data = __spreadProps$k(__spreadValues$q({}, this.data), {
47
- foreignKey: __spreadValues$q({ table: fnOrTable, columns: [column] }, options)
48
- });
49
- } else {
50
- cloned.data = __spreadProps$k(__spreadValues$q({}, this.data), {
51
- foreignKey: __spreadValues$q({ fn: fnOrTable, columns: [column] }, options)
52
- });
39
+ if (keys.length > 0 && keys.length < Object.keys(values).length) {
40
+ for (const key in values) {
41
+ if (!keys.includes(key)) {
42
+ throw new Error(`Query variable \`${key}\` is unused`);
43
+ }
53
44
  }
54
- return cloned;
55
- }
56
- hidden() {
57
- return Object.assign(this, { isHidden: true });
58
- }
59
- nullable() {
60
- this.isNullable = true;
61
- return this;
62
- }
63
- encode(fn) {
64
- const self = this;
65
- self.encodeFn = fn;
66
- return self;
67
- }
68
- parse(fn) {
69
- this.parseFn = fn;
70
- this.parseItem = fn;
71
- return this;
72
- }
73
- as(column) {
74
- return addColumnData(this, "as", column);
75
- }
76
- toSQL() {
77
- return this.dataType;
78
45
  }
79
- default(value) {
80
- return addColumnData(this, "default", value);
81
- }
82
- index(options = {}) {
83
- return addColumnData(this, "index", options);
84
- }
85
- unique(options = {}) {
86
- return addColumnData(this, "index", __spreadProps$k(__spreadValues$q({}, options), { unique: true }));
87
- }
88
- comment(comment) {
89
- return addColumnData(this, "comment", comment);
90
- }
91
- validationDefault(value) {
92
- return addColumnData(this, "validationDefault", value);
93
- }
94
- compression(compression) {
95
- return addColumnData(this, "compression", compression);
96
- }
97
- collate(collate) {
98
- return addColumnData(this, "collate", collate);
99
- }
100
- modifyQuery(cb) {
101
- return addColumnData(this, "modifyQuery", cb);
102
- }
103
- transform(fn) {
104
- const cloned = Object.create(this);
105
- cloned.chain = [...this.chain, ["transform", fn]];
106
- return cloned;
107
- }
108
- to(fn, type) {
109
- const cloned = Object.create(type);
110
- cloned.chain = [...this.chain, ["to", fn, type], ...cloned.chain];
111
- return cloned;
112
- }
113
- refine(check) {
114
- const cloned = Object.create(this);
115
- cloned.chain = [...this.chain, ["refine", check]];
116
- return cloned;
117
- }
118
- superRefine(check) {
119
- const cloned = Object.create(this);
120
- cloned.chain = [...this.chain, ["superRefine", check]];
121
- return cloned;
122
- }
123
- }
124
-
125
- const singleQuoteRegex = /'/g;
126
- const doubleQuoteRegex = /"/g;
127
- const quoteValue$1 = (value) => {
128
- const type = typeof value;
129
- if (type === "number")
130
- return String(value);
131
- else if (type === "string")
132
- return `"${value.replace(doubleQuoteRegex, '\\"').replace(singleQuoteRegex, "''")}"`;
133
- else if (type === "boolean")
134
- return value ? "true" : "false";
135
- else if (value instanceof Date)
136
- return `"${value.toISOString()}"`;
137
- else if (Array.isArray(value))
138
- return quoteArray(value);
139
- else if (type === null || type === void 0)
140
- return "NULL";
141
- else
142
- return `"${JSON.stringify(value).replace(doubleQuoteRegex, '\\"').replace(singleQuoteRegex, "''")}"`;
46
+ return arr.join("'");
143
47
  };
144
- const quoteArray = (array) => `'{${array.map(quoteValue$1).join(",")}}'`;
145
- const quote = (value) => {
146
- const type = typeof value;
147
- if (type === "number")
148
- return `${value}`;
149
- else if (type === "string")
150
- return `'${value.replace(singleQuoteRegex, "''")}'`;
151
- else if (type === "boolean")
152
- return value ? "true" : "false";
153
- else if (value instanceof Date)
154
- return `'${value.toISOString()}'`;
155
- else if (Array.isArray(value))
156
- return quoteArray(value);
157
- else if (value === null || value === void 0)
158
- return "NULL";
159
- else
160
- return `'${JSON.stringify(value).replace(singleQuoteRegex, "''")}'`;
48
+ const getRawSql = (raw2) => {
49
+ return raw2.__raw;
50
+ };
51
+ const EMPTY_OBJECT = {};
52
+ const getQueryParsers = (q) => {
53
+ return q.query.parsers || q.columnsParsers;
161
54
  };
162
55
 
163
- const defaultsKey = Symbol("defaults");
164
- const queryTypeWithLimitOne = {
165
- one: true,
166
- oneOrThrow: true
56
+ const q = (sql) => `"${sql}"`;
57
+ const qc = (column, quotedAs) => quotedAs ? `${quotedAs}.${q(column)}` : column;
58
+ const quoteFullColumn = (fullColumn, quotedAs) => {
59
+ const index = fullColumn.indexOf(".");
60
+ if (index !== -1) {
61
+ return `${q(fullColumn.slice(0, index))}.${q(fullColumn.slice(index + 1))}`;
62
+ } else if (quotedAs) {
63
+ return `${quotedAs}.${q(fullColumn)}`;
64
+ } else {
65
+ return q(fullColumn);
66
+ }
67
+ };
68
+ const expressionToSql = (expr, values, quotedAs) => {
69
+ return typeof expr === "object" && isRaw(expr) ? getRaw(expr, values) : quoteFullColumn(expr, quotedAs);
70
+ };
71
+ const quoteSchemaAndTable = (schema, table) => {
72
+ return schema ? `${q(schema)}.${q(table)}` : q(table);
73
+ };
74
+ const addValue = (values, value) => {
75
+ values.push(value);
76
+ return `$${values.length}`;
167
77
  };
168
- const isQueryReturnsAll = (q) => !q.query.returnType || q.query.returnType === "all";
169
78
 
170
79
  const pushDistinctSql = (ctx, distinct, quotedAs) => {
171
80
  ctx.sql.push("DISTINCT");
@@ -225,24 +134,24 @@ const windowToSql = (window, values, quotedAs) => {
225
134
  }
226
135
  };
227
136
 
228
- const processJoinItem = (ctx, model, args, quotedAs) => {
137
+ const processJoinItem = (ctx, table, args, quotedAs) => {
229
138
  let target;
230
139
  let conditions;
231
140
  const [first] = args;
232
141
  if (typeof first === "string") {
233
- if (first in model.relations) {
142
+ if (first in table.relations) {
234
143
  const {
235
144
  key,
236
145
  query: toQuery,
237
146
  joinQuery
238
- } = model.relations[first];
239
- const jq = joinQuery(model, toQuery);
147
+ } = table.relations[first];
148
+ const jq = joinQuery(table, toQuery);
240
149
  const { query } = jq;
241
- const table = typeof query.from === "string" ? query.from : jq.table;
242
- target = quoteSchemaAndTable(query.schema, table);
150
+ const tableName = typeof query.from === "string" ? query.from : jq.table;
151
+ target = quoteSchemaAndTable(query.schema, tableName);
243
152
  const as = query.as || key;
244
153
  const joinAs = q(as);
245
- if (as !== table) {
154
+ if (as !== tableName) {
246
155
  target += ` AS ${joinAs}`;
247
156
  }
248
157
  const queryData = {
@@ -251,7 +160,7 @@ const processJoinItem = (ctx, model, args, quotedAs) => {
251
160
  };
252
161
  if (args[1]) {
253
162
  const arg = args[1](
254
- new ctx.onQueryBuilder(jq, jq.shape, model)
163
+ new ctx.onQueryBuilder(jq, jq.shape, table)
255
164
  ).query;
256
165
  if (arg.and)
257
166
  queryData.and.push(...arg.and);
@@ -261,7 +170,7 @@ const processJoinItem = (ctx, model, args, quotedAs) => {
261
170
  conditions = whereToSql(ctx, jq, queryData, joinAs);
262
171
  } else {
263
172
  target = q(first);
264
- conditions = processArgs(args, ctx, model, first, target, quotedAs);
173
+ conditions = processArgs(args, ctx, table, first, target, quotedAs);
265
174
  }
266
175
  } else {
267
176
  const query = first.query;
@@ -275,8 +184,8 @@ const processJoinItem = (ctx, model, args, quotedAs) => {
275
184
  target += ` AS ${quoted}`;
276
185
  }
277
186
  }
278
- conditions = processArgs(args, ctx, model, first, joinAs, quotedAs);
279
- const whereSql = whereToSql(ctx, model, query, joinAs);
187
+ conditions = processArgs(args, ctx, table, first, joinAs, quotedAs);
188
+ const whereSql = whereToSql(ctx, table, query, joinAs);
280
189
  if (whereSql) {
281
190
  if (conditions)
282
191
  conditions += ` AND ${whereSql}`;
@@ -286,21 +195,21 @@ const processJoinItem = (ctx, model, args, quotedAs) => {
286
195
  }
287
196
  return { target, conditions };
288
197
  };
289
- const processArgs = (args, ctx, model, first, joinAs, quotedAs) => {
198
+ const processArgs = (args, ctx, table, first, joinAs, quotedAs) => {
290
199
  var _a;
291
200
  if (args.length === 2) {
292
201
  const arg = args[1];
293
202
  if (typeof arg === "function") {
294
203
  let shape;
295
204
  if (typeof first === "string") {
296
- shape = (_a = model.query.withShapes) == null ? void 0 : _a[first];
205
+ shape = (_a = table.query.withShapes) == null ? void 0 : _a[first];
297
206
  if (!shape) {
298
207
  throw new Error("Cannot get shape of `with` statement");
299
208
  }
300
209
  } else {
301
210
  shape = first.shape;
302
211
  }
303
- const jq = arg(new ctx.onQueryBuilder(first, shape, model));
212
+ const jq = arg(new ctx.onQueryBuilder(first, shape, table));
304
213
  return whereToSql(ctx, jq, jq.query, joinAs);
305
214
  } else {
306
215
  return getObjectOrRawConditions(arg, ctx.values, quotedAs, joinAs);
@@ -335,11 +244,11 @@ const getObjectOrRawConditions = (data, values, quotedAs, joinAs) => {
335
244
  return pairs.join(", ");
336
245
  }
337
246
  };
338
- const pushJoinSql = (ctx, model, query, quotedAs) => {
247
+ const pushJoinSql = (ctx, table, query, quotedAs) => {
339
248
  query.join.forEach((item) => {
340
249
  const { target, conditions } = processJoinItem(
341
250
  ctx,
342
- model,
251
+ table,
343
252
  item.args,
344
253
  quotedAs
345
254
  );
@@ -349,41 +258,41 @@ const pushJoinSql = (ctx, model, query, quotedAs) => {
349
258
  });
350
259
  };
351
260
 
352
- const pushWhereStatementSql = (ctx, model, query, quotedAs) => {
353
- const res = whereToSql(ctx, model, query, quotedAs, false);
261
+ const pushWhereStatementSql = (ctx, table, query, quotedAs) => {
262
+ const res = whereToSql(ctx, table, query, quotedAs, false);
354
263
  if (res) {
355
264
  ctx.sql.push("WHERE", res);
356
265
  }
357
266
  };
358
- const pushWhereToSql = (sql, ctx, model, query, quotedAs, not) => {
359
- const res = whereToSql(ctx, model, query, quotedAs, not);
267
+ const pushWhereToSql = (sql, ctx, table, query, quotedAs, not) => {
268
+ const res = whereToSql(ctx, table, query, quotedAs, not);
360
269
  if (res) {
361
270
  sql.push(res);
362
271
  }
363
272
  };
364
- const whereToSql = (ctx, model, query, quotedAs, not) => {
273
+ const whereToSql = (ctx, table, query, quotedAs, not) => {
365
274
  if (query.or) {
366
275
  const ors = query.and ? [query.and, ...query.or] : query.or;
367
- return ors.map((and) => processAnds(and, ctx, model, quotedAs, not)).join(" OR ");
276
+ return ors.map((and) => processAnds(and, ctx, table, quotedAs, not)).join(" OR ");
368
277
  } else if (query.and) {
369
- return processAnds(query.and, ctx, model, quotedAs, not);
278
+ return processAnds(query.and, ctx, table, quotedAs, not);
370
279
  } else {
371
280
  return void 0;
372
281
  }
373
282
  };
374
- const processAnds = (and, ctx, model, quotedAs, not) => {
283
+ const processAnds = (and, ctx, table, quotedAs, not) => {
375
284
  const ands = [];
376
- and.forEach((data) => processWhere(ands, ctx, model, data, quotedAs, not));
285
+ and.forEach((data) => processWhere(ands, ctx, table, data, quotedAs, not));
377
286
  return ands.join(" AND ");
378
287
  };
379
- const processWhere = (ands, ctx, model, data, quotedAs, not) => {
288
+ const processWhere = (ands, ctx, table, data, quotedAs, not) => {
380
289
  const prefix = not ? "NOT " : "";
381
290
  if (typeof data === "function") {
382
- const qb = data(new ctx.whereQueryBuilder(model, model.shape));
291
+ const qb = data(new ctx.whereQueryBuilder(table, table.shape));
383
292
  pushWhereToSql(ands, ctx, qb, qb.query, quotedAs, not);
384
293
  return;
385
294
  }
386
- if ("prototype" in data || "__model" in data) {
295
+ if ("prototype" in data || "__table" in data) {
387
296
  const query = data;
388
297
  const sql = whereToSql(
389
298
  ctx,
@@ -404,15 +313,15 @@ const processWhere = (ands, ctx, model, data, quotedAs, not) => {
404
313
  const value = data[key];
405
314
  if (key === "AND") {
406
315
  const arr = toArray(value);
407
- ands.push(processAnds(arr, ctx, model, quotedAs, not));
316
+ ands.push(processAnds(arr, ctx, table, quotedAs, not));
408
317
  } else if (key === "OR") {
409
318
  const arr = value.map(toArray);
410
319
  ands.push(
411
- arr.map((and) => processAnds(and, ctx, model, quotedAs, not)).join(" OR ")
320
+ arr.map((and) => processAnds(and, ctx, table, quotedAs, not)).join(" OR ")
412
321
  );
413
322
  } else if (key === "NOT") {
414
323
  const arr = toArray(value);
415
- ands.push(processAnds(arr, ctx, model, quotedAs, !not));
324
+ ands.push(processAnds(arr, ctx, table, quotedAs, !not));
416
325
  } else if (key === "ON") {
417
326
  if (Array.isArray(value)) {
418
327
  const item = value;
@@ -421,7 +330,7 @@ const processWhere = (ands, ctx, model, data, quotedAs, not) => {
421
330
  const rightColumn = quoteFullColumn(
422
331
  item[2],
423
332
  getQueryAs({
424
- table: model.table,
333
+ table: table.table,
425
334
  query: { as: quotedAs }
426
335
  })
427
336
  );
@@ -454,7 +363,7 @@ const processWhere = (ands, ctx, model, data, quotedAs, not) => {
454
363
  joinItems.forEach((item) => {
455
364
  const { target, conditions } = processJoinItem(
456
365
  ctx,
457
- model,
366
+ table,
458
367
  item,
459
368
  quotedAs
460
369
  );
@@ -471,7 +380,7 @@ const processWhere = (ands, ctx, model, data, quotedAs, not) => {
471
380
  )}`
472
381
  );
473
382
  } else {
474
- const column = model.shape[key];
383
+ const column = table.shape[key];
475
384
  if (!column) {
476
385
  throw new Error(`Unknown column ${key} provided to condition`);
477
386
  }
@@ -519,29 +428,29 @@ const pushIn = (ands, prefix, quotedAs, values, arg) => {
519
428
  );
520
429
  };
521
430
 
522
- var __defProp$p = Object.defineProperty;
523
- var __defProps$j = Object.defineProperties;
524
- var __getOwnPropDescs$j = Object.getOwnPropertyDescriptors;
525
- var __getOwnPropSymbols$q = Object.getOwnPropertySymbols;
526
- var __hasOwnProp$q = Object.prototype.hasOwnProperty;
527
- var __propIsEnum$q = Object.prototype.propertyIsEnumerable;
528
- var __defNormalProp$p = (obj, key, value) => key in obj ? __defProp$p(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
529
- var __spreadValues$p = (a, b) => {
431
+ var __defProp$q = Object.defineProperty;
432
+ var __defProps$k = Object.defineProperties;
433
+ var __getOwnPropDescs$k = Object.getOwnPropertyDescriptors;
434
+ var __getOwnPropSymbols$r = Object.getOwnPropertySymbols;
435
+ var __hasOwnProp$r = Object.prototype.hasOwnProperty;
436
+ var __propIsEnum$r = Object.prototype.propertyIsEnumerable;
437
+ var __defNormalProp$q = (obj, key, value) => key in obj ? __defProp$q(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
438
+ var __spreadValues$q = (a, b) => {
530
439
  for (var prop in b || (b = {}))
531
- if (__hasOwnProp$q.call(b, prop))
532
- __defNormalProp$p(a, prop, b[prop]);
533
- if (__getOwnPropSymbols$q)
534
- for (var prop of __getOwnPropSymbols$q(b)) {
535
- if (__propIsEnum$q.call(b, prop))
536
- __defNormalProp$p(a, prop, b[prop]);
440
+ if (__hasOwnProp$r.call(b, prop))
441
+ __defNormalProp$q(a, prop, b[prop]);
442
+ if (__getOwnPropSymbols$r)
443
+ for (var prop of __getOwnPropSymbols$r(b)) {
444
+ if (__propIsEnum$r.call(b, prop))
445
+ __defNormalProp$q(a, prop, b[prop]);
537
446
  }
538
447
  return a;
539
448
  };
540
- var __spreadProps$j = (a, b) => __defProps$j(a, __getOwnPropDescs$j(b));
541
- const aggregateToSql = (ctx, model, item, quotedAs) => {
449
+ var __spreadProps$k = (a, b) => __defProps$k(a, __getOwnPropDescs$k(b));
450
+ const aggregateToSql = (ctx, table, item, quotedAs) => {
542
451
  var _a;
543
452
  const sql = [`${item.function}(`];
544
- ctx = __spreadProps$j(__spreadValues$p({}, ctx), { sql });
453
+ ctx = __spreadProps$k(__spreadValues$q({}, ctx), { sql });
545
454
  const options = item.options || EMPTY_OBJECT;
546
455
  if (options.distinct && !options.withinGroup)
547
456
  sql.push("DISTINCT ");
@@ -581,7 +490,7 @@ const aggregateToSql = (ctx, model, item, quotedAs) => {
581
490
  if (options.filter || options.filterOr) {
582
491
  const whereSql = whereToSql(
583
492
  ctx,
584
- model,
493
+ table,
585
494
  {
586
495
  and: options.filter ? [options.filter] : void 0,
587
496
  or: (_a = options.filterOr) == null ? void 0 : _a.map((item2) => [item2])
@@ -638,6 +547,44 @@ class UnhandledTypeError extends PormInternalError {
638
547
  }
639
548
  }
640
549
 
550
+ const singleQuoteRegex = /'/g;
551
+ const doubleQuoteRegex = /"/g;
552
+ const quoteValue$1 = (value) => {
553
+ const type = typeof value;
554
+ if (type === "number")
555
+ return String(value);
556
+ else if (type === "string")
557
+ return `"${value.replace(doubleQuoteRegex, '\\"').replace(singleQuoteRegex, "''")}"`;
558
+ else if (type === "boolean")
559
+ return value ? "true" : "false";
560
+ else if (value instanceof Date)
561
+ return `"${value.toISOString()}"`;
562
+ else if (Array.isArray(value))
563
+ return quoteArray(value);
564
+ else if (type === null || type === void 0)
565
+ return "NULL";
566
+ else
567
+ return `"${JSON.stringify(value).replace(doubleQuoteRegex, '\\"').replace(singleQuoteRegex, "''")}"`;
568
+ };
569
+ const quoteArray = (array) => `'{${array.map(quoteValue$1).join(",")}}'`;
570
+ const quote = (value) => {
571
+ const type = typeof value;
572
+ if (type === "number")
573
+ return `${value}`;
574
+ else if (type === "string")
575
+ return `'${value.replace(singleQuoteRegex, "''")}'`;
576
+ else if (type === "boolean")
577
+ return value ? "true" : "false";
578
+ else if (value instanceof Date)
579
+ return `'${value.toISOString()}'`;
580
+ else if (Array.isArray(value))
581
+ return quoteArray(value);
582
+ else if (value === null || value === void 0)
583
+ return "NULL";
584
+ else
585
+ return `'${JSON.stringify(value).replace(singleQuoteRegex, "''")}'`;
586
+ };
587
+
641
588
  const relationQueryKey = Symbol("relationQuery");
642
589
  const isRequiredRelationKey = Symbol("isRequiredRelation");
643
590
 
@@ -677,10 +624,10 @@ const jsonToSql = (item, values, quotedAs) => {
677
624
  }
678
625
  return "";
679
626
  };
680
- const pushSelectSql = (ctx, model, query, quotedAs) => {
681
- ctx.sql.push(selectToSql(ctx, model, query, quotedAs));
627
+ const pushSelectSql = (ctx, table, query, quotedAs) => {
628
+ ctx.sql.push(selectToSql(ctx, table, query, quotedAs));
682
629
  };
683
- const selectToSql = (ctx, model, query, quotedAs) => {
630
+ const selectToSql = (ctx, table, query, quotedAs) => {
684
631
  var _a;
685
632
  if (query.select) {
686
633
  const list = [];
@@ -717,13 +664,13 @@ const selectToSql = (ctx, model, query, quotedAs) => {
717
664
  list.push(
718
665
  `${item.function}(${selectToSql(
719
666
  ctx,
720
- model,
667
+ table,
721
668
  { select: item.arguments },
722
669
  quotedAs
723
670
  )})${item.as ? ` AS ${q(item.as)}` : ""}`
724
671
  );
725
672
  } else {
726
- list.push(aggregateToSql(ctx, model, item, quotedAs));
673
+ list.push(aggregateToSql(ctx, table, item, quotedAs));
727
674
  }
728
675
  }
729
676
  });
@@ -752,7 +699,7 @@ const pushSubQuerySql = (query, as, values, list) => {
752
699
  }
753
700
  select.length = 0;
754
701
  select[0] = { selectAs: { c: first } };
755
- query = query._wrap(query.__model.clone());
702
+ query = query._wrap(query.__table.clone());
756
703
  query._getOptional(raw(`COALESCE(json_agg("c"), '[]')`));
757
704
  break;
758
705
  }
@@ -781,12 +728,12 @@ const aggregateOptionNames = [
781
728
  "filterOr",
782
729
  "withinGroup"
783
730
  ];
784
- const pushHavingSql = (ctx, model, query, quotedAs) => {
785
- const conditions = havingToSql(ctx, model, query, quotedAs);
731
+ const pushHavingSql = (ctx, table, query, quotedAs) => {
732
+ const conditions = havingToSql(ctx, table, query, quotedAs);
786
733
  if (conditions.length)
787
734
  ctx.sql.push("HAVING", conditions);
788
735
  };
789
- const havingToSql = (ctx, model, query, quotedAs) => {
736
+ const havingToSql = (ctx, table, query, quotedAs) => {
790
737
  const or = query.having && query.havingOr ? [query.having, ...query.havingOr] : query.having ? [query.having] : query.havingOr;
791
738
  if (!(or == null ? void 0 : or.length))
792
739
  return "";
@@ -794,7 +741,7 @@ const havingToSql = (ctx, model, query, quotedAs) => {
794
741
  or.forEach((and) => {
795
742
  const ands = [];
796
743
  and.forEach((item) => {
797
- if ("prototype" in item || "__model" in item) {
744
+ if ("prototype" in item || "__table" in item) {
798
745
  const query2 = item;
799
746
  const sql = havingToSql(
800
747
  ctx,
@@ -820,7 +767,7 @@ const havingToSql = (ctx, model, query, quotedAs) => {
820
767
  if (!aggregateOptionNames.includes(
821
768
  op
822
769
  )) {
823
- const operator = model.shape[column].operators[op];
770
+ const operator = table.shape[column].operators[op];
824
771
  if (!operator) {
825
772
  throw new Error(
826
773
  `Unknown operator ${op} provided to condition`
@@ -828,7 +775,7 @@ const havingToSql = (ctx, model, query, quotedAs) => {
828
775
  }
829
776
  const expression = aggregateToSql(
830
777
  ctx,
831
- model,
778
+ table,
832
779
  {
833
780
  function: key,
834
781
  arg: column,
@@ -849,7 +796,7 @@ const havingToSql = (ctx, model, query, quotedAs) => {
849
796
  ands.push(
850
797
  `${aggregateToSql(
851
798
  ctx,
852
- model,
799
+ table,
853
800
  {
854
801
  function: key,
855
802
  arg: column,
@@ -915,17 +862,17 @@ const queryKeysOfNotSimpleQuery = [
915
862
  "for"
916
863
  ];
917
864
 
918
- const pushFromAndAs = (ctx, model, query, quotedAs) => {
865
+ const pushFromAndAs = (ctx, table, query, quotedAs) => {
919
866
  ctx.sql.push("FROM");
920
867
  if (query.fromOnly)
921
868
  ctx.sql.push("ONLY");
922
- const from = getFrom(model, query, ctx.values);
869
+ const from = getFrom(table, query, ctx.values);
923
870
  ctx.sql.push(from);
924
871
  if (query.as && quotedAs && quotedAs !== from) {
925
872
  ctx.sql.push("AS", quotedAs);
926
873
  }
927
874
  };
928
- const getFrom = (model, query, values) => {
875
+ const getFrom = (table, query, values) => {
929
876
  if (query.from) {
930
877
  if (typeof query.from === "object") {
931
878
  if (isRaw(query.from)) {
@@ -944,7 +891,7 @@ const getFrom = (model, query, values) => {
944
891
  }
945
892
  return quoteSchemaAndTable(query.schema, query.from);
946
893
  }
947
- return quoteSchemaAndTable(query.schema, model.table);
894
+ return quoteSchemaAndTable(query.schema, table.table);
948
895
  };
949
896
 
950
897
  const pushQueryArray = (q, key, value) => {
@@ -974,7 +921,7 @@ const setQueryObjectValue = (q, object, key, value) => {
974
921
  return q;
975
922
  };
976
923
 
977
- const pushInsertSql = (ctx, model, query, quotedAs) => {
924
+ const pushInsertSql = (ctx, table, query, quotedAs) => {
978
925
  const quotedColumns = query.columns.map(q);
979
926
  ctx.sql.push(`INSERT INTO ${quotedAs}(${quotedColumns.join(", ")})`);
980
927
  if (query.fromQuery) {
@@ -1029,22 +976,22 @@ const pushInsertSql = (ctx, model, query, quotedAs) => {
1029
976
  ctx.sql.push("DO UPDATE SET", set);
1030
977
  }
1031
978
  }
1032
- pushWhereStatementSql(ctx, model, query, quotedAs);
1033
- pushReturningSql(ctx, model, query, quotedAs);
979
+ pushWhereStatementSql(ctx, table, query, quotedAs);
980
+ pushReturningSql(ctx, table, query, quotedAs);
1034
981
  };
1035
982
  const encodeRow = (ctx, row) => {
1036
983
  return row.map(
1037
984
  (value) => value === void 0 ? "DEFAULT" : addValue(ctx.values, value)
1038
985
  ).join(", ");
1039
986
  };
1040
- const pushReturningSql = (ctx, model, query, quotedAs) => {
987
+ const pushReturningSql = (ctx, table, query, quotedAs) => {
1041
988
  if (query.select) {
1042
- ctx.sql.push(`RETURNING ${selectToSql(ctx, model, query, quotedAs)}`);
989
+ ctx.sql.push(`RETURNING ${selectToSql(ctx, table, query, quotedAs)}`);
1043
990
  }
1044
991
  };
1045
992
 
1046
- const pushUpdateSql = (ctx, model, query, quotedAs) => {
1047
- const quotedTable = quoteSchemaAndTable(query.schema, model.table);
993
+ const pushUpdateSql = (ctx, table, query, quotedAs) => {
994
+ const quotedTable = quoteSchemaAndTable(query.schema, table.table);
1048
995
  ctx.sql.push(`UPDATE ${quotedTable}`);
1049
996
  if (quotedTable !== quotedAs) {
1050
997
  ctx.sql.push(`AS ${quotedAs}`);
@@ -1053,8 +1000,8 @@ const pushUpdateSql = (ctx, model, query, quotedAs) => {
1053
1000
  const set = [];
1054
1001
  processData(ctx, set, query.updateData);
1055
1002
  ctx.sql.push(set.join(", "));
1056
- pushWhereStatementSql(ctx, model, query, quotedAs);
1057
- pushReturningSql(ctx, model, query, quotedAs);
1003
+ pushWhereStatementSql(ctx, table, query, quotedAs);
1004
+ pushReturningSql(ctx, table, query, quotedAs);
1058
1005
  };
1059
1006
  const processData = (ctx, set, data) => {
1060
1007
  let append;
@@ -1091,9 +1038,9 @@ const processValue = (values, key, value) => {
1091
1038
  return addValue(values, value);
1092
1039
  };
1093
1040
 
1094
- const pushDeleteSql = (ctx, model, query, quotedAs) => {
1041
+ const pushDeleteSql = (ctx, table, query, quotedAs) => {
1095
1042
  var _a, _b, _c;
1096
- const from = q(model.table);
1043
+ const from = q(table.table);
1097
1044
  ctx.sql.push(`DELETE FROM ${from}`);
1098
1045
  if (from !== quotedAs) {
1099
1046
  ctx.sql.push(`AS ${quotedAs}`);
@@ -1101,12 +1048,12 @@ const pushDeleteSql = (ctx, model, query, quotedAs) => {
1101
1048
  let conditions;
1102
1049
  if ((_a = query.join) == null ? void 0 : _a.length) {
1103
1050
  const items = query.join.map(
1104
- (item) => processJoinItem(ctx, model, item.args, quotedAs)
1051
+ (item) => processJoinItem(ctx, table, item.args, quotedAs)
1105
1052
  );
1106
1053
  ctx.sql.push(`USING ${items.map((item) => item.target).join(", ")}`);
1107
1054
  conditions = items.map((item) => item.conditions).filter(Boolean).join(" AND ");
1108
1055
  }
1109
- pushWhereStatementSql(ctx, model, query, quotedAs);
1056
+ pushWhereStatementSql(ctx, table, query, quotedAs);
1110
1057
  if (conditions == null ? void 0 : conditions.length) {
1111
1058
  if (((_b = query.and) == null ? void 0 : _b.length) || ((_c = query.or) == null ? void 0 : _c.length)) {
1112
1059
  ctx.sql.push("AND", conditions);
@@ -1114,7 +1061,7 @@ const pushDeleteSql = (ctx, model, query, quotedAs) => {
1114
1061
  ctx.sql.push("WHERE", conditions);
1115
1062
  }
1116
1063
  }
1117
- pushReturningSql(ctx, model, query, quotedAs);
1064
+ pushReturningSql(ctx, table, query, quotedAs);
1118
1065
  };
1119
1066
 
1120
1067
  const pushTruncateSql = (ctx, table, query) => {
@@ -1137,13 +1084,13 @@ const pushColumnInfoSql = (ctx, table, query) => {
1137
1084
  }
1138
1085
  };
1139
1086
 
1140
- const pushCopySql = (ctx, model, query, quotedAs) => {
1087
+ const pushCopySql = (ctx, table, query, quotedAs) => {
1141
1088
  const { sql } = ctx;
1142
1089
  const { copy } = query;
1143
1090
  const columns = copy.columns ? `(${copy.columns.map(q).join(", ")})` : "";
1144
1091
  const target = "from" in copy ? copy.from : copy.to;
1145
1092
  sql.push(
1146
- `COPY ${q(model.table)}${columns} ${"from" in copy ? "FROM" : "TO"} ${typeof target === "string" ? quote(target) : `PROGRAM ${quote(target.program)}`}`
1093
+ `COPY ${q(table.table)}${columns} ${"from" in copy ? "FROM" : "TO"} ${typeof target === "string" ? quote(target) : `PROGRAM ${quote(target.program)}`}`
1147
1094
  );
1148
1095
  if (Object.keys(copy).length > (copy.columns ? 2 : 1)) {
1149
1096
  const options = [];
@@ -1173,19 +1120,19 @@ const pushCopySql = (ctx, model, query, quotedAs) => {
1173
1120
  options.push(`ENCODING ${quote(copy.encoding)}`);
1174
1121
  sql.push(`WITH (${options.join(", ")})`);
1175
1122
  }
1176
- pushWhereStatementSql(ctx, model, query, quotedAs);
1123
+ pushWhereStatementSql(ctx, table, query, quotedAs);
1177
1124
  };
1178
1125
 
1179
1126
  const toSqlCacheKey = Symbol("toSqlCache");
1180
- const toSql = (model, options) => {
1181
- return !(options == null ? void 0 : options.clearCache) && model.query[toSqlCacheKey] || (model.query[toSqlCacheKey] = makeSql(model, options));
1127
+ const toSql = (table, options) => {
1128
+ return !(options == null ? void 0 : options.clearCache) && table.query[toSqlCacheKey] || (table.query[toSqlCacheKey] = makeSql(table, options));
1182
1129
  };
1183
- const makeSql = (model, { values = [] } = {}) => {
1184
- const query = model.query;
1130
+ const makeSql = (table, { values = [] } = {}) => {
1131
+ const query = table.query;
1185
1132
  const sql = [];
1186
1133
  const ctx = {
1187
- whereQueryBuilder: model.whereQueryBuilder,
1188
- onQueryBuilder: model.onQueryBuilder,
1134
+ whereQueryBuilder: table.whereQueryBuilder,
1135
+ onQueryBuilder: table.onQueryBuilder,
1189
1136
  sql,
1190
1137
  values
1191
1138
  };
@@ -1194,56 +1141,56 @@ const makeSql = (model, { values = [] } = {}) => {
1194
1141
  }
1195
1142
  if (query.type) {
1196
1143
  if (query.type === "truncate") {
1197
- if (!model.table)
1144
+ if (!table.table)
1198
1145
  throw new Error("Table is missing for truncate");
1199
- pushTruncateSql(ctx, model.table, query);
1146
+ pushTruncateSql(ctx, table.table, query);
1200
1147
  return { text: sql.join(" "), values };
1201
1148
  }
1202
1149
  if (query.type === "columnInfo") {
1203
- if (!model.table)
1150
+ if (!table.table)
1204
1151
  throw new Error("Table is missing for truncate");
1205
- pushColumnInfoSql(ctx, model.table, query);
1152
+ pushColumnInfoSql(ctx, table.table, query);
1206
1153
  return { text: sql.join(" "), values };
1207
1154
  }
1208
- if (!model.table)
1155
+ if (!table.table)
1209
1156
  throw new Error(`Table is missing for ${query.type}`);
1210
- const quotedAs2 = q(query.as || model.table);
1157
+ const quotedAs2 = q(query.as || table.table);
1211
1158
  if (query.type === "insert") {
1212
- pushInsertSql(ctx, model, query, q(model.table));
1159
+ pushInsertSql(ctx, table, query, q(table.table));
1213
1160
  return { text: sql.join(" "), values };
1214
1161
  }
1215
1162
  if (query.type === "update") {
1216
- pushUpdateSql(ctx, model, query, quotedAs2);
1163
+ pushUpdateSql(ctx, table, query, quotedAs2);
1217
1164
  return { text: sql.join(" "), values };
1218
1165
  }
1219
1166
  if (query.type === "delete") {
1220
- pushDeleteSql(ctx, model, query, quotedAs2);
1167
+ pushDeleteSql(ctx, table, query, quotedAs2);
1221
1168
  return { text: sql.join(" "), values };
1222
1169
  }
1223
1170
  if (query.type === "copy") {
1224
- pushCopySql(ctx, model, query, quotedAs2);
1171
+ pushCopySql(ctx, table, query, quotedAs2);
1225
1172
  return { text: sql.join(" "), values };
1226
1173
  }
1227
1174
  }
1228
- const quotedAs = model.table && q(query.as || model.table);
1175
+ const quotedAs = table.table && q(query.as || table.table);
1229
1176
  sql.push("SELECT");
1230
1177
  if (query.distinct) {
1231
1178
  pushDistinctSql(ctx, query.distinct, quotedAs);
1232
1179
  }
1233
- pushSelectSql(ctx, model, query, quotedAs);
1234
- if (model.table || query.from) {
1235
- pushFromAndAs(ctx, model, query, quotedAs);
1180
+ pushSelectSql(ctx, table, query, quotedAs);
1181
+ if (table.table || query.from) {
1182
+ pushFromAndAs(ctx, table, query, quotedAs);
1236
1183
  }
1237
1184
  if (query.join) {
1238
1185
  pushJoinSql(
1239
1186
  ctx,
1240
- model,
1187
+ table,
1241
1188
  query,
1242
1189
  quotedAs
1243
1190
  );
1244
1191
  }
1245
1192
  if (query.and || query.or) {
1246
- pushWhereStatementSql(ctx, model, query, quotedAs);
1193
+ pushWhereStatementSql(ctx, table, query, quotedAs);
1247
1194
  }
1248
1195
  if (query.group) {
1249
1196
  const group = query.group.map(
@@ -1252,7 +1199,7 @@ const makeSql = (model, { values = [] } = {}) => {
1252
1199
  sql.push(`GROUP BY ${group.join(", ")}`);
1253
1200
  }
1254
1201
  if (query.having || query.havingOr) {
1255
- pushHavingSql(ctx, model, query, quotedAs);
1202
+ pushHavingSql(ctx, table, query, quotedAs);
1256
1203
  }
1257
1204
  if (query.window) {
1258
1205
  const window = [];
@@ -1359,19 +1306,19 @@ const cloneQueryArrays = (q) => {
1359
1306
  }
1360
1307
  };
1361
1308
 
1362
- var __defProp$o = Object.defineProperty;
1363
- var __getOwnPropSymbols$p = Object.getOwnPropertySymbols;
1364
- var __hasOwnProp$p = Object.prototype.hasOwnProperty;
1365
- var __propIsEnum$p = Object.prototype.propertyIsEnumerable;
1366
- var __defNormalProp$o = (obj, key, value) => key in obj ? __defProp$o(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1367
- var __spreadValues$o = (a, b) => {
1309
+ var __defProp$p = Object.defineProperty;
1310
+ var __getOwnPropSymbols$q = Object.getOwnPropertySymbols;
1311
+ var __hasOwnProp$q = Object.prototype.hasOwnProperty;
1312
+ var __propIsEnum$q = Object.prototype.propertyIsEnumerable;
1313
+ var __defNormalProp$p = (obj, key, value) => key in obj ? __defProp$p(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1314
+ var __spreadValues$p = (a, b) => {
1368
1315
  for (var prop in b || (b = {}))
1369
- if (__hasOwnProp$p.call(b, prop))
1370
- __defNormalProp$o(a, prop, b[prop]);
1371
- if (__getOwnPropSymbols$p)
1372
- for (var prop of __getOwnPropSymbols$p(b)) {
1373
- if (__propIsEnum$p.call(b, prop))
1374
- __defNormalProp$o(a, prop, b[prop]);
1316
+ if (__hasOwnProp$q.call(b, prop))
1317
+ __defNormalProp$p(a, prop, b[prop]);
1318
+ if (__getOwnPropSymbols$q)
1319
+ for (var prop of __getOwnPropSymbols$q(b)) {
1320
+ if (__propIsEnum$q.call(b, prop))
1321
+ __defNormalProp$p(a, prop, b[prop]);
1375
1322
  }
1376
1323
  return a;
1377
1324
  };
@@ -1390,7 +1337,7 @@ const joinTruthy = (...strings) => {
1390
1337
  return strings.filter((string) => string).join("");
1391
1338
  };
1392
1339
  const getClonedQueryData = (query) => {
1393
- const cloned = __spreadValues$o({}, query);
1340
+ const cloned = __spreadValues$p({}, query);
1394
1341
  delete cloned[toSqlCacheKey];
1395
1342
  cloneQueryArrays(cloned);
1396
1343
  return cloned;
@@ -1418,72 +1365,251 @@ const pushOrNewArray = (arr, value) => {
1418
1365
  } else {
1419
1366
  return [value];
1420
1367
  }
1421
- };
1422
-
1423
- const raw = (sql, values) => ({
1424
- __raw: sql,
1425
- __values: values
1426
- });
1427
- const isRaw = (obj) => "__raw" in obj;
1428
- const keys = [];
1429
- const getRaw = (raw2, valuesArray) => {
1430
- if (raw2.__values === false) {
1431
- return raw2.__raw;
1368
+ };
1369
+ const singleQuote = (s) => `'${s.replaceAll("\\", "\\\\").replaceAll("'", "\\'")}'`;
1370
+
1371
+ var __defProp$o = Object.defineProperty;
1372
+ var __defProps$j = Object.defineProperties;
1373
+ var __getOwnPropDescs$j = Object.getOwnPropertyDescriptors;
1374
+ var __getOwnPropSymbols$p = Object.getOwnPropertySymbols;
1375
+ var __hasOwnProp$p = Object.prototype.hasOwnProperty;
1376
+ var __propIsEnum$p = Object.prototype.propertyIsEnumerable;
1377
+ var __defNormalProp$o = (obj, key, value) => key in obj ? __defProp$o(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1378
+ var __spreadValues$o = (a, b) => {
1379
+ for (var prop in b || (b = {}))
1380
+ if (__hasOwnProp$p.call(b, prop))
1381
+ __defNormalProp$o(a, prop, b[prop]);
1382
+ if (__getOwnPropSymbols$p)
1383
+ for (var prop of __getOwnPropSymbols$p(b)) {
1384
+ if (__propIsEnum$p.call(b, prop))
1385
+ __defNormalProp$o(a, prop, b[prop]);
1386
+ }
1387
+ return a;
1388
+ };
1389
+ var __spreadProps$j = (a, b) => __defProps$j(a, __getOwnPropDescs$j(b));
1390
+ const addColumnData = (q, key, value) => {
1391
+ const cloned = Object.create(q);
1392
+ cloned.data = __spreadProps$j(__spreadValues$o({}, q.data), { [key]: value });
1393
+ return cloned;
1394
+ };
1395
+ const columnChainToCode = (chain, t, code, append) => {
1396
+ const result = toArray(code);
1397
+ if (typeof append === "string") {
1398
+ if (append) {
1399
+ if (result.length === 1 && typeof result[0] === "string") {
1400
+ result[0] += append;
1401
+ } else {
1402
+ result.push(append);
1403
+ }
1404
+ }
1405
+ } else {
1406
+ if (append.length)
1407
+ result.push(...append);
1408
+ }
1409
+ for (const item of chain) {
1410
+ if (item[0] === "transform") {
1411
+ result.push(`.transform(${item[1].toString()})`);
1412
+ } else if (item[0] === "to") {
1413
+ const type = toArray(item[2].toCode(t));
1414
+ result.push(`.to(${item[1].toString()}, `, ...type, ")");
1415
+ } else if (item[0] === "refine") {
1416
+ result.push(`.refine(${item[1].toString()})`);
1417
+ } else if (item[0] === "superRefine") {
1418
+ result.push(`.superRefine(${item[1].toString()})`);
1419
+ }
1420
+ }
1421
+ return result.length === 1 && typeof result[0] === "string" ? result[0] : result;
1422
+ };
1423
+ const columnCode = (type, t, code) => {
1424
+ const append = [];
1425
+ const { foreignKey, index, validationDefault } = type.data;
1426
+ if (type.isPrimaryKey)
1427
+ append.push(".primaryKey()");
1428
+ if (foreignKey) {
1429
+ append.push(`.foreignKey(`);
1430
+ if ("fn" in foreignKey) {
1431
+ append.push(foreignKey.fn.toString());
1432
+ } else {
1433
+ append.push(singleQuote(foreignKey.table));
1434
+ }
1435
+ append.push(`, ${singleQuote(foreignKey.columns[0])}`);
1436
+ const hasOptions = foreignKey.name || foreignKey.match || foreignKey.onUpdate || foreignKey.onDelete;
1437
+ if (hasOptions) {
1438
+ const arr = [];
1439
+ if (foreignKey.name)
1440
+ arr.push(`name: ${singleQuote(foreignKey.name)},`);
1441
+ if (foreignKey.match)
1442
+ arr.push(`match: ${singleQuote(foreignKey.match)},`);
1443
+ if (foreignKey.onUpdate)
1444
+ arr.push(`onUpdate: ${singleQuote(foreignKey.onUpdate)},`);
1445
+ if (foreignKey.onDelete)
1446
+ arr.push(`onDelete: ${singleQuote(foreignKey.onDelete)},`);
1447
+ append.push(", {", arr, "}");
1448
+ }
1449
+ append.push(")");
1450
+ }
1451
+ if (type.isHidden)
1452
+ append.push(".hidden()");
1453
+ if (type.isNullable)
1454
+ append.push(".nullable()");
1455
+ if ("isNonEmpty" in type.data)
1456
+ append.push(".nonEmpty()");
1457
+ if (type.encodeFn)
1458
+ append.push(`.encode(${type.encodeFn.toString()})`);
1459
+ if (type.parseFn && !("hideFromCode" in type.parseFn))
1460
+ append.push(`.parse(${type.parseFn.toString()})`);
1461
+ if (type.data.as)
1462
+ append.push(`.as(${type.data.as.toCode(t)})`);
1463
+ if (type.data.default)
1464
+ append.push(`.default(${JSON.stringify(type.data.default)})`);
1465
+ if (index) {
1466
+ append.push(`.${index.unique ? "unique" : "index"}(`);
1467
+ for (const key in index) {
1468
+ if (key === "unique")
1469
+ continue;
1470
+ const arr = [];
1471
+ if (index.expression)
1472
+ arr.push(
1473
+ `expression: ${typeof index.expression === "string" ? singleQuote(index.expression) : index.expression},`
1474
+ );
1475
+ if (index.collate)
1476
+ arr.push(`collate: ${singleQuote(index.collate)},`);
1477
+ if (index.operator)
1478
+ arr.push(`operator: ${singleQuote(index.operator)},`);
1479
+ if (index.order)
1480
+ arr.push(`order: ${singleQuote(index.order)},`);
1481
+ if (index.name)
1482
+ arr.push(`name: ${singleQuote(index.name)},`);
1483
+ if (index.unique)
1484
+ arr.push(`unique: true,`);
1485
+ if (index.using)
1486
+ arr.push(`using: ${singleQuote(index.using)},`);
1487
+ if (index.include)
1488
+ arr.push(
1489
+ `include: ${typeof index.include === "string" ? singleQuote(index.include) : `[${index.include.map(singleQuote).join(", ")}]`},`
1490
+ );
1491
+ if (index.with)
1492
+ arr.push(`with: ${singleQuote(index.with)},`);
1493
+ if (index.tablespace)
1494
+ arr.push(`tablespace: ${singleQuote(index.tablespace)},`);
1495
+ if (index.where)
1496
+ arr.push(`where: ${singleQuote(index.where)},`);
1497
+ append.push("{", arr, "}");
1498
+ break;
1499
+ }
1500
+ append.push(")");
1501
+ }
1502
+ if (type.data.comment)
1503
+ append.push(`.comment(${singleQuote(type.data.comment)})`);
1504
+ if (validationDefault) {
1505
+ append.push(
1506
+ `.validationDefault(${typeof validationDefault === "function" ? validationDefault.toString() : typeof validationDefault === "string" ? singleQuote(validationDefault) : JSON.stringify(validationDefault)})`
1507
+ );
1508
+ }
1509
+ if (type.data.compression)
1510
+ append.push(`.compression(${singleQuote(type.data.compression)})`);
1511
+ if (type.data.collate)
1512
+ append.push(`.collate(${singleQuote(type.data.collate)})`);
1513
+ if (type.data.modifyQuery)
1514
+ append.push(`.modifyQuery(${type.data.modifyQuery.toString()})`);
1515
+ return columnChainToCode(type.chain, t, code, append);
1516
+ };
1517
+ class ColumnType {
1518
+ constructor() {
1519
+ this.data = {};
1520
+ this.isPrimaryKey = false;
1521
+ this.isHidden = false;
1522
+ this.isNullable = false;
1523
+ this.hasDefault = false;
1524
+ this.chain = [];
1525
+ }
1526
+ primaryKey() {
1527
+ const cloned = Object.create(this);
1528
+ return Object.assign(cloned, { isPrimaryKey: true });
1529
+ }
1530
+ foreignKey(fnOrTable, column, options = {}) {
1531
+ const cloned = Object.create(this);
1532
+ if (typeof fnOrTable === "string") {
1533
+ cloned.data = __spreadProps$j(__spreadValues$o({}, this.data), {
1534
+ foreignKey: __spreadValues$o({ table: fnOrTable, columns: [column] }, options)
1535
+ });
1536
+ } else {
1537
+ cloned.data = __spreadProps$j(__spreadValues$o({}, this.data), {
1538
+ foreignKey: __spreadValues$o({ fn: fnOrTable, columns: [column] }, options)
1539
+ });
1540
+ }
1541
+ return cloned;
1542
+ }
1543
+ hidden() {
1544
+ return Object.assign(Object.create(this), { isHidden: true });
1432
1545
  }
1433
- const arr = raw2.__raw.split("'");
1434
- const values = raw2.__values || emptyObject;
1435
- const len = arr.length;
1436
- keys.length = 0;
1437
- for (let i = 0; i < len; i += 2) {
1438
- arr[i] = arr[i].replace(/\$(\w+)/g, (_, key) => {
1439
- const value = values[key];
1440
- if (value === void 0) {
1441
- throw new Error(`Query variable \`${key}\` is not provided`);
1442
- }
1443
- keys.push(key);
1444
- valuesArray.push(value);
1445
- return `$${valuesArray.length}`;
1546
+ nullable() {
1547
+ return Object.assign(Object.create(this), {
1548
+ isNullable: true
1446
1549
  });
1447
1550
  }
1448
- if (keys.length > 0 && keys.length < Object.keys(values).length) {
1449
- for (const key in values) {
1450
- if (!keys.includes(key)) {
1451
- throw new Error(`Query variable \`${key}\` is unused`);
1452
- }
1453
- }
1551
+ encode(fn) {
1552
+ return Object.assign(Object.create(this), {
1553
+ encodeFn: fn
1554
+ });
1454
1555
  }
1455
- return arr.join("'");
1456
- };
1457
- const getRawSql = (raw2) => {
1458
- return raw2.__raw;
1459
- };
1460
- const EMPTY_OBJECT = {};
1461
- const getQueryParsers = (q) => {
1462
- return q.query.parsers || q.columnsParsers;
1463
- };
1464
-
1465
- const q = (sql) => `"${sql}"`;
1466
- const qc = (column, quotedAs) => quotedAs ? `${quotedAs}.${q(column)}` : column;
1467
- const quoteFullColumn = (fullColumn, quotedAs) => {
1468
- const index = fullColumn.indexOf(".");
1469
- if (index !== -1) {
1470
- return `${q(fullColumn.slice(0, index))}.${q(fullColumn.slice(index + 1))}`;
1471
- } else if (quotedAs) {
1472
- return `${quotedAs}.${q(fullColumn)}`;
1473
- } else {
1474
- return q(fullColumn);
1556
+ parse(fn) {
1557
+ return Object.assign(Object.create(this), {
1558
+ parseFn: fn,
1559
+ parseItem: fn
1560
+ });
1475
1561
  }
1476
- };
1477
- const expressionToSql = (expr, values, quotedAs) => {
1478
- return typeof expr === "object" && isRaw(expr) ? getRaw(expr, values) : quoteFullColumn(expr, quotedAs);
1479
- };
1480
- const quoteSchemaAndTable = (schema, table) => {
1481
- return schema ? `${q(schema)}.${q(table)}` : q(table);
1482
- };
1483
- const addValue = (values, value) => {
1484
- values.push(value);
1485
- return `$${values.length}`;
1486
- };
1562
+ as(column) {
1563
+ return addColumnData(this, "as", column);
1564
+ }
1565
+ toSQL() {
1566
+ return this.dataType;
1567
+ }
1568
+ default(value) {
1569
+ return addColumnData(this, "default", value);
1570
+ }
1571
+ index(options = {}) {
1572
+ return addColumnData(this, "index", options);
1573
+ }
1574
+ unique(options = {}) {
1575
+ return addColumnData(this, "index", __spreadProps$j(__spreadValues$o({}, options), { unique: true }));
1576
+ }
1577
+ comment(comment) {
1578
+ return addColumnData(this, "comment", comment);
1579
+ }
1580
+ validationDefault(value) {
1581
+ return addColumnData(this, "validationDefault", value);
1582
+ }
1583
+ compression(compression) {
1584
+ return addColumnData(this, "compression", compression);
1585
+ }
1586
+ collate(collate) {
1587
+ return addColumnData(this, "collate", collate);
1588
+ }
1589
+ modifyQuery(cb) {
1590
+ return addColumnData(this, "modifyQuery", cb);
1591
+ }
1592
+ transform(fn) {
1593
+ const cloned = Object.create(this);
1594
+ cloned.chain = [...this.chain, ["transform", fn]];
1595
+ return cloned;
1596
+ }
1597
+ to(fn, type) {
1598
+ const cloned = Object.create(this);
1599
+ cloned.chain = [...this.chain, ["to", fn, type], ...cloned.chain];
1600
+ return cloned;
1601
+ }
1602
+ refine(check) {
1603
+ const cloned = Object.create(this);
1604
+ cloned.chain = [...this.chain, ["refine", check]];
1605
+ return cloned;
1606
+ }
1607
+ superRefine(check) {
1608
+ const cloned = Object.create(this);
1609
+ cloned.chain = [...this.chain, ["superRefine", check]];
1610
+ return cloned;
1611
+ }
1612
+ }
1487
1613
 
1488
1614
  var __defProp$n = Object.defineProperty;
1489
1615
  var __defProps$i = Object.defineProperties;
@@ -1682,20 +1808,22 @@ function length(value) {
1682
1808
  function size(value) {
1683
1809
  return setDataValue(this, "size", value);
1684
1810
  }
1685
- function nonempty() {
1686
- return setDataValue(this, "min", 1);
1811
+ function nonEmpty() {
1812
+ const cloned = setDataValue(this, "min", 1);
1813
+ cloned.data.isNonEmpty = true;
1814
+ return cloned;
1687
1815
  }
1688
1816
  const arrayMethods = {
1689
1817
  min,
1690
1818
  max,
1691
1819
  length,
1692
- nonempty
1820
+ nonEmpty
1693
1821
  };
1694
1822
  const setMethods = {
1695
1823
  min,
1696
1824
  max,
1697
1825
  size,
1698
- nonempty
1826
+ nonEmpty
1699
1827
  };
1700
1828
  const stringTypeMethods = () => __spreadProps$h(__spreadValues$m({}, arrayMethods), {
1701
1829
  email() {
@@ -1781,6 +1909,20 @@ const dateTypeMethods = {
1781
1909
  }
1782
1910
  };
1783
1911
 
1912
+ const numberDataToCode = (data) => {
1913
+ let code = "";
1914
+ if (data.gte !== void 0)
1915
+ code += `.min(${data.gte})`;
1916
+ if (data.gt !== void 0)
1917
+ code += `.gt(${data.gt})`;
1918
+ if (data.lte !== void 0)
1919
+ code += `.max(${data.lte})`;
1920
+ if (data.lt !== void 0)
1921
+ code += `.lt(${data.lt})`;
1922
+ if (data.multipleOf !== void 0)
1923
+ code += `.step(${data.multipleOf})`;
1924
+ return code;
1925
+ };
1784
1926
  class NumberBaseColumn extends ColumnType {
1785
1927
  constructor() {
1786
1928
  super(...arguments);
@@ -1812,6 +1954,14 @@ class DecimalBaseColumn extends ColumnType {
1812
1954
  scale
1813
1955
  };
1814
1956
  }
1957
+ toCode(t) {
1958
+ const { precision, scale } = this.data;
1959
+ return columnCode(
1960
+ this,
1961
+ t,
1962
+ `${t}.decimal(${precision || ""}${scale ? `, ${scale}` : ""})`
1963
+ );
1964
+ }
1815
1965
  toSQL() {
1816
1966
  const { precision, scale } = this.data;
1817
1967
  return joinTruthy(
@@ -1826,6 +1976,9 @@ class SmallIntColumn extends IntegerBaseColumn {
1826
1976
  this.dataType = "smallint";
1827
1977
  this.parseItem = parseInt;
1828
1978
  }
1979
+ toCode(t) {
1980
+ return columnCode(this, t, `${t}.smallint()${numberDataToCode(this.data)}`);
1981
+ }
1829
1982
  }
1830
1983
  class IntegerColumn extends IntegerBaseColumn {
1831
1984
  constructor() {
@@ -1833,12 +1986,18 @@ class IntegerColumn extends IntegerBaseColumn {
1833
1986
  this.dataType = "integer";
1834
1987
  this.parseItem = parseInt;
1835
1988
  }
1989
+ toCode(t) {
1990
+ return columnCode(this, t, `${t}.integer()${numberDataToCode(this.data)}`);
1991
+ }
1836
1992
  }
1837
1993
  class BigIntColumn extends NumberAsStringBaseColumn {
1838
1994
  constructor() {
1839
1995
  super(...arguments);
1840
1996
  this.dataType = "bigint";
1841
1997
  }
1998
+ toCode(t) {
1999
+ return columnCode(this, t, `${t}.bigint()`);
2000
+ }
1842
2001
  }
1843
2002
  class DecimalColumn extends DecimalBaseColumn {
1844
2003
  }
@@ -1848,12 +2007,18 @@ class RealColumn extends NumberBaseColumn {
1848
2007
  this.dataType = "real";
1849
2008
  this.parseItem = parseFloat;
1850
2009
  }
2010
+ toCode(t) {
2011
+ return columnCode(this, t, `${t}.real()${numberDataToCode(this.data)}`);
2012
+ }
1851
2013
  }
1852
2014
  class DoublePrecisionColumn extends NumberAsStringBaseColumn {
1853
2015
  constructor() {
1854
2016
  super(...arguments);
1855
2017
  this.dataType = "double precision";
1856
2018
  }
2019
+ toCode(t) {
2020
+ return columnCode(this, t, `${t}.doublePrecision()`);
2021
+ }
1857
2022
  }
1858
2023
  class SmallSerialColumn extends IntegerBaseColumn {
1859
2024
  constructor() {
@@ -1862,6 +2027,13 @@ class SmallSerialColumn extends IntegerBaseColumn {
1862
2027
  this.parseItem = parseInt;
1863
2028
  this.hasDefault = true;
1864
2029
  }
2030
+ toCode(t) {
2031
+ return columnCode(
2032
+ this,
2033
+ t,
2034
+ `${t}.smallSerial()${numberDataToCode(this.data)}`
2035
+ );
2036
+ }
1865
2037
  }
1866
2038
  class SerialColumn extends IntegerBaseColumn {
1867
2039
  constructor() {
@@ -1870,6 +2042,9 @@ class SerialColumn extends IntegerBaseColumn {
1870
2042
  this.parseItem = parseInt;
1871
2043
  this.hasDefault = true;
1872
2044
  }
2045
+ toCode(t) {
2046
+ return columnCode(this, t, `${t}.serial()${numberDataToCode(this.data)}`);
2047
+ }
1873
2048
  }
1874
2049
  class BigSerialColumn extends NumberAsStringBaseColumn {
1875
2050
  constructor() {
@@ -1877,8 +2052,38 @@ class BigSerialColumn extends NumberAsStringBaseColumn {
1877
2052
  this.dataType = "bigserial";
1878
2053
  this.hasDefault = true;
1879
2054
  }
2055
+ toCode(t) {
2056
+ return columnCode(this, t, `${t}.bigSerial()`);
2057
+ }
1880
2058
  }
1881
2059
 
2060
+ const stringDataToCode = (data) => {
2061
+ let code = "";
2062
+ const { min, isNonEmpty } = data;
2063
+ if (min !== void 0 && (!isNonEmpty || isNonEmpty && min !== 1))
2064
+ code += `.min(${min})`;
2065
+ if (data.max !== void 0)
2066
+ code += `.max(${data.max})`;
2067
+ if (data.length !== void 0)
2068
+ code += `.length(${data.length})`;
2069
+ if (data.email !== void 0)
2070
+ code += `.email()`;
2071
+ if (data.url !== void 0)
2072
+ code += `.url()`;
2073
+ if (data.uuid !== void 0)
2074
+ code += `.uuid()`;
2075
+ if (data.cuid !== void 0)
2076
+ code += `.cuid()`;
2077
+ if (data.regex)
2078
+ code += `.regex(${data.regex.toString()})`;
2079
+ if (data.startsWith !== void 0)
2080
+ code += `.startsWith(${singleQuote(data.startsWith)})`;
2081
+ if (data.endsWith !== void 0)
2082
+ code += `.endsWith(${singleQuote(data.endsWith)})`;
2083
+ if (data.cuid !== void 0)
2084
+ code += `.trim()`;
2085
+ return code;
2086
+ };
1882
2087
  const textMethods = stringTypeMethods();
1883
2088
  class TextBaseColumn extends ColumnType {
1884
2089
  constructor() {
@@ -1891,12 +2096,12 @@ assignMethodsToClass(TextBaseColumn, textMethods);
1891
2096
  class LimitedTextBaseColumn extends TextBaseColumn {
1892
2097
  constructor(limit) {
1893
2098
  super();
1894
- this.data = { max: limit };
2099
+ this.data = { arg: limit };
1895
2100
  }
1896
2101
  toSQL() {
1897
2102
  return joinTruthy(
1898
2103
  this.dataType,
1899
- this.data.max !== void 0 && `(${this.data.max})`
2104
+ this.data.arg !== void 0 && `(${this.data.arg})`
1900
2105
  );
1901
2106
  }
1902
2107
  }
@@ -1905,12 +2110,28 @@ class VarCharColumn extends LimitedTextBaseColumn {
1905
2110
  super(...arguments);
1906
2111
  this.dataType = "varchar";
1907
2112
  }
2113
+ toCode(t) {
2114
+ const { arg } = this.data;
2115
+ return columnCode(
2116
+ this,
2117
+ t,
2118
+ `${t}.varchar(${arg != null ? arg : ""})${stringDataToCode(this.data)}`
2119
+ );
2120
+ }
1908
2121
  }
1909
2122
  class CharColumn extends LimitedTextBaseColumn {
1910
2123
  constructor() {
1911
2124
  super(...arguments);
1912
2125
  this.dataType = "char";
1913
2126
  }
2127
+ toCode(t) {
2128
+ const { arg } = this.data;
2129
+ return columnCode(
2130
+ this,
2131
+ t,
2132
+ `${t}.char(${arg != null ? arg : ""})${stringDataToCode(this.data)}`
2133
+ );
2134
+ }
1914
2135
  }
1915
2136
  class TextColumn extends TextBaseColumn {
1916
2137
  constructor() {
@@ -1918,6 +2139,9 @@ class TextColumn extends TextBaseColumn {
1918
2139
  this.dataType = "text";
1919
2140
  this.operators = Operators.text;
1920
2141
  }
2142
+ toCode(t) {
2143
+ return columnCode(this, t, `${t}.text()${stringDataToCode(this.data)}`);
2144
+ }
1921
2145
  }
1922
2146
  class ByteaColumn extends ColumnType {
1923
2147
  constructor() {
@@ -1925,6 +2149,9 @@ class ByteaColumn extends ColumnType {
1925
2149
  this.dataType = "bytea";
1926
2150
  this.operators = Operators.text;
1927
2151
  }
2152
+ toCode(t) {
2153
+ return columnCode(this, t, `${t}.bytea()`);
2154
+ }
1928
2155
  }
1929
2156
  class PointColumn extends ColumnType {
1930
2157
  constructor() {
@@ -1932,56 +2159,85 @@ class PointColumn extends ColumnType {
1932
2159
  this.dataType = "point";
1933
2160
  this.operators = Operators.text;
1934
2161
  }
2162
+ toCode(t) {
2163
+ return columnCode(this, t, `${t}.point()`);
2164
+ }
1935
2165
  }
1936
2166
  class LineColumn extends ColumnType {
1937
2167
  constructor() {
1938
2168
  super(...arguments);
1939
- this.dataType = "point";
2169
+ this.dataType = "line";
1940
2170
  this.operators = Operators.text;
1941
2171
  }
2172
+ toCode(t) {
2173
+ return columnCode(this, t, `${t}.line()`);
2174
+ }
1942
2175
  }
1943
2176
  class LsegColumn extends ColumnType {
1944
2177
  constructor() {
1945
2178
  super(...arguments);
1946
- this.dataType = "point";
2179
+ this.dataType = "lseg";
1947
2180
  this.operators = Operators.text;
1948
2181
  }
2182
+ toCode(t) {
2183
+ return columnCode(this, t, `${t}.lseg()`);
2184
+ }
1949
2185
  }
1950
2186
  class BoxColumn extends ColumnType {
1951
2187
  constructor() {
1952
2188
  super(...arguments);
1953
- this.dataType = "point";
2189
+ this.dataType = "box";
1954
2190
  this.operators = Operators.text;
1955
2191
  }
2192
+ toCode(t) {
2193
+ return columnCode(this, t, `${t}.box()`);
2194
+ }
1956
2195
  }
1957
2196
  class PathColumn extends ColumnType {
1958
2197
  constructor() {
1959
2198
  super(...arguments);
1960
- this.dataType = "point";
2199
+ this.dataType = "path";
1961
2200
  this.operators = Operators.text;
1962
2201
  }
2202
+ toCode(t) {
2203
+ return columnCode(this, t, `${t}.path()`);
2204
+ }
1963
2205
  }
1964
2206
  class PolygonColumn extends ColumnType {
1965
2207
  constructor() {
1966
2208
  super(...arguments);
1967
- this.dataType = "point";
2209
+ this.dataType = "polygon";
1968
2210
  this.operators = Operators.text;
1969
2211
  }
2212
+ toCode(t) {
2213
+ return columnCode(this, t, `${t}.polygon()`);
2214
+ }
1970
2215
  }
1971
2216
  class CircleColumn extends ColumnType {
1972
2217
  constructor() {
1973
2218
  super(...arguments);
1974
- this.dataType = "point";
2219
+ this.dataType = "circle";
1975
2220
  this.operators = Operators.text;
1976
2221
  }
2222
+ toCode(t) {
2223
+ return columnCode(this, t, `${t}.circle()`);
2224
+ }
1977
2225
  }
1978
2226
  class MoneyColumn extends NumberBaseColumn {
1979
2227
  constructor() {
1980
2228
  super(...arguments);
1981
2229
  this.dataType = "money";
1982
- this.parseFn = (input) => {
1983
- return parseFloat(input.replace(/,/g, "").replace(/\$/g, ""));
1984
- };
2230
+ this.parseFn = Object.assign(
2231
+ function(input) {
2232
+ return parseFloat(input.replace(/,/g, "").replace(/\$/g, ""));
2233
+ },
2234
+ {
2235
+ hideFromCode: true
2236
+ }
2237
+ );
2238
+ }
2239
+ toCode(t) {
2240
+ return columnCode(this, t, `${t}.money()`);
1985
2241
  }
1986
2242
  }
1987
2243
  class CidrColumn extends ColumnType {
@@ -1990,6 +2246,9 @@ class CidrColumn extends ColumnType {
1990
2246
  this.dataType = "cidr";
1991
2247
  this.operators = Operators.text;
1992
2248
  }
2249
+ toCode(t) {
2250
+ return columnCode(this, t, `${t}.cidr()`);
2251
+ }
1993
2252
  }
1994
2253
  class InetColumn extends ColumnType {
1995
2254
  constructor() {
@@ -1997,6 +2256,9 @@ class InetColumn extends ColumnType {
1997
2256
  this.dataType = "inet";
1998
2257
  this.operators = Operators.text;
1999
2258
  }
2259
+ toCode(t) {
2260
+ return columnCode(this, t, `${t}.inet()`);
2261
+ }
2000
2262
  }
2001
2263
  class MacAddrColumn extends ColumnType {
2002
2264
  constructor() {
@@ -2004,6 +2266,9 @@ class MacAddrColumn extends ColumnType {
2004
2266
  this.dataType = "macaddr";
2005
2267
  this.operators = Operators.text;
2006
2268
  }
2269
+ toCode(t) {
2270
+ return columnCode(this, t, `${t}.macaddr()`);
2271
+ }
2007
2272
  }
2008
2273
  class MacAddr8Column extends ColumnType {
2009
2274
  constructor() {
@@ -2011,6 +2276,9 @@ class MacAddr8Column extends ColumnType {
2011
2276
  this.dataType = "macaddr8";
2012
2277
  this.operators = Operators.text;
2013
2278
  }
2279
+ toCode(t) {
2280
+ return columnCode(this, t, `${t}.macaddr8()`);
2281
+ }
2014
2282
  }
2015
2283
  class BitColumn extends ColumnType {
2016
2284
  constructor(length) {
@@ -2019,6 +2287,10 @@ class BitColumn extends ColumnType {
2019
2287
  this.operators = Operators.text;
2020
2288
  this.data = { length };
2021
2289
  }
2290
+ toCode(t) {
2291
+ const { length } = this.data;
2292
+ return columnCode(this, t, `${t}.bit(${length})`);
2293
+ }
2022
2294
  toSQL() {
2023
2295
  return joinTruthy(
2024
2296
  this.dataType,
@@ -2033,6 +2305,10 @@ class BitVaryingColumn extends ColumnType {
2033
2305
  this.operators = Operators.text;
2034
2306
  this.data = { length };
2035
2307
  }
2308
+ toCode(t) {
2309
+ const { length } = this.data;
2310
+ return columnCode(this, t, `${t}.bitVarying(${length != null ? length : ""})`);
2311
+ }
2036
2312
  toSQL() {
2037
2313
  return joinTruthy(
2038
2314
  this.dataType,
@@ -2046,6 +2322,9 @@ class TsVectorColumn extends ColumnType {
2046
2322
  this.dataType = "tsvector";
2047
2323
  this.operators = Operators.text;
2048
2324
  }
2325
+ toCode(t) {
2326
+ return columnCode(this, t, `${t}.tsvector()`);
2327
+ }
2049
2328
  }
2050
2329
  class TsQueryColumn extends ColumnType {
2051
2330
  constructor() {
@@ -2053,6 +2332,9 @@ class TsQueryColumn extends ColumnType {
2053
2332
  this.dataType = "tsquery";
2054
2333
  this.operators = Operators.text;
2055
2334
  }
2335
+ toCode(t) {
2336
+ return columnCode(this, t, `${t}.tsquery()`);
2337
+ }
2056
2338
  }
2057
2339
  class UUIDColumn extends ColumnType {
2058
2340
  constructor() {
@@ -2060,6 +2342,9 @@ class UUIDColumn extends ColumnType {
2060
2342
  this.dataType = "uuid";
2061
2343
  this.operators = Operators.text;
2062
2344
  }
2345
+ toCode(t) {
2346
+ return columnCode(this, t, `${t}.uuid()`);
2347
+ }
2063
2348
  }
2064
2349
  class XMLColumn extends ColumnType {
2065
2350
  constructor() {
@@ -2067,6 +2352,9 @@ class XMLColumn extends ColumnType {
2067
2352
  this.dataType = "xml";
2068
2353
  this.operators = Operators.text;
2069
2354
  }
2355
+ toCode(t) {
2356
+ return columnCode(this, t, `${t}.xml()`);
2357
+ }
2070
2358
  }
2071
2359
 
2072
2360
  class DateBaseColumn extends ColumnType {
@@ -2083,11 +2371,22 @@ class DateBaseColumn extends ColumnType {
2083
2371
  }
2084
2372
  }
2085
2373
  assignMethodsToClass(DateBaseColumn, dateTypeMethods);
2374
+ const dateDataToCode = (data) => {
2375
+ let code = "";
2376
+ if (data.min)
2377
+ code += `.min(new Date('${data.min.toISOString()}'))`;
2378
+ if (data.max)
2379
+ code += `.max(new Date('${data.max.toISOString()}'))`;
2380
+ return code;
2381
+ };
2086
2382
  class DateColumn extends DateBaseColumn {
2087
2383
  constructor() {
2088
2384
  super(...arguments);
2089
2385
  this.dataType = "date";
2090
2386
  }
2387
+ toCode(t) {
2388
+ return columnCode(this, t, `${t}.date()${dateDataToCode(this.data)}`);
2389
+ }
2091
2390
  }
2092
2391
  class DateTimeBaseClass extends DateBaseColumn {
2093
2392
  constructor(precision) {
@@ -2115,6 +2414,14 @@ class TimestampColumn extends DateTimeBaseClass {
2115
2414
  super(...arguments);
2116
2415
  this.dataType = "timestamp";
2117
2416
  }
2417
+ toCode(t) {
2418
+ const { precision } = this.data;
2419
+ return columnCode(
2420
+ this,
2421
+ t,
2422
+ `${t}.timestamp(${precision || ""})${dateDataToCode(this.data)}`
2423
+ );
2424
+ }
2118
2425
  }
2119
2426
  class TimestampWithTimeZoneColumn extends DateTimeWithTimeZoneBaseClass {
2120
2427
  constructor() {
@@ -2122,12 +2429,30 @@ class TimestampWithTimeZoneColumn extends DateTimeWithTimeZoneBaseClass {
2122
2429
  this.dataType = "timestamp with time zone";
2123
2430
  this.baseDataType = "timestamp";
2124
2431
  }
2432
+ toCode(t) {
2433
+ const { precision } = this.data;
2434
+ return columnCode(
2435
+ this,
2436
+ t,
2437
+ `${t}.timestampWithTimeZone(${precision || ""})${dateDataToCode(
2438
+ this.data
2439
+ )}`
2440
+ );
2441
+ }
2125
2442
  }
2126
2443
  class TimeColumn extends DateTimeBaseClass {
2127
2444
  constructor() {
2128
2445
  super(...arguments);
2129
2446
  this.dataType = "time";
2130
2447
  }
2448
+ toCode(t) {
2449
+ const { precision } = this.data;
2450
+ return columnCode(
2451
+ this,
2452
+ t,
2453
+ `${t}.time(${precision || ""})${dateDataToCode(this.data)}`
2454
+ );
2455
+ }
2131
2456
  }
2132
2457
  class TimeWithTimeZoneColumn extends DateTimeWithTimeZoneBaseClass {
2133
2458
  constructor() {
@@ -2135,6 +2460,14 @@ class TimeWithTimeZoneColumn extends DateTimeWithTimeZoneBaseClass {
2135
2460
  this.dataType = "time with time zone";
2136
2461
  this.baseDataType = "time";
2137
2462
  }
2463
+ toCode(t) {
2464
+ const { precision } = this.data;
2465
+ return columnCode(
2466
+ this,
2467
+ t,
2468
+ `${t}.timeWithTimeZone(${precision || ""})${dateDataToCode(this.data)}`
2469
+ );
2470
+ }
2138
2471
  }
2139
2472
  class IntervalColumn extends ColumnType {
2140
2473
  constructor(fields, precision) {
@@ -2143,6 +2476,14 @@ class IntervalColumn extends ColumnType {
2143
2476
  this.operators = Operators.date;
2144
2477
  this.data = { fields, precision };
2145
2478
  }
2479
+ toCode(t) {
2480
+ const { fields, precision } = this.data;
2481
+ return columnCode(
2482
+ this,
2483
+ t,
2484
+ `${t}.interval(${[fields && `'${fields}'`, precision && String(precision)].filter((part) => part).join(", ")})`
2485
+ );
2486
+ }
2146
2487
  toSQL() {
2147
2488
  return joinTruthy(
2148
2489
  this.dataType,
@@ -2159,6 +2500,9 @@ class BooleanColumn extends ColumnType {
2159
2500
  this.operators = Operators.boolean;
2160
2501
  this.parseItem = (input) => input[0] === "t";
2161
2502
  }
2503
+ toCode(t) {
2504
+ return columnCode(this, t, `${t}.boolean()`);
2505
+ }
2162
2506
  }
2163
2507
 
2164
2508
  class EnumColumn extends ColumnType {
@@ -2169,6 +2513,13 @@ class EnumColumn extends ColumnType {
2169
2513
  this.operators = Operators.any;
2170
2514
  this.dataType = "enum";
2171
2515
  }
2516
+ toCode(t) {
2517
+ return columnCode(
2518
+ this,
2519
+ t,
2520
+ `${t}.enum('${this.enumName}', [${this.options.map((option) => `'${option}'`).join(", ")}])`
2521
+ );
2522
+ }
2172
2523
  toSql() {
2173
2524
  return this.enumName;
2174
2525
  }
@@ -2307,14 +2658,38 @@ const intersection = (left, right) => {
2307
2658
  return constructType({
2308
2659
  dataType: "intersection",
2309
2660
  left,
2310
- right
2661
+ right,
2662
+ toCode(t) {
2663
+ return toCode(this, t, [
2664
+ this.left.toCode(t),
2665
+ ".and(",
2666
+ this.right.toCode(t),
2667
+ ")"
2668
+ ]);
2669
+ }
2311
2670
  });
2312
2671
  };
2313
2672
 
2314
2673
  const union = (types) => {
2315
2674
  return constructType({
2316
2675
  dataType: "union",
2317
- types
2676
+ types,
2677
+ toCode(t) {
2678
+ const last = this.types.length - 1;
2679
+ return toCode(
2680
+ this,
2681
+ t,
2682
+ this.types.flatMap((type, i) => {
2683
+ const item = [...toArray(type.toCode(t))];
2684
+ if (i < last) {
2685
+ item.push(`${i > 0 ? ")" : ""}.or(`);
2686
+ } else {
2687
+ item.push(")");
2688
+ }
2689
+ return item;
2690
+ })
2691
+ );
2692
+ }
2318
2693
  });
2319
2694
  };
2320
2695
 
@@ -2337,11 +2712,34 @@ var __spreadValues$i = (a, b) => {
2337
2712
  return a;
2338
2713
  };
2339
2714
  var __spreadProps$d = (a, b) => __defProps$d(a, __getOwnPropDescs$d(b));
2715
+ const toCode = (type, t, code) => {
2716
+ let append = "";
2717
+ if (type.data.nullable && type.data.optional) {
2718
+ append += ".nullish()";
2719
+ } else if (type.data.nullable) {
2720
+ append += ".nullable()";
2721
+ } else if (type.data.optional) {
2722
+ append += ".optional()";
2723
+ }
2724
+ if (type.data.isDeepPartial) {
2725
+ append += ".deepPartial()";
2726
+ }
2727
+ if (type.data.isNonEmpty) {
2728
+ append += ".nonEmpty()";
2729
+ }
2730
+ if (type.data.default) {
2731
+ append += `.default(${JSON.stringify(type.data.default)})`;
2732
+ }
2733
+ return columnChainToCode(type.chain, t, code, append);
2734
+ };
2340
2735
  const baseTypeMethods = {
2341
2736
  type: void 0,
2342
2737
  data: {},
2343
2738
  dataType: "any",
2344
2739
  chain: [],
2740
+ toCode() {
2741
+ throw new Error("toCode is not implemented");
2742
+ },
2345
2743
  optional() {
2346
2744
  return optional(this);
2347
2745
  },
@@ -2361,7 +2759,7 @@ const baseTypeMethods = {
2361
2759
  return notNullish(this);
2362
2760
  },
2363
2761
  deepPartial() {
2364
- return this;
2762
+ return this.optional();
2365
2763
  },
2366
2764
  transform(fn) {
2367
2765
  return __spreadProps$d(__spreadValues$i({}, this), {
@@ -2369,7 +2767,7 @@ const baseTypeMethods = {
2369
2767
  });
2370
2768
  },
2371
2769
  to(fn, type) {
2372
- return __spreadProps$d(__spreadValues$i({}, type), {
2770
+ return __spreadProps$d(__spreadValues$i({}, this), {
2373
2771
  chain: [...this.chain, ["to", fn, type], ...type.chain]
2374
2772
  });
2375
2773
  },
@@ -2426,13 +2824,24 @@ const array = (element) => {
2426
2824
  return constructType(__spreadValues$h({
2427
2825
  dataType: "array",
2428
2826
  element,
2827
+ toCode(t) {
2828
+ let code = ".array()";
2829
+ const { min, max, length, isNonEmpty } = this.data;
2830
+ if (min !== void 0 && (!isNonEmpty || isNonEmpty && min !== 1))
2831
+ code += `.min(${min})`;
2832
+ if (max !== void 0)
2833
+ code += `.max(${max})`;
2834
+ if (length !== void 0)
2835
+ code += `.length(${length})`;
2836
+ return toCode(this, t, [...toArray(this.element.toCode(t)), code]);
2837
+ },
2429
2838
  deepPartial() {
2430
2839
  return __spreadProps$c(__spreadValues$h({}, this), {
2431
- element: this.element.deepPartial()
2840
+ element: this.element.deepPartial(),
2841
+ data: __spreadProps$c(__spreadValues$h({}, this.data), {
2842
+ isDeepPartial: true
2843
+ })
2432
2844
  });
2433
- },
2434
- nonEmpty() {
2435
- return this.min(1);
2436
2845
  }
2437
2846
  }, arrayMethods));
2438
2847
  };
@@ -2468,6 +2877,13 @@ const discriminatedUnion = (discriminator, options) => {
2468
2877
  discriminatorValue: void 0,
2469
2878
  options: optionsMap,
2470
2879
  _option: void 0,
2880
+ toCode(t) {
2881
+ return toCode(this, t, [
2882
+ `${t}.discriminatedUnion(${singleQuote(this.discriminator)}, [`,
2883
+ options.flatMap((option) => option.toCode(t)),
2884
+ "])"
2885
+ ]);
2886
+ },
2471
2887
  deepPartial() {
2472
2888
  const newOptionsMap = /* @__PURE__ */ new Map();
2473
2889
  optionsMap.forEach((option, key) => {
@@ -2493,14 +2909,24 @@ const enumType = (options) => {
2493
2909
  return constructType({
2494
2910
  dataType: "enum",
2495
2911
  enum: arrayToEnum(options),
2496
- options
2912
+ options,
2913
+ toCode(t) {
2914
+ return toCode(
2915
+ this,
2916
+ t,
2917
+ `${t}.enum([${options.map(singleQuote).join(", ")}])`
2918
+ );
2919
+ }
2497
2920
  });
2498
2921
  };
2499
2922
 
2500
2923
  const instanceOf = (cls) => {
2501
2924
  return constructType({
2502
2925
  dataType: "instanceOf",
2503
- class: cls
2926
+ class: cls,
2927
+ toCode(t) {
2928
+ return toCode(this, t, `${t}.instanceOf(${this.class.name})`);
2929
+ }
2504
2930
  });
2505
2931
  };
2506
2932
 
@@ -2529,8 +2955,18 @@ const lazy = (fn) => {
2529
2955
  getter() {
2530
2956
  return this.typeCache || (this.typeCache = fn());
2531
2957
  },
2958
+ toCode(t) {
2959
+ return toCode(this, t, [
2960
+ `${t}.lazy(() => `,
2961
+ ...toArray(this.getter().toCode(t)),
2962
+ ")"
2963
+ ]);
2964
+ },
2532
2965
  deepPartial() {
2533
2966
  return __spreadProps$a(__spreadValues$f({}, this), {
2967
+ data: __spreadProps$a(__spreadValues$f({}, this.data), {
2968
+ isDeepPartial: true
2969
+ }),
2534
2970
  typeCache: void 0,
2535
2971
  getter: () => this.getter().deepPartial()
2536
2972
  });
@@ -2540,7 +2976,15 @@ const lazy = (fn) => {
2540
2976
 
2541
2977
  const literal = (value) => constructType({
2542
2978
  dataType: "literal",
2543
- value
2979
+ value,
2980
+ toCode(t) {
2981
+ const { value: value2 } = this;
2982
+ return toCode(
2983
+ this,
2984
+ t,
2985
+ `${t}.literal(${typeof value2 === "string" ? singleQuote(value2) : value2})`
2986
+ );
2987
+ }
2544
2988
  });
2545
2989
 
2546
2990
  var __defProp$e = Object.defineProperty;
@@ -2567,8 +3011,18 @@ const map = (keyType, valueType) => {
2567
3011
  dataType: "map",
2568
3012
  keyType,
2569
3013
  valueType,
3014
+ toCode(t) {
3015
+ return toCode(
3016
+ this,
3017
+ t,
3018
+ `${t}.map(${this.keyType.toCode(t)}, ${this.valueType.toCode(t)})`
3019
+ );
3020
+ },
2570
3021
  deepPartial() {
2571
3022
  return __spreadProps$9(__spreadValues$e({}, this), {
3023
+ data: __spreadProps$9(__spreadValues$e({}, this.data), {
3024
+ isDeepPartial: true
3025
+ }),
2572
3026
  keyType: this.keyType.deepPartial(),
2573
3027
  valueType: this.valueType.deepPartial()
2574
3028
  });
@@ -2590,7 +3044,10 @@ const nativeEnum = (givenEnum) => {
2590
3044
  return constructType({
2591
3045
  dataType: "nativeEnum",
2592
3046
  enum: givenEnum,
2593
- options
3047
+ options,
3048
+ toCode(t) {
3049
+ return toCode(this, t, `${t}.nativeEnum(enum)`);
3050
+ }
2594
3051
  });
2595
3052
  };
2596
3053
 
@@ -2619,6 +3076,23 @@ const object = (shape) => {
2619
3076
  shape,
2620
3077
  unknownKeys: "strip",
2621
3078
  catchAllType: void 0,
3079
+ toCode(t) {
3080
+ const { shape: shape2 } = this;
3081
+ const arr = [];
3082
+ for (const key in shape2) {
3083
+ arr.push(`${key}: ${shape2[key].toCode(t)},`);
3084
+ }
3085
+ let lastLine = "})";
3086
+ if (this.unknownKeys === "passthrough") {
3087
+ lastLine += ".passthrough()";
3088
+ } else if (this.unknownKeys === "strict") {
3089
+ lastLine += ".strict()";
3090
+ }
3091
+ if (this.catchAllType) {
3092
+ lastLine += `.catchAll(${this.catchAllType.toCode(t)})`;
3093
+ }
3094
+ return toCode(this, t, [`${t}.object({`, arr, lastLine]);
3095
+ },
2622
3096
  extend(add) {
2623
3097
  return object(
2624
3098
  Object.assign(__spreadValues$d({}, this.shape), add)
@@ -2709,66 +3183,145 @@ var __spreadValues$c = (a, b) => {
2709
3183
  var __spreadProps$7 = (a, b) => __defProps$7(a, __getOwnPropDescs$7(b));
2710
3184
  const any = () => {
2711
3185
  return constructType({
2712
- dataType: "any"
3186
+ dataType: "any",
3187
+ toCode(t) {
3188
+ return toCode(this, t, `${t}.any()`);
3189
+ }
2713
3190
  });
2714
3191
  };
2715
- const bigIntMethods = __spreadValues$c({
3192
+ const bigIntMethods = __spreadProps$7(__spreadValues$c({
2716
3193
  dataType: "bigint"
2717
- }, numberTypeMethods);
3194
+ }, numberTypeMethods), {
3195
+ toCode(t) {
3196
+ return toCode(this, t, `${t}.bigint()`);
3197
+ }
3198
+ });
2718
3199
  const bigint = () => {
2719
3200
  return constructType(bigIntMethods);
2720
3201
  };
2721
3202
  const boolean = () => {
2722
3203
  return constructType({
2723
- dataType: "boolean"
3204
+ dataType: "boolean",
3205
+ toCode(t) {
3206
+ return toCode(this, t, `${t}.boolean()`);
3207
+ }
2724
3208
  });
2725
3209
  };
2726
3210
  const nan = () => {
2727
3211
  return constructType({
2728
- dataType: "nan"
3212
+ dataType: "nan",
3213
+ toCode(t) {
3214
+ return toCode(this, t, `${t}.nan()`);
3215
+ }
2729
3216
  });
2730
3217
  };
2731
3218
  const never = () => {
2732
3219
  return constructType({
2733
- dataType: "never"
3220
+ dataType: "never",
3221
+ toCode(t) {
3222
+ return toCode(this, t, `${t}.never()`);
3223
+ }
2734
3224
  });
2735
3225
  };
2736
3226
  const nullType = () => {
2737
3227
  return constructType({
2738
- dataType: "null"
3228
+ dataType: "null",
3229
+ toCode(t) {
3230
+ return toCode(this, t, `${t}.null()`);
3231
+ }
2739
3232
  });
2740
3233
  };
2741
3234
  const numberMethods = __spreadProps$7(__spreadValues$c({}, numberTypeMethods), {
2742
- dataType: "number"
3235
+ dataType: "number",
3236
+ toCode(t) {
3237
+ let code = `${t}.number()`;
3238
+ if (this.data.gte !== void 0)
3239
+ code += `.min(${this.data.gte})`;
3240
+ if (this.data.gt !== void 0)
3241
+ code += `.gt(${this.data.gt})`;
3242
+ if (this.data.lte !== void 0)
3243
+ code += `.max(${this.data.lte})`;
3244
+ if (this.data.lt !== void 0)
3245
+ code += `.lt(${this.data.lt})`;
3246
+ if (this.data.multipleOf !== void 0)
3247
+ code += `.step(${this.data.multipleOf})`;
3248
+ if (this.data.int)
3249
+ code += `.int()`;
3250
+ return toCode(this, t, code);
3251
+ }
2743
3252
  });
2744
3253
  const number = () => {
2745
3254
  return constructType(numberMethods);
2746
3255
  };
2747
3256
  const dateMethods = __spreadProps$7(__spreadValues$c({}, dateTypeMethods), {
2748
- dataType: "date"
3257
+ dataType: "date",
3258
+ toCode(t) {
3259
+ let code = `${t}.date()`;
3260
+ if (this.data.min)
3261
+ code += `.min(new Date('${this.data.min.toISOString()}'))`;
3262
+ if (this.data.max)
3263
+ code += `.max(new Date('${this.data.max.toISOString()}'))`;
3264
+ return toCode(this, t, code);
3265
+ }
2749
3266
  });
2750
3267
  const date = () => {
2751
3268
  return constructType(dateMethods);
2752
3269
  };
2753
3270
  const stringMethods = __spreadProps$7(__spreadValues$c({}, stringTypeMethods()), {
2754
- dataType: "string"
3271
+ dataType: "string",
3272
+ toCode(t) {
3273
+ let code = `${t}.string()`;
3274
+ const { min, isNonEmpty } = this.data;
3275
+ if (min !== void 0 && (!isNonEmpty || isNonEmpty && min !== 1))
3276
+ code += `.min(${min})`;
3277
+ if (this.data.max !== void 0)
3278
+ code += `.max(${this.data.max})`;
3279
+ if (this.data.length !== void 0)
3280
+ code += `.length(${this.data.length})`;
3281
+ if (this.data.email !== void 0)
3282
+ code += `.email()`;
3283
+ if (this.data.url !== void 0)
3284
+ code += `.url()`;
3285
+ if (this.data.uuid !== void 0)
3286
+ code += `.uuid()`;
3287
+ if (this.data.cuid !== void 0)
3288
+ code += `.cuid()`;
3289
+ if (this.data.regex)
3290
+ code += `.regex(${this.data.regex.toString()})`;
3291
+ if (this.data.startsWith !== void 0)
3292
+ code += `.startsWith(${singleQuote(this.data.startsWith)})`;
3293
+ if (this.data.endsWith !== void 0)
3294
+ code += `.endsWith(${singleQuote(this.data.endsWith)})`;
3295
+ if (this.data.cuid !== void 0)
3296
+ code += `.trim()`;
3297
+ return toCode(this, t, code);
3298
+ }
2755
3299
  });
2756
3300
  const string = () => {
2757
3301
  return constructType(stringMethods);
2758
3302
  };
2759
3303
  const undefinedType = () => {
2760
3304
  return constructType({
2761
- dataType: "undefined"
3305
+ dataType: "undefined",
3306
+ toCode(t) {
3307
+ return toCode(this, t, `${t}.undefined()`);
3308
+ }
2762
3309
  });
2763
3310
  };
2764
3311
  const unknown = () => {
2765
3312
  return constructType({
2766
- dataType: "unknown"
3313
+ dataType: "unknown",
3314
+ toCode(t) {
3315
+ return toCode(this, t, `${t}.unknown()`);
3316
+ }
2767
3317
  });
2768
3318
  };
2769
3319
  const voidType = () => {
2770
3320
  return constructType({
2771
- dataType: "void"
3321
+ dataType: "void",
3322
+ toCode(t) {
3323
+ return toCode(this, t, `${t}.void()`);
3324
+ }
2772
3325
  });
2773
3326
  };
2774
3327
  const scalarTypes = {
@@ -2811,6 +3364,13 @@ function record(...args) {
2811
3364
  dataType: "record",
2812
3365
  keyType,
2813
3366
  valueType,
3367
+ toCode(t) {
3368
+ return toCode(
3369
+ this,
3370
+ t,
3371
+ `${t}.record(${args.length === 1 ? this.valueType.toCode(t) : `${this.keyType.toCode(t)}, ${this.valueType.toCode(t)}`})`
3372
+ );
3373
+ },
2814
3374
  deepPartial() {
2815
3375
  return __spreadProps$6(__spreadValues$b({}, this), {
2816
3376
  valueType: this.valueType.deepPartial()
@@ -2842,13 +3402,25 @@ const set = (valueType) => {
2842
3402
  return constructType(__spreadValues$a({
2843
3403
  dataType: "set",
2844
3404
  valueType,
3405
+ toCode(t) {
3406
+ let append = ")";
3407
+ const { min, max, size, isNonEmpty } = this.data;
3408
+ if (min !== void 0 && (!isNonEmpty || isNonEmpty && min !== 1))
3409
+ append += `.min(${min})`;
3410
+ if (max !== void 0)
3411
+ append += `.max(${max})`;
3412
+ if (size !== void 0)
3413
+ append += `.size(${size})`;
3414
+ return toCode(this, t, [
3415
+ `${t}.set(`,
3416
+ ...toArray(this.valueType.toCode(t)),
3417
+ append
3418
+ ]);
3419
+ },
2845
3420
  deepPartial() {
2846
3421
  return __spreadProps$5(__spreadValues$a({}, this), {
2847
3422
  valueType: this.valueType.deepPartial()
2848
3423
  });
2849
- },
2850
- nonEmpty() {
2851
- return this.min(1);
2852
3424
  }
2853
3425
  }, setMethods));
2854
3426
  };
@@ -2877,6 +3449,13 @@ const tuple = (items, rest = null) => {
2877
3449
  dataType: "tuple",
2878
3450
  items,
2879
3451
  restType: rest,
3452
+ toCode(t) {
3453
+ return toCode(
3454
+ this,
3455
+ t,
3456
+ `${t}.tuple([${this.items.map((item) => item.toCode(t)).join(", ")}]${this.restType ? `, ${this.restType.toCode(t)}` : ""})`
3457
+ );
3458
+ },
2880
3459
  rest(rest2) {
2881
3460
  return __spreadProps$4(__spreadValues$9({}, this), {
2882
3461
  restType: rest2
@@ -2937,6 +3516,10 @@ class JSONColumn extends ColumnType {
2937
3516
  const schema = typeof schemaOrFn === "function" ? schemaOrFn(jsonTypes) : schemaOrFn;
2938
3517
  this.data = { schema };
2939
3518
  }
3519
+ toCode(t) {
3520
+ const { schema } = this.data;
3521
+ return columnCode(this, t, `${t}.json((t) => ${schema.toCode("t")})`);
3522
+ }
2940
3523
  }
2941
3524
  class JSONTextColumn extends ColumnType {
2942
3525
  constructor() {
@@ -2944,6 +3527,9 @@ class JSONTextColumn extends ColumnType {
2944
3527
  this.dataType = "json";
2945
3528
  this.operators = Operators.text;
2946
3529
  }
3530
+ toCode(t) {
3531
+ return columnCode(this, t, `${t}.jsonText()`);
3532
+ }
2947
3533
  }
2948
3534
 
2949
3535
  class ArrayColumn extends ColumnType {
@@ -2951,23 +3537,43 @@ class ArrayColumn extends ColumnType {
2951
3537
  super();
2952
3538
  this.dataType = "array";
2953
3539
  this.operators = Operators.array;
2954
- this.parseFn = (input) => {
2955
- const entries = [];
2956
- parseArray(
2957
- input,
2958
- 0,
2959
- input.length,
2960
- entries,
2961
- false,
2962
- this.data.item
2963
- );
2964
- return entries;
2965
- };
3540
+ this.parseFn = Object.assign(
3541
+ (input) => {
3542
+ const entries = [];
3543
+ parseArray(
3544
+ input,
3545
+ 0,
3546
+ input.length,
3547
+ entries,
3548
+ false,
3549
+ this.data.item
3550
+ );
3551
+ return entries;
3552
+ },
3553
+ {
3554
+ hideFromCode: true
3555
+ }
3556
+ );
2966
3557
  this.data = { item };
2967
3558
  }
2968
3559
  toSQL() {
2969
3560
  return `${this.data.item.toSQL()}[]`;
2970
3561
  }
3562
+ toCode(t) {
3563
+ let code = ")";
3564
+ const { min, max, length, isNonEmpty } = this.data;
3565
+ if (min !== void 0 && (!isNonEmpty || isNonEmpty && min !== 1))
3566
+ code += `.min(${min})`;
3567
+ if (max !== void 0)
3568
+ code += `.max(${max})`;
3569
+ if (length !== void 0)
3570
+ code += `.length(${length})`;
3571
+ return columnCode(this, t, [
3572
+ "t.array(",
3573
+ ...toArray(this.data.item.toCode(t)),
3574
+ code
3575
+ ]);
3576
+ }
2971
3577
  }
2972
3578
  const parseArray = (input, pos, len, entries, nested, item) => {
2973
3579
  if (input[0] === "[") {
@@ -3205,6 +3811,9 @@ class VirtualColumn extends ColumnType {
3205
3811
  this.dataType = "";
3206
3812
  this.operators = Operators.any;
3207
3813
  }
3814
+ toCode() {
3815
+ throw new Error(`toCode is not implemented for virtual column`);
3816
+ }
3208
3817
  }
3209
3818
 
3210
3819
  var __getOwnPropSymbols$7 = Object.getOwnPropertySymbols;
@@ -4158,9 +4767,9 @@ class Delete {
4158
4767
 
4159
4768
  const forQueryBuilder = (q, type, tableNames) => {
4160
4769
  q.query.for = { type, tableNames };
4161
- q.__model = Object.create(q.__model);
4162
- q.__model.__model = q.__model;
4163
- Object.assign(q.__model, {
4770
+ q.__table = Object.create(q.__table);
4771
+ q.__table.__table = q.__table;
4772
+ Object.assign(q.__table, {
4164
4773
  noWait() {
4165
4774
  return this.clone()._noWait();
4166
4775
  },
@@ -4251,7 +4860,7 @@ var __spreadValues$5 = (a, b) => {
4251
4860
  return a;
4252
4861
  };
4253
4862
  const processHavingArg = (arg) => {
4254
- if ("__model" in arg || isRaw(arg)) {
4863
+ if ("__table" in arg || isRaw(arg)) {
4255
4864
  return arg;
4256
4865
  } else {
4257
4866
  const processed = __spreadValues$5({}, arg);
@@ -4698,13 +5307,13 @@ class WhereQueryBuilder extends Where {
4698
5307
  this.withData = {};
4699
5308
  this.table = typeof q === "object" ? q.table : q;
4700
5309
  this.shape = shape;
4701
- this.__model = this;
5310
+ this.__table = this;
4702
5311
  if (typeof q === "object" && q.query.as) {
4703
5312
  this.query.as = q.query.as;
4704
5313
  }
4705
5314
  }
4706
5315
  clone() {
4707
- const cloned = Object.create(this.__model);
5316
+ const cloned = Object.create(this.__table);
4708
5317
  cloned.query = getClonedQueryData(this.query);
4709
5318
  return cloned;
4710
5319
  }
@@ -4845,7 +5454,7 @@ class Json {
4845
5454
  return this.clone()._json();
4846
5455
  }
4847
5456
  _json() {
4848
- const q = this._wrap(this.__model.clone());
5457
+ const q = this._wrap(this.__table.clone());
4849
5458
  q._getOptional(
4850
5459
  raw(
4851
5460
  queryTypeWithLimitOne[this.query.returnType] ? `row_to_json("t".*)` : `COALESCE(json_agg(row_to_json("t".*)), '[]')`
@@ -5251,7 +5860,7 @@ class Update {
5251
5860
  ctx.resultAll = await handleResult(q, queryResult);
5252
5861
  if (ctx.updateLater) {
5253
5862
  await Promise.all(ctx.updateLaterPromises);
5254
- const t = this.__model.clone().transacting(q);
5863
+ const t = this.__table.clone().transacting(q);
5255
5864
  const keys = this.primaryKeys;
5256
5865
  t._whereIn(
5257
5866
  keys,
@@ -5500,7 +6109,7 @@ class QueryMethods {
5500
6109
  return this;
5501
6110
  }
5502
6111
  clone() {
5503
- const cloned = Object.create(this.__model);
6112
+ const cloned = Object.create(this.__table);
5504
6113
  cloned.query = getClonedQueryData(this.query);
5505
6114
  return cloned;
5506
6115
  }
@@ -5684,7 +6293,7 @@ class Db {
5684
6293
  this.whereQueryBuilder = WhereQueryBuilder;
5685
6294
  this.onQueryBuilder = OnQueryBuilder;
5686
6295
  var _a, _b;
5687
- this.__model = this;
6296
+ this.__table = this;
5688
6297
  const logger = options.logger || console;
5689
6298
  this.query = {
5690
6299
  adapter,
@@ -5907,6 +6516,8 @@ exports.array = array;
5907
6516
  exports.arrayToEnum = arrayToEnum;
5908
6517
  exports.checkIfASimpleQuery = checkIfASimpleQuery;
5909
6518
  exports.cloneQueryArrays = cloneQueryArrays;
6519
+ exports.columnChainToCode = columnChainToCode;
6520
+ exports.columnCode = columnCode;
5910
6521
  exports.columnTypes = columnTypes;
5911
6522
  exports.columnUtils = utils;
5912
6523
  exports.constructType = constructType;
@@ -5969,7 +6580,9 @@ exports.resetTableData = resetTableData;
5969
6580
  exports.scalarTypes = scalarTypes;
5970
6581
  exports.set = set;
5971
6582
  exports.setQueryObjectValue = setQueryObjectValue;
6583
+ exports.singleQuote = singleQuote;
5972
6584
  exports.toArray = toArray;
6585
+ exports.toCode = toCode;
5973
6586
  exports.toSql = toSql;
5974
6587
  exports.toSqlCacheKey = toSqlCacheKey;
5975
6588
  exports.tuple = tuple;