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.esm.js CHANGED
@@ -1,167 +1,76 @@
1
1
  import { types, Pool, DatabaseError } from 'pg';
2
2
 
3
- var __defProp$q = Object.defineProperty;
4
- var __defProps$k = Object.defineProperties;
5
- var __getOwnPropDescs$k = Object.getOwnPropertyDescriptors;
6
- var __getOwnPropSymbols$r = Object.getOwnPropertySymbols;
7
- var __hasOwnProp$r = Object.prototype.hasOwnProperty;
8
- var __propIsEnum$r = Object.prototype.propertyIsEnumerable;
9
- var __defNormalProp$q = (obj, key, value) => key in obj ? __defProp$q(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
10
- var __spreadValues$q = (a, b) => {
11
- for (var prop in b || (b = {}))
12
- if (__hasOwnProp$r.call(b, prop))
13
- __defNormalProp$q(a, prop, b[prop]);
14
- if (__getOwnPropSymbols$r)
15
- for (var prop of __getOwnPropSymbols$r(b)) {
16
- if (__propIsEnum$r.call(b, prop))
17
- __defNormalProp$q(a, prop, b[prop]);
18
- }
19
- return a;
20
- };
21
- var __spreadProps$k = (a, b) => __defProps$k(a, __getOwnPropDescs$k(b));
22
- const addColumnData = (q, key, value) => {
23
- const cloned = Object.create(q);
24
- cloned.data = __spreadProps$k(__spreadValues$q({}, q.data), { [key]: value });
25
- return cloned;
3
+ const defaultsKey = Symbol("defaults");
4
+ const queryTypeWithLimitOne = {
5
+ one: true,
6
+ oneOrThrow: true
26
7
  };
27
- class ColumnType {
28
- constructor() {
29
- this.data = {};
30
- this.isPrimaryKey = false;
31
- this.isHidden = false;
32
- this.isNullable = false;
33
- this.hasDefault = false;
34
- this.chain = [];
8
+ const isQueryReturnsAll = (q) => !q.query.returnType || q.query.returnType === "all";
9
+
10
+ const raw = (sql, values) => ({
11
+ __raw: sql,
12
+ __values: values
13
+ });
14
+ const isRaw = (obj) => "__raw" in obj;
15
+ const keys = [];
16
+ const getRaw = (raw2, valuesArray) => {
17
+ if (raw2.__values === false) {
18
+ return raw2.__raw;
35
19
  }
36
- primaryKey() {
37
- return Object.assign(this, { isPrimaryKey: true });
20
+ const arr = raw2.__raw.split("'");
21
+ const values = raw2.__values || emptyObject;
22
+ const len = arr.length;
23
+ keys.length = 0;
24
+ for (let i = 0; i < len; i += 2) {
25
+ arr[i] = arr[i].replace(/\$(\w+)/g, (_, key) => {
26
+ const value = values[key];
27
+ if (value === void 0) {
28
+ throw new Error(`Query variable \`${key}\` is not provided`);
29
+ }
30
+ keys.push(key);
31
+ valuesArray.push(value);
32
+ return `$${valuesArray.length}`;
33
+ });
38
34
  }
39
- foreignKey(fnOrTable, column, options = {}) {
40
- const cloned = Object.create(this);
41
- if (typeof fnOrTable === "string") {
42
- cloned.data = __spreadProps$k(__spreadValues$q({}, this.data), {
43
- foreignKey: __spreadValues$q({ table: fnOrTable, columns: [column] }, options)
44
- });
45
- } else {
46
- cloned.data = __spreadProps$k(__spreadValues$q({}, this.data), {
47
- foreignKey: __spreadValues$q({ fn: fnOrTable, columns: [column] }, options)
48
- });
35
+ if (keys.length > 0 && keys.length < Object.keys(values).length) {
36
+ for (const key in values) {
37
+ if (!keys.includes(key)) {
38
+ throw new Error(`Query variable \`${key}\` is unused`);
39
+ }
49
40
  }
50
- return cloned;
51
- }
52
- hidden() {
53
- return Object.assign(this, { isHidden: true });
54
- }
55
- nullable() {
56
- this.isNullable = true;
57
- return this;
58
- }
59
- encode(fn) {
60
- const self = this;
61
- self.encodeFn = fn;
62
- return self;
63
- }
64
- parse(fn) {
65
- this.parseFn = fn;
66
- this.parseItem = fn;
67
- return this;
68
- }
69
- as(column) {
70
- return addColumnData(this, "as", column);
71
- }
72
- toSQL() {
73
- return this.dataType;
74
41
  }
75
- default(value) {
76
- return addColumnData(this, "default", value);
77
- }
78
- index(options = {}) {
79
- return addColumnData(this, "index", options);
80
- }
81
- unique(options = {}) {
82
- return addColumnData(this, "index", __spreadProps$k(__spreadValues$q({}, options), { unique: true }));
83
- }
84
- comment(comment) {
85
- return addColumnData(this, "comment", comment);
86
- }
87
- validationDefault(value) {
88
- return addColumnData(this, "validationDefault", value);
89
- }
90
- compression(compression) {
91
- return addColumnData(this, "compression", compression);
92
- }
93
- collate(collate) {
94
- return addColumnData(this, "collate", collate);
95
- }
96
- modifyQuery(cb) {
97
- return addColumnData(this, "modifyQuery", cb);
98
- }
99
- transform(fn) {
100
- const cloned = Object.create(this);
101
- cloned.chain = [...this.chain, ["transform", fn]];
102
- return cloned;
103
- }
104
- to(fn, type) {
105
- const cloned = Object.create(type);
106
- cloned.chain = [...this.chain, ["to", fn, type], ...cloned.chain];
107
- return cloned;
108
- }
109
- refine(check) {
110
- const cloned = Object.create(this);
111
- cloned.chain = [...this.chain, ["refine", check]];
112
- return cloned;
113
- }
114
- superRefine(check) {
115
- const cloned = Object.create(this);
116
- cloned.chain = [...this.chain, ["superRefine", check]];
117
- return cloned;
118
- }
119
- }
120
-
121
- const singleQuoteRegex = /'/g;
122
- const doubleQuoteRegex = /"/g;
123
- const quoteValue$1 = (value) => {
124
- const type = typeof value;
125
- if (type === "number")
126
- return String(value);
127
- else if (type === "string")
128
- return `"${value.replace(doubleQuoteRegex, '\\"').replace(singleQuoteRegex, "''")}"`;
129
- else if (type === "boolean")
130
- return value ? "true" : "false";
131
- else if (value instanceof Date)
132
- return `"${value.toISOString()}"`;
133
- else if (Array.isArray(value))
134
- return quoteArray(value);
135
- else if (type === null || type === void 0)
136
- return "NULL";
137
- else
138
- return `"${JSON.stringify(value).replace(doubleQuoteRegex, '\\"').replace(singleQuoteRegex, "''")}"`;
42
+ return arr.join("'");
139
43
  };
140
- const quoteArray = (array) => `'{${array.map(quoteValue$1).join(",")}}'`;
141
- const quote = (value) => {
142
- const type = typeof value;
143
- if (type === "number")
144
- return `${value}`;
145
- else if (type === "string")
146
- return `'${value.replace(singleQuoteRegex, "''")}'`;
147
- else if (type === "boolean")
148
- return value ? "true" : "false";
149
- else if (value instanceof Date)
150
- return `'${value.toISOString()}'`;
151
- else if (Array.isArray(value))
152
- return quoteArray(value);
153
- else if (value === null || value === void 0)
154
- return "NULL";
155
- else
156
- return `'${JSON.stringify(value).replace(singleQuoteRegex, "''")}'`;
44
+ const getRawSql = (raw2) => {
45
+ return raw2.__raw;
46
+ };
47
+ const EMPTY_OBJECT = {};
48
+ const getQueryParsers = (q) => {
49
+ return q.query.parsers || q.columnsParsers;
157
50
  };
158
51
 
159
- const defaultsKey = Symbol("defaults");
160
- const queryTypeWithLimitOne = {
161
- one: true,
162
- oneOrThrow: true
52
+ const q = (sql) => `"${sql}"`;
53
+ const qc = (column, quotedAs) => quotedAs ? `${quotedAs}.${q(column)}` : column;
54
+ const quoteFullColumn = (fullColumn, quotedAs) => {
55
+ const index = fullColumn.indexOf(".");
56
+ if (index !== -1) {
57
+ return `${q(fullColumn.slice(0, index))}.${q(fullColumn.slice(index + 1))}`;
58
+ } else if (quotedAs) {
59
+ return `${quotedAs}.${q(fullColumn)}`;
60
+ } else {
61
+ return q(fullColumn);
62
+ }
63
+ };
64
+ const expressionToSql = (expr, values, quotedAs) => {
65
+ return typeof expr === "object" && isRaw(expr) ? getRaw(expr, values) : quoteFullColumn(expr, quotedAs);
66
+ };
67
+ const quoteSchemaAndTable = (schema, table) => {
68
+ return schema ? `${q(schema)}.${q(table)}` : q(table);
69
+ };
70
+ const addValue = (values, value) => {
71
+ values.push(value);
72
+ return `$${values.length}`;
163
73
  };
164
- const isQueryReturnsAll = (q) => !q.query.returnType || q.query.returnType === "all";
165
74
 
166
75
  const pushDistinctSql = (ctx, distinct, quotedAs) => {
167
76
  ctx.sql.push("DISTINCT");
@@ -221,24 +130,24 @@ const windowToSql = (window, values, quotedAs) => {
221
130
  }
222
131
  };
223
132
 
224
- const processJoinItem = (ctx, model, args, quotedAs) => {
133
+ const processJoinItem = (ctx, table, args, quotedAs) => {
225
134
  let target;
226
135
  let conditions;
227
136
  const [first] = args;
228
137
  if (typeof first === "string") {
229
- if (first in model.relations) {
138
+ if (first in table.relations) {
230
139
  const {
231
140
  key,
232
141
  query: toQuery,
233
142
  joinQuery
234
- } = model.relations[first];
235
- const jq = joinQuery(model, toQuery);
143
+ } = table.relations[first];
144
+ const jq = joinQuery(table, toQuery);
236
145
  const { query } = jq;
237
- const table = typeof query.from === "string" ? query.from : jq.table;
238
- target = quoteSchemaAndTable(query.schema, table);
146
+ const tableName = typeof query.from === "string" ? query.from : jq.table;
147
+ target = quoteSchemaAndTable(query.schema, tableName);
239
148
  const as = query.as || key;
240
149
  const joinAs = q(as);
241
- if (as !== table) {
150
+ if (as !== tableName) {
242
151
  target += ` AS ${joinAs}`;
243
152
  }
244
153
  const queryData = {
@@ -247,7 +156,7 @@ const processJoinItem = (ctx, model, args, quotedAs) => {
247
156
  };
248
157
  if (args[1]) {
249
158
  const arg = args[1](
250
- new ctx.onQueryBuilder(jq, jq.shape, model)
159
+ new ctx.onQueryBuilder(jq, jq.shape, table)
251
160
  ).query;
252
161
  if (arg.and)
253
162
  queryData.and.push(...arg.and);
@@ -257,7 +166,7 @@ const processJoinItem = (ctx, model, args, quotedAs) => {
257
166
  conditions = whereToSql(ctx, jq, queryData, joinAs);
258
167
  } else {
259
168
  target = q(first);
260
- conditions = processArgs(args, ctx, model, first, target, quotedAs);
169
+ conditions = processArgs(args, ctx, table, first, target, quotedAs);
261
170
  }
262
171
  } else {
263
172
  const query = first.query;
@@ -271,8 +180,8 @@ const processJoinItem = (ctx, model, args, quotedAs) => {
271
180
  target += ` AS ${quoted}`;
272
181
  }
273
182
  }
274
- conditions = processArgs(args, ctx, model, first, joinAs, quotedAs);
275
- const whereSql = whereToSql(ctx, model, query, joinAs);
183
+ conditions = processArgs(args, ctx, table, first, joinAs, quotedAs);
184
+ const whereSql = whereToSql(ctx, table, query, joinAs);
276
185
  if (whereSql) {
277
186
  if (conditions)
278
187
  conditions += ` AND ${whereSql}`;
@@ -282,21 +191,21 @@ const processJoinItem = (ctx, model, args, quotedAs) => {
282
191
  }
283
192
  return { target, conditions };
284
193
  };
285
- const processArgs = (args, ctx, model, first, joinAs, quotedAs) => {
194
+ const processArgs = (args, ctx, table, first, joinAs, quotedAs) => {
286
195
  var _a;
287
196
  if (args.length === 2) {
288
197
  const arg = args[1];
289
198
  if (typeof arg === "function") {
290
199
  let shape;
291
200
  if (typeof first === "string") {
292
- shape = (_a = model.query.withShapes) == null ? void 0 : _a[first];
201
+ shape = (_a = table.query.withShapes) == null ? void 0 : _a[first];
293
202
  if (!shape) {
294
203
  throw new Error("Cannot get shape of `with` statement");
295
204
  }
296
205
  } else {
297
206
  shape = first.shape;
298
207
  }
299
- const jq = arg(new ctx.onQueryBuilder(first, shape, model));
208
+ const jq = arg(new ctx.onQueryBuilder(first, shape, table));
300
209
  return whereToSql(ctx, jq, jq.query, joinAs);
301
210
  } else {
302
211
  return getObjectOrRawConditions(arg, ctx.values, quotedAs, joinAs);
@@ -331,11 +240,11 @@ const getObjectOrRawConditions = (data, values, quotedAs, joinAs) => {
331
240
  return pairs.join(", ");
332
241
  }
333
242
  };
334
- const pushJoinSql = (ctx, model, query, quotedAs) => {
243
+ const pushJoinSql = (ctx, table, query, quotedAs) => {
335
244
  query.join.forEach((item) => {
336
245
  const { target, conditions } = processJoinItem(
337
246
  ctx,
338
- model,
247
+ table,
339
248
  item.args,
340
249
  quotedAs
341
250
  );
@@ -345,41 +254,41 @@ const pushJoinSql = (ctx, model, query, quotedAs) => {
345
254
  });
346
255
  };
347
256
 
348
- const pushWhereStatementSql = (ctx, model, query, quotedAs) => {
349
- const res = whereToSql(ctx, model, query, quotedAs, false);
257
+ const pushWhereStatementSql = (ctx, table, query, quotedAs) => {
258
+ const res = whereToSql(ctx, table, query, quotedAs, false);
350
259
  if (res) {
351
260
  ctx.sql.push("WHERE", res);
352
261
  }
353
262
  };
354
- const pushWhereToSql = (sql, ctx, model, query, quotedAs, not) => {
355
- const res = whereToSql(ctx, model, query, quotedAs, not);
263
+ const pushWhereToSql = (sql, ctx, table, query, quotedAs, not) => {
264
+ const res = whereToSql(ctx, table, query, quotedAs, not);
356
265
  if (res) {
357
266
  sql.push(res);
358
267
  }
359
268
  };
360
- const whereToSql = (ctx, model, query, quotedAs, not) => {
269
+ const whereToSql = (ctx, table, query, quotedAs, not) => {
361
270
  if (query.or) {
362
271
  const ors = query.and ? [query.and, ...query.or] : query.or;
363
- return ors.map((and) => processAnds(and, ctx, model, quotedAs, not)).join(" OR ");
272
+ return ors.map((and) => processAnds(and, ctx, table, quotedAs, not)).join(" OR ");
364
273
  } else if (query.and) {
365
- return processAnds(query.and, ctx, model, quotedAs, not);
274
+ return processAnds(query.and, ctx, table, quotedAs, not);
366
275
  } else {
367
276
  return void 0;
368
277
  }
369
278
  };
370
- const processAnds = (and, ctx, model, quotedAs, not) => {
279
+ const processAnds = (and, ctx, table, quotedAs, not) => {
371
280
  const ands = [];
372
- and.forEach((data) => processWhere(ands, ctx, model, data, quotedAs, not));
281
+ and.forEach((data) => processWhere(ands, ctx, table, data, quotedAs, not));
373
282
  return ands.join(" AND ");
374
283
  };
375
- const processWhere = (ands, ctx, model, data, quotedAs, not) => {
284
+ const processWhere = (ands, ctx, table, data, quotedAs, not) => {
376
285
  const prefix = not ? "NOT " : "";
377
286
  if (typeof data === "function") {
378
- const qb = data(new ctx.whereQueryBuilder(model, model.shape));
287
+ const qb = data(new ctx.whereQueryBuilder(table, table.shape));
379
288
  pushWhereToSql(ands, ctx, qb, qb.query, quotedAs, not);
380
289
  return;
381
290
  }
382
- if ("prototype" in data || "__model" in data) {
291
+ if ("prototype" in data || "__table" in data) {
383
292
  const query = data;
384
293
  const sql = whereToSql(
385
294
  ctx,
@@ -400,15 +309,15 @@ const processWhere = (ands, ctx, model, data, quotedAs, not) => {
400
309
  const value = data[key];
401
310
  if (key === "AND") {
402
311
  const arr = toArray(value);
403
- ands.push(processAnds(arr, ctx, model, quotedAs, not));
312
+ ands.push(processAnds(arr, ctx, table, quotedAs, not));
404
313
  } else if (key === "OR") {
405
314
  const arr = value.map(toArray);
406
315
  ands.push(
407
- arr.map((and) => processAnds(and, ctx, model, quotedAs, not)).join(" OR ")
316
+ arr.map((and) => processAnds(and, ctx, table, quotedAs, not)).join(" OR ")
408
317
  );
409
318
  } else if (key === "NOT") {
410
319
  const arr = toArray(value);
411
- ands.push(processAnds(arr, ctx, model, quotedAs, !not));
320
+ ands.push(processAnds(arr, ctx, table, quotedAs, !not));
412
321
  } else if (key === "ON") {
413
322
  if (Array.isArray(value)) {
414
323
  const item = value;
@@ -417,7 +326,7 @@ const processWhere = (ands, ctx, model, data, quotedAs, not) => {
417
326
  const rightColumn = quoteFullColumn(
418
327
  item[2],
419
328
  getQueryAs({
420
- table: model.table,
329
+ table: table.table,
421
330
  query: { as: quotedAs }
422
331
  })
423
332
  );
@@ -450,7 +359,7 @@ const processWhere = (ands, ctx, model, data, quotedAs, not) => {
450
359
  joinItems.forEach((item) => {
451
360
  const { target, conditions } = processJoinItem(
452
361
  ctx,
453
- model,
362
+ table,
454
363
  item,
455
364
  quotedAs
456
365
  );
@@ -467,7 +376,7 @@ const processWhere = (ands, ctx, model, data, quotedAs, not) => {
467
376
  )}`
468
377
  );
469
378
  } else {
470
- const column = model.shape[key];
379
+ const column = table.shape[key];
471
380
  if (!column) {
472
381
  throw new Error(`Unknown column ${key} provided to condition`);
473
382
  }
@@ -515,29 +424,29 @@ const pushIn = (ands, prefix, quotedAs, values, arg) => {
515
424
  );
516
425
  };
517
426
 
518
- var __defProp$p = Object.defineProperty;
519
- var __defProps$j = Object.defineProperties;
520
- var __getOwnPropDescs$j = Object.getOwnPropertyDescriptors;
521
- var __getOwnPropSymbols$q = Object.getOwnPropertySymbols;
522
- var __hasOwnProp$q = Object.prototype.hasOwnProperty;
523
- var __propIsEnum$q = Object.prototype.propertyIsEnumerable;
524
- var __defNormalProp$p = (obj, key, value) => key in obj ? __defProp$p(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
525
- var __spreadValues$p = (a, b) => {
427
+ var __defProp$q = Object.defineProperty;
428
+ var __defProps$k = Object.defineProperties;
429
+ var __getOwnPropDescs$k = Object.getOwnPropertyDescriptors;
430
+ var __getOwnPropSymbols$r = Object.getOwnPropertySymbols;
431
+ var __hasOwnProp$r = Object.prototype.hasOwnProperty;
432
+ var __propIsEnum$r = Object.prototype.propertyIsEnumerable;
433
+ var __defNormalProp$q = (obj, key, value) => key in obj ? __defProp$q(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
434
+ var __spreadValues$q = (a, b) => {
526
435
  for (var prop in b || (b = {}))
527
- if (__hasOwnProp$q.call(b, prop))
528
- __defNormalProp$p(a, prop, b[prop]);
529
- if (__getOwnPropSymbols$q)
530
- for (var prop of __getOwnPropSymbols$q(b)) {
531
- if (__propIsEnum$q.call(b, prop))
532
- __defNormalProp$p(a, prop, b[prop]);
436
+ if (__hasOwnProp$r.call(b, prop))
437
+ __defNormalProp$q(a, prop, b[prop]);
438
+ if (__getOwnPropSymbols$r)
439
+ for (var prop of __getOwnPropSymbols$r(b)) {
440
+ if (__propIsEnum$r.call(b, prop))
441
+ __defNormalProp$q(a, prop, b[prop]);
533
442
  }
534
443
  return a;
535
444
  };
536
- var __spreadProps$j = (a, b) => __defProps$j(a, __getOwnPropDescs$j(b));
537
- const aggregateToSql = (ctx, model, item, quotedAs) => {
445
+ var __spreadProps$k = (a, b) => __defProps$k(a, __getOwnPropDescs$k(b));
446
+ const aggregateToSql = (ctx, table, item, quotedAs) => {
538
447
  var _a;
539
448
  const sql = [`${item.function}(`];
540
- ctx = __spreadProps$j(__spreadValues$p({}, ctx), { sql });
449
+ ctx = __spreadProps$k(__spreadValues$q({}, ctx), { sql });
541
450
  const options = item.options || EMPTY_OBJECT;
542
451
  if (options.distinct && !options.withinGroup)
543
452
  sql.push("DISTINCT ");
@@ -577,7 +486,7 @@ const aggregateToSql = (ctx, model, item, quotedAs) => {
577
486
  if (options.filter || options.filterOr) {
578
487
  const whereSql = whereToSql(
579
488
  ctx,
580
- model,
489
+ table,
581
490
  {
582
491
  and: options.filter ? [options.filter] : void 0,
583
492
  or: (_a = options.filterOr) == null ? void 0 : _a.map((item2) => [item2])
@@ -634,6 +543,44 @@ class UnhandledTypeError extends PormInternalError {
634
543
  }
635
544
  }
636
545
 
546
+ const singleQuoteRegex = /'/g;
547
+ const doubleQuoteRegex = /"/g;
548
+ const quoteValue$1 = (value) => {
549
+ const type = typeof value;
550
+ if (type === "number")
551
+ return String(value);
552
+ else if (type === "string")
553
+ return `"${value.replace(doubleQuoteRegex, '\\"').replace(singleQuoteRegex, "''")}"`;
554
+ else if (type === "boolean")
555
+ return value ? "true" : "false";
556
+ else if (value instanceof Date)
557
+ return `"${value.toISOString()}"`;
558
+ else if (Array.isArray(value))
559
+ return quoteArray(value);
560
+ else if (type === null || type === void 0)
561
+ return "NULL";
562
+ else
563
+ return `"${JSON.stringify(value).replace(doubleQuoteRegex, '\\"').replace(singleQuoteRegex, "''")}"`;
564
+ };
565
+ const quoteArray = (array) => `'{${array.map(quoteValue$1).join(",")}}'`;
566
+ const quote = (value) => {
567
+ const type = typeof value;
568
+ if (type === "number")
569
+ return `${value}`;
570
+ else if (type === "string")
571
+ return `'${value.replace(singleQuoteRegex, "''")}'`;
572
+ else if (type === "boolean")
573
+ return value ? "true" : "false";
574
+ else if (value instanceof Date)
575
+ return `'${value.toISOString()}'`;
576
+ else if (Array.isArray(value))
577
+ return quoteArray(value);
578
+ else if (value === null || value === void 0)
579
+ return "NULL";
580
+ else
581
+ return `'${JSON.stringify(value).replace(singleQuoteRegex, "''")}'`;
582
+ };
583
+
637
584
  const relationQueryKey = Symbol("relationQuery");
638
585
  const isRequiredRelationKey = Symbol("isRequiredRelation");
639
586
 
@@ -673,10 +620,10 @@ const jsonToSql = (item, values, quotedAs) => {
673
620
  }
674
621
  return "";
675
622
  };
676
- const pushSelectSql = (ctx, model, query, quotedAs) => {
677
- ctx.sql.push(selectToSql(ctx, model, query, quotedAs));
623
+ const pushSelectSql = (ctx, table, query, quotedAs) => {
624
+ ctx.sql.push(selectToSql(ctx, table, query, quotedAs));
678
625
  };
679
- const selectToSql = (ctx, model, query, quotedAs) => {
626
+ const selectToSql = (ctx, table, query, quotedAs) => {
680
627
  var _a;
681
628
  if (query.select) {
682
629
  const list = [];
@@ -713,13 +660,13 @@ const selectToSql = (ctx, model, query, quotedAs) => {
713
660
  list.push(
714
661
  `${item.function}(${selectToSql(
715
662
  ctx,
716
- model,
663
+ table,
717
664
  { select: item.arguments },
718
665
  quotedAs
719
666
  )})${item.as ? ` AS ${q(item.as)}` : ""}`
720
667
  );
721
668
  } else {
722
- list.push(aggregateToSql(ctx, model, item, quotedAs));
669
+ list.push(aggregateToSql(ctx, table, item, quotedAs));
723
670
  }
724
671
  }
725
672
  });
@@ -748,7 +695,7 @@ const pushSubQuerySql = (query, as, values, list) => {
748
695
  }
749
696
  select.length = 0;
750
697
  select[0] = { selectAs: { c: first } };
751
- query = query._wrap(query.__model.clone());
698
+ query = query._wrap(query.__table.clone());
752
699
  query._getOptional(raw(`COALESCE(json_agg("c"), '[]')`));
753
700
  break;
754
701
  }
@@ -777,12 +724,12 @@ const aggregateOptionNames = [
777
724
  "filterOr",
778
725
  "withinGroup"
779
726
  ];
780
- const pushHavingSql = (ctx, model, query, quotedAs) => {
781
- const conditions = havingToSql(ctx, model, query, quotedAs);
727
+ const pushHavingSql = (ctx, table, query, quotedAs) => {
728
+ const conditions = havingToSql(ctx, table, query, quotedAs);
782
729
  if (conditions.length)
783
730
  ctx.sql.push("HAVING", conditions);
784
731
  };
785
- const havingToSql = (ctx, model, query, quotedAs) => {
732
+ const havingToSql = (ctx, table, query, quotedAs) => {
786
733
  const or = query.having && query.havingOr ? [query.having, ...query.havingOr] : query.having ? [query.having] : query.havingOr;
787
734
  if (!(or == null ? void 0 : or.length))
788
735
  return "";
@@ -790,7 +737,7 @@ const havingToSql = (ctx, model, query, quotedAs) => {
790
737
  or.forEach((and) => {
791
738
  const ands = [];
792
739
  and.forEach((item) => {
793
- if ("prototype" in item || "__model" in item) {
740
+ if ("prototype" in item || "__table" in item) {
794
741
  const query2 = item;
795
742
  const sql = havingToSql(
796
743
  ctx,
@@ -816,7 +763,7 @@ const havingToSql = (ctx, model, query, quotedAs) => {
816
763
  if (!aggregateOptionNames.includes(
817
764
  op
818
765
  )) {
819
- const operator = model.shape[column].operators[op];
766
+ const operator = table.shape[column].operators[op];
820
767
  if (!operator) {
821
768
  throw new Error(
822
769
  `Unknown operator ${op} provided to condition`
@@ -824,7 +771,7 @@ const havingToSql = (ctx, model, query, quotedAs) => {
824
771
  }
825
772
  const expression = aggregateToSql(
826
773
  ctx,
827
- model,
774
+ table,
828
775
  {
829
776
  function: key,
830
777
  arg: column,
@@ -845,7 +792,7 @@ const havingToSql = (ctx, model, query, quotedAs) => {
845
792
  ands.push(
846
793
  `${aggregateToSql(
847
794
  ctx,
848
- model,
795
+ table,
849
796
  {
850
797
  function: key,
851
798
  arg: column,
@@ -911,17 +858,17 @@ const queryKeysOfNotSimpleQuery = [
911
858
  "for"
912
859
  ];
913
860
 
914
- const pushFromAndAs = (ctx, model, query, quotedAs) => {
861
+ const pushFromAndAs = (ctx, table, query, quotedAs) => {
915
862
  ctx.sql.push("FROM");
916
863
  if (query.fromOnly)
917
864
  ctx.sql.push("ONLY");
918
- const from = getFrom(model, query, ctx.values);
865
+ const from = getFrom(table, query, ctx.values);
919
866
  ctx.sql.push(from);
920
867
  if (query.as && quotedAs && quotedAs !== from) {
921
868
  ctx.sql.push("AS", quotedAs);
922
869
  }
923
870
  };
924
- const getFrom = (model, query, values) => {
871
+ const getFrom = (table, query, values) => {
925
872
  if (query.from) {
926
873
  if (typeof query.from === "object") {
927
874
  if (isRaw(query.from)) {
@@ -940,7 +887,7 @@ const getFrom = (model, query, values) => {
940
887
  }
941
888
  return quoteSchemaAndTable(query.schema, query.from);
942
889
  }
943
- return quoteSchemaAndTable(query.schema, model.table);
890
+ return quoteSchemaAndTable(query.schema, table.table);
944
891
  };
945
892
 
946
893
  const pushQueryArray = (q, key, value) => {
@@ -970,7 +917,7 @@ const setQueryObjectValue = (q, object, key, value) => {
970
917
  return q;
971
918
  };
972
919
 
973
- const pushInsertSql = (ctx, model, query, quotedAs) => {
920
+ const pushInsertSql = (ctx, table, query, quotedAs) => {
974
921
  const quotedColumns = query.columns.map(q);
975
922
  ctx.sql.push(`INSERT INTO ${quotedAs}(${quotedColumns.join(", ")})`);
976
923
  if (query.fromQuery) {
@@ -1025,22 +972,22 @@ const pushInsertSql = (ctx, model, query, quotedAs) => {
1025
972
  ctx.sql.push("DO UPDATE SET", set);
1026
973
  }
1027
974
  }
1028
- pushWhereStatementSql(ctx, model, query, quotedAs);
1029
- pushReturningSql(ctx, model, query, quotedAs);
975
+ pushWhereStatementSql(ctx, table, query, quotedAs);
976
+ pushReturningSql(ctx, table, query, quotedAs);
1030
977
  };
1031
978
  const encodeRow = (ctx, row) => {
1032
979
  return row.map(
1033
980
  (value) => value === void 0 ? "DEFAULT" : addValue(ctx.values, value)
1034
981
  ).join(", ");
1035
982
  };
1036
- const pushReturningSql = (ctx, model, query, quotedAs) => {
983
+ const pushReturningSql = (ctx, table, query, quotedAs) => {
1037
984
  if (query.select) {
1038
- ctx.sql.push(`RETURNING ${selectToSql(ctx, model, query, quotedAs)}`);
985
+ ctx.sql.push(`RETURNING ${selectToSql(ctx, table, query, quotedAs)}`);
1039
986
  }
1040
987
  };
1041
988
 
1042
- const pushUpdateSql = (ctx, model, query, quotedAs) => {
1043
- const quotedTable = quoteSchemaAndTable(query.schema, model.table);
989
+ const pushUpdateSql = (ctx, table, query, quotedAs) => {
990
+ const quotedTable = quoteSchemaAndTable(query.schema, table.table);
1044
991
  ctx.sql.push(`UPDATE ${quotedTable}`);
1045
992
  if (quotedTable !== quotedAs) {
1046
993
  ctx.sql.push(`AS ${quotedAs}`);
@@ -1049,8 +996,8 @@ const pushUpdateSql = (ctx, model, query, quotedAs) => {
1049
996
  const set = [];
1050
997
  processData(ctx, set, query.updateData);
1051
998
  ctx.sql.push(set.join(", "));
1052
- pushWhereStatementSql(ctx, model, query, quotedAs);
1053
- pushReturningSql(ctx, model, query, quotedAs);
999
+ pushWhereStatementSql(ctx, table, query, quotedAs);
1000
+ pushReturningSql(ctx, table, query, quotedAs);
1054
1001
  };
1055
1002
  const processData = (ctx, set, data) => {
1056
1003
  let append;
@@ -1087,9 +1034,9 @@ const processValue = (values, key, value) => {
1087
1034
  return addValue(values, value);
1088
1035
  };
1089
1036
 
1090
- const pushDeleteSql = (ctx, model, query, quotedAs) => {
1037
+ const pushDeleteSql = (ctx, table, query, quotedAs) => {
1091
1038
  var _a, _b, _c;
1092
- const from = q(model.table);
1039
+ const from = q(table.table);
1093
1040
  ctx.sql.push(`DELETE FROM ${from}`);
1094
1041
  if (from !== quotedAs) {
1095
1042
  ctx.sql.push(`AS ${quotedAs}`);
@@ -1097,12 +1044,12 @@ const pushDeleteSql = (ctx, model, query, quotedAs) => {
1097
1044
  let conditions;
1098
1045
  if ((_a = query.join) == null ? void 0 : _a.length) {
1099
1046
  const items = query.join.map(
1100
- (item) => processJoinItem(ctx, model, item.args, quotedAs)
1047
+ (item) => processJoinItem(ctx, table, item.args, quotedAs)
1101
1048
  );
1102
1049
  ctx.sql.push(`USING ${items.map((item) => item.target).join(", ")}`);
1103
1050
  conditions = items.map((item) => item.conditions).filter(Boolean).join(" AND ");
1104
1051
  }
1105
- pushWhereStatementSql(ctx, model, query, quotedAs);
1052
+ pushWhereStatementSql(ctx, table, query, quotedAs);
1106
1053
  if (conditions == null ? void 0 : conditions.length) {
1107
1054
  if (((_b = query.and) == null ? void 0 : _b.length) || ((_c = query.or) == null ? void 0 : _c.length)) {
1108
1055
  ctx.sql.push("AND", conditions);
@@ -1110,7 +1057,7 @@ const pushDeleteSql = (ctx, model, query, quotedAs) => {
1110
1057
  ctx.sql.push("WHERE", conditions);
1111
1058
  }
1112
1059
  }
1113
- pushReturningSql(ctx, model, query, quotedAs);
1060
+ pushReturningSql(ctx, table, query, quotedAs);
1114
1061
  };
1115
1062
 
1116
1063
  const pushTruncateSql = (ctx, table, query) => {
@@ -1133,13 +1080,13 @@ const pushColumnInfoSql = (ctx, table, query) => {
1133
1080
  }
1134
1081
  };
1135
1082
 
1136
- const pushCopySql = (ctx, model, query, quotedAs) => {
1083
+ const pushCopySql = (ctx, table, query, quotedAs) => {
1137
1084
  const { sql } = ctx;
1138
1085
  const { copy } = query;
1139
1086
  const columns = copy.columns ? `(${copy.columns.map(q).join(", ")})` : "";
1140
1087
  const target = "from" in copy ? copy.from : copy.to;
1141
1088
  sql.push(
1142
- `COPY ${q(model.table)}${columns} ${"from" in copy ? "FROM" : "TO"} ${typeof target === "string" ? quote(target) : `PROGRAM ${quote(target.program)}`}`
1089
+ `COPY ${q(table.table)}${columns} ${"from" in copy ? "FROM" : "TO"} ${typeof target === "string" ? quote(target) : `PROGRAM ${quote(target.program)}`}`
1143
1090
  );
1144
1091
  if (Object.keys(copy).length > (copy.columns ? 2 : 1)) {
1145
1092
  const options = [];
@@ -1169,19 +1116,19 @@ const pushCopySql = (ctx, model, query, quotedAs) => {
1169
1116
  options.push(`ENCODING ${quote(copy.encoding)}`);
1170
1117
  sql.push(`WITH (${options.join(", ")})`);
1171
1118
  }
1172
- pushWhereStatementSql(ctx, model, query, quotedAs);
1119
+ pushWhereStatementSql(ctx, table, query, quotedAs);
1173
1120
  };
1174
1121
 
1175
1122
  const toSqlCacheKey = Symbol("toSqlCache");
1176
- const toSql = (model, options) => {
1177
- return !(options == null ? void 0 : options.clearCache) && model.query[toSqlCacheKey] || (model.query[toSqlCacheKey] = makeSql(model, options));
1123
+ const toSql = (table, options) => {
1124
+ return !(options == null ? void 0 : options.clearCache) && table.query[toSqlCacheKey] || (table.query[toSqlCacheKey] = makeSql(table, options));
1178
1125
  };
1179
- const makeSql = (model, { values = [] } = {}) => {
1180
- const query = model.query;
1126
+ const makeSql = (table, { values = [] } = {}) => {
1127
+ const query = table.query;
1181
1128
  const sql = [];
1182
1129
  const ctx = {
1183
- whereQueryBuilder: model.whereQueryBuilder,
1184
- onQueryBuilder: model.onQueryBuilder,
1130
+ whereQueryBuilder: table.whereQueryBuilder,
1131
+ onQueryBuilder: table.onQueryBuilder,
1185
1132
  sql,
1186
1133
  values
1187
1134
  };
@@ -1190,56 +1137,56 @@ const makeSql = (model, { values = [] } = {}) => {
1190
1137
  }
1191
1138
  if (query.type) {
1192
1139
  if (query.type === "truncate") {
1193
- if (!model.table)
1140
+ if (!table.table)
1194
1141
  throw new Error("Table is missing for truncate");
1195
- pushTruncateSql(ctx, model.table, query);
1142
+ pushTruncateSql(ctx, table.table, query);
1196
1143
  return { text: sql.join(" "), values };
1197
1144
  }
1198
1145
  if (query.type === "columnInfo") {
1199
- if (!model.table)
1146
+ if (!table.table)
1200
1147
  throw new Error("Table is missing for truncate");
1201
- pushColumnInfoSql(ctx, model.table, query);
1148
+ pushColumnInfoSql(ctx, table.table, query);
1202
1149
  return { text: sql.join(" "), values };
1203
1150
  }
1204
- if (!model.table)
1151
+ if (!table.table)
1205
1152
  throw new Error(`Table is missing for ${query.type}`);
1206
- const quotedAs2 = q(query.as || model.table);
1153
+ const quotedAs2 = q(query.as || table.table);
1207
1154
  if (query.type === "insert") {
1208
- pushInsertSql(ctx, model, query, q(model.table));
1155
+ pushInsertSql(ctx, table, query, q(table.table));
1209
1156
  return { text: sql.join(" "), values };
1210
1157
  }
1211
1158
  if (query.type === "update") {
1212
- pushUpdateSql(ctx, model, query, quotedAs2);
1159
+ pushUpdateSql(ctx, table, query, quotedAs2);
1213
1160
  return { text: sql.join(" "), values };
1214
1161
  }
1215
1162
  if (query.type === "delete") {
1216
- pushDeleteSql(ctx, model, query, quotedAs2);
1163
+ pushDeleteSql(ctx, table, query, quotedAs2);
1217
1164
  return { text: sql.join(" "), values };
1218
1165
  }
1219
1166
  if (query.type === "copy") {
1220
- pushCopySql(ctx, model, query, quotedAs2);
1167
+ pushCopySql(ctx, table, query, quotedAs2);
1221
1168
  return { text: sql.join(" "), values };
1222
1169
  }
1223
1170
  }
1224
- const quotedAs = model.table && q(query.as || model.table);
1171
+ const quotedAs = table.table && q(query.as || table.table);
1225
1172
  sql.push("SELECT");
1226
1173
  if (query.distinct) {
1227
1174
  pushDistinctSql(ctx, query.distinct, quotedAs);
1228
1175
  }
1229
- pushSelectSql(ctx, model, query, quotedAs);
1230
- if (model.table || query.from) {
1231
- pushFromAndAs(ctx, model, query, quotedAs);
1176
+ pushSelectSql(ctx, table, query, quotedAs);
1177
+ if (table.table || query.from) {
1178
+ pushFromAndAs(ctx, table, query, quotedAs);
1232
1179
  }
1233
1180
  if (query.join) {
1234
1181
  pushJoinSql(
1235
1182
  ctx,
1236
- model,
1183
+ table,
1237
1184
  query,
1238
1185
  quotedAs
1239
1186
  );
1240
1187
  }
1241
1188
  if (query.and || query.or) {
1242
- pushWhereStatementSql(ctx, model, query, quotedAs);
1189
+ pushWhereStatementSql(ctx, table, query, quotedAs);
1243
1190
  }
1244
1191
  if (query.group) {
1245
1192
  const group = query.group.map(
@@ -1248,7 +1195,7 @@ const makeSql = (model, { values = [] } = {}) => {
1248
1195
  sql.push(`GROUP BY ${group.join(", ")}`);
1249
1196
  }
1250
1197
  if (query.having || query.havingOr) {
1251
- pushHavingSql(ctx, model, query, quotedAs);
1198
+ pushHavingSql(ctx, table, query, quotedAs);
1252
1199
  }
1253
1200
  if (query.window) {
1254
1201
  const window = [];
@@ -1355,19 +1302,19 @@ const cloneQueryArrays = (q) => {
1355
1302
  }
1356
1303
  };
1357
1304
 
1358
- var __defProp$o = Object.defineProperty;
1359
- var __getOwnPropSymbols$p = Object.getOwnPropertySymbols;
1360
- var __hasOwnProp$p = Object.prototype.hasOwnProperty;
1361
- var __propIsEnum$p = Object.prototype.propertyIsEnumerable;
1362
- var __defNormalProp$o = (obj, key, value) => key in obj ? __defProp$o(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1363
- var __spreadValues$o = (a, b) => {
1305
+ var __defProp$p = Object.defineProperty;
1306
+ var __getOwnPropSymbols$q = Object.getOwnPropertySymbols;
1307
+ var __hasOwnProp$q = Object.prototype.hasOwnProperty;
1308
+ var __propIsEnum$q = Object.prototype.propertyIsEnumerable;
1309
+ var __defNormalProp$p = (obj, key, value) => key in obj ? __defProp$p(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1310
+ var __spreadValues$p = (a, b) => {
1364
1311
  for (var prop in b || (b = {}))
1365
- if (__hasOwnProp$p.call(b, prop))
1366
- __defNormalProp$o(a, prop, b[prop]);
1367
- if (__getOwnPropSymbols$p)
1368
- for (var prop of __getOwnPropSymbols$p(b)) {
1369
- if (__propIsEnum$p.call(b, prop))
1370
- __defNormalProp$o(a, prop, b[prop]);
1312
+ if (__hasOwnProp$q.call(b, prop))
1313
+ __defNormalProp$p(a, prop, b[prop]);
1314
+ if (__getOwnPropSymbols$q)
1315
+ for (var prop of __getOwnPropSymbols$q(b)) {
1316
+ if (__propIsEnum$q.call(b, prop))
1317
+ __defNormalProp$p(a, prop, b[prop]);
1371
1318
  }
1372
1319
  return a;
1373
1320
  };
@@ -1386,7 +1333,7 @@ const joinTruthy = (...strings) => {
1386
1333
  return strings.filter((string) => string).join("");
1387
1334
  };
1388
1335
  const getClonedQueryData = (query) => {
1389
- const cloned = __spreadValues$o({}, query);
1336
+ const cloned = __spreadValues$p({}, query);
1390
1337
  delete cloned[toSqlCacheKey];
1391
1338
  cloneQueryArrays(cloned);
1392
1339
  return cloned;
@@ -1414,72 +1361,251 @@ const pushOrNewArray = (arr, value) => {
1414
1361
  } else {
1415
1362
  return [value];
1416
1363
  }
1417
- };
1418
-
1419
- const raw = (sql, values) => ({
1420
- __raw: sql,
1421
- __values: values
1422
- });
1423
- const isRaw = (obj) => "__raw" in obj;
1424
- const keys = [];
1425
- const getRaw = (raw2, valuesArray) => {
1426
- if (raw2.__values === false) {
1427
- return raw2.__raw;
1364
+ };
1365
+ const singleQuote = (s) => `'${s.replaceAll("\\", "\\\\").replaceAll("'", "\\'")}'`;
1366
+
1367
+ var __defProp$o = Object.defineProperty;
1368
+ var __defProps$j = Object.defineProperties;
1369
+ var __getOwnPropDescs$j = Object.getOwnPropertyDescriptors;
1370
+ var __getOwnPropSymbols$p = Object.getOwnPropertySymbols;
1371
+ var __hasOwnProp$p = Object.prototype.hasOwnProperty;
1372
+ var __propIsEnum$p = Object.prototype.propertyIsEnumerable;
1373
+ var __defNormalProp$o = (obj, key, value) => key in obj ? __defProp$o(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1374
+ var __spreadValues$o = (a, b) => {
1375
+ for (var prop in b || (b = {}))
1376
+ if (__hasOwnProp$p.call(b, prop))
1377
+ __defNormalProp$o(a, prop, b[prop]);
1378
+ if (__getOwnPropSymbols$p)
1379
+ for (var prop of __getOwnPropSymbols$p(b)) {
1380
+ if (__propIsEnum$p.call(b, prop))
1381
+ __defNormalProp$o(a, prop, b[prop]);
1382
+ }
1383
+ return a;
1384
+ };
1385
+ var __spreadProps$j = (a, b) => __defProps$j(a, __getOwnPropDescs$j(b));
1386
+ const addColumnData = (q, key, value) => {
1387
+ const cloned = Object.create(q);
1388
+ cloned.data = __spreadProps$j(__spreadValues$o({}, q.data), { [key]: value });
1389
+ return cloned;
1390
+ };
1391
+ const columnChainToCode = (chain, t, code, append) => {
1392
+ const result = toArray(code);
1393
+ if (typeof append === "string") {
1394
+ if (append) {
1395
+ if (result.length === 1 && typeof result[0] === "string") {
1396
+ result[0] += append;
1397
+ } else {
1398
+ result.push(append);
1399
+ }
1400
+ }
1401
+ } else {
1402
+ if (append.length)
1403
+ result.push(...append);
1404
+ }
1405
+ for (const item of chain) {
1406
+ if (item[0] === "transform") {
1407
+ result.push(`.transform(${item[1].toString()})`);
1408
+ } else if (item[0] === "to") {
1409
+ const type = toArray(item[2].toCode(t));
1410
+ result.push(`.to(${item[1].toString()}, `, ...type, ")");
1411
+ } else if (item[0] === "refine") {
1412
+ result.push(`.refine(${item[1].toString()})`);
1413
+ } else if (item[0] === "superRefine") {
1414
+ result.push(`.superRefine(${item[1].toString()})`);
1415
+ }
1416
+ }
1417
+ return result.length === 1 && typeof result[0] === "string" ? result[0] : result;
1418
+ };
1419
+ const columnCode = (type, t, code) => {
1420
+ const append = [];
1421
+ const { foreignKey, index, validationDefault } = type.data;
1422
+ if (type.isPrimaryKey)
1423
+ append.push(".primaryKey()");
1424
+ if (foreignKey) {
1425
+ append.push(`.foreignKey(`);
1426
+ if ("fn" in foreignKey) {
1427
+ append.push(foreignKey.fn.toString());
1428
+ } else {
1429
+ append.push(singleQuote(foreignKey.table));
1430
+ }
1431
+ append.push(`, ${singleQuote(foreignKey.columns[0])}`);
1432
+ const hasOptions = foreignKey.name || foreignKey.match || foreignKey.onUpdate || foreignKey.onDelete;
1433
+ if (hasOptions) {
1434
+ const arr = [];
1435
+ if (foreignKey.name)
1436
+ arr.push(`name: ${singleQuote(foreignKey.name)},`);
1437
+ if (foreignKey.match)
1438
+ arr.push(`match: ${singleQuote(foreignKey.match)},`);
1439
+ if (foreignKey.onUpdate)
1440
+ arr.push(`onUpdate: ${singleQuote(foreignKey.onUpdate)},`);
1441
+ if (foreignKey.onDelete)
1442
+ arr.push(`onDelete: ${singleQuote(foreignKey.onDelete)},`);
1443
+ append.push(", {", arr, "}");
1444
+ }
1445
+ append.push(")");
1446
+ }
1447
+ if (type.isHidden)
1448
+ append.push(".hidden()");
1449
+ if (type.isNullable)
1450
+ append.push(".nullable()");
1451
+ if ("isNonEmpty" in type.data)
1452
+ append.push(".nonEmpty()");
1453
+ if (type.encodeFn)
1454
+ append.push(`.encode(${type.encodeFn.toString()})`);
1455
+ if (type.parseFn && !("hideFromCode" in type.parseFn))
1456
+ append.push(`.parse(${type.parseFn.toString()})`);
1457
+ if (type.data.as)
1458
+ append.push(`.as(${type.data.as.toCode(t)})`);
1459
+ if (type.data.default)
1460
+ append.push(`.default(${JSON.stringify(type.data.default)})`);
1461
+ if (index) {
1462
+ append.push(`.${index.unique ? "unique" : "index"}(`);
1463
+ for (const key in index) {
1464
+ if (key === "unique")
1465
+ continue;
1466
+ const arr = [];
1467
+ if (index.expression)
1468
+ arr.push(
1469
+ `expression: ${typeof index.expression === "string" ? singleQuote(index.expression) : index.expression},`
1470
+ );
1471
+ if (index.collate)
1472
+ arr.push(`collate: ${singleQuote(index.collate)},`);
1473
+ if (index.operator)
1474
+ arr.push(`operator: ${singleQuote(index.operator)},`);
1475
+ if (index.order)
1476
+ arr.push(`order: ${singleQuote(index.order)},`);
1477
+ if (index.name)
1478
+ arr.push(`name: ${singleQuote(index.name)},`);
1479
+ if (index.unique)
1480
+ arr.push(`unique: true,`);
1481
+ if (index.using)
1482
+ arr.push(`using: ${singleQuote(index.using)},`);
1483
+ if (index.include)
1484
+ arr.push(
1485
+ `include: ${typeof index.include === "string" ? singleQuote(index.include) : `[${index.include.map(singleQuote).join(", ")}]`},`
1486
+ );
1487
+ if (index.with)
1488
+ arr.push(`with: ${singleQuote(index.with)},`);
1489
+ if (index.tablespace)
1490
+ arr.push(`tablespace: ${singleQuote(index.tablespace)},`);
1491
+ if (index.where)
1492
+ arr.push(`where: ${singleQuote(index.where)},`);
1493
+ append.push("{", arr, "}");
1494
+ break;
1495
+ }
1496
+ append.push(")");
1497
+ }
1498
+ if (type.data.comment)
1499
+ append.push(`.comment(${singleQuote(type.data.comment)})`);
1500
+ if (validationDefault) {
1501
+ append.push(
1502
+ `.validationDefault(${typeof validationDefault === "function" ? validationDefault.toString() : typeof validationDefault === "string" ? singleQuote(validationDefault) : JSON.stringify(validationDefault)})`
1503
+ );
1504
+ }
1505
+ if (type.data.compression)
1506
+ append.push(`.compression(${singleQuote(type.data.compression)})`);
1507
+ if (type.data.collate)
1508
+ append.push(`.collate(${singleQuote(type.data.collate)})`);
1509
+ if (type.data.modifyQuery)
1510
+ append.push(`.modifyQuery(${type.data.modifyQuery.toString()})`);
1511
+ return columnChainToCode(type.chain, t, code, append);
1512
+ };
1513
+ class ColumnType {
1514
+ constructor() {
1515
+ this.data = {};
1516
+ this.isPrimaryKey = false;
1517
+ this.isHidden = false;
1518
+ this.isNullable = false;
1519
+ this.hasDefault = false;
1520
+ this.chain = [];
1521
+ }
1522
+ primaryKey() {
1523
+ const cloned = Object.create(this);
1524
+ return Object.assign(cloned, { isPrimaryKey: true });
1525
+ }
1526
+ foreignKey(fnOrTable, column, options = {}) {
1527
+ const cloned = Object.create(this);
1528
+ if (typeof fnOrTable === "string") {
1529
+ cloned.data = __spreadProps$j(__spreadValues$o({}, this.data), {
1530
+ foreignKey: __spreadValues$o({ table: fnOrTable, columns: [column] }, options)
1531
+ });
1532
+ } else {
1533
+ cloned.data = __spreadProps$j(__spreadValues$o({}, this.data), {
1534
+ foreignKey: __spreadValues$o({ fn: fnOrTable, columns: [column] }, options)
1535
+ });
1536
+ }
1537
+ return cloned;
1538
+ }
1539
+ hidden() {
1540
+ return Object.assign(Object.create(this), { isHidden: true });
1428
1541
  }
1429
- const arr = raw2.__raw.split("'");
1430
- const values = raw2.__values || emptyObject;
1431
- const len = arr.length;
1432
- keys.length = 0;
1433
- for (let i = 0; i < len; i += 2) {
1434
- arr[i] = arr[i].replace(/\$(\w+)/g, (_, key) => {
1435
- const value = values[key];
1436
- if (value === void 0) {
1437
- throw new Error(`Query variable \`${key}\` is not provided`);
1438
- }
1439
- keys.push(key);
1440
- valuesArray.push(value);
1441
- return `$${valuesArray.length}`;
1542
+ nullable() {
1543
+ return Object.assign(Object.create(this), {
1544
+ isNullable: true
1442
1545
  });
1443
1546
  }
1444
- if (keys.length > 0 && keys.length < Object.keys(values).length) {
1445
- for (const key in values) {
1446
- if (!keys.includes(key)) {
1447
- throw new Error(`Query variable \`${key}\` is unused`);
1448
- }
1449
- }
1547
+ encode(fn) {
1548
+ return Object.assign(Object.create(this), {
1549
+ encodeFn: fn
1550
+ });
1450
1551
  }
1451
- return arr.join("'");
1452
- };
1453
- const getRawSql = (raw2) => {
1454
- return raw2.__raw;
1455
- };
1456
- const EMPTY_OBJECT = {};
1457
- const getQueryParsers = (q) => {
1458
- return q.query.parsers || q.columnsParsers;
1459
- };
1460
-
1461
- const q = (sql) => `"${sql}"`;
1462
- const qc = (column, quotedAs) => quotedAs ? `${quotedAs}.${q(column)}` : column;
1463
- const quoteFullColumn = (fullColumn, quotedAs) => {
1464
- const index = fullColumn.indexOf(".");
1465
- if (index !== -1) {
1466
- return `${q(fullColumn.slice(0, index))}.${q(fullColumn.slice(index + 1))}`;
1467
- } else if (quotedAs) {
1468
- return `${quotedAs}.${q(fullColumn)}`;
1469
- } else {
1470
- return q(fullColumn);
1552
+ parse(fn) {
1553
+ return Object.assign(Object.create(this), {
1554
+ parseFn: fn,
1555
+ parseItem: fn
1556
+ });
1471
1557
  }
1472
- };
1473
- const expressionToSql = (expr, values, quotedAs) => {
1474
- return typeof expr === "object" && isRaw(expr) ? getRaw(expr, values) : quoteFullColumn(expr, quotedAs);
1475
- };
1476
- const quoteSchemaAndTable = (schema, table) => {
1477
- return schema ? `${q(schema)}.${q(table)}` : q(table);
1478
- };
1479
- const addValue = (values, value) => {
1480
- values.push(value);
1481
- return `$${values.length}`;
1482
- };
1558
+ as(column) {
1559
+ return addColumnData(this, "as", column);
1560
+ }
1561
+ toSQL() {
1562
+ return this.dataType;
1563
+ }
1564
+ default(value) {
1565
+ return addColumnData(this, "default", value);
1566
+ }
1567
+ index(options = {}) {
1568
+ return addColumnData(this, "index", options);
1569
+ }
1570
+ unique(options = {}) {
1571
+ return addColumnData(this, "index", __spreadProps$j(__spreadValues$o({}, options), { unique: true }));
1572
+ }
1573
+ comment(comment) {
1574
+ return addColumnData(this, "comment", comment);
1575
+ }
1576
+ validationDefault(value) {
1577
+ return addColumnData(this, "validationDefault", value);
1578
+ }
1579
+ compression(compression) {
1580
+ return addColumnData(this, "compression", compression);
1581
+ }
1582
+ collate(collate) {
1583
+ return addColumnData(this, "collate", collate);
1584
+ }
1585
+ modifyQuery(cb) {
1586
+ return addColumnData(this, "modifyQuery", cb);
1587
+ }
1588
+ transform(fn) {
1589
+ const cloned = Object.create(this);
1590
+ cloned.chain = [...this.chain, ["transform", fn]];
1591
+ return cloned;
1592
+ }
1593
+ to(fn, type) {
1594
+ const cloned = Object.create(this);
1595
+ cloned.chain = [...this.chain, ["to", fn, type], ...cloned.chain];
1596
+ return cloned;
1597
+ }
1598
+ refine(check) {
1599
+ const cloned = Object.create(this);
1600
+ cloned.chain = [...this.chain, ["refine", check]];
1601
+ return cloned;
1602
+ }
1603
+ superRefine(check) {
1604
+ const cloned = Object.create(this);
1605
+ cloned.chain = [...this.chain, ["superRefine", check]];
1606
+ return cloned;
1607
+ }
1608
+ }
1483
1609
 
1484
1610
  var __defProp$n = Object.defineProperty;
1485
1611
  var __defProps$i = Object.defineProperties;
@@ -1678,20 +1804,22 @@ function length(value) {
1678
1804
  function size(value) {
1679
1805
  return setDataValue(this, "size", value);
1680
1806
  }
1681
- function nonempty() {
1682
- return setDataValue(this, "min", 1);
1807
+ function nonEmpty() {
1808
+ const cloned = setDataValue(this, "min", 1);
1809
+ cloned.data.isNonEmpty = true;
1810
+ return cloned;
1683
1811
  }
1684
1812
  const arrayMethods = {
1685
1813
  min,
1686
1814
  max,
1687
1815
  length,
1688
- nonempty
1816
+ nonEmpty
1689
1817
  };
1690
1818
  const setMethods = {
1691
1819
  min,
1692
1820
  max,
1693
1821
  size,
1694
- nonempty
1822
+ nonEmpty
1695
1823
  };
1696
1824
  const stringTypeMethods = () => __spreadProps$h(__spreadValues$m({}, arrayMethods), {
1697
1825
  email() {
@@ -1777,6 +1905,20 @@ const dateTypeMethods = {
1777
1905
  }
1778
1906
  };
1779
1907
 
1908
+ const numberDataToCode = (data) => {
1909
+ let code = "";
1910
+ if (data.gte !== void 0)
1911
+ code += `.min(${data.gte})`;
1912
+ if (data.gt !== void 0)
1913
+ code += `.gt(${data.gt})`;
1914
+ if (data.lte !== void 0)
1915
+ code += `.max(${data.lte})`;
1916
+ if (data.lt !== void 0)
1917
+ code += `.lt(${data.lt})`;
1918
+ if (data.multipleOf !== void 0)
1919
+ code += `.step(${data.multipleOf})`;
1920
+ return code;
1921
+ };
1780
1922
  class NumberBaseColumn extends ColumnType {
1781
1923
  constructor() {
1782
1924
  super(...arguments);
@@ -1808,6 +1950,14 @@ class DecimalBaseColumn extends ColumnType {
1808
1950
  scale
1809
1951
  };
1810
1952
  }
1953
+ toCode(t) {
1954
+ const { precision, scale } = this.data;
1955
+ return columnCode(
1956
+ this,
1957
+ t,
1958
+ `${t}.decimal(${precision || ""}${scale ? `, ${scale}` : ""})`
1959
+ );
1960
+ }
1811
1961
  toSQL() {
1812
1962
  const { precision, scale } = this.data;
1813
1963
  return joinTruthy(
@@ -1822,6 +1972,9 @@ class SmallIntColumn extends IntegerBaseColumn {
1822
1972
  this.dataType = "smallint";
1823
1973
  this.parseItem = parseInt;
1824
1974
  }
1975
+ toCode(t) {
1976
+ return columnCode(this, t, `${t}.smallint()${numberDataToCode(this.data)}`);
1977
+ }
1825
1978
  }
1826
1979
  class IntegerColumn extends IntegerBaseColumn {
1827
1980
  constructor() {
@@ -1829,12 +1982,18 @@ class IntegerColumn extends IntegerBaseColumn {
1829
1982
  this.dataType = "integer";
1830
1983
  this.parseItem = parseInt;
1831
1984
  }
1985
+ toCode(t) {
1986
+ return columnCode(this, t, `${t}.integer()${numberDataToCode(this.data)}`);
1987
+ }
1832
1988
  }
1833
1989
  class BigIntColumn extends NumberAsStringBaseColumn {
1834
1990
  constructor() {
1835
1991
  super(...arguments);
1836
1992
  this.dataType = "bigint";
1837
1993
  }
1994
+ toCode(t) {
1995
+ return columnCode(this, t, `${t}.bigint()`);
1996
+ }
1838
1997
  }
1839
1998
  class DecimalColumn extends DecimalBaseColumn {
1840
1999
  }
@@ -1844,12 +2003,18 @@ class RealColumn extends NumberBaseColumn {
1844
2003
  this.dataType = "real";
1845
2004
  this.parseItem = parseFloat;
1846
2005
  }
2006
+ toCode(t) {
2007
+ return columnCode(this, t, `${t}.real()${numberDataToCode(this.data)}`);
2008
+ }
1847
2009
  }
1848
2010
  class DoublePrecisionColumn extends NumberAsStringBaseColumn {
1849
2011
  constructor() {
1850
2012
  super(...arguments);
1851
2013
  this.dataType = "double precision";
1852
2014
  }
2015
+ toCode(t) {
2016
+ return columnCode(this, t, `${t}.doublePrecision()`);
2017
+ }
1853
2018
  }
1854
2019
  class SmallSerialColumn extends IntegerBaseColumn {
1855
2020
  constructor() {
@@ -1858,6 +2023,13 @@ class SmallSerialColumn extends IntegerBaseColumn {
1858
2023
  this.parseItem = parseInt;
1859
2024
  this.hasDefault = true;
1860
2025
  }
2026
+ toCode(t) {
2027
+ return columnCode(
2028
+ this,
2029
+ t,
2030
+ `${t}.smallSerial()${numberDataToCode(this.data)}`
2031
+ );
2032
+ }
1861
2033
  }
1862
2034
  class SerialColumn extends IntegerBaseColumn {
1863
2035
  constructor() {
@@ -1866,6 +2038,9 @@ class SerialColumn extends IntegerBaseColumn {
1866
2038
  this.parseItem = parseInt;
1867
2039
  this.hasDefault = true;
1868
2040
  }
2041
+ toCode(t) {
2042
+ return columnCode(this, t, `${t}.serial()${numberDataToCode(this.data)}`);
2043
+ }
1869
2044
  }
1870
2045
  class BigSerialColumn extends NumberAsStringBaseColumn {
1871
2046
  constructor() {
@@ -1873,8 +2048,38 @@ class BigSerialColumn extends NumberAsStringBaseColumn {
1873
2048
  this.dataType = "bigserial";
1874
2049
  this.hasDefault = true;
1875
2050
  }
2051
+ toCode(t) {
2052
+ return columnCode(this, t, `${t}.bigSerial()`);
2053
+ }
1876
2054
  }
1877
2055
 
2056
+ const stringDataToCode = (data) => {
2057
+ let code = "";
2058
+ const { min, isNonEmpty } = data;
2059
+ if (min !== void 0 && (!isNonEmpty || isNonEmpty && min !== 1))
2060
+ code += `.min(${min})`;
2061
+ if (data.max !== void 0)
2062
+ code += `.max(${data.max})`;
2063
+ if (data.length !== void 0)
2064
+ code += `.length(${data.length})`;
2065
+ if (data.email !== void 0)
2066
+ code += `.email()`;
2067
+ if (data.url !== void 0)
2068
+ code += `.url()`;
2069
+ if (data.uuid !== void 0)
2070
+ code += `.uuid()`;
2071
+ if (data.cuid !== void 0)
2072
+ code += `.cuid()`;
2073
+ if (data.regex)
2074
+ code += `.regex(${data.regex.toString()})`;
2075
+ if (data.startsWith !== void 0)
2076
+ code += `.startsWith(${singleQuote(data.startsWith)})`;
2077
+ if (data.endsWith !== void 0)
2078
+ code += `.endsWith(${singleQuote(data.endsWith)})`;
2079
+ if (data.cuid !== void 0)
2080
+ code += `.trim()`;
2081
+ return code;
2082
+ };
1878
2083
  const textMethods = stringTypeMethods();
1879
2084
  class TextBaseColumn extends ColumnType {
1880
2085
  constructor() {
@@ -1887,12 +2092,12 @@ assignMethodsToClass(TextBaseColumn, textMethods);
1887
2092
  class LimitedTextBaseColumn extends TextBaseColumn {
1888
2093
  constructor(limit) {
1889
2094
  super();
1890
- this.data = { max: limit };
2095
+ this.data = { arg: limit };
1891
2096
  }
1892
2097
  toSQL() {
1893
2098
  return joinTruthy(
1894
2099
  this.dataType,
1895
- this.data.max !== void 0 && `(${this.data.max})`
2100
+ this.data.arg !== void 0 && `(${this.data.arg})`
1896
2101
  );
1897
2102
  }
1898
2103
  }
@@ -1901,12 +2106,28 @@ class VarCharColumn extends LimitedTextBaseColumn {
1901
2106
  super(...arguments);
1902
2107
  this.dataType = "varchar";
1903
2108
  }
2109
+ toCode(t) {
2110
+ const { arg } = this.data;
2111
+ return columnCode(
2112
+ this,
2113
+ t,
2114
+ `${t}.varchar(${arg != null ? arg : ""})${stringDataToCode(this.data)}`
2115
+ );
2116
+ }
1904
2117
  }
1905
2118
  class CharColumn extends LimitedTextBaseColumn {
1906
2119
  constructor() {
1907
2120
  super(...arguments);
1908
2121
  this.dataType = "char";
1909
2122
  }
2123
+ toCode(t) {
2124
+ const { arg } = this.data;
2125
+ return columnCode(
2126
+ this,
2127
+ t,
2128
+ `${t}.char(${arg != null ? arg : ""})${stringDataToCode(this.data)}`
2129
+ );
2130
+ }
1910
2131
  }
1911
2132
  class TextColumn extends TextBaseColumn {
1912
2133
  constructor() {
@@ -1914,6 +2135,9 @@ class TextColumn extends TextBaseColumn {
1914
2135
  this.dataType = "text";
1915
2136
  this.operators = Operators.text;
1916
2137
  }
2138
+ toCode(t) {
2139
+ return columnCode(this, t, `${t}.text()${stringDataToCode(this.data)}`);
2140
+ }
1917
2141
  }
1918
2142
  class ByteaColumn extends ColumnType {
1919
2143
  constructor() {
@@ -1921,6 +2145,9 @@ class ByteaColumn extends ColumnType {
1921
2145
  this.dataType = "bytea";
1922
2146
  this.operators = Operators.text;
1923
2147
  }
2148
+ toCode(t) {
2149
+ return columnCode(this, t, `${t}.bytea()`);
2150
+ }
1924
2151
  }
1925
2152
  class PointColumn extends ColumnType {
1926
2153
  constructor() {
@@ -1928,56 +2155,85 @@ class PointColumn extends ColumnType {
1928
2155
  this.dataType = "point";
1929
2156
  this.operators = Operators.text;
1930
2157
  }
2158
+ toCode(t) {
2159
+ return columnCode(this, t, `${t}.point()`);
2160
+ }
1931
2161
  }
1932
2162
  class LineColumn extends ColumnType {
1933
2163
  constructor() {
1934
2164
  super(...arguments);
1935
- this.dataType = "point";
2165
+ this.dataType = "line";
1936
2166
  this.operators = Operators.text;
1937
2167
  }
2168
+ toCode(t) {
2169
+ return columnCode(this, t, `${t}.line()`);
2170
+ }
1938
2171
  }
1939
2172
  class LsegColumn extends ColumnType {
1940
2173
  constructor() {
1941
2174
  super(...arguments);
1942
- this.dataType = "point";
2175
+ this.dataType = "lseg";
1943
2176
  this.operators = Operators.text;
1944
2177
  }
2178
+ toCode(t) {
2179
+ return columnCode(this, t, `${t}.lseg()`);
2180
+ }
1945
2181
  }
1946
2182
  class BoxColumn extends ColumnType {
1947
2183
  constructor() {
1948
2184
  super(...arguments);
1949
- this.dataType = "point";
2185
+ this.dataType = "box";
1950
2186
  this.operators = Operators.text;
1951
2187
  }
2188
+ toCode(t) {
2189
+ return columnCode(this, t, `${t}.box()`);
2190
+ }
1952
2191
  }
1953
2192
  class PathColumn extends ColumnType {
1954
2193
  constructor() {
1955
2194
  super(...arguments);
1956
- this.dataType = "point";
2195
+ this.dataType = "path";
1957
2196
  this.operators = Operators.text;
1958
2197
  }
2198
+ toCode(t) {
2199
+ return columnCode(this, t, `${t}.path()`);
2200
+ }
1959
2201
  }
1960
2202
  class PolygonColumn extends ColumnType {
1961
2203
  constructor() {
1962
2204
  super(...arguments);
1963
- this.dataType = "point";
2205
+ this.dataType = "polygon";
1964
2206
  this.operators = Operators.text;
1965
2207
  }
2208
+ toCode(t) {
2209
+ return columnCode(this, t, `${t}.polygon()`);
2210
+ }
1966
2211
  }
1967
2212
  class CircleColumn extends ColumnType {
1968
2213
  constructor() {
1969
2214
  super(...arguments);
1970
- this.dataType = "point";
2215
+ this.dataType = "circle";
1971
2216
  this.operators = Operators.text;
1972
2217
  }
2218
+ toCode(t) {
2219
+ return columnCode(this, t, `${t}.circle()`);
2220
+ }
1973
2221
  }
1974
2222
  class MoneyColumn extends NumberBaseColumn {
1975
2223
  constructor() {
1976
2224
  super(...arguments);
1977
2225
  this.dataType = "money";
1978
- this.parseFn = (input) => {
1979
- return parseFloat(input.replace(/,/g, "").replace(/\$/g, ""));
1980
- };
2226
+ this.parseFn = Object.assign(
2227
+ function(input) {
2228
+ return parseFloat(input.replace(/,/g, "").replace(/\$/g, ""));
2229
+ },
2230
+ {
2231
+ hideFromCode: true
2232
+ }
2233
+ );
2234
+ }
2235
+ toCode(t) {
2236
+ return columnCode(this, t, `${t}.money()`);
1981
2237
  }
1982
2238
  }
1983
2239
  class CidrColumn extends ColumnType {
@@ -1986,6 +2242,9 @@ class CidrColumn extends ColumnType {
1986
2242
  this.dataType = "cidr";
1987
2243
  this.operators = Operators.text;
1988
2244
  }
2245
+ toCode(t) {
2246
+ return columnCode(this, t, `${t}.cidr()`);
2247
+ }
1989
2248
  }
1990
2249
  class InetColumn extends ColumnType {
1991
2250
  constructor() {
@@ -1993,6 +2252,9 @@ class InetColumn extends ColumnType {
1993
2252
  this.dataType = "inet";
1994
2253
  this.operators = Operators.text;
1995
2254
  }
2255
+ toCode(t) {
2256
+ return columnCode(this, t, `${t}.inet()`);
2257
+ }
1996
2258
  }
1997
2259
  class MacAddrColumn extends ColumnType {
1998
2260
  constructor() {
@@ -2000,6 +2262,9 @@ class MacAddrColumn extends ColumnType {
2000
2262
  this.dataType = "macaddr";
2001
2263
  this.operators = Operators.text;
2002
2264
  }
2265
+ toCode(t) {
2266
+ return columnCode(this, t, `${t}.macaddr()`);
2267
+ }
2003
2268
  }
2004
2269
  class MacAddr8Column extends ColumnType {
2005
2270
  constructor() {
@@ -2007,6 +2272,9 @@ class MacAddr8Column extends ColumnType {
2007
2272
  this.dataType = "macaddr8";
2008
2273
  this.operators = Operators.text;
2009
2274
  }
2275
+ toCode(t) {
2276
+ return columnCode(this, t, `${t}.macaddr8()`);
2277
+ }
2010
2278
  }
2011
2279
  class BitColumn extends ColumnType {
2012
2280
  constructor(length) {
@@ -2015,6 +2283,10 @@ class BitColumn extends ColumnType {
2015
2283
  this.operators = Operators.text;
2016
2284
  this.data = { length };
2017
2285
  }
2286
+ toCode(t) {
2287
+ const { length } = this.data;
2288
+ return columnCode(this, t, `${t}.bit(${length})`);
2289
+ }
2018
2290
  toSQL() {
2019
2291
  return joinTruthy(
2020
2292
  this.dataType,
@@ -2029,6 +2301,10 @@ class BitVaryingColumn extends ColumnType {
2029
2301
  this.operators = Operators.text;
2030
2302
  this.data = { length };
2031
2303
  }
2304
+ toCode(t) {
2305
+ const { length } = this.data;
2306
+ return columnCode(this, t, `${t}.bitVarying(${length != null ? length : ""})`);
2307
+ }
2032
2308
  toSQL() {
2033
2309
  return joinTruthy(
2034
2310
  this.dataType,
@@ -2042,6 +2318,9 @@ class TsVectorColumn extends ColumnType {
2042
2318
  this.dataType = "tsvector";
2043
2319
  this.operators = Operators.text;
2044
2320
  }
2321
+ toCode(t) {
2322
+ return columnCode(this, t, `${t}.tsvector()`);
2323
+ }
2045
2324
  }
2046
2325
  class TsQueryColumn extends ColumnType {
2047
2326
  constructor() {
@@ -2049,6 +2328,9 @@ class TsQueryColumn extends ColumnType {
2049
2328
  this.dataType = "tsquery";
2050
2329
  this.operators = Operators.text;
2051
2330
  }
2331
+ toCode(t) {
2332
+ return columnCode(this, t, `${t}.tsquery()`);
2333
+ }
2052
2334
  }
2053
2335
  class UUIDColumn extends ColumnType {
2054
2336
  constructor() {
@@ -2056,6 +2338,9 @@ class UUIDColumn extends ColumnType {
2056
2338
  this.dataType = "uuid";
2057
2339
  this.operators = Operators.text;
2058
2340
  }
2341
+ toCode(t) {
2342
+ return columnCode(this, t, `${t}.uuid()`);
2343
+ }
2059
2344
  }
2060
2345
  class XMLColumn extends ColumnType {
2061
2346
  constructor() {
@@ -2063,6 +2348,9 @@ class XMLColumn extends ColumnType {
2063
2348
  this.dataType = "xml";
2064
2349
  this.operators = Operators.text;
2065
2350
  }
2351
+ toCode(t) {
2352
+ return columnCode(this, t, `${t}.xml()`);
2353
+ }
2066
2354
  }
2067
2355
 
2068
2356
  class DateBaseColumn extends ColumnType {
@@ -2079,11 +2367,22 @@ class DateBaseColumn extends ColumnType {
2079
2367
  }
2080
2368
  }
2081
2369
  assignMethodsToClass(DateBaseColumn, dateTypeMethods);
2370
+ const dateDataToCode = (data) => {
2371
+ let code = "";
2372
+ if (data.min)
2373
+ code += `.min(new Date('${data.min.toISOString()}'))`;
2374
+ if (data.max)
2375
+ code += `.max(new Date('${data.max.toISOString()}'))`;
2376
+ return code;
2377
+ };
2082
2378
  class DateColumn extends DateBaseColumn {
2083
2379
  constructor() {
2084
2380
  super(...arguments);
2085
2381
  this.dataType = "date";
2086
2382
  }
2383
+ toCode(t) {
2384
+ return columnCode(this, t, `${t}.date()${dateDataToCode(this.data)}`);
2385
+ }
2087
2386
  }
2088
2387
  class DateTimeBaseClass extends DateBaseColumn {
2089
2388
  constructor(precision) {
@@ -2111,6 +2410,14 @@ class TimestampColumn extends DateTimeBaseClass {
2111
2410
  super(...arguments);
2112
2411
  this.dataType = "timestamp";
2113
2412
  }
2413
+ toCode(t) {
2414
+ const { precision } = this.data;
2415
+ return columnCode(
2416
+ this,
2417
+ t,
2418
+ `${t}.timestamp(${precision || ""})${dateDataToCode(this.data)}`
2419
+ );
2420
+ }
2114
2421
  }
2115
2422
  class TimestampWithTimeZoneColumn extends DateTimeWithTimeZoneBaseClass {
2116
2423
  constructor() {
@@ -2118,12 +2425,30 @@ class TimestampWithTimeZoneColumn extends DateTimeWithTimeZoneBaseClass {
2118
2425
  this.dataType = "timestamp with time zone";
2119
2426
  this.baseDataType = "timestamp";
2120
2427
  }
2428
+ toCode(t) {
2429
+ const { precision } = this.data;
2430
+ return columnCode(
2431
+ this,
2432
+ t,
2433
+ `${t}.timestampWithTimeZone(${precision || ""})${dateDataToCode(
2434
+ this.data
2435
+ )}`
2436
+ );
2437
+ }
2121
2438
  }
2122
2439
  class TimeColumn extends DateTimeBaseClass {
2123
2440
  constructor() {
2124
2441
  super(...arguments);
2125
2442
  this.dataType = "time";
2126
2443
  }
2444
+ toCode(t) {
2445
+ const { precision } = this.data;
2446
+ return columnCode(
2447
+ this,
2448
+ t,
2449
+ `${t}.time(${precision || ""})${dateDataToCode(this.data)}`
2450
+ );
2451
+ }
2127
2452
  }
2128
2453
  class TimeWithTimeZoneColumn extends DateTimeWithTimeZoneBaseClass {
2129
2454
  constructor() {
@@ -2131,6 +2456,14 @@ class TimeWithTimeZoneColumn extends DateTimeWithTimeZoneBaseClass {
2131
2456
  this.dataType = "time with time zone";
2132
2457
  this.baseDataType = "time";
2133
2458
  }
2459
+ toCode(t) {
2460
+ const { precision } = this.data;
2461
+ return columnCode(
2462
+ this,
2463
+ t,
2464
+ `${t}.timeWithTimeZone(${precision || ""})${dateDataToCode(this.data)}`
2465
+ );
2466
+ }
2134
2467
  }
2135
2468
  class IntervalColumn extends ColumnType {
2136
2469
  constructor(fields, precision) {
@@ -2139,6 +2472,14 @@ class IntervalColumn extends ColumnType {
2139
2472
  this.operators = Operators.date;
2140
2473
  this.data = { fields, precision };
2141
2474
  }
2475
+ toCode(t) {
2476
+ const { fields, precision } = this.data;
2477
+ return columnCode(
2478
+ this,
2479
+ t,
2480
+ `${t}.interval(${[fields && `'${fields}'`, precision && String(precision)].filter((part) => part).join(", ")})`
2481
+ );
2482
+ }
2142
2483
  toSQL() {
2143
2484
  return joinTruthy(
2144
2485
  this.dataType,
@@ -2155,6 +2496,9 @@ class BooleanColumn extends ColumnType {
2155
2496
  this.operators = Operators.boolean;
2156
2497
  this.parseItem = (input) => input[0] === "t";
2157
2498
  }
2499
+ toCode(t) {
2500
+ return columnCode(this, t, `${t}.boolean()`);
2501
+ }
2158
2502
  }
2159
2503
 
2160
2504
  class EnumColumn extends ColumnType {
@@ -2165,6 +2509,13 @@ class EnumColumn extends ColumnType {
2165
2509
  this.operators = Operators.any;
2166
2510
  this.dataType = "enum";
2167
2511
  }
2512
+ toCode(t) {
2513
+ return columnCode(
2514
+ this,
2515
+ t,
2516
+ `${t}.enum('${this.enumName}', [${this.options.map((option) => `'${option}'`).join(", ")}])`
2517
+ );
2518
+ }
2168
2519
  toSql() {
2169
2520
  return this.enumName;
2170
2521
  }
@@ -2303,14 +2654,38 @@ const intersection = (left, right) => {
2303
2654
  return constructType({
2304
2655
  dataType: "intersection",
2305
2656
  left,
2306
- right
2657
+ right,
2658
+ toCode(t) {
2659
+ return toCode(this, t, [
2660
+ this.left.toCode(t),
2661
+ ".and(",
2662
+ this.right.toCode(t),
2663
+ ")"
2664
+ ]);
2665
+ }
2307
2666
  });
2308
2667
  };
2309
2668
 
2310
2669
  const union = (types) => {
2311
2670
  return constructType({
2312
2671
  dataType: "union",
2313
- types
2672
+ types,
2673
+ toCode(t) {
2674
+ const last = this.types.length - 1;
2675
+ return toCode(
2676
+ this,
2677
+ t,
2678
+ this.types.flatMap((type, i) => {
2679
+ const item = [...toArray(type.toCode(t))];
2680
+ if (i < last) {
2681
+ item.push(`${i > 0 ? ")" : ""}.or(`);
2682
+ } else {
2683
+ item.push(")");
2684
+ }
2685
+ return item;
2686
+ })
2687
+ );
2688
+ }
2314
2689
  });
2315
2690
  };
2316
2691
 
@@ -2333,11 +2708,34 @@ var __spreadValues$i = (a, b) => {
2333
2708
  return a;
2334
2709
  };
2335
2710
  var __spreadProps$d = (a, b) => __defProps$d(a, __getOwnPropDescs$d(b));
2711
+ const toCode = (type, t, code) => {
2712
+ let append = "";
2713
+ if (type.data.nullable && type.data.optional) {
2714
+ append += ".nullish()";
2715
+ } else if (type.data.nullable) {
2716
+ append += ".nullable()";
2717
+ } else if (type.data.optional) {
2718
+ append += ".optional()";
2719
+ }
2720
+ if (type.data.isDeepPartial) {
2721
+ append += ".deepPartial()";
2722
+ }
2723
+ if (type.data.isNonEmpty) {
2724
+ append += ".nonEmpty()";
2725
+ }
2726
+ if (type.data.default) {
2727
+ append += `.default(${JSON.stringify(type.data.default)})`;
2728
+ }
2729
+ return columnChainToCode(type.chain, t, code, append);
2730
+ };
2336
2731
  const baseTypeMethods = {
2337
2732
  type: void 0,
2338
2733
  data: {},
2339
2734
  dataType: "any",
2340
2735
  chain: [],
2736
+ toCode() {
2737
+ throw new Error("toCode is not implemented");
2738
+ },
2341
2739
  optional() {
2342
2740
  return optional(this);
2343
2741
  },
@@ -2357,7 +2755,7 @@ const baseTypeMethods = {
2357
2755
  return notNullish(this);
2358
2756
  },
2359
2757
  deepPartial() {
2360
- return this;
2758
+ return this.optional();
2361
2759
  },
2362
2760
  transform(fn) {
2363
2761
  return __spreadProps$d(__spreadValues$i({}, this), {
@@ -2365,7 +2763,7 @@ const baseTypeMethods = {
2365
2763
  });
2366
2764
  },
2367
2765
  to(fn, type) {
2368
- return __spreadProps$d(__spreadValues$i({}, type), {
2766
+ return __spreadProps$d(__spreadValues$i({}, this), {
2369
2767
  chain: [...this.chain, ["to", fn, type], ...type.chain]
2370
2768
  });
2371
2769
  },
@@ -2422,13 +2820,24 @@ const array = (element) => {
2422
2820
  return constructType(__spreadValues$h({
2423
2821
  dataType: "array",
2424
2822
  element,
2823
+ toCode(t) {
2824
+ let code = ".array()";
2825
+ const { min, max, length, isNonEmpty } = this.data;
2826
+ if (min !== void 0 && (!isNonEmpty || isNonEmpty && min !== 1))
2827
+ code += `.min(${min})`;
2828
+ if (max !== void 0)
2829
+ code += `.max(${max})`;
2830
+ if (length !== void 0)
2831
+ code += `.length(${length})`;
2832
+ return toCode(this, t, [...toArray(this.element.toCode(t)), code]);
2833
+ },
2425
2834
  deepPartial() {
2426
2835
  return __spreadProps$c(__spreadValues$h({}, this), {
2427
- element: this.element.deepPartial()
2836
+ element: this.element.deepPartial(),
2837
+ data: __spreadProps$c(__spreadValues$h({}, this.data), {
2838
+ isDeepPartial: true
2839
+ })
2428
2840
  });
2429
- },
2430
- nonEmpty() {
2431
- return this.min(1);
2432
2841
  }
2433
2842
  }, arrayMethods));
2434
2843
  };
@@ -2464,6 +2873,13 @@ const discriminatedUnion = (discriminator, options) => {
2464
2873
  discriminatorValue: void 0,
2465
2874
  options: optionsMap,
2466
2875
  _option: void 0,
2876
+ toCode(t) {
2877
+ return toCode(this, t, [
2878
+ `${t}.discriminatedUnion(${singleQuote(this.discriminator)}, [`,
2879
+ options.flatMap((option) => option.toCode(t)),
2880
+ "])"
2881
+ ]);
2882
+ },
2467
2883
  deepPartial() {
2468
2884
  const newOptionsMap = /* @__PURE__ */ new Map();
2469
2885
  optionsMap.forEach((option, key) => {
@@ -2489,14 +2905,24 @@ const enumType = (options) => {
2489
2905
  return constructType({
2490
2906
  dataType: "enum",
2491
2907
  enum: arrayToEnum(options),
2492
- options
2908
+ options,
2909
+ toCode(t) {
2910
+ return toCode(
2911
+ this,
2912
+ t,
2913
+ `${t}.enum([${options.map(singleQuote).join(", ")}])`
2914
+ );
2915
+ }
2493
2916
  });
2494
2917
  };
2495
2918
 
2496
2919
  const instanceOf = (cls) => {
2497
2920
  return constructType({
2498
2921
  dataType: "instanceOf",
2499
- class: cls
2922
+ class: cls,
2923
+ toCode(t) {
2924
+ return toCode(this, t, `${t}.instanceOf(${this.class.name})`);
2925
+ }
2500
2926
  });
2501
2927
  };
2502
2928
 
@@ -2525,8 +2951,18 @@ const lazy = (fn) => {
2525
2951
  getter() {
2526
2952
  return this.typeCache || (this.typeCache = fn());
2527
2953
  },
2954
+ toCode(t) {
2955
+ return toCode(this, t, [
2956
+ `${t}.lazy(() => `,
2957
+ ...toArray(this.getter().toCode(t)),
2958
+ ")"
2959
+ ]);
2960
+ },
2528
2961
  deepPartial() {
2529
2962
  return __spreadProps$a(__spreadValues$f({}, this), {
2963
+ data: __spreadProps$a(__spreadValues$f({}, this.data), {
2964
+ isDeepPartial: true
2965
+ }),
2530
2966
  typeCache: void 0,
2531
2967
  getter: () => this.getter().deepPartial()
2532
2968
  });
@@ -2536,7 +2972,15 @@ const lazy = (fn) => {
2536
2972
 
2537
2973
  const literal = (value) => constructType({
2538
2974
  dataType: "literal",
2539
- value
2975
+ value,
2976
+ toCode(t) {
2977
+ const { value: value2 } = this;
2978
+ return toCode(
2979
+ this,
2980
+ t,
2981
+ `${t}.literal(${typeof value2 === "string" ? singleQuote(value2) : value2})`
2982
+ );
2983
+ }
2540
2984
  });
2541
2985
 
2542
2986
  var __defProp$e = Object.defineProperty;
@@ -2563,8 +3007,18 @@ const map = (keyType, valueType) => {
2563
3007
  dataType: "map",
2564
3008
  keyType,
2565
3009
  valueType,
3010
+ toCode(t) {
3011
+ return toCode(
3012
+ this,
3013
+ t,
3014
+ `${t}.map(${this.keyType.toCode(t)}, ${this.valueType.toCode(t)})`
3015
+ );
3016
+ },
2566
3017
  deepPartial() {
2567
3018
  return __spreadProps$9(__spreadValues$e({}, this), {
3019
+ data: __spreadProps$9(__spreadValues$e({}, this.data), {
3020
+ isDeepPartial: true
3021
+ }),
2568
3022
  keyType: this.keyType.deepPartial(),
2569
3023
  valueType: this.valueType.deepPartial()
2570
3024
  });
@@ -2586,7 +3040,10 @@ const nativeEnum = (givenEnum) => {
2586
3040
  return constructType({
2587
3041
  dataType: "nativeEnum",
2588
3042
  enum: givenEnum,
2589
- options
3043
+ options,
3044
+ toCode(t) {
3045
+ return toCode(this, t, `${t}.nativeEnum(enum)`);
3046
+ }
2590
3047
  });
2591
3048
  };
2592
3049
 
@@ -2615,6 +3072,23 @@ const object = (shape) => {
2615
3072
  shape,
2616
3073
  unknownKeys: "strip",
2617
3074
  catchAllType: void 0,
3075
+ toCode(t) {
3076
+ const { shape: shape2 } = this;
3077
+ const arr = [];
3078
+ for (const key in shape2) {
3079
+ arr.push(`${key}: ${shape2[key].toCode(t)},`);
3080
+ }
3081
+ let lastLine = "})";
3082
+ if (this.unknownKeys === "passthrough") {
3083
+ lastLine += ".passthrough()";
3084
+ } else if (this.unknownKeys === "strict") {
3085
+ lastLine += ".strict()";
3086
+ }
3087
+ if (this.catchAllType) {
3088
+ lastLine += `.catchAll(${this.catchAllType.toCode(t)})`;
3089
+ }
3090
+ return toCode(this, t, [`${t}.object({`, arr, lastLine]);
3091
+ },
2618
3092
  extend(add) {
2619
3093
  return object(
2620
3094
  Object.assign(__spreadValues$d({}, this.shape), add)
@@ -2705,66 +3179,145 @@ var __spreadValues$c = (a, b) => {
2705
3179
  var __spreadProps$7 = (a, b) => __defProps$7(a, __getOwnPropDescs$7(b));
2706
3180
  const any = () => {
2707
3181
  return constructType({
2708
- dataType: "any"
3182
+ dataType: "any",
3183
+ toCode(t) {
3184
+ return toCode(this, t, `${t}.any()`);
3185
+ }
2709
3186
  });
2710
3187
  };
2711
- const bigIntMethods = __spreadValues$c({
3188
+ const bigIntMethods = __spreadProps$7(__spreadValues$c({
2712
3189
  dataType: "bigint"
2713
- }, numberTypeMethods);
3190
+ }, numberTypeMethods), {
3191
+ toCode(t) {
3192
+ return toCode(this, t, `${t}.bigint()`);
3193
+ }
3194
+ });
2714
3195
  const bigint = () => {
2715
3196
  return constructType(bigIntMethods);
2716
3197
  };
2717
3198
  const boolean = () => {
2718
3199
  return constructType({
2719
- dataType: "boolean"
3200
+ dataType: "boolean",
3201
+ toCode(t) {
3202
+ return toCode(this, t, `${t}.boolean()`);
3203
+ }
2720
3204
  });
2721
3205
  };
2722
3206
  const nan = () => {
2723
3207
  return constructType({
2724
- dataType: "nan"
3208
+ dataType: "nan",
3209
+ toCode(t) {
3210
+ return toCode(this, t, `${t}.nan()`);
3211
+ }
2725
3212
  });
2726
3213
  };
2727
3214
  const never = () => {
2728
3215
  return constructType({
2729
- dataType: "never"
3216
+ dataType: "never",
3217
+ toCode(t) {
3218
+ return toCode(this, t, `${t}.never()`);
3219
+ }
2730
3220
  });
2731
3221
  };
2732
3222
  const nullType = () => {
2733
3223
  return constructType({
2734
- dataType: "null"
3224
+ dataType: "null",
3225
+ toCode(t) {
3226
+ return toCode(this, t, `${t}.null()`);
3227
+ }
2735
3228
  });
2736
3229
  };
2737
3230
  const numberMethods = __spreadProps$7(__spreadValues$c({}, numberTypeMethods), {
2738
- dataType: "number"
3231
+ dataType: "number",
3232
+ toCode(t) {
3233
+ let code = `${t}.number()`;
3234
+ if (this.data.gte !== void 0)
3235
+ code += `.min(${this.data.gte})`;
3236
+ if (this.data.gt !== void 0)
3237
+ code += `.gt(${this.data.gt})`;
3238
+ if (this.data.lte !== void 0)
3239
+ code += `.max(${this.data.lte})`;
3240
+ if (this.data.lt !== void 0)
3241
+ code += `.lt(${this.data.lt})`;
3242
+ if (this.data.multipleOf !== void 0)
3243
+ code += `.step(${this.data.multipleOf})`;
3244
+ if (this.data.int)
3245
+ code += `.int()`;
3246
+ return toCode(this, t, code);
3247
+ }
2739
3248
  });
2740
3249
  const number = () => {
2741
3250
  return constructType(numberMethods);
2742
3251
  };
2743
3252
  const dateMethods = __spreadProps$7(__spreadValues$c({}, dateTypeMethods), {
2744
- dataType: "date"
3253
+ dataType: "date",
3254
+ toCode(t) {
3255
+ let code = `${t}.date()`;
3256
+ if (this.data.min)
3257
+ code += `.min(new Date('${this.data.min.toISOString()}'))`;
3258
+ if (this.data.max)
3259
+ code += `.max(new Date('${this.data.max.toISOString()}'))`;
3260
+ return toCode(this, t, code);
3261
+ }
2745
3262
  });
2746
3263
  const date = () => {
2747
3264
  return constructType(dateMethods);
2748
3265
  };
2749
3266
  const stringMethods = __spreadProps$7(__spreadValues$c({}, stringTypeMethods()), {
2750
- dataType: "string"
3267
+ dataType: "string",
3268
+ toCode(t) {
3269
+ let code = `${t}.string()`;
3270
+ const { min, isNonEmpty } = this.data;
3271
+ if (min !== void 0 && (!isNonEmpty || isNonEmpty && min !== 1))
3272
+ code += `.min(${min})`;
3273
+ if (this.data.max !== void 0)
3274
+ code += `.max(${this.data.max})`;
3275
+ if (this.data.length !== void 0)
3276
+ code += `.length(${this.data.length})`;
3277
+ if (this.data.email !== void 0)
3278
+ code += `.email()`;
3279
+ if (this.data.url !== void 0)
3280
+ code += `.url()`;
3281
+ if (this.data.uuid !== void 0)
3282
+ code += `.uuid()`;
3283
+ if (this.data.cuid !== void 0)
3284
+ code += `.cuid()`;
3285
+ if (this.data.regex)
3286
+ code += `.regex(${this.data.regex.toString()})`;
3287
+ if (this.data.startsWith !== void 0)
3288
+ code += `.startsWith(${singleQuote(this.data.startsWith)})`;
3289
+ if (this.data.endsWith !== void 0)
3290
+ code += `.endsWith(${singleQuote(this.data.endsWith)})`;
3291
+ if (this.data.cuid !== void 0)
3292
+ code += `.trim()`;
3293
+ return toCode(this, t, code);
3294
+ }
2751
3295
  });
2752
3296
  const string = () => {
2753
3297
  return constructType(stringMethods);
2754
3298
  };
2755
3299
  const undefinedType = () => {
2756
3300
  return constructType({
2757
- dataType: "undefined"
3301
+ dataType: "undefined",
3302
+ toCode(t) {
3303
+ return toCode(this, t, `${t}.undefined()`);
3304
+ }
2758
3305
  });
2759
3306
  };
2760
3307
  const unknown = () => {
2761
3308
  return constructType({
2762
- dataType: "unknown"
3309
+ dataType: "unknown",
3310
+ toCode(t) {
3311
+ return toCode(this, t, `${t}.unknown()`);
3312
+ }
2763
3313
  });
2764
3314
  };
2765
3315
  const voidType = () => {
2766
3316
  return constructType({
2767
- dataType: "void"
3317
+ dataType: "void",
3318
+ toCode(t) {
3319
+ return toCode(this, t, `${t}.void()`);
3320
+ }
2768
3321
  });
2769
3322
  };
2770
3323
  const scalarTypes = {
@@ -2807,6 +3360,13 @@ function record(...args) {
2807
3360
  dataType: "record",
2808
3361
  keyType,
2809
3362
  valueType,
3363
+ toCode(t) {
3364
+ return toCode(
3365
+ this,
3366
+ t,
3367
+ `${t}.record(${args.length === 1 ? this.valueType.toCode(t) : `${this.keyType.toCode(t)}, ${this.valueType.toCode(t)}`})`
3368
+ );
3369
+ },
2810
3370
  deepPartial() {
2811
3371
  return __spreadProps$6(__spreadValues$b({}, this), {
2812
3372
  valueType: this.valueType.deepPartial()
@@ -2838,13 +3398,25 @@ const set = (valueType) => {
2838
3398
  return constructType(__spreadValues$a({
2839
3399
  dataType: "set",
2840
3400
  valueType,
3401
+ toCode(t) {
3402
+ let append = ")";
3403
+ const { min, max, size, isNonEmpty } = this.data;
3404
+ if (min !== void 0 && (!isNonEmpty || isNonEmpty && min !== 1))
3405
+ append += `.min(${min})`;
3406
+ if (max !== void 0)
3407
+ append += `.max(${max})`;
3408
+ if (size !== void 0)
3409
+ append += `.size(${size})`;
3410
+ return toCode(this, t, [
3411
+ `${t}.set(`,
3412
+ ...toArray(this.valueType.toCode(t)),
3413
+ append
3414
+ ]);
3415
+ },
2841
3416
  deepPartial() {
2842
3417
  return __spreadProps$5(__spreadValues$a({}, this), {
2843
3418
  valueType: this.valueType.deepPartial()
2844
3419
  });
2845
- },
2846
- nonEmpty() {
2847
- return this.min(1);
2848
3420
  }
2849
3421
  }, setMethods));
2850
3422
  };
@@ -2873,6 +3445,13 @@ const tuple = (items, rest = null) => {
2873
3445
  dataType: "tuple",
2874
3446
  items,
2875
3447
  restType: rest,
3448
+ toCode(t) {
3449
+ return toCode(
3450
+ this,
3451
+ t,
3452
+ `${t}.tuple([${this.items.map((item) => item.toCode(t)).join(", ")}]${this.restType ? `, ${this.restType.toCode(t)}` : ""})`
3453
+ );
3454
+ },
2876
3455
  rest(rest2) {
2877
3456
  return __spreadProps$4(__spreadValues$9({}, this), {
2878
3457
  restType: rest2
@@ -2933,6 +3512,10 @@ class JSONColumn extends ColumnType {
2933
3512
  const schema = typeof schemaOrFn === "function" ? schemaOrFn(jsonTypes) : schemaOrFn;
2934
3513
  this.data = { schema };
2935
3514
  }
3515
+ toCode(t) {
3516
+ const { schema } = this.data;
3517
+ return columnCode(this, t, `${t}.json((t) => ${schema.toCode("t")})`);
3518
+ }
2936
3519
  }
2937
3520
  class JSONTextColumn extends ColumnType {
2938
3521
  constructor() {
@@ -2940,6 +3523,9 @@ class JSONTextColumn extends ColumnType {
2940
3523
  this.dataType = "json";
2941
3524
  this.operators = Operators.text;
2942
3525
  }
3526
+ toCode(t) {
3527
+ return columnCode(this, t, `${t}.jsonText()`);
3528
+ }
2943
3529
  }
2944
3530
 
2945
3531
  class ArrayColumn extends ColumnType {
@@ -2947,23 +3533,43 @@ class ArrayColumn extends ColumnType {
2947
3533
  super();
2948
3534
  this.dataType = "array";
2949
3535
  this.operators = Operators.array;
2950
- this.parseFn = (input) => {
2951
- const entries = [];
2952
- parseArray(
2953
- input,
2954
- 0,
2955
- input.length,
2956
- entries,
2957
- false,
2958
- this.data.item
2959
- );
2960
- return entries;
2961
- };
3536
+ this.parseFn = Object.assign(
3537
+ (input) => {
3538
+ const entries = [];
3539
+ parseArray(
3540
+ input,
3541
+ 0,
3542
+ input.length,
3543
+ entries,
3544
+ false,
3545
+ this.data.item
3546
+ );
3547
+ return entries;
3548
+ },
3549
+ {
3550
+ hideFromCode: true
3551
+ }
3552
+ );
2962
3553
  this.data = { item };
2963
3554
  }
2964
3555
  toSQL() {
2965
3556
  return `${this.data.item.toSQL()}[]`;
2966
3557
  }
3558
+ toCode(t) {
3559
+ let code = ")";
3560
+ const { min, max, length, isNonEmpty } = this.data;
3561
+ if (min !== void 0 && (!isNonEmpty || isNonEmpty && min !== 1))
3562
+ code += `.min(${min})`;
3563
+ if (max !== void 0)
3564
+ code += `.max(${max})`;
3565
+ if (length !== void 0)
3566
+ code += `.length(${length})`;
3567
+ return columnCode(this, t, [
3568
+ "t.array(",
3569
+ ...toArray(this.data.item.toCode(t)),
3570
+ code
3571
+ ]);
3572
+ }
2967
3573
  }
2968
3574
  const parseArray = (input, pos, len, entries, nested, item) => {
2969
3575
  if (input[0] === "[") {
@@ -3201,6 +3807,9 @@ class VirtualColumn extends ColumnType {
3201
3807
  this.dataType = "";
3202
3808
  this.operators = Operators.any;
3203
3809
  }
3810
+ toCode() {
3811
+ throw new Error(`toCode is not implemented for virtual column`);
3812
+ }
3204
3813
  }
3205
3814
 
3206
3815
  var __getOwnPropSymbols$7 = Object.getOwnPropertySymbols;
@@ -4154,9 +4763,9 @@ class Delete {
4154
4763
 
4155
4764
  const forQueryBuilder = (q, type, tableNames) => {
4156
4765
  q.query.for = { type, tableNames };
4157
- q.__model = Object.create(q.__model);
4158
- q.__model.__model = q.__model;
4159
- Object.assign(q.__model, {
4766
+ q.__table = Object.create(q.__table);
4767
+ q.__table.__table = q.__table;
4768
+ Object.assign(q.__table, {
4160
4769
  noWait() {
4161
4770
  return this.clone()._noWait();
4162
4771
  },
@@ -4247,7 +4856,7 @@ var __spreadValues$5 = (a, b) => {
4247
4856
  return a;
4248
4857
  };
4249
4858
  const processHavingArg = (arg) => {
4250
- if ("__model" in arg || isRaw(arg)) {
4859
+ if ("__table" in arg || isRaw(arg)) {
4251
4860
  return arg;
4252
4861
  } else {
4253
4862
  const processed = __spreadValues$5({}, arg);
@@ -4694,13 +5303,13 @@ class WhereQueryBuilder extends Where {
4694
5303
  this.withData = {};
4695
5304
  this.table = typeof q === "object" ? q.table : q;
4696
5305
  this.shape = shape;
4697
- this.__model = this;
5306
+ this.__table = this;
4698
5307
  if (typeof q === "object" && q.query.as) {
4699
5308
  this.query.as = q.query.as;
4700
5309
  }
4701
5310
  }
4702
5311
  clone() {
4703
- const cloned = Object.create(this.__model);
5312
+ const cloned = Object.create(this.__table);
4704
5313
  cloned.query = getClonedQueryData(this.query);
4705
5314
  return cloned;
4706
5315
  }
@@ -4841,7 +5450,7 @@ class Json {
4841
5450
  return this.clone()._json();
4842
5451
  }
4843
5452
  _json() {
4844
- const q = this._wrap(this.__model.clone());
5453
+ const q = this._wrap(this.__table.clone());
4845
5454
  q._getOptional(
4846
5455
  raw(
4847
5456
  queryTypeWithLimitOne[this.query.returnType] ? `row_to_json("t".*)` : `COALESCE(json_agg(row_to_json("t".*)), '[]')`
@@ -5247,7 +5856,7 @@ class Update {
5247
5856
  ctx.resultAll = await handleResult(q, queryResult);
5248
5857
  if (ctx.updateLater) {
5249
5858
  await Promise.all(ctx.updateLaterPromises);
5250
- const t = this.__model.clone().transacting(q);
5859
+ const t = this.__table.clone().transacting(q);
5251
5860
  const keys = this.primaryKeys;
5252
5861
  t._whereIn(
5253
5862
  keys,
@@ -5496,7 +6105,7 @@ class QueryMethods {
5496
6105
  return this;
5497
6106
  }
5498
6107
  clone() {
5499
- const cloned = Object.create(this.__model);
6108
+ const cloned = Object.create(this.__table);
5500
6109
  cloned.query = getClonedQueryData(this.query);
5501
6110
  return cloned;
5502
6111
  }
@@ -5680,7 +6289,7 @@ class Db {
5680
6289
  this.whereQueryBuilder = WhereQueryBuilder;
5681
6290
  this.onQueryBuilder = OnQueryBuilder;
5682
6291
  var _a, _b;
5683
- this.__model = this;
6292
+ this.__table = this;
5684
6293
  const logger = options.logger || console;
5685
6294
  this.query = {
5686
6295
  adapter,
@@ -5792,5 +6401,5 @@ const createDb = (_a) => {
5792
6401
  return db;
5793
6402
  };
5794
6403
 
5795
- export { Adapter, Aggregate, ArrayColumn, ArrayOfColumnsObjects, BigIntColumn, BigSerialColumn, BitColumn, BitVaryingColumn, BooleanColumn, BoxColumn, ByteaColumn, CharColumn, CidrColumn, CircleColumn, Clear, ColumnInfoMethods, ColumnType, ColumnsObject, Create, DateBaseColumn, DateColumn, DateTimeBaseClass, DateTimeWithTimeZoneBaseClass, Db, DecimalBaseColumn, DecimalColumn, Delete, DoublePrecisionColumn, EMPTY_OBJECT, EnumColumn, For, From, Having, InetColumn, IntegerBaseColumn, IntegerColumn, IntervalColumn, JSONColumn, JSONTextColumn, Join, Json, LimitedTextBaseColumn, LineColumn, LsegColumn, MacAddr8Column, MacAddrColumn, MergeQueryMethods, MoneyColumn, MoreThanOneRowError, NotFoundError, NumberAsStringBaseColumn, NumberBaseColumn, OnConflictQueryBuilder, OnQueryBuilder, Operators, PathColumn, PluckResultColumnType, PointColumn, PolygonColumn, PormError, PormInternalError, QueryCallbacks, QueryError, QueryGet, QueryLog, QueryMethods, QueryUpsert, RawMethods, RealColumn, Select, SerialColumn, SmallIntColumn, SmallSerialColumn, TextBaseColumn, TextColumn, Then, TimeColumn, TimeWithTimeZoneColumn, TimestampColumn, TimestampWithTimeZoneColumn, Transaction, TransactionAdapter, TsQueryColumn, TsVectorColumn, UUIDColumn, UnhandledTypeError, Union, Update, VarCharColumn, VirtualColumn, Where, WhereQueryBuilder, With, XMLColumn, addOr, addOrNot, addParserForRawExpression, addParserForSelectItem, addParserToQuery, addQueryOn, addQueryOrOn, addWhere, addWhereIn, addWhereNot, aggregate1FunctionNames, anyShape, applyMixins, array, arrayToEnum, checkIfASimpleQuery, cloneQueryArrays, columnTypes, utils as columnUtils, constructType, createDb, createOperator, defaultsKey, discriminatedUnion, emptyObject, enumType, getClonedQueryData, getColumnTypes, getQueryAs, getQueryParsers, getRaw, getRawSql, getTableData, getValidEnumValues, getValueKey, handleResult, instanceOf, intersection, isQueryReturnsAll, isRaw, isRequiredRelationKey, joinTruthy, jsonTypes, lazy, literal, logColors, logParamToLogObject, makeRegexToFindInSql, makeSql, map, nativeEnum, newTableData, noop, notNullable, notNullish, nullable, nullish, object, optional, parseRecord, parseResult, processSelectArg, pushOrNewArray, pushOrNewArrayToObject, pushQueryArray, pushQueryOn, pushQueryOrOn, pushQueryValue, queryMethodByReturnType, queryTypeWithLimitOne, quote, raw, record, relationQueryKey, required, resetTableData, scalarTypes, set, setQueryObjectValue, toArray, toSql, toSqlCacheKey, tuple, union };
6404
+ export { Adapter, Aggregate, ArrayColumn, ArrayOfColumnsObjects, BigIntColumn, BigSerialColumn, BitColumn, BitVaryingColumn, BooleanColumn, BoxColumn, ByteaColumn, CharColumn, CidrColumn, CircleColumn, Clear, ColumnInfoMethods, ColumnType, ColumnsObject, Create, DateBaseColumn, DateColumn, DateTimeBaseClass, DateTimeWithTimeZoneBaseClass, Db, DecimalBaseColumn, DecimalColumn, Delete, DoublePrecisionColumn, EMPTY_OBJECT, EnumColumn, For, From, Having, InetColumn, IntegerBaseColumn, IntegerColumn, IntervalColumn, JSONColumn, JSONTextColumn, Join, Json, LimitedTextBaseColumn, LineColumn, LsegColumn, MacAddr8Column, MacAddrColumn, MergeQueryMethods, MoneyColumn, MoreThanOneRowError, NotFoundError, NumberAsStringBaseColumn, NumberBaseColumn, OnConflictQueryBuilder, OnQueryBuilder, Operators, PathColumn, PluckResultColumnType, PointColumn, PolygonColumn, PormError, PormInternalError, QueryCallbacks, QueryError, QueryGet, QueryLog, QueryMethods, QueryUpsert, RawMethods, RealColumn, Select, SerialColumn, SmallIntColumn, SmallSerialColumn, TextBaseColumn, TextColumn, Then, TimeColumn, TimeWithTimeZoneColumn, TimestampColumn, TimestampWithTimeZoneColumn, Transaction, TransactionAdapter, TsQueryColumn, TsVectorColumn, UUIDColumn, UnhandledTypeError, Union, Update, VarCharColumn, VirtualColumn, Where, WhereQueryBuilder, With, XMLColumn, addOr, addOrNot, addParserForRawExpression, addParserForSelectItem, addParserToQuery, addQueryOn, addQueryOrOn, addWhere, addWhereIn, addWhereNot, aggregate1FunctionNames, anyShape, applyMixins, array, arrayToEnum, checkIfASimpleQuery, cloneQueryArrays, columnChainToCode, columnCode, columnTypes, utils as columnUtils, constructType, createDb, createOperator, defaultsKey, discriminatedUnion, emptyObject, enumType, getClonedQueryData, getColumnTypes, getQueryAs, getQueryParsers, getRaw, getRawSql, getTableData, getValidEnumValues, getValueKey, handleResult, instanceOf, intersection, isQueryReturnsAll, isRaw, isRequiredRelationKey, joinTruthy, jsonTypes, lazy, literal, logColors, logParamToLogObject, makeRegexToFindInSql, makeSql, map, nativeEnum, newTableData, noop, notNullable, notNullish, nullable, nullish, object, optional, parseRecord, parseResult, processSelectArg, pushOrNewArray, pushOrNewArrayToObject, pushQueryArray, pushQueryOn, pushQueryOrOn, pushQueryValue, queryMethodByReturnType, queryTypeWithLimitOne, quote, raw, record, relationQueryKey, required, resetTableData, scalarTypes, set, setQueryObjectValue, singleQuote, toArray, toCode, toSql, toSqlCacheKey, tuple, union };
5796
6405
  //# sourceMappingURL=index.esm.js.map