@expressive/sql 0.4.3 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +53 -0
  2. package/dist/bin.d.ts +1 -0
  3. package/dist/bin.js +9 -0
  4. package/dist/bin.js.map +1 -0
  5. package/dist/cli.d.ts +6 -0
  6. package/dist/cli.js +80 -0
  7. package/dist/cli.js.map +1 -0
  8. package/dist/columns/Bool.d.ts +36 -0
  9. package/dist/columns/Bool.js +27 -0
  10. package/dist/columns/Bool.js.map +1 -0
  11. package/dist/columns/Num.d.ts +54 -0
  12. package/dist/columns/Num.js +37 -0
  13. package/dist/columns/Num.js.map +1 -0
  14. package/dist/columns/One.d.ts +24 -0
  15. package/dist/columns/One.js +14 -0
  16. package/dist/columns/One.js.map +1 -0
  17. package/dist/columns/Str.d.ts +35 -0
  18. package/dist/columns/Str.js +20 -0
  19. package/dist/columns/Str.js.map +1 -0
  20. package/dist/columns/Time.d.ts +47 -0
  21. package/dist/columns/Time.js +40 -0
  22. package/dist/columns/Time.js.map +1 -0
  23. package/dist/connection/Connection.d.ts +43 -0
  24. package/dist/connection/Connection.js +142 -0
  25. package/dist/connection/Connection.js.map +1 -0
  26. package/dist/connection/Generator.d.ts +32 -0
  27. package/dist/connection/Generator.js +209 -0
  28. package/dist/connection/Generator.js.map +1 -0
  29. package/dist/datatypes.d.ts +69 -0
  30. package/dist/datatypes.js +42 -0
  31. package/dist/datatypes.js.map +1 -0
  32. package/dist/dispatch.d.ts +6 -0
  33. package/dist/dispatch.js +44 -0
  34. package/dist/dispatch.js.map +1 -0
  35. package/dist/index.d.ts +11 -692
  36. package/dist/index.js +13 -1092
  37. package/dist/sqlite/SQLiteConnection.d.ts +48 -0
  38. package/dist/sqlite/SQLiteConnection.js +343 -0
  39. package/dist/sqlite/SQLiteConnection.js.map +1 -0
  40. package/dist/sqlite/SQLiteGenerator.d.ts +14 -0
  41. package/dist/sqlite/SQLiteGenerator.js +54 -0
  42. package/dist/sqlite/SQLiteGenerator.js.map +1 -0
  43. package/dist/sqlite/engine.d.ts +14 -0
  44. package/dist/sqlite/engine.js +104 -0
  45. package/dist/sqlite/engine.js.map +1 -0
  46. package/dist/utils.d.ts +5 -0
  47. package/dist/utils.js +8 -0
  48. package/dist/utils.js.map +1 -0
  49. package/package.json +62 -10
  50. package/dist/index.d.mts +0 -692
  51. package/dist/index.mjs +0 -1052
package/dist/index.mjs DELETED
@@ -1,1052 +0,0 @@
1
- // src/utils.ts
2
- function capitalize(string) {
3
- return string[0].toUpperCase() + string.slice(1);
4
- }
5
- function isIterable(obj) {
6
- return obj != null && typeof obj[Symbol.iterator] === "function";
7
- }
8
- function underscore(str) {
9
- return str.replace(/([a-z])([A-Z])/g, "$1_$2").toLowerCase();
10
- }
11
- function escape(value) {
12
- if (typeof value != "string")
13
- return value;
14
- const escaped = value.replace(/[\0\n\r\b\t\\'"\x1a]/g, (s) => s == "\0" ? "\\0" : s == "\n" ? "\\n" : s == "\r" ? "\\r" : s == "\b" ? "\\b" : s == " " ? "\\t" : s == "" ? "\\Z" : "\\" + s).replace(/[\x00-\x1f\x7f-\x9f]/g, (ch) => "\\x" + ch.charCodeAt(0).toString(16).padStart(2, "0"));
15
- return `'${escaped}'`;
16
- }
17
- var {
18
- assign,
19
- create,
20
- defineProperty,
21
- entries,
22
- freeze,
23
- getOwnPropertyDescriptor,
24
- getOwnPropertyNames,
25
- values
26
- } = Object;
27
-
28
- // src/type/Field.ts
29
- var Field = class {
30
- constructor() {
31
- this.type = "";
32
- this.unique = false;
33
- this.nullable = false;
34
- this.optional = false;
35
- this.absent = false;
36
- this.increment = false;
37
- }
38
- /** Real datatype of this field in database. */
39
- get datatype() {
40
- return this.type;
41
- }
42
- static new(...options) {
43
- return Object.assign(new this(), ...options.map((x) => typeof x === "string" ? { column: x } : x === null ? { nullable: true } : x));
44
- }
45
- /**
46
- * This method dictates behavior of this field when converted from a javascript context to SQL.
47
- *
48
- * Use this method to validate, sanitize or convert data before it is inserted into the database.
49
- */
50
- set(value) {
51
- return value;
52
- }
53
- /**
54
- * This method dictates behavior of this field when converted from a SQL context to javascript.
55
- *
56
- * Use this method to parse data incoming from the database itself. For example, you might convert
57
- * a TINYINT(1) field to a boolean, or a DATETIME field to a Date object.
58
- */
59
- get(value) {
60
- return value;
61
- }
62
- };
63
- defineProperty(Field, "does", {
64
- value: (callback) => callback
65
- });
66
-
67
- // src/columns/Bool.ts
68
- var BooleanColumn = class extends Field {
69
- get(value) {
70
- const [TRUE] = this.either || [1];
71
- return value === true || value === TRUE;
72
- }
73
- set(value) {
74
- const [TRUE, FALSE] = this.either || [1, 0];
75
- if (typeof value !== "boolean")
76
- throw "Value must be a boolean.";
77
- return value ? TRUE : FALSE;
78
- }
79
- };
80
- function Bool(...opts) {
81
- return Bool.Type.new(...opts);
82
- }
83
- Bool.Type = BooleanColumn;
84
-
85
- // src/columns/Num.ts
86
- var NumericColumn = class extends Field {
87
- set(value) {
88
- if (typeof value !== "number" || isNaN(value))
89
- throw `Got '${value}' but value must be a number.`;
90
- return value;
91
- }
92
- };
93
- function Num(...opts) {
94
- return Num.Type.new(...opts);
95
- }
96
- Num.Type = NumericColumn;
97
-
98
- // src/columns/One.ts
99
- var ForeignColumn = class extends Field {
100
- constructor() {
101
- super(...arguments);
102
- this.nullable = false;
103
- }
104
- set(value) {
105
- if (this.query?.tables.has(value))
106
- return value[this.reference.column];
107
- return value;
108
- }
109
- use(query) {
110
- const table = query.use(this.entity);
111
- query.where(table.id, "=", this);
112
- return table;
113
- }
114
- };
115
- function One(entity, ...options) {
116
- const field = "id";
117
- const column = underscore(entity.name) + "_" + field;
118
- const reference = entity.fields.get(field);
119
- return One.Type.new({ column, reference }, ...options, { entity });
120
- }
121
- One.Type = ForeignColumn;
122
-
123
- // src/columns/Str.ts
124
- var StringColumn = class extends Field {
125
- set(value) {
126
- if (typeof value !== "string")
127
- throw "Value must be a string.";
128
- if (this.length && value.length > this.length)
129
- throw `Value length ${value.length} exceeds maximum of ${this.length}.`;
130
- return value;
131
- }
132
- };
133
- function Str(...opts) {
134
- return Str.Type.new(...opts);
135
- }
136
- Str.Type = StringColumn;
137
-
138
- // src/columns/Time.ts
139
- var TimeColumn = class extends Field {
140
- get(value) {
141
- if (value instanceof Date)
142
- return value;
143
- return new Date(value.replace(/[-]/g, "/"));
144
- }
145
- set(value) {
146
- if (value === "NOW")
147
- return "CURRENT_TIMESTAMP";
148
- else if (value instanceof Date)
149
- return value.toISOString().slice(0, 19).replace("T", " ");
150
- else if (typeof value === "string")
151
- return value;
152
- else
153
- throw "Value must be a Date, string, or 'NOW'.";
154
- }
155
- };
156
- function Time(...opts) {
157
- return Time.Type.new(...opts);
158
- }
159
- Time.Type = TimeColumn;
160
-
161
- // src/connection/Connection.ts
162
- import { format } from "sql-formatter";
163
-
164
- // src/query/Builder.ts
165
- var Builder = class {
166
- constructor() {
167
- /**
168
- * Parameters which will be sent with query.
169
- * May either be placeholders for a template, or values
170
- * which the query deems unsafe to interpolate directly.
171
- */
172
- this.params = [];
173
- this.filters = new Group();
174
- this.pending = /* @__PURE__ */ new Set();
175
- this.order = /* @__PURE__ */ new Map();
176
- this.tables = /* @__PURE__ */ new Map();
177
- this.deletes = /* @__PURE__ */ new Set();
178
- this.updates = /* @__PURE__ */ new Map();
179
- this.inserts = /* @__PURE__ */ new Map();
180
- this.register = /* @__PURE__ */ new Map();
181
- }
182
- commit(returns) {
183
- if (this.returns)
184
- throw new Error("This query has already been committed.");
185
- this.pending.forEach((fn) => fn());
186
- this.pending.clear();
187
- if (typeof returns === "function")
188
- returns = returns();
189
- if (returns instanceof Field || returns instanceof Value) {
190
- this.returns = returns;
191
- } else if (returns) {
192
- let scan2 = function(obj, path) {
193
- getOwnPropertyNames(obj).forEach((key) => {
194
- const use = path ? `${path}.${key}` : key;
195
- let selects = obj[key];
196
- if (typeof selects == "function")
197
- selects = selects();
198
- if (selects instanceof Field || selects instanceof Value || typeof selects != "object")
199
- columns.set(use, selects);
200
- else
201
- scan2(selects, use);
202
- });
203
- };
204
- var scan = scan2;
205
- const columns = /* @__PURE__ */ new Map();
206
- scan2(returns);
207
- this.returns = columns;
208
- }
209
- }
210
- inject(args) {
211
- return Array.from({ length: args }, (_, i) => {
212
- const p = new Parameter(i);
213
- return () => {
214
- if (this.params.includes(p))
215
- throw new Error(`Parameter ${i} is already defined.`);
216
- else
217
- this.params.push(p);
218
- return p;
219
- };
220
- });
221
- }
222
- table(table) {
223
- const target = this.tables.get(table);
224
- return {
225
- delete: () => {
226
- this.deletes.add(target);
227
- },
228
- update: (data) => {
229
- const inserts = /* @__PURE__ */ new Map();
230
- Object.entries(data).forEach(([key, value]) => {
231
- const field = target.fields.get(key);
232
- if (value instanceof DataField)
233
- value.field = field;
234
- inserts.set(field, value);
235
- });
236
- this.updates.set(target, inserts);
237
- }
238
- };
239
- }
240
- compare(field) {
241
- const use = (op2) => (right, orEqual) => this.where(field, orEqual ? op2 + "=" : op2, right);
242
- return {
243
- equal: use("="),
244
- in: use("IN"),
245
- not: use("<>"),
246
- over: use(">"),
247
- under: use("<")
248
- };
249
- }
250
- field(field) {
251
- return {
252
- ...this.compare(field),
253
- asc: () => {
254
- this.order.set(field, "asc");
255
- },
256
- desc: () => {
257
- this.order.set(field, "desc");
258
- }
259
- };
260
- }
261
- andOr(...args) {
262
- const local = new Group();
263
- this.filters.add(local);
264
- for (const eq of args) {
265
- if (eq instanceof Cond && eq.restricted)
266
- throw new Error(
267
- `Cannot use ${eq.left} ${eq.op} ${eq.right} in a group.`
268
- );
269
- this.filters.delete(eq);
270
- local.add(eq);
271
- }
272
- return local;
273
- }
274
- use(type, arg2, ...rest) {
275
- const { fields, schema } = type;
276
- const { tables } = this;
277
- const proxy = {};
278
- const table = {
279
- name: type.table,
280
- fields: /* @__PURE__ */ new Map(),
281
- joins: [],
282
- proxy,
283
- optional: arg2 === true,
284
- toString() {
285
- return this.alias ? this.name + " " + this.alias : this.name;
286
- }
287
- };
288
- if (rest.length)
289
- arg2 = this.with([arg2, ...rest]);
290
- if (schema) {
291
- table.alias = "T" + tables.size;
292
- table.name = schema + "." + table.name;
293
- }
294
- tables.set(proxy, table);
295
- fields.forEach((field, key) => {
296
- field = create(field);
297
- field.query = this;
298
- field.table = table;
299
- field.toString = () => `${table.alias || table.name}.${field.column}`;
300
- table.fields.set(key, field);
301
- this.register.set(uid(), field);
302
- let value;
303
- defineProperty(proxy, key, {
304
- get: () => value || (value = field.use ? field.use(this) : field)
305
- });
306
- });
307
- if (typeof arg2 == "object")
308
- this.insert(table, arg2);
309
- freeze(proxy);
310
- return table.proxy;
311
- }
312
- insert(table, input) {
313
- const inserts = /* @__PURE__ */ new Map();
314
- for (const [key, field] of table.fields) {
315
- let value = input[key];
316
- if (value instanceof DataField)
317
- value.field = field;
318
- else
319
- value = this.digest(value, field);
320
- if (value !== void 0)
321
- inserts.set(field, value);
322
- }
323
- this.inserts.set(table, inserts);
324
- }
325
- digest(value, field) {
326
- if (value != null)
327
- try {
328
- return field.set(value);
329
- } catch (err) {
330
- let message = `Provided value for ${field.parent}.${field.column} but not acceptable for type ${field.datatype}.`;
331
- if (err instanceof Error) {
332
- err.message = message + "\n" + err.message;
333
- throw err;
334
- }
335
- if (typeof err == "string")
336
- message += "\n" + err;
337
- throw new Error(message);
338
- }
339
- else if (!field.nullable && !field.optional && !field.increment)
340
- throw new Error(
341
- `Can't assign to \`${field.parent}.${field.property}\`. A value is required but got ${value}.`
342
- );
343
- }
344
- where(left, op2, right) {
345
- if (typeof right == "function")
346
- right = right();
347
- if (right === null && !left.nullable)
348
- throw new Error(`Column ${left} is not nullable.`);
349
- if (right instanceof Field || right instanceof DataField) {
350
- const where = new Cond(left, op2, right, true);
351
- if (right instanceof DataField) {
352
- right.field = left;
353
- right.table.joins.push(where);
354
- } else
355
- left.table.joins.push(where);
356
- return where;
357
- }
358
- if (right instanceof Parameter) {
359
- right.digest = left.set.bind(left);
360
- }
361
- return this.filters.add(left, op2, right);
362
- }
363
- with(data) {
364
- return new DataTable(this, data).proxy;
365
- }
366
- accept(args) {
367
- return Array.from(this.params || [], (p) => p.toParam(args));
368
- }
369
- parse(raw) {
370
- const { returns: selects } = this;
371
- if (selects instanceof Map) {
372
- const values2 = {};
373
- selects.forEach((field, column) => {
374
- const path = column.split(".");
375
- const property = path.pop();
376
- let target = values2;
377
- for (const step of path)
378
- target = target[step] || (target[step] = {});
379
- const value2 = raw[column];
380
- if (value2 === void 0)
381
- return;
382
- target[property] = value2 === null && field instanceof Field && field.nullable ? null : field instanceof Field ? field.get(value2) : selects instanceof Parameter ? selects.digest(value2) : value2;
383
- });
384
- return values2;
385
- }
386
- const value = values(raw)[0];
387
- if (selects instanceof Parameter)
388
- return selects.digest(value);
389
- if (selects instanceof Field)
390
- return selects.get(value);
391
- return raw;
392
- }
393
- };
394
- var Value = class {
395
- };
396
- var Parameter = class extends Value {
397
- constructor(arg) {
398
- super();
399
- this.index = -1;
400
- if (typeof arg == "number")
401
- this.index = arg;
402
- else if (typeof arg == "function")
403
- this.toParam = arg;
404
- }
405
- digest(value) {
406
- return value;
407
- }
408
- toParam(from) {
409
- return this.digest(from[this.index]);
410
- }
411
- };
412
- var DataField = class extends Value {
413
- constructor(column, table) {
414
- super();
415
- this.column = column;
416
- this.table = table;
417
- }
418
- get datatype() {
419
- return this.field?.datatype || "";
420
- }
421
- };
422
- var DataTable = class extends Parameter {
423
- constructor(parent, input) {
424
- super();
425
- this.parent = parent;
426
- this.output = [];
427
- this.used = /* @__PURE__ */ new Set();
428
- this.joins = [];
429
- this.optional = false;
430
- this.fields = /* @__PURE__ */ new Map();
431
- this.name = "input";
432
- const proxy = {};
433
- const keys = /* @__PURE__ */ new Set();
434
- for (const item of input)
435
- Object.keys(item).forEach(keys.add, keys);
436
- for (const key of keys) {
437
- const value = new DataField(key, this);
438
- defineProperty(proxy, key, {
439
- enumerable: true,
440
- get: () => {
441
- this.used.add(value);
442
- return value;
443
- }
444
- });
445
- }
446
- this.proxy = proxy;
447
- this.index = parent.params.length;
448
- parent.params.push(this);
449
- parent.tables.set(proxy, this);
450
- parent.pending.add(() => {
451
- Array.from(input, (entry, index) => {
452
- const emit = {};
453
- for (const { column, field } of this.used) {
454
- if (!field)
455
- throw new Error(`Field for input ${column} is not defined.`);
456
- try {
457
- emit[column] = this.parent.digest(entry[column], field);
458
- } catch (err) {
459
- let message = `A provided value at \`${column}\` at index [${index}] is not acceptable.`;
460
- if (err instanceof Error) {
461
- err.message = message + "\n" + err.message;
462
- throw err;
463
- }
464
- if (typeof err == "string")
465
- message += "\n" + err;
466
- throw new Error(message);
467
- }
468
- }
469
- this.output.push(emit);
470
- });
471
- });
472
- }
473
- toParam() {
474
- return Array.from(this.output, (row) => Array.from(this.used, (field) => row[field.column]));
475
- }
476
- };
477
- var Cond = class {
478
- constructor(left, op2, right, restricted = false) {
479
- this.left = left;
480
- this.op = op2;
481
- this.right = right;
482
- this.restricted = restricted;
483
- }
484
- };
485
- var Group = class {
486
- constructor() {
487
- this.children = /* @__PURE__ */ new Set();
488
- }
489
- add(left, op2, right) {
490
- if (left instanceof Field)
491
- left = new Cond(left, op2, right);
492
- this.children.add(left);
493
- return left;
494
- }
495
- delete(child) {
496
- this.children.delete(child);
497
- }
498
- get size() {
499
- return this.children.size;
500
- }
501
- };
502
- var QueryTemplate = class extends Value {
503
- constructor(from, parent) {
504
- super();
505
- this.from = from;
506
- this.parts = from.split(/(\0[a-zA-Z0-9]+)/).filter(Boolean).map((part) => parent.register.get(part) || part);
507
- }
508
- };
509
- function uid() {
510
- return "\0" + Math.random().toString(32).slice(2, 7);
511
- }
512
-
513
- // src/query/Computed.ts
514
- function op(operator, rank, unary) {
515
- return (left, right) => {
516
- return new Computed(operator, left, unary ? void 0 : right, rank);
517
- };
518
- }
519
- var MathOps = {
520
- add: op("+", 4),
521
- sub: op("-", 4),
522
- mul: op("*", 5),
523
- div: op("/", 5),
524
- mod: op("%", 5),
525
- neg: op("-", 7, true),
526
- pos: op("+", 7, true)
527
- };
528
- var BitWise = {
529
- not: op("~", 6, true),
530
- left: op("<<", 3),
531
- right: op(">>", 3),
532
- and: op("&", 2),
533
- or: op("|", 0),
534
- xor: op("^", 1)
535
- };
536
- var Computed = class extends Value {
537
- constructor(operator, value, right, rank = 0) {
538
- super();
539
- this.operator = operator;
540
- this.rank = rank;
541
- if (right === void 0)
542
- this.right = value;
543
- else {
544
- this.left = value;
545
- this.right = right;
546
- }
547
- }
548
- };
549
-
550
- // src/connection/Generator.ts
551
- var Generator = class {
552
- constructor(query) {
553
- this.query = query;
554
- this.cte = /* @__PURE__ */ new Map();
555
- }
556
- toString() {
557
- const parts = [
558
- this.with(),
559
- this.insert() || this.update() || this.delete() || this.select(),
560
- this.where(),
561
- this.order(),
562
- this.limit()
563
- ];
564
- return parts.flat(Infinity).filter(Boolean).join(" ");
565
- }
566
- escape(name) {
567
- return String(name).split(".").map((x) => `\`${x}\``).join(".");
568
- }
569
- insert() {
570
- const { inserts, tables } = this.query;
571
- if (!inserts.size)
572
- return false;
573
- const [[table, data]] = inserts;
574
- const keys = [];
575
- const values2 = [];
576
- for (const [field, value] of data) {
577
- keys.push(this.escape(field.column));
578
- values2.push(this.value(value));
579
- }
580
- return [
581
- "INSERT INTO",
582
- this.escape(table.name),
583
- `(${keys}) SELECT ${values2}`,
584
- tables.size > 1 && this.from()
585
- ];
586
- }
587
- with() {
588
- const cte = [];
589
- this.query.tables.forEach((table) => {
590
- if (table instanceof DataTable)
591
- cte.push(`${this.escape(table.name)} AS (${this.jsonTable(table)})`);
592
- });
593
- if (cte.length)
594
- return "WITH " + cte.join();
595
- }
596
- value(input) {
597
- if (input instanceof Value || input instanceof Field)
598
- return this.reference(input);
599
- if (typeof input === "string")
600
- return `'${input.replace(/'/g, "\\'")}'`;
601
- return String(input);
602
- }
603
- jsonTable(table) {
604
- throw new Error("Not implemented.");
605
- }
606
- computed(from) {
607
- let { left, operator, right } = from;
608
- if (right instanceof Computed) {
609
- const value = this.computed(right);
610
- right = right.rank <= from.rank ? `(${value})` : value;
611
- }
612
- if (!left)
613
- return `${operator}${right}`;
614
- if (left instanceof Computed) {
615
- const value = this.computed(left);
616
- left = left.rank < from.rank ? `(${value})` : value;
617
- }
618
- return `${left} ${operator} ${right}`;
619
- }
620
- joins(main) {
621
- const output = [];
622
- const applied = /* @__PURE__ */ new Set();
623
- for (const table of this.query.tables.values()) {
624
- if (table === main)
625
- continue;
626
- const { alias, name, optional } = table;
627
- if (table.joins.length === 0)
628
- throw new Error(`Table ${name} has no joins.`);
629
- const joins = table.joins.filter((x) => {
630
- if (!applied.has(x)) {
631
- applied.add(x);
632
- return true;
633
- }
634
- });
635
- const mode = optional ? "LEFT" : "INNER";
636
- const as = this.escape(name) + (alias ? ` ${this.escape(alias)}` : "");
637
- const conds = joins.map((x) => this.filter(x.left, x.op, x.right));
638
- output.push(`${mode} JOIN ${as} ON ${conds.join(" AND ")}`);
639
- }
640
- if (output.length)
641
- return output.join(" ");
642
- }
643
- set(updates) {
644
- const sets = [];
645
- for (const [_table, data] of updates)
646
- for (let [field, value] of data) {
647
- if (value === void 0)
648
- continue;
649
- if (value instanceof Field || value instanceof Value) {
650
- value = this.reference(value);
651
- } else if (value === null) {
652
- if (field.nullable)
653
- value = "NULL";
654
- else
655
- throw new Error(`Column ${field} is not nullable.`);
656
- } else
657
- value = escape(field.set(value));
658
- sets.push(`${this.escape(field.column)} = ${value}`);
659
- }
660
- if (!sets.length)
661
- throw new Error("Update contains no values.");
662
- return `SET ${sets}`;
663
- }
664
- update(multiTableAllowed = false) {
665
- const { updates } = this.query;
666
- if (!updates.size)
667
- return;
668
- if (updates.size > 1 && !multiTableAllowed)
669
- throw new Error("Engine does not support multi-table updates.");
670
- const [main] = updates.keys();
671
- return [
672
- "UPDATE",
673
- this.escape(main),
674
- this.joins(main),
675
- this.set(updates)
676
- ];
677
- }
678
- delete() {
679
- const { query } = this;
680
- const [main] = this.query.deletes;
681
- if (!main)
682
- return;
683
- const { alias, name } = main;
684
- const target = query.tables.size > 1 && (alias || name);
685
- return ["DELETE", target, "FROM", this.escape(name), this.joins(main)];
686
- }
687
- reference(from) {
688
- if (from instanceof DataField)
689
- return this.escape(from.table.name + "." + from.column);
690
- if (from instanceof QueryTemplate)
691
- return from.parts.map((x) => String(this.reference(x))).join("");
692
- if (from instanceof Computed)
693
- return this.computed(from);
694
- if (from instanceof Parameter)
695
- return this.param(from);
696
- if (from instanceof Field) {
697
- const column = this.escape(from.column);
698
- const { table } = from;
699
- if (table)
700
- return this.escape(table.alias || table.name) + "." + column;
701
- }
702
- return String(from);
703
- }
704
- select() {
705
- const { returns, tables } = this.query;
706
- const [main] = tables.values();
707
- const selection = returns instanceof Map ? (
708
- // TODO: simplify this
709
- Array.from(returns).filter(([_alias, field]) => {
710
- return field instanceof Field ? !field.absent : true;
711
- }).map(([alias, field]) => this.value(field) + ` AS "${alias}"`).join(", ")
712
- ) : returns ? this.reference(returns) : "COUNT(*)";
713
- return [
714
- "SELECT",
715
- selection,
716
- this.from(),
717
- this.joins(main)
718
- ];
719
- }
720
- from() {
721
- const [main] = this.query.tables.values();
722
- if (main)
723
- return ["FROM", this.escape(main.name), main.alias];
724
- }
725
- param(from) {
726
- return "?";
727
- }
728
- filter(left, op2, right) {
729
- const raw = (value) => escape(left.set(value));
730
- if (right === null) {
731
- right === "NULL";
732
- if (op2 == "=")
733
- op2 = "IS";
734
- else if (op2 == "!=")
735
- op2 = "IS NOT";
736
- else
737
- throw new Error("Cannot compare NULL with " + op2);
738
- } else if (right instanceof Array)
739
- right = `(${right.map(raw)})`;
740
- else if (right instanceof Field || right instanceof Value)
741
- right = this.reference(right);
742
- else
743
- right = raw(right);
744
- return `${this.reference(left)} ${op2} ${right}`;
745
- }
746
- where() {
747
- const { filters } = this.query;
748
- if (!filters.size) return;
749
- const combine = (group, or) => {
750
- return Array.from(group.children, (cond, i) => {
751
- if (cond instanceof Group) {
752
- const inner = combine(cond, !or);
753
- const first = or !== false && i === 0;
754
- return cond.size === 1 || first ? inner : `(${inner})`;
755
- }
756
- return this.filter(cond.left, cond.op, cond.right);
757
- }).join(or ? " OR " : " AND ");
758
- };
759
- return ["WHERE", combine(filters)];
760
- }
761
- order() {
762
- const { order } = this.query;
763
- if (order.size)
764
- return "ORDER BY " + Array.from(order, ([x, y]) => `${this.reference(x)} ${y}`);
765
- }
766
- limit() {
767
- const { limit } = this.query;
768
- if (limit)
769
- return ["LIMIT", limit];
770
- }
771
- };
772
-
773
- // src/connection/Connection.ts
774
- var Connection = class {
775
- constructor(using) {
776
- this.ready = false;
777
- this.using = new Set(values(using).map((type) => {
778
- if (type.hasOwnProperty("connection"))
779
- throw new Error(`Type ${type.name} already has assigned connection.`);
780
- type.connection = this;
781
- return type;
782
- }));
783
- }
784
- query(factory) {
785
- const connection = this;
786
- return Query(function(where, fn) {
787
- where.connection = connection;
788
- return factory.call(this, where, fn);
789
- });
790
- }
791
- async then(onfulfilled, onrejected) {
792
- return (this.ready ? Promise.resolve() : this.sync()).then(() => {
793
- Object.defineProperty(this, "then", { value: void 0 });
794
- if (onfulfilled)
795
- onfulfilled(this);
796
- }).catch(onrejected);
797
- }
798
- async close() {
799
- for (const type of this.using)
800
- delete type.connection;
801
- }
802
- };
803
- var NoConnection = class extends Connection {
804
- constructor() {
805
- super([]);
806
- }
807
- get schema() {
808
- throw new Error("No connection to generate schema.");
809
- }
810
- prepare(builder) {
811
- const template = String(new Generator(builder));
812
- async function run() {
813
- throw new Error("No connection to run query.");
814
- }
815
- return {
816
- all: run,
817
- get: run,
818
- run,
819
- toString() {
820
- return pretty(template);
821
- }
822
- };
823
- }
824
- async sync() {
825
- return this;
826
- }
827
- async close() {
828
- return;
829
- }
830
- };
831
- function pretty(sql) {
832
- return format(sql, { keywordCase: "upper" }).replace(/ - > > /g, " ->> ").replace(/`([a-zA-Z][a-zA-Z0-9_]*)`/g, "$1");
833
- }
834
- Connection.None = new NoConnection();
835
-
836
- // src/type/Primary.ts
837
- var PrimaryColumn = class extends Field {
838
- constructor() {
839
- super(...arguments);
840
- this.type = "integer";
841
- this.nullable = false;
842
- this.optional = true;
843
- this.primary = true;
844
- this.unique = true;
845
- this.increment = true;
846
- }
847
- init(property, parent) {
848
- const { tableName, tableSchema, columnName } = this;
849
- if (tableName)
850
- parent.table = typeof tableName == "function" ? tableName(parent) : tableName;
851
- if (tableSchema)
852
- parent.schema = typeof tableSchema == "function" ? tableSchema(parent) : tableSchema;
853
- if (columnName)
854
- parent.fields.forEach((field, property2) => {
855
- field.column = columnName(property2, field, parent);
856
- });
857
- }
858
- };
859
- function Primary(...opts) {
860
- return PrimaryColumn.new(...opts);
861
- }
862
-
863
- // src/type/Table.ts
864
- var REGISTER = /* @__PURE__ */ new Map();
865
- var _Table = class _Table {
866
- constructor() {
867
- /**
868
- * Primary key of this entity.
869
- * May be any name in the actual database, however requred to be `id` as property of this type.
870
- */
871
- this.id = Primary();
872
- }
873
- static get fields() {
874
- let fields = REGISTER.get(this);
875
- if (!fields) {
876
- fields = /* @__PURE__ */ new Map();
877
- defineProperty(this, "fields", { value: fields });
878
- const reference = new this();
879
- for (const key in reference) {
880
- const { value } = getOwnPropertyDescriptor(reference, key);
881
- if (value instanceof Field) {
882
- fields.set(key, value);
883
- if (!value.column)
884
- value.column = underscore(key);
885
- } else throw new Error(
886
- `Entities do not support normal values, only fields. Did you forget to import \`${capitalize(typeof value)}\`?`
887
- );
888
- }
889
- fields.forEach((field, key) => {
890
- field.parent = this;
891
- field.property = key;
892
- if (field.init)
893
- field.init(key, this);
894
- });
895
- }
896
- return fields;
897
- }
898
- static get table() {
899
- return this.table = underscore(this.name.replace(/\d+$/, ""));
900
- }
901
- static set table(value) {
902
- defineProperty(this, "table", { value });
903
- }
904
- static toString() {
905
- return this.name;
906
- }
907
- static is(obj) {
908
- return typeof obj === "function" && obj.prototype instanceof _Table;
909
- }
910
- static insert(arg1, arg2) {
911
- let data;
912
- if (typeof arg2 == "function") {
913
- if (typeof arg1 == "number")
914
- data = Array.from({ length: arg1 }, (_, i) => arg2(i));
915
- else if (isIterable(arg1))
916
- data = Array.from(arg1, arg2);
917
- else
918
- throw new Error("Map function needs an input iterable or a number to generate data.");
919
- } else if (isIterable(arg1))
920
- data = Array.from(arg1);
921
- else if (typeof arg1 == "object")
922
- data = [arg1];
923
- else
924
- throw new Error("Invalid input for insert method.");
925
- return Query((where) => {
926
- where(this, ...data);
927
- });
928
- }
929
- static get(arg1, arg2) {
930
- const limit = typeof arg1 == "number" ? arg1 : void 0;
931
- const query = typeof arg1 == "function" ? arg1 : arg2;
932
- return Query((where) => {
933
- const self = where(this);
934
- if (limit)
935
- where(limit);
936
- return typeof query == "function" && query(self, where) || self;
937
- });
938
- }
939
- static one(query) {
940
- return Query((where) => {
941
- const self = where(this);
942
- if (typeof query == "function")
943
- return query(self, where) || self;
944
- if (typeof query == "number")
945
- where(self.id).equal(query);
946
- else
947
- where(self.id).desc();
948
- return self;
949
- }).one(true);
950
- }
951
- };
952
- _Table.schema = "";
953
- var Table2 = _Table;
954
-
955
- // src/query/Query.ts
956
- function Query(factory) {
957
- let connection = void 0;
958
- function where(arg1) {
959
- if (Table2.is(arg1)) {
960
- if (!connection)
961
- connection = arg1.connection;
962
- else if (connection !== arg1.connection)
963
- throw new Error(
964
- `Joined entity ${arg1} does not share a connection with other tables in Query.`
965
- );
966
- return builder.use(arg1, ...Array.from(arguments).slice(1));
967
- }
968
- if (arg1 instanceof Field)
969
- return builder.field(arg1);
970
- if (builder.tables.has(arg1))
971
- return builder.table(arg1);
972
- if (arg1 instanceof Cond || arg1 instanceof Group)
973
- return builder.andOr(...arguments);
974
- if (typeof arg1 == "number") {
975
- builder.limit = arg1;
976
- return;
977
- }
978
- if (typeof arg1 == "string")
979
- return new QueryTemplate(arg1, builder);
980
- if (Symbol.iterator in arg1)
981
- return builder.with(arg1);
982
- throw new Error(`Argument ${arg1} is not a query argument.`);
983
- }
984
- defineProperty(where, "connection", {
985
- get() {
986
- return connection;
987
- },
988
- set(conn) {
989
- connection = conn;
990
- }
991
- });
992
- const builder = new Builder();
993
- const fn = factory.length > 1 ? assign((template) => new QueryTemplate(template, builder), Query.fn) : void 0;
994
- let result = factory.call(builder, where, fn);
995
- let args;
996
- if (typeof result === "function") {
997
- const params = builder.inject(args = result.length);
998
- result = result(...params);
999
- }
1000
- builder.commit(result);
1001
- if (!connection)
1002
- connection = Connection.None;
1003
- const statement = connection.prepare(builder);
1004
- const runner = (...params) => {
1005
- const get = () => statement.all(params).then((a) => a.map((x) => builder.parse(x)));
1006
- const query = create(Query.prototype);
1007
- params = builder.accept(params);
1008
- assign(query, {
1009
- params,
1010
- toString: statement.toString,
1011
- then(resolve, reject) {
1012
- const run = builder.returns ? get() : statement.run(params);
1013
- return run.then(resolve).catch(reject);
1014
- }
1015
- });
1016
- if (builder.returns)
1017
- assign(query, {
1018
- get,
1019
- async one(orFail) {
1020
- const res = await statement.get();
1021
- if (res)
1022
- return builder.parse(res);
1023
- if (orFail)
1024
- throw new Error("Query returned no results.");
1025
- }
1026
- });
1027
- return query;
1028
- };
1029
- if (typeof args == "number") {
1030
- runner.toString = statement.toString;
1031
- return runner;
1032
- }
1033
- return runner();
1034
- }
1035
- Query.Builder = Builder;
1036
- Query.fn = { ...MathOps, bit: BitWise };
1037
- export {
1038
- Bool,
1039
- Builder,
1040
- Connection,
1041
- DataTable,
1042
- Field,
1043
- Generator,
1044
- Num,
1045
- One,
1046
- Parameter,
1047
- Primary,
1048
- Query,
1049
- Str,
1050
- Table2 as Table,
1051
- Time
1052
- };