@expressive/sql 0.4.4 → 0.6.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 (52) hide show
  1. package/README.md +54 -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 +37 -0
  9. package/dist/columns/Bool.js +28 -0
  10. package/dist/columns/Bool.js.map +1 -0
  11. package/dist/columns/Num.d.ts +59 -0
  12. package/dist/columns/Num.js +42 -0
  13. package/dist/columns/Num.js.map +1 -0
  14. package/dist/columns/One.d.ts +25 -0
  15. package/dist/columns/One.js +15 -0
  16. package/dist/columns/One.js.map +1 -0
  17. package/dist/columns/Str.d.ts +36 -0
  18. package/dist/columns/Str.js +21 -0
  19. package/dist/columns/Str.js.map +1 -0
  20. package/dist/columns/Time.d.ts +52 -0
  21. package/dist/columns/Time.js +45 -0
  22. package/dist/columns/Time.js.map +1 -0
  23. package/dist/connection/Connection.d.ts +61 -0
  24. package/dist/connection/Connection.js +104 -0
  25. package/dist/connection/Connection.js.map +1 -0
  26. package/dist/connection/Generator.d.ts +68 -0
  27. package/dist/connection/Generator.js +242 -0
  28. package/dist/connection/Generator.js.map +1 -0
  29. package/dist/datatypes.d.ts +102 -0
  30. package/dist/datatypes.js +47 -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 +12 -692
  36. package/dist/index.js +13 -1092
  37. package/dist/sqlite/SQLiteConnection.d.ts +83 -0
  38. package/dist/sqlite/SQLiteConnection.js +395 -0
  39. package/dist/sqlite/SQLiteConnection.js.map +1 -0
  40. package/dist/sqlite/SQLiteGenerator.d.ts +15 -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 +47 -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 +64 -11
  50. package/skills/expressive-sql/SKILL.md +136 -0
  51. package/dist/index.d.mts +0 -692
  52. package/dist/index.mjs +0 -1052
@@ -0,0 +1,104 @@
1
+ import "../columns/Bool.js";
2
+ import "../columns/Num.js";
3
+ import "../columns/One.js";
4
+ import "../columns/Str.js";
5
+ import "../columns/Time.js";
6
+ import { Connection as Connection$1 } from "@expressive/orm";
7
+ import { Builder, Parameter } from "@expressive/orm/driver";
8
+
9
+ //#region src/connection/Connection.ts
10
+ function ref({ schema, table }) {
11
+ return schema ? `${schema}.${table}` : table;
12
+ }
13
+ /**
14
+ * Base class of a SQL driver - implements orm's floor as queries through `prepare`.
15
+ *
16
+ * The floor is `select`, `insert`, `update` and `remove`.
17
+ *
18
+ * A dialect supplies `schema`, `prepare`, `sync` and `plan`, and `transact` to enable `transaction`.
19
+ * Each statement throws when no bound or loaded class owns its table.
20
+ */
21
+ var Connection = class extends Connection$1 {
22
+ async select(table, constraints, limit, offset) {
23
+ const { builder, target, bind, run } = statement(this, table);
24
+ for (const [column, op, value] of constraints) {
25
+ const field = lookup(target, column);
26
+ if (op === "asc" || op === "desc") builder.order.set(field, op);
27
+ else if (op === "IS NULL") builder.filters.add(field, "=", null);
28
+ else if (op === "IS NOT NULL") builder.filters.add(field, "<>", null);
29
+ else if (value === null) builder.filters.add(field, op, null);
30
+ else builder.filters.add(field, op, Array.isArray(value) ? value.map(bind) : bind(value));
31
+ }
32
+ builder.limit = limit;
33
+ builder.offset = offset;
34
+ builder.commit(target.proxy);
35
+ return (await this.prepare(builder).all(run())).map((raw) => decode(builder, raw));
36
+ }
37
+ async insert(table, data, returns, conflict) {
38
+ const { builder, target, bind, run } = statement(this, table);
39
+ const values = /* @__PURE__ */ new Map();
40
+ for (const field of target.fields.values()) if (field.column in data) values.set(field, bind(data[field.column]));
41
+ builder.inserts.set(target, values);
42
+ if (conflict) builder.conflict = {
43
+ on: conflict.on.map((column) => lookup(target, column)),
44
+ update: conflict.update?.map((column) => lookup(target, column)),
45
+ set: new Map(Object.entries(conflict.set || {}).map(([column, value]) => [lookup(target, column), bind(value)]))
46
+ };
47
+ if (!returns) return this.prepare(builder).run(run());
48
+ builder.commit(target.proxy);
49
+ const [row] = await this.prepare(builder).all(run());
50
+ return row && decode(builder, row);
51
+ }
52
+ async update(table, id, data) {
53
+ const { builder, target, bind, run } = statement(this, table);
54
+ const values = /* @__PURE__ */ new Map();
55
+ for (const column in data) values.set(lookup(target, column), bind(data[column]));
56
+ builder.updates.set(target, values);
57
+ identify(builder, target, id, bind);
58
+ await this.prepare(builder).run(run());
59
+ }
60
+ async remove(table, id) {
61
+ const { builder, target, bind, run } = statement(this, table);
62
+ builder.deletes.add(target);
63
+ identify(builder, target, id, bind);
64
+ await this.prepare(builder).run(run());
65
+ }
66
+ };
67
+ function identify(builder, target, id, bind) {
68
+ const { parts } = target.fields.get("id");
69
+ if (parts) parts.forEach((part, i) => builder.filters.add(lookup(target, part.column), "=", bind(id[i])));
70
+ else builder.filters.add(target.fields.get("id"), "=", bind(id));
71
+ }
72
+ function statement(connection, table) {
73
+ const type = [...connection.using, ...connection._loaded.keys()].find((type) => ref(type) === table);
74
+ if (!type) throw new Error(`Table ${table} is not used by this connection.`);
75
+ const builder = new Builder();
76
+ const target = builder.tables.get(builder.use(type));
77
+ const params = [];
78
+ return {
79
+ builder,
80
+ target,
81
+ bind(value) {
82
+ const param = new Parameter(params.length);
83
+ params.push(value);
84
+ builder.params.push(param);
85
+ return param;
86
+ },
87
+ run: () => builder.accept(params)
88
+ };
89
+ }
90
+ function lookup(table, column) {
91
+ for (const field of table.fields.values()) if (field.column === column) return field;
92
+ throw new Error(`Column ${column} does not exist in ${table.name}.`);
93
+ }
94
+ function decode(builder, raw) {
95
+ const row = {};
96
+ builder.returns.forEach((field, key) => {
97
+ row[field.column] = raw[key];
98
+ });
99
+ return row;
100
+ }
101
+
102
+ //#endregion
103
+ export { Connection };
104
+ //# sourceMappingURL=Connection.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Connection.js","names":["Base"],"sources":["../../src/connection/Connection.ts"],"sourcesContent":["import '../columns/Bool';\nimport '../columns/Num';\nimport '../columns/One';\nimport '../columns/Str';\nimport '../columns/Time';\n\nimport { Connection as Base, Field, Query, Type } from '@expressive/orm';\nimport { Builder, Parameter } from '@expressive/orm/driver';\n\ndeclare namespace Connection {\n type Types = Base.Types;\n\n type Ready<T extends Connection = Connection> = Base.Ready<T>;\n\n type Change = Base.Change;\n\n type Conflict = Base.Conflict;\n\n type Key = Base.Key;\n\n /** An open transaction's journal. */\n type Transaction = Base.Journal;\n\n /** One change `sync` would make. */\n interface Step {\n table: string;\n /** Column the step adds or indexes. Absent for a table step. */\n column?: string;\n /** What it does, like `create table user`. */\n action: string;\n /** The mismatch it resolves - what `sync(false)` reports. */\n reason: string;\n /** Statements applying it. */\n sql: string[];\n }\n\n /** What `sync` would do, and what stops it. */\n interface Plan {\n steps: Step[];\n /** Mismatches `sync` cannot fix. Any makes it throw. */\n problems: string[];\n }\n}\n\nfunction ref({ schema, table }: Query.Table){\n return schema ? `${schema}.${table}` : table;\n}\n\n/**\n * Base class of a SQL driver - implements orm's floor as queries through `prepare`.\n *\n * The floor is `select`, `insert`, `update` and `remove`.\n *\n * A dialect supplies `schema`, `prepare`, `sync` and `plan`, and `transact` to enable `transaction`.\n * Each statement throws when no bound or loaded class owns its table.\n */\nabstract class Connection extends Base {\n /** DDL creating every bound class's table and indexes. */\n abstract get schema(): string;\n\n /**\n * Bring the database in line with the bound classes, then mark the connection ready.\n *\n * Creates missing tables, columns and indexes. `fix` false changes nothing and throws for anything missing.\n * `force` also converts columns whose type or nullability drifted. Throws for any problem `plan` reports.\n */\n abstract sync(fix?: boolean, force?: boolean): Promise<this>;\n\n /** List what `sync` would change, and what it could not, without applying anything. */\n abstract plan(force?: boolean): Promise<Connection.Plan>;\n\n /** Compile a `Query` builder to a statement in this dialect. */\n abstract prepare(builder: Builder): Builder.Statement;\n\n async select(table: string, constraints: Type.Constraint[], limit?: number, offset?: number){\n const { builder, target, bind, run } = statement(this, table);\n\n for (const [column, op, value] of constraints) {\n const field = lookup(target, column);\n\n if (op === 'asc' || op === 'desc')\n builder.order.set(field, op);\n else if (op === 'IS NULL')\n builder.filters.add(field, '=', null);\n else if (op === 'IS NOT NULL')\n builder.filters.add(field, '<>', null);\n else if (value === null)\n builder.filters.add(field, op, null);\n else\n builder.filters.add(field, op, Array.isArray(value) ? value.map(bind) : bind(value));\n }\n\n builder.limit = limit;\n builder.offset = offset;\n builder.commit(target.proxy);\n\n const rows = await this.prepare(builder).all(run());\n\n return rows.map(raw => decode(builder, raw));\n }\n\n async insert(table: string, data: Record<string, any>, returns?: boolean, conflict?: Connection.Conflict){\n const { builder, target, bind, run } = statement(this, table);\n const values: Builder.Insert = new Map();\n\n for (const field of target.fields.values())\n if (field.column in data)\n values.set(field, bind(data[field.column]));\n\n builder.inserts.set(target, values);\n\n if (conflict)\n builder.conflict = {\n on: conflict.on.map(column => lookup(target, column)),\n update: conflict.update?.map(column => lookup(target, column)),\n set: new Map(Object.entries(conflict.set || {}).map(([column, value]) => [lookup(target, column), bind(value)]))\n };\n\n if (!returns)\n return this.prepare(builder).run(run());\n\n builder.commit(target.proxy);\n\n const [row] = await this.prepare(builder).all(run());\n\n return row && decode(builder, row);\n }\n\n async update(table: string, id: Connection.Key, data: Record<string, any>){\n const { builder, target, bind, run } = statement(this, table);\n const values: Builder.Insert = new Map();\n\n for (const column in data)\n values.set(lookup(target, column), bind(data[column]));\n\n builder.updates.set(target, values);\n identify(builder, target, id, bind);\n\n await this.prepare(builder).run(run());\n }\n\n async remove(table: string, id: Connection.Key){\n const { builder, target, bind, run } = statement(this, table);\n\n builder.deletes.add(target);\n identify(builder, target, id, bind);\n\n await this.prepare(builder).run(run());\n }\n}\n\nfunction identify(builder: Builder, target: Builder.ITable, id: Connection.Key, bind: (value: unknown) => Parameter){\n const { parts } = target.fields.get(\"id\")!;\n\n if (parts)\n parts.forEach((part, i) => builder.filters.add(lookup(target, part.column), '=', bind((id as unknown[])[i])));\n else\n builder.filters.add(target.fields.get(\"id\")!, '=', bind(id));\n}\n\nfunction statement(connection: Connection, table: string){\n const type = [...connection.using, ...connection._loaded.keys()].find(type => ref(type) === table);\n\n if (!type)\n throw new Error(`Table ${table} is not used by this connection.`);\n\n const builder = new Builder();\n const target = builder.tables.get(builder.use(type))!;\n const params: unknown[] = [];\n\n return {\n builder,\n target,\n bind(value: unknown){\n const param = new Parameter(params.length);\n\n params.push(value);\n builder.params.push(param);\n\n return param;\n },\n run: () => builder.accept(params)\n };\n}\n\nfunction lookup(table: Builder.ITable, column: string){\n for (const field of table.fields.values())\n if (field.column === column)\n return field;\n\n throw new Error(`Column ${column} does not exist in ${table.name}.`);\n}\n\nfunction decode(builder: Builder, raw: Record<string, any>){\n const row: Record<string, any> = {};\n\n (builder.returns as Map<string, Field>).forEach((field, key) => {\n row[field.column] = raw[key];\n });\n\n return row;\n}\n\nexport { Connection };\n"],"mappings":";;;;;;;;;AA4CA,SAAS,IAAI,EAAE,QAAQ,SAAqB;AAC1C,QAAO,SAAS,GAAG,OAAO,GAAG,UAAU;;;;;;;;;;AAWzC,IAAe,aAAf,cAAkCA,aAAK;CAkBrC,MAAM,OAAO,OAAe,aAAgC,OAAgB,QAAgB;EAC1F,MAAM,EAAE,SAAS,QAAQ,MAAM,QAAQ,UAAU,MAAM,MAAM;AAE7D,OAAK,MAAM,CAAC,QAAQ,IAAI,UAAU,aAAa;GAC7C,MAAM,QAAQ,OAAO,QAAQ,OAAO;AAEpC,OAAI,OAAO,SAAS,OAAO,OACzB,SAAQ,MAAM,IAAI,OAAO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AAM,SAAS,QAAQ,OAAO,IAAI,QAAQ,IAAI,KAAK,CAAC;CACpD,MAAM,SAAoB,EAAE;AAE5B,QAAO;EACL;EACA;EACA,KAAK,OAAe;GAClB,MAAM,QAAQ,IAAI,UAAU,OAAO,OAAO;AAE1C,UAAO,KAAK,MAAM;AAClB,WAAQ,OAAO,KAAK,MAAM;AAE1B,UAAO;;EAET,WAAW,QAAQ,OAAO,OAAO;EAClC;;AAGH,SAAS,OAAO,OAAuB,QAAe;AACpD,MAAK,MAAM,SAAS,MAAM,OAAO,QAAQ,CACvC,KAAI,MAAM,WAAW,OACnB,QAAO;AAEX,OAAM,IAAI,MAAM,UAAU,OAAO,qBAAqB,MAAM,KAAK,GAAG;;AAGtE,SAAS,OAAO,SAAkB,KAAyB;CACzD,MAAM,MAA2B,EAAE;AAEnC,CAAC,QAAQ,QAA+B,SAAS,OAAO,QAAQ;AAC9D,MAAI,MAAM,UAAU,IAAI;GACxB;AAEF,QAAO"}
@@ -0,0 +1,68 @@
1
+ import { Field } from "@expressive/orm";
2
+ import { Builder, Computed, DataTable, Parameter } from "@expressive/orm/driver";
3
+
4
+ //#region src/connection/Generator.d.ts
5
+ /**
6
+ * Renders a `Query` builder as one SQL statement - `String(generator)`.
7
+ *
8
+ * A dialect subclasses it and overrides the protected hooks. Literals render inline, escaped; parameters bind.
9
+ */
10
+ declare class Generator {
11
+ query: Builder;
12
+ constructor(query: Builder);
13
+ toString(): string;
14
+ /** Quote an identifier, each dotted part on its own. */
15
+ escape(name: unknown): string;
16
+ /** `INSERT INTO`, or `false` when the query inserts nothing. */
17
+ protected insert(): false | unknown[];
18
+ /** Order an insert's data CTE, target and select - for a dialect placing `WITH` elsewhere. */
19
+ protected insertWith(cte: string | undefined, into: unknown[], select: unknown[]): unknown[];
20
+ /** `ON CONFLICT` clause of an upsert. */
21
+ protected upsert(): string[] | undefined;
22
+ /** `RETURNING` clause of an insert that selects. */
23
+ protected returning(): string | undefined;
24
+ /** `WITH` clause over the query's data tables. */
25
+ protected with(): string | undefined;
26
+ /** A value - `now`, a reference, or a literal. */
27
+ protected value(input: unknown, field?: Field): string;
28
+ /** A literal - every literal in values, `SET` and `WHERE` passes through it. */
29
+ protected literal(value: unknown): string;
30
+ /** A table with its alias - for `FROM`, joins, `UPDATE` and `DELETE`. */
31
+ protected table({
32
+ name,
33
+ alias
34
+ }: Builder.ITable): string;
35
+ /** The current time - `CURRENT_TIMESTAMP`; a dialect renders it per `field`'s storage. */
36
+ protected now(_field?: Field): string;
37
+ /** Select a data table's rows out of its bound parameter. The base throws - a dialect implements it. */
38
+ protected jsonTable(_table: DataTable): string;
39
+ /** An arithmetic expression, parenthesized by operator rank. */
40
+ protected computed(from: Computed<unknown>): string;
41
+ /** `JOIN` clauses for every table but `main`. Throws for a table without a join condition. */
42
+ protected joins(main: Builder.ITable): string | undefined;
43
+ /** `SET` clause of an update. Throws without values. */
44
+ protected set(updates: Map<Builder.ITable, Builder.Insert>): string;
45
+ /** `UPDATE` head. Throws when the query updates more than one table. */
46
+ protected update(): (string | undefined)[] | undefined;
47
+ /** `DELETE FROM` head. */
48
+ protected delete(): (string | false | undefined)[] | undefined;
49
+ /** A column, parameter, data column, raw template or expression. */
50
+ protected reference(from: unknown): string;
51
+ /** `SELECT` head with joins - `COUNT(*)` when the query selects nothing. */
52
+ protected select(): (string | string[] | undefined)[];
53
+ /** `FROM` clause of the main table. */
54
+ protected from(): string[] | undefined;
55
+ /** A parameter placeholder. */
56
+ protected param(_from: Parameter): string;
57
+ /** One condition. `null` renders `IS` / `IS NOT`; an empty list a constant. */
58
+ protected filter(left: Field, op: string, right: unknown): string;
59
+ /** `WHERE` clause - top level joined with AND, alternating with OR by depth. */
60
+ protected where(): string[] | undefined;
61
+ /** `ORDER BY` clause. */
62
+ protected order(): string | undefined;
63
+ /** `LIMIT` and `OFFSET` clauses. */
64
+ protected limit(): (string | 0 | undefined)[];
65
+ }
66
+ //#endregion
67
+ export { Generator };
68
+ //# sourceMappingURL=Generator.d.ts.map
@@ -0,0 +1,242 @@
1
+ import { escape } from "../utils.js";
2
+ import { Field, now } from "@expressive/orm";
3
+ import { Computed, DataField, DataTable, Parameter, QueryTemplate } from "@expressive/orm/driver";
4
+
5
+ //#region src/connection/Generator.ts
6
+ function isValue(input) {
7
+ return input instanceof Field || input instanceof Parameter || input instanceof DataField || input instanceof QueryTemplate || input instanceof Computed;
8
+ }
9
+ /**
10
+ * Renders a `Query` builder as one SQL statement - `String(generator)`.
11
+ *
12
+ * A dialect subclasses it and overrides the protected hooks. Literals render inline, escaped; parameters bind.
13
+ */
14
+ var Generator = class {
15
+ constructor(query) {
16
+ this.query = query;
17
+ }
18
+ toString() {
19
+ return [
20
+ this.insert() || [this.with(), this.update() || this.delete() || this.select()],
21
+ this.where(),
22
+ this.order(),
23
+ this.limit(),
24
+ this.upsert(),
25
+ this.returning()
26
+ ].flat(Infinity).filter(Boolean).join(" ");
27
+ }
28
+ /** Quote an identifier, each dotted part on its own. */
29
+ escape(name) {
30
+ return String(name).split(".").map((x) => `\`${x}\``).join(".");
31
+ }
32
+ /** `INSERT INTO`, or `false` when the query inserts nothing. */
33
+ insert() {
34
+ const { inserts, tables } = this.query;
35
+ if (!inserts.size) return false;
36
+ const [[table, data]] = inserts;
37
+ const keys = [];
38
+ const values = [];
39
+ for (const [field, value] of data) {
40
+ keys.push(this.escape(field.column));
41
+ values.push(this.value(value, field));
42
+ }
43
+ if (!keys.length && tables.size > 1) throw new Error(`Insert into ${table.name} for each joined row needs at least one value.`);
44
+ const into = ["INSERT INTO", this.escape(table.name)];
45
+ if (!keys.length) return [
46
+ this.with(),
47
+ into,
48
+ "DEFAULT VALUES"
49
+ ];
50
+ return this.insertWith(this.with(), [into, `(${keys})`], [`SELECT ${values}`, tables.size > 1 && this.from()]);
51
+ }
52
+ /** Order an insert's data CTE, target and select - for a dialect placing `WITH` elsewhere. */
53
+ insertWith(cte, into, select) {
54
+ return [
55
+ cte,
56
+ into,
57
+ select
58
+ ];
59
+ }
60
+ /** `ON CONFLICT` clause of an upsert. */
61
+ upsert() {
62
+ const { conflict } = this.query;
63
+ if (!conflict) return;
64
+ const on = `ON CONFLICT (${conflict.on.map((field) => this.escape(field.column))})`;
65
+ if (!conflict.update) return [on, "DO NOTHING"];
66
+ const set = conflict.update.map(({ column }) => `${this.escape(column)} = excluded.${this.escape(column)}`);
67
+ for (const [field, value] of conflict.set) set.push(`${this.escape(field.column)} = ${this.value(value)}`);
68
+ if (!set.length) set.push(...conflict.on.map(({ column }) => `${this.escape(column)} = excluded.${this.escape(column)}`));
69
+ return [
70
+ on,
71
+ "DO UPDATE SET",
72
+ set.join(", ")
73
+ ];
74
+ }
75
+ /** `RETURNING` clause of an insert that selects. */
76
+ returning() {
77
+ const { inserts, returns } = this.query;
78
+ if (!inserts.size || !returns) return;
79
+ return "RETURNING " + (returns instanceof Map ? Array.from(returns, ([alias, field]) => `${this.value(field)} AS "${alias}"`).join(", ") : this.reference(returns));
80
+ }
81
+ /** `WITH` clause over the query's data tables. */
82
+ with() {
83
+ const cte = [];
84
+ this.query.tables.forEach((table) => {
85
+ if (table instanceof DataTable) cte.push(`${this.escape(table.name)} AS (${this.jsonTable(table)})`);
86
+ });
87
+ if (cte.length) return "WITH " + cte.join();
88
+ }
89
+ /** A value - `now`, a reference, or a literal. */
90
+ value(input, field) {
91
+ if (input === now) return this.now(field);
92
+ if (isValue(input)) return this.reference(input);
93
+ return this.literal(input);
94
+ }
95
+ /** A literal - every literal in values, `SET` and `WHERE` passes through it. */
96
+ literal(value) {
97
+ return String(escape(value));
98
+ }
99
+ /** A table with its alias - for `FROM`, joins, `UPDATE` and `DELETE`. */
100
+ table({ name, alias }) {
101
+ return this.escape(name) + (alias ? ` ${this.escape(alias)}` : "");
102
+ }
103
+ /** The current time - `CURRENT_TIMESTAMP`; a dialect renders it per `field`'s storage. */
104
+ now(_field) {
105
+ return "CURRENT_TIMESTAMP";
106
+ }
107
+ /** Select a data table's rows out of its bound parameter. The base throws - a dialect implements it. */
108
+ jsonTable(_table) {
109
+ throw new Error("Not implemented.");
110
+ }
111
+ /** An arithmetic expression, parenthesized by operator rank. */
112
+ computed(from) {
113
+ const { left, operator, right, rank } = from;
114
+ const side = (input, tight) => {
115
+ if (!(input instanceof Computed)) return this.value(input);
116
+ const value = this.computed(input);
117
+ return (tight ? input.rank <= rank : input.rank < rank) ? `(${value})` : value;
118
+ };
119
+ if (left === void 0) return operator + side(right, true);
120
+ return `${side(left, false)} ${operator} ${side(right, true)}`;
121
+ }
122
+ /** `JOIN` clauses for every table but `main`. Throws for a table without a join condition. */
123
+ joins(main) {
124
+ const output = [];
125
+ for (const table of this.query.tables.values()) {
126
+ if (table === main) continue;
127
+ const { name, optional } = table;
128
+ if (table.joins.length === 0) throw new Error(`Table ${name} has no joins.`);
129
+ const mode = optional ? "LEFT" : "INNER";
130
+ const conds = table.joins.map((x) => this.filter(x.left, x.op, x.right));
131
+ output.push(`${mode} JOIN ${this.table(table)} ON ${conds.join(" AND ")}`);
132
+ }
133
+ if (output.length) return output.join(" ");
134
+ }
135
+ /** `SET` clause of an update. Throws without values. */
136
+ set(updates) {
137
+ const sets = [];
138
+ for (const [_table, data] of updates) for (const [field, value] of data) sets.push(`${this.escape(field.column)} = ${value === now ? this.now(field) : isValue(value) ? this.reference(value) : value === null ? "NULL" : this.literal(value)}`);
139
+ if (!sets.length) throw new Error("Update contains no values.");
140
+ return `SET ${sets}`;
141
+ }
142
+ /** `UPDATE` head. Throws when the query updates more than one table. */
143
+ update() {
144
+ const { updates } = this.query;
145
+ if (!updates.size) return;
146
+ if (updates.size > 1) throw new Error("Engine does not support multi-table updates.");
147
+ const [main] = updates.keys();
148
+ return [
149
+ "UPDATE",
150
+ this.table(main),
151
+ this.joins(main),
152
+ this.set(updates)
153
+ ];
154
+ }
155
+ /** `DELETE FROM` head. */
156
+ delete() {
157
+ const { query } = this;
158
+ const [main] = query.deletes;
159
+ if (!main) return;
160
+ const { alias, name } = main;
161
+ return [
162
+ "DELETE",
163
+ query.tables.size > 1 && (alias || name),
164
+ "FROM",
165
+ this.table(main),
166
+ this.joins(main)
167
+ ];
168
+ }
169
+ /** A column, parameter, data column, raw template or expression. */
170
+ reference(from) {
171
+ if (from instanceof DataField) return this.escape(from.table.name + "." + from.column);
172
+ if (from instanceof QueryTemplate) return from.from;
173
+ if (from instanceof Computed) return this.computed(from);
174
+ if (from instanceof Parameter) return this.param(from);
175
+ const { table, column } = from;
176
+ return this.escape(table.alias || table.name) + "." + this.escape(column);
177
+ }
178
+ /** `SELECT` head with joins - `COUNT(*)` when the query selects nothing. */
179
+ select() {
180
+ const { returns, tables } = this.query;
181
+ const [main] = tables.values();
182
+ return [
183
+ "SELECT",
184
+ returns instanceof Map ? Array.from(returns, ([alias, field]) => this.value(field) + ` AS "${alias}"`).join(", ") : returns ? this.reference(returns) : "COUNT(*)",
185
+ this.from(),
186
+ main && this.joins(main)
187
+ ];
188
+ }
189
+ /** `FROM` clause of the main table. */
190
+ from() {
191
+ const [main] = this.query.tables.values();
192
+ if (main) return ["FROM", this.table(main)];
193
+ }
194
+ /** A parameter placeholder. */
195
+ param(_from) {
196
+ return "?";
197
+ }
198
+ /** One condition. `null` renders `IS` / `IS NOT`; an empty list a constant. */
199
+ filter(left, op, right) {
200
+ const raw = (value) => value === now ? this.now(left) : isValue(value) ? this.reference(value) : this.literal(op.includes("LIKE") ? value : left.set(value));
201
+ if (right === null) {
202
+ if (op == "=") op = "IS";
203
+ else if (op == "<>" || op == "!=") op = "IS NOT";
204
+ else throw new Error("Cannot compare NULL with " + op);
205
+ right = "NULL";
206
+ } else if (right instanceof Array) {
207
+ if (!right.length) return op == "NOT IN" ? "1 = 1" : "1 = 0";
208
+ right = `(${right.map(raw)})`;
209
+ } else right = raw(right);
210
+ return `${this.reference(left)} ${op} ${right}`;
211
+ }
212
+ /** `WHERE` clause - top level joined with AND, alternating with OR by depth. */
213
+ where() {
214
+ const { filters } = this.query;
215
+ if (!filters.size) return;
216
+ const combine = (group, or) => {
217
+ return Array.from(group.children, (cond, i) => {
218
+ if ("children" in cond) {
219
+ const inner = combine(cond, !or);
220
+ const first = or !== false && i === 0;
221
+ return cond.size === 1 || first ? inner : `(${inner})`;
222
+ }
223
+ return this.filter(cond.left, cond.op, cond.right);
224
+ }).join(or ? " OR " : " AND ");
225
+ };
226
+ return ["WHERE", combine(filters)];
227
+ }
228
+ /** `ORDER BY` clause. */
229
+ order() {
230
+ const { order } = this.query;
231
+ if (order.size) return "ORDER BY " + Array.from(order, ([x, y]) => `${this.reference(x)} ${y}`);
232
+ }
233
+ /** `LIMIT` and `OFFSET` clauses. */
234
+ limit() {
235
+ const { limit, offset } = this.query;
236
+ return [limit && `LIMIT ${limit}`, offset && `OFFSET ${offset}`];
237
+ }
238
+ };
239
+
240
+ //#endregion
241
+ export { Generator };
242
+ //# sourceMappingURL=Generator.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Generator.js","names":[],"sources":["../../src/connection/Generator.ts"],"sourcesContent":["import { Field, now } from '@expressive/orm';\nimport { Builder, Computed, DataField, DataTable, Parameter, QueryTemplate } from '@expressive/orm/driver';\n\nimport { escape } from '../utils';\n\ntype Expression = Builder[\"filters\"];\n\nfunction isValue(input: unknown){\n return (\n input instanceof Field ||\n input instanceof Parameter ||\n input instanceof DataField ||\n input instanceof QueryTemplate ||\n input instanceof Computed\n );\n}\n\n/**\n * Renders a `Query` builder as one SQL statement - `String(generator)`.\n *\n * A dialect subclasses it and overrides the protected hooks. Literals render inline, escaped; parameters bind.\n */\nexport class Generator {\n constructor(public query: Builder){}\n\n toString() {\n const parts = [\n this.insert() || [\n this.with(),\n this.update() ||\n this.delete() ||\n this.select()\n ],\n this.where(),\n this.order(),\n this.limit(),\n this.upsert(),\n this.returning()\n ];\n\n return parts.flat(Infinity).filter(Boolean).join(' ');\n }\n\n /** Quote an identifier, each dotted part on its own. */\n escape(name: unknown){\n return String(name).split('.').map(x => `\\`${x}\\``).join('.');\n }\n\n /** `INSERT INTO`, or `false` when the query inserts nothing. */\n protected insert() {\n const { inserts, tables } = this.query;\n\n if (!inserts.size)\n return false;\n\n const [[table, data]] = inserts;\n\n const keys: string[] = [];\n const values: string[] = [];\n\n for (const [field, value] of data) {\n keys.push(this.escape(field.column));\n values.push(this.value(value, field));\n }\n\n if (!keys.length && tables.size > 1)\n throw new Error(`Insert into ${table.name} for each joined row needs at least one value.`);\n\n const into = ['INSERT INTO', this.escape(table.name)];\n\n if (!keys.length)\n return [this.with(), into, 'DEFAULT VALUES'];\n\n return this.insertWith(this.with(), [into, `(${keys})`], [\n `SELECT ${values}`,\n tables.size > 1 && this.from()\n ]);\n }\n\n /** Order an insert's data CTE, target and select - for a dialect placing `WITH` elsewhere. */\n protected insertWith(cte: string | undefined, into: unknown[], select: unknown[]): unknown[] {\n return [cte, into, select];\n }\n\n /** `ON CONFLICT` clause of an upsert. */\n protected upsert(){\n const { conflict } = this.query;\n\n if (!conflict)\n return;\n\n const on = `ON CONFLICT (${conflict.on.map(field => this.escape(field.column))})`;\n\n if (!conflict.update)\n return [on, 'DO NOTHING'];\n\n const set = conflict.update.map(({ column }) => `${this.escape(column)} = excluded.${this.escape(column)}`);\n\n for (const [field, value] of conflict.set)\n set.push(`${this.escape(field.column)} = ${this.value(value)}`);\n\n if (!set.length)\n set.push(...conflict.on.map(({ column }) => `${this.escape(column)} = excluded.${this.escape(column)}`));\n\n return [on, 'DO UPDATE SET', set.join(', ')];\n }\n\n /** `RETURNING` clause of an insert that selects. */\n protected returning(){\n const { inserts, returns } = this.query;\n\n if (!inserts.size || !returns)\n return;\n\n return 'RETURNING ' + (\n returns instanceof Map\n ? Array.from(returns, ([alias, field]) => `${this.value(field)} AS \"${alias}\"`).join(', ')\n : this.reference(returns)\n );\n }\n\n /** `WITH` clause over the query's data tables. */\n protected with(){\n const cte = [] as string[];\n\n this.query.tables.forEach((table) => {\n if (table instanceof DataTable)\n cte.push(`${this.escape(table.name)} AS (${this.jsonTable(table)})`);\n });\n\n if(cte.length)\n return 'WITH ' + cte.join();\n }\n\n /** A value - `now`, a reference, or a literal. */\n protected value(input: unknown, field?: Field){\n if(input === now)\n return this.now(field);\n\n if(isValue(input))\n return this.reference(input);\n\n return this.literal(input);\n }\n\n /** A literal - every literal in values, `SET` and `WHERE` passes through it. */\n protected literal(value: unknown){\n return String(escape(value));\n }\n\n /** A table with its alias - for `FROM`, joins, `UPDATE` and `DELETE`. */\n protected table({ name, alias }: Builder.ITable){\n return this.escape(name) + (alias ? ` ${this.escape(alias)}` : \"\");\n }\n\n /** The current time - `CURRENT_TIMESTAMP`; a dialect renders it per `field`'s storage. */\n protected now(_field?: Field){\n return \"CURRENT_TIMESTAMP\";\n }\n\n /** Select a data table's rows out of its bound parameter. The base throws - a dialect implements it. */\n protected jsonTable(_table: DataTable): string {\n throw new Error(\"Not implemented.\");\n }\n\n /** An arithmetic expression, parenthesized by operator rank. */\n protected computed(from: Computed<unknown>): string {\n const { left, operator, right, rank } = from;\n const side = (input: unknown, tight: boolean) => {\n if(!(input instanceof Computed))\n return this.value(input);\n\n const value = this.computed(input);\n\n return (tight ? input.rank <= rank : input.rank < rank) ? `(${value})` : value;\n }\n\n if(left === undefined)\n return operator + side(right, true);\n\n return `${side(left, false)} ${operator} ${side(right, true)}`;\n }\n\n /** `JOIN` clauses for every table but `main`. Throws for a table without a join condition. */\n protected joins(main: Builder.ITable){\n const output: string[] = [];\n\n for(const table of this.query.tables.values()){\n if(table === main)\n continue;\n\n const { name, optional } = table;\n\n if(table.joins.length === 0)\n throw new Error(`Table ${name} has no joins.`);\n\n const mode = optional ? \"LEFT\" : \"INNER\";\n const conds = table.joins.map(x => this.filter(x.left, x.op, x.right));\n\n output.push(`${mode} JOIN ${this.table(table)} ON ${conds.join(' AND ')}`);\n }\n\n if(output.length)\n return output.join(' ');\n }\n\n /** `SET` clause of an update. Throws without values. */\n protected set(updates: Map<Builder.ITable, Builder.Insert>){\n const sets: string[] = [];\n\n for(const [_table, data] of updates)\n for(const [field, value] of data)\n sets.push(`${this.escape(field.column)} = ${\n value === now ? this.now(field) :\n isValue(value) ? this.reference(value) :\n value === null ? 'NULL' :\n this.literal(value)\n }`);\n\n if(!sets.length)\n throw new Error('Update contains no values.');\n\n return `SET ${sets}`;\n }\n\n /** `UPDATE` head. Throws when the query updates more than one table. */\n protected update(){\n const { updates } = this.query;\n\n if(!updates.size)\n return;\n\n if(updates.size > 1)\n throw new Error('Engine does not support multi-table updates.');\n\n const [ main ] = updates.keys();\n\n return [\n 'UPDATE',\n this.table(main),\n this.joins(main),\n this.set(updates)\n ]\n }\n\n /** `DELETE FROM` head. */\n protected delete(){\n const { query } = this;\n const [ main ] = query.deletes;\n\n if(!main)\n return;\n\n const { alias, name } = main;\n const target = query.tables.size > 1 && (alias || name);\n\n return ['DELETE', target, 'FROM', this.table(main), this.joins(main)]\n }\n\n /** A column, parameter, data column, raw template or expression. */\n protected reference(from: unknown): string {\n if(from instanceof DataField)\n return this.escape(from.table.name + '.' + from.column);\n\n if(from instanceof QueryTemplate)\n return from.from;\n\n if(from instanceof Computed)\n return this.computed(from);\n\n if(from instanceof Parameter)\n return this.param(from);\n\n const { table, column } = from as Field;\n\n return this.escape(table!.alias || table!.name) + \".\" + this.escape(column);\n }\n\n /** `SELECT` head with joins - `COUNT(*)` when the query selects nothing. */\n protected select(){\n const { returns, tables } = this.query;\n const [ main ] = tables.values();\n\n const selection =\n returns instanceof Map ?\n Array.from(returns, ([alias, field]) => this.value(field) + ` AS \"${alias}\"`).join(', ') :\n returns ?\n this.reference(returns) :\n 'COUNT(*)';\n\n return [\n \"SELECT\",\n selection,\n this.from(),\n main && this.joins(main)\n ]\n }\n\n /** `FROM` clause of the main table. */\n protected from(){\n const [ main ] = this.query.tables.values();\n\n if(main)\n return [\"FROM\", this.table(main)]\n }\n\n /** A parameter placeholder. */\n protected param(_from: Parameter){\n return \"?\";\n }\n\n /** One condition. `null` renders `IS` / `IS NOT`; an empty list a constant. */\n protected filter(left: Field, op: string, right: unknown){\n const raw = (value: unknown) => (\n value === now ? this.now(left) :\n isValue(value) ? this.reference(value) :\n this.literal(op.includes(\"LIKE\") ? value : left.set(value))\n );\n\n if (right === null){\n if(op == '=')\n op = 'IS';\n else if(op == '<>' || op == '!=')\n op = 'IS NOT';\n else\n throw new Error('Cannot compare NULL with ' + op);\n\n right = 'NULL';\n }\n else if(right instanceof Array){\n if(!right.length)\n return op == 'NOT IN' ? '1 = 1' : '1 = 0';\n\n right = `(${right.map(raw)})`;\n }\n else\n right = raw(right);\n\n return `${this.reference(left)} ${op} ${right}`;\n }\n\n /** `WHERE` clause - top level joined with AND, alternating with OR by depth. */\n protected where() {\n const { filters } = this.query;\n\n if (!filters.size) return;\n\n const combine = (group: Expression, or?: boolean): string => {\n return Array\n .from(group.children, (cond, i) => {\n if (\"children\" in cond) {\n const inner = combine(cond, !or);\n const first = or !== false && i === 0;\n return cond.size === 1 || first ? inner : `(${inner})`;\n }\n\n return this.filter(cond.left, cond.op, cond.right);\n })\n .join(or ? ' OR ' : ' AND ');\n };\n\n return ['WHERE', combine(filters)];\n }\n\n /** `ORDER BY` clause. */\n protected order(){\n const { order } = this.query;\n\n if(order.size)\n return 'ORDER BY ' +\n Array.from(order, ([x, y]) => `${this.reference(x)} ${y}`);\n }\n\n /** `LIMIT` and `OFFSET` clauses. */\n protected limit(){\n const { limit, offset } = this.query;\n\n return [\n limit && `LIMIT ${limit}`,\n offset && `OFFSET ${offset}`\n ];\n }\n}\n"],"mappings":";;;;;AAOA,SAAS,QAAQ,OAAe;AAC9B,QACE,iBAAiB,SACjB,iBAAiB,aACjB,iBAAiB,aACjB,iBAAiB,iBACjB,iBAAiB;;;;;;;AASrB,IAAa,YAAb,MAAuB;CACrB,YAAY,AAAO,OAAe;EAAf;;CAEnB,WAAW;AAeT,SAdc;GACZ,KAAK,QAAQ,IAAI,CACf,KAAK,MAAM,EACX,KAAK,QAAQ,IACb,KAAK,QAAQ,IACb,KAAK,QAAQ,CACd;GACD,KAAK,OAAO;GACZ,KAAK,OAAO;GACZ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,SAAS,KAAK,QAAQ,QAAQ,IAAI,MAAM;;AAGtD,WAAO,KAAK,OAAO,KAAK,MAAM,KAAK,IAAI,KAAK,MAAM;KAClD,CACD,KAAK,KAAK,SAAS,QAAQ;;AAGhC,SAAO,CAAC,SAAS,QAAQ,QAAQ,CAAC;;;CAIpC,AAAU,QAAO;EACf,MAAM,EAAE,UAAU,KAAK;AAEvB,MAAG,MAAM,KACP,QAAO,cACL,MAAM,KAAK,QAAQ,CAAC,GAAG,OAAO,GAAG,KAAK,UAAU,EAAE,CAAC,GAAG,IAAI;;;CAIhE,AAAU,QAAO;EACf,MAAM,EAAE,OAAO,WAAW,KAAK;AAE/B,SAAO,CACL,SAAS,SAAS,SAClB,UAAU,UAAU,SACrB"}
@@ -0,0 +1,102 @@
1
+ import { now } from "@expressive/orm";
2
+
3
+ //#region src/datatypes.d.ts
4
+ interface Datatypes {
5
+ /** The current time - rendered by the database in the column's storage; statics take the app's clock. */
6
+ readonly now: typeof now;
7
+ /** `str` (default) - unbounded text. `date` - ISO 8601 text. `bool` - text, with `either`. */
8
+ readonly text: {
9
+ readonly type: "text";
10
+ };
11
+ /** `str` - a UUID. As `key(sql.uuid)`, a UUIDv7 is generated on insert when absent. */
12
+ readonly uuid: {
13
+ readonly type: "uuid";
14
+ };
15
+ /**
16
+ * 32-bit integer - for `num`, `one` (default), `bool` and `date`.
17
+ *
18
+ * On `num` a fraction or a value out of range throws on write. `bool` stores 1 or 0; `date`, epoch seconds.
19
+ */
20
+ readonly integer: {
21
+ readonly type: "integer";
22
+ };
23
+ /** `num` - 16-bit integer; a fraction or a value out of range throws on write. */
24
+ readonly smallint: {
25
+ readonly type: "smallint";
26
+ };
27
+ /** `num`, `one` - 64-bit integer. On `num` a fraction throws on write. */
28
+ readonly bigint: {
29
+ readonly type: "bigint";
30
+ };
31
+ /** `num` - floating point. */
32
+ readonly real: {
33
+ readonly type: "real";
34
+ };
35
+ /** `num` - floating point. */
36
+ readonly float: {
37
+ readonly type: "float";
38
+ };
39
+ /** `num` - floating point, `double precision` in schema. */
40
+ readonly double: {
41
+ readonly type: "double";
42
+ };
43
+ /** `bool` (default). */
44
+ readonly boolean: {
45
+ readonly type: "boolean";
46
+ };
47
+ /** `date` (default) - date and time. */
48
+ readonly timestamp: {
49
+ readonly type: "timestamp";
50
+ };
51
+ /** `date` - a calendar day, `YYYY-MM-DD`. Written from the UTC day, read as local midnight. */
52
+ readonly date: {
53
+ readonly type: "date";
54
+ };
55
+ /** `date` - time of day, `HH:MM:SS` UTC, read on 1970-01-01. */
56
+ readonly time: {
57
+ readonly type: "time";
58
+ };
59
+ /** `date` - epoch milliseconds in a 64-bit integer. */
60
+ readonly ms: {
61
+ readonly type: "ms";
62
+ };
63
+ /** `date` - epoch seconds in an integer. */
64
+ readonly seconds: {
65
+ readonly type: "seconds";
66
+ };
67
+ /** `str` - text up to `length` characters; longer throws on write. `bool` - with `either`. */
68
+ readonly varchar: <N extends number>(length: N) => {
69
+ readonly type: "varchar";
70
+ readonly length: N;
71
+ };
72
+ /** `str` - fixed-length text; longer than `length` throws on write. */
73
+ readonly char: <N extends number>(length: N) => {
74
+ readonly type: "char";
75
+ readonly length: N;
76
+ };
77
+ /**
78
+ * `num` - exact decimal of `precision` digits, `scale` (default 0) after the point.
79
+ *
80
+ * A value past either throws on write.
81
+ */
82
+ readonly numeric: (precision: number, scale?: number) => {
83
+ readonly type: "numeric";
84
+ readonly precision: number;
85
+ readonly scale: number;
86
+ };
87
+ /** `num` - exact decimal, as `numeric`. */
88
+ readonly decimal: (precision: number, scale?: number) => {
89
+ readonly type: "decimal";
90
+ readonly precision: number;
91
+ readonly scale: number;
92
+ };
93
+ }
94
+ /**
95
+ * Column datatypes, passed to a field helper - `str(sql.varchar(255))`, `date(sql.ms)`.
96
+ *
97
+ * Each fits only the helpers named on it; elsewhere it is a type error.
98
+ */
99
+ declare const sql: Datatypes;
100
+ //#endregion
101
+ export { sql };
102
+ //# sourceMappingURL=datatypes.d.ts.map
@@ -0,0 +1,47 @@
1
+ import { now } from "@expressive/orm";
2
+
3
+ //#region src/datatypes.ts
4
+ /**
5
+ * Column datatypes, passed to a field helper - `str(sql.varchar(255))`, `date(sql.ms)`.
6
+ *
7
+ * Each fits only the helpers named on it; elsewhere it is a type error.
8
+ */
9
+ const sql = {
10
+ now,
11
+ text: { type: "text" },
12
+ uuid: { type: "uuid" },
13
+ integer: { type: "integer" },
14
+ smallint: { type: "smallint" },
15
+ bigint: { type: "bigint" },
16
+ real: { type: "real" },
17
+ float: { type: "float" },
18
+ double: { type: "double" },
19
+ boolean: { type: "boolean" },
20
+ timestamp: { type: "timestamp" },
21
+ date: { type: "date" },
22
+ time: { type: "time" },
23
+ ms: { type: "ms" },
24
+ seconds: { type: "seconds" },
25
+ varchar: (length) => ({
26
+ type: "varchar",
27
+ length
28
+ }),
29
+ char: (length) => ({
30
+ type: "char",
31
+ length
32
+ }),
33
+ numeric: (precision, scale = 0) => ({
34
+ type: "numeric",
35
+ precision,
36
+ scale
37
+ }),
38
+ decimal: (precision, scale = 0) => ({
39
+ type: "decimal",
40
+ precision,
41
+ scale
42
+ })
43
+ };
44
+
45
+ //#endregion
46
+ export { sql };
47
+ //# sourceMappingURL=datatypes.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"datatypes.js","names":[],"sources":["../src/datatypes.ts"],"sourcesContent":["import { now } from '@expressive/orm';\n\ninterface Datatypes {\n /** The current time - rendered by the database in the column's storage; statics take the app's clock. */\n readonly now: typeof now;\n /** `str` (default) - unbounded text. `date` - ISO 8601 text. `bool` - text, with `either`. */\n readonly text: { readonly type: \"text\" };\n /** `str` - a UUID. As `key(sql.uuid)`, a UUIDv7 is generated on insert when absent. */\n readonly uuid: { readonly type: \"uuid\" };\n /**\n * 32-bit integer - for `num`, `one` (default), `bool` and `date`.\n *\n * On `num` a fraction or a value out of range throws on write. `bool` stores 1 or 0; `date`, epoch seconds.\n */\n readonly integer: { readonly type: \"integer\" };\n /** `num` - 16-bit integer; a fraction or a value out of range throws on write. */\n readonly smallint: { readonly type: \"smallint\" };\n /** `num`, `one` - 64-bit integer. On `num` a fraction throws on write. */\n readonly bigint: { readonly type: \"bigint\" };\n /** `num` - floating point. */\n readonly real: { readonly type: \"real\" };\n /** `num` - floating point. */\n readonly float: { readonly type: \"float\" };\n /** `num` - floating point, `double precision` in schema. */\n readonly double: { readonly type: \"double\" };\n /** `bool` (default). */\n readonly boolean: { readonly type: \"boolean\" };\n /** `date` (default) - date and time. */\n readonly timestamp: { readonly type: \"timestamp\" };\n /** `date` - a calendar day, `YYYY-MM-DD`. Written from the UTC day, read as local midnight. */\n readonly date: { readonly type: \"date\" };\n /** `date` - time of day, `HH:MM:SS` UTC, read on 1970-01-01. */\n readonly time: { readonly type: \"time\" };\n /** `date` - epoch milliseconds in a 64-bit integer. */\n readonly ms: { readonly type: \"ms\" };\n /** `date` - epoch seconds in an integer. */\n readonly seconds: { readonly type: \"seconds\" };\n /** `str` - text up to `length` characters; longer throws on write. `bool` - with `either`. */\n readonly varchar: <N extends number>(length: N) => { readonly type: \"varchar\"; readonly length: N };\n /** `str` - fixed-length text; longer than `length` throws on write. */\n readonly char: <N extends number>(length: N) => { readonly type: \"char\"; readonly length: N };\n /**\n * `num` - exact decimal of `precision` digits, `scale` (default 0) after the point.\n *\n * A value past either throws on write.\n */\n readonly numeric: (precision: number, scale?: number) => { readonly type: \"numeric\"; readonly precision: number; readonly scale: number };\n /** `num` - exact decimal, as `numeric`. */\n readonly decimal: (precision: number, scale?: number) => { readonly type: \"decimal\"; readonly precision: number; readonly scale: number };\n}\n\n/**\n * Column datatypes, passed to a field helper - `str(sql.varchar(255))`, `date(sql.ms)`.\n *\n * Each fits only the helpers named on it; elsewhere it is a type error.\n */\nconst sql: Datatypes = {\n now,\n text: { type: \"text\" },\n uuid: { type: \"uuid\" },\n integer: { type: \"integer\" },\n smallint: { type: \"smallint\" },\n bigint: { type: \"bigint\" },\n real: { type: \"real\" },\n float: { type: \"float\" },\n double: { type: \"double\" },\n boolean: { type: \"boolean\" },\n timestamp: { type: \"timestamp\" },\n date: { type: \"date\" },\n time: { type: \"time\" },\n ms: { type: \"ms\" },\n seconds: { type: \"seconds\" },\n varchar: <N extends number>(length: N) => ({ type: \"varchar\", length }) as const,\n char: <N extends number>(length: N) => ({ type: \"char\", length }) as const,\n numeric: (precision: number, scale = 0) => ({ type: \"numeric\", precision, scale }) as const,\n decimal: (precision: number, scale = 0) => ({ type: \"decimal\", precision, scale }) as const\n};\n\nexport { sql };\n"],"mappings":";;;;;;;;AAwDA,MAAM,MAAiB;CACrB;CACA,MAAM,EAAE,MAAM,QAAQ;CACtB,MAAM,EAAE,MAAM,QAAQ;CACtB,SAAS,EAAE,MAAM,WAAW;CAC5B,UAAU,EAAE,MAAM,YAAY;CAC9B,QAAQ,EAAE,MAAM,UAAU;CAC1B,MAAM,EAAE,MAAM,QAAQ;CACtB,OAAO,EAAE,MAAM,SAAS;CACxB,QAAQ,EAAE,MAAM,UAAU;CAC1B,SAAS,EAAE,MAAM,WAAW;CAC5B,WAAW,EAAE,MAAM,aAAa;CAChC,MAAM,EAAE,MAAM,QAAQ;CACtB,MAAM,EAAE,MAAM,QAAQ;CACtB,IAAI,EAAE,MAAM,MAAM;CAClB,SAAS,EAAE,MAAM,WAAW;CAC5B,UAA4B,YAAe;EAAE,MAAM;EAAW;EAAQ;CACtE,OAAyB,YAAe;EAAE,MAAM;EAAQ;EAAQ;CAChE,UAAU,WAAmB,QAAQ,OAAO;EAAE,MAAM;EAAW;EAAW;EAAO;CACjF,UAAU,WAAmB,QAAQ,OAAO;EAAE,MAAM;EAAW;EAAW;EAAO;CAClF"}
@@ -0,0 +1,6 @@
1
+ //#region src/dispatch.d.ts
2
+ type Output = Pick<Console, "log" | "error">;
3
+ declare function dispatch(args: string[], cwd: string, out: Output): Promise<number>;
4
+ //#endregion
5
+ export { dispatch };
6
+ //# sourceMappingURL=dispatch.d.ts.map