@expressive/sql 0.1.0 → 0.2.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.
@@ -1,241 +0,0 @@
1
- import { Connection } from '../connection/Connection';
2
- import { Field } from '../type/Field';
3
- import { Type } from '../type/Type';
4
- import { assign, create, defineProperty } from '../utils';
5
- import { Builder as QB, Cond, Group, Builder } from './Builder';
6
- import { Computed } from './Computed';
7
-
8
- declare namespace Query {
9
- type Table = QB.Table;
10
-
11
- type From<T extends Type = Type> = {
12
- [K in Type.Fields<T>]: T[K] extends Field.Queries<infer U> ? U : T[K];
13
- }
14
-
15
- type Join<T extends Type = Type> = {
16
- [K in Type.Fields<T>]?: T[K] extends Field.Queries<infer U> ? U : T[K];
17
- }
18
-
19
- type Update<T extends Type> = { [K in Type.Fields<T>]?: Updates<T[K]> };
20
-
21
- type FromData<T extends {}> = { [K in keyof T]: Field<T[K]> };
22
-
23
- type Value<T = any> = T | Field<T> | Computed<T>
24
-
25
- type Insert<T extends Type> =
26
- & { [K in Type.Required<T>]: Field.Assigns<T[K]> | Field; }
27
- & { [K in Type.Fields<T>]?: Field.Assigns<T[K]> | Field }
28
-
29
- /** Main callback for adding instructions to a Query. */
30
- type Where = {
31
- /**
32
- * Declare inserts to be made into a given table.
33
- */
34
- <T extends Type>(entity: Type.EntityType<T>, ...inserts: Insert<T>[]): Query.From<T>;
35
-
36
- /**
37
- * Create a reference to the primary table, returned
38
- * object can be used to query against that table.
39
- */
40
- <T extends Type>(entity: Type.EntityType<T>): Query.From<T>;
41
-
42
- /**
43
- * Registers a type as a left join, returned object has optional
44
- * properties which may be undefined where the join is not present.
45
- */
46
- <T extends Type>(entity: Type.EntityType<T>, optional: true): Query.Join<T>;
47
-
48
- /**
49
- * Select a table for comparison or write operations.
50
- */
51
- <T extends Type>(field: Query.From<T> | Query.Join<T>): Query.Verbs<T>;
52
-
53
- /**
54
- * Prepare comparison against a particilar field,
55
- * returns operations for the given type.
56
- */
57
- <T extends Field>(field: T | undefined): Query.Asserts<T>;
58
-
59
- <T extends {}>(data: Iterable<T>): { [K in keyof T]: Field<T[K]> };
60
-
61
- /**
62
- * Accepts other where() assertions for nesting in parenthesis.
63
- *
64
- * Will alternate between AND-OR depending on depth, starting with OR.
65
- */
66
- (...orWhere: (Cond | Group)[]): Group;
67
-
68
- /** Specify the limit of results returned. */
69
- (limit: number): void;
70
-
71
- connection: Connection.Ready;
72
- }
73
-
74
- type Updates<T> = Field.Updates<T> | T | Field;
75
-
76
- type Function<R> = (this: Builder, where: Where) => R;
77
-
78
- type Factory<R, A extends any[]> = (this: Builder, where: Where) => (...args: A) => R;
79
-
80
- interface Template<A extends any[]> {
81
- (...args: A): Query;
82
-
83
- /** Prepared query for this template. */
84
- toString(): string;
85
- }
86
-
87
- type TemplateSelects<T, A extends any[]> = (...args: A) => Selects<T>;
88
-
89
- type Extract<T> =
90
- T extends Field.Returns<infer R> ? R :
91
- T extends From<infer U> ? { [J in Type.Fields<U>]: Extract<U[J]> } :
92
- T extends {} ? { [K in keyof T]: Extract<T[K]> } :
93
- T;
94
-
95
- type Asserts<T extends Field> = ReturnType<T["where"]> & {
96
- asc(): void;
97
- desc(): void;
98
- };
99
-
100
- interface Verbs <T extends Type> {
101
- delete(): void;
102
- update(values: Query.Update<T>): void;
103
- }
104
-
105
- interface Selects<T> extends Query<Extract<T>[]> {
106
- /**
107
- * Returns rows which match creteria.
108
- */
109
- get(): Promise<Extract<T>[]>;
110
-
111
- /**
112
- * Returns the first row that matches creteria.
113
- *
114
- * @param orFail If true, will throw an error if no match is found.
115
- */
116
- one(orFail?: boolean): Promise<Extract<T>>;
117
- }
118
- }
119
-
120
- interface Query<T = any> extends PromiseLike<T> {
121
- /** Returns the SQL string prepared by this query. */
122
- toString(): string;
123
-
124
- /**
125
- * Inputs to be sent with SQL for this query.
126
- * Data has already been serialized and matched to query parameters in template.
127
- */
128
- params: (string | number)[];
129
- }
130
-
131
- function Query<T extends {}, A extends unknown[]>(from: Query.Factory<T, A>): Query.TemplateSelects<T, A>;
132
-
133
- function Query<A extends unknown[]>(from: Query.Factory<void, A>): Query.Template<A>;
134
-
135
- function Query<T extends {}>(from: Query.Function<T>): Query.Selects<T>;
136
-
137
- /**
138
- * Creates a new query.
139
- * Will return the number of rows that would be selected or modified.
140
- */
141
- function Query(from: Query.Function<void>): Query<number>;
142
-
143
- function Query(factory: Query.Function<unknown> | Query.Factory<unknown, any[]>){
144
- let connection: Connection | undefined = undefined;
145
-
146
- function where(arg1: any): any {
147
- if(Type.is(arg1)){
148
- if(!connection)
149
- connection = arg1.connection;
150
- else if(connection !== arg1.connection)
151
- throw new Error(
152
- `Joined entity ${arg1} does not share a connection with other tables in Query.`
153
- );
154
-
155
- return builder.use(arg1, ...Array.from(arguments).slice(1));
156
- }
157
-
158
- if(arg1 instanceof Field)
159
- return builder.field(arg1);
160
-
161
- if(builder.tables.has(arg1))
162
- return builder.table(arg1);
163
-
164
- if(arg1 instanceof Cond || arg1 instanceof Group)
165
- return builder.andOr(...arguments);
166
-
167
- if(typeof arg1 == "number"){
168
- builder.limit = arg1;
169
- return;
170
- }
171
-
172
- if(Symbol.iterator in arg1)
173
- return builder.with(arg1);
174
-
175
- throw new Error(`Argument ${arg1} is not a query argument.`);
176
- }
177
-
178
- defineProperty(where, "connection", {
179
- get(){ return connection },
180
- set(conn){ connection = conn }
181
- })
182
-
183
- const builder = new QB();
184
- let result = factory.call(builder, where as Query.Where);
185
- let args: number | undefined;
186
-
187
- if(typeof result === 'function'){
188
- const params = builder.inject(args = result.length);
189
- result = (result as Function)(...params);
190
- }
191
-
192
- builder.commit(result);
193
-
194
- if(!connection)
195
- connection = Connection.None;
196
-
197
- const template = connection.generate(builder);
198
- const statement = connection.prepare(template);
199
- const runner = (...params: any[]) => {
200
- const get = () => statement.all(params).then(a => a.map(x => builder.parse(x)));
201
- const query = create(Query.prototype) as Query;
202
-
203
- params = builder.accept(params);
204
-
205
- assign(query, <Query>{
206
- params,
207
- toString: statement.toString,
208
- then(resolve, reject){
209
- const run = builder.returns ? get() : statement.run(params);
210
- return run.then(resolve).catch(reject);
211
- }
212
- });
213
-
214
- if (builder.returns)
215
- assign(query, {
216
- get,
217
- one: async (orFail?: boolean) => {
218
- const res = await statement.get();
219
-
220
- if(res)
221
- return builder.parse(res);
222
-
223
- if (orFail)
224
- throw new Error("Query returned no results.");
225
- }
226
- });
227
-
228
- return query;
229
- };
230
-
231
- if(typeof args == "number"){
232
- runner.toString = statement.toString;
233
- return runner;
234
- }
235
-
236
- return runner();
237
- }
238
-
239
- Query.Builder = QB;
240
-
241
- export { Query };
@@ -1,48 +0,0 @@
1
- import { Query, Str, Type } from '..';
2
-
3
- class Foo extends Type {
4
- value = Str();
5
- color = Str();
6
- }
7
-
8
- class Bar extends Type {
9
- value = Str();
10
- color = Str();
11
- }
12
-
13
- it("will generate query", () => {
14
- const query = Query(where => {
15
- const foo = where(Foo);
16
-
17
- where(foo.value).is("Hello World!");
18
- where(foo).delete();
19
- });
20
-
21
- expect(query).toMatchInlineSnapshot(`
22
- DELETE FROM
23
- foo
24
- WHERE
25
- foo.value = 'Hello World!'
26
- `);
27
- })
28
-
29
- it("will include FROM statement where JOIN exists", () => {
30
- const query = Query(where => {
31
- const foo = where(Foo);
32
- const bar = where(Bar);
33
-
34
- where(bar.color).is(foo.color);
35
- where(bar.value).is("Hello World!");
36
-
37
- where(foo).delete();
38
- });
39
-
40
- expect(query).toMatchInlineSnapshot(`
41
- DELETE foo
42
- FROM
43
- foo
44
- INNER JOIN bar ON bar.color = foo.color
45
- WHERE
46
- bar.value = 'Hello World!'
47
- `);
48
- })
@@ -1,47 +0,0 @@
1
- import { Str, Type } from '..';
2
-
3
- class Foo extends Type {
4
- name = Str();
5
- color = Str();
6
- }
7
-
8
- it("will throw for bad value", async () => {
9
- const insert = () => (
10
- Foo.insert({
11
- name: "foobar",
12
- // @ts-expect-error
13
- color: 3
14
- })
15
- )
16
-
17
- expect(insert).toThrowErrorMatchingInlineSnapshot(`
18
- Provided value for Foo.color but not acceptable for type varchar(255).
19
- Value must be a string.
20
- `);
21
- })
22
-
23
- it("will throw for no value non-nullable", async () => {
24
- const insert = () => {
25
- // @ts-expect-error
26
- Foo.insert({ name: "foobar" })
27
- }
28
-
29
- expect(insert).toThrowErrorMatchingInlineSnapshot(
30
- `Can't assign to \`Foo.color\`. A value is required but got undefined.`
31
- );
32
- })
33
-
34
- it("will add index to specify error", async () => {
35
- const insert = () => {
36
- Foo.insert([
37
- { name: "foo", color: "red" },
38
- // @ts-expect-error
39
- { name: "bar" }
40
- ])
41
- }
42
-
43
- expect(insert).toThrowErrorMatchingInlineSnapshot(`
44
- A provided value at \`color\` at index [1] is not acceptable.
45
- Can't assign to \`Foo.color\`. A value is required but got undefined.
46
- `);
47
- })
@@ -1,242 +0,0 @@
1
- import { Num, Query, Str, Table, Type } from '..';
2
-
3
- class Foo extends Type {
4
- name = Str();
5
- color = Str();
6
- }
7
-
8
- class Bar extends Type {
9
- name = Str();
10
- color = Str();
11
- rating = Num();
12
- }
13
-
14
- class Baz extends Type {
15
- color = Str();
16
- rating = Num();
17
- }
18
-
19
- it("will join using function", async () => {
20
- const query = Query(where => {
21
- const foo = where(Foo);
22
- const bar = where(Bar);
23
-
24
- where(bar.name).not(foo.name);
25
- where(bar.color).is(foo.color);
26
-
27
- where(foo.name).not("Danny");
28
- where(bar.rating).over(50);
29
- });
30
-
31
- expect(query).toMatchInlineSnapshot(`
32
- SELECT
33
- COUNT(*)
34
- FROM
35
- foo
36
- INNER JOIN bar ON bar.name <> foo.name
37
- AND bar.color = foo.color
38
- WHERE
39
- foo.name <> 'Danny'
40
- AND bar.rating > 50
41
- `);
42
- })
43
-
44
- it("will join multiple", async () => {
45
- const query = Query(where => {
46
- const foo = where(Foo);
47
- const bar = where(Bar);
48
- const baz = where(Baz);
49
-
50
- where(bar.color).is(foo.color);
51
- where(baz.rating).is(bar.rating);
52
-
53
- where(foo.name).not("Danny");
54
- where(bar.rating).over(50);
55
- where(baz.color).is("blue");
56
- });
57
-
58
- type Returns = Query<number>;
59
-
60
- expect<Returns>(query).toMatchInlineSnapshot(`
61
- SELECT
62
- COUNT(*)
63
- FROM
64
- foo
65
- INNER JOIN bar ON bar.color = foo.color
66
- INNER JOIN baz ON baz.rating = bar.rating
67
- WHERE
68
- foo.name <> 'Danny'
69
- AND bar.rating > 50
70
- AND baz.color = 'blue'
71
- `);
72
- })
73
-
74
- it("will throw if joins are composed", async () => {
75
- const query = () => Query(where => {
76
- const foo = where(Foo);
77
- const bar = where(Bar);
78
-
79
- where(
80
- where(bar.color).is(foo.color)
81
- );
82
- });
83
-
84
- expect(query).toThrowErrorMatchingInlineSnapshot(
85
- `Cannot use bar.color = foo.color in a group.`
86
- );
87
- });
88
-
89
- it.skip("will filter for comparisons to later tables", async () => {
90
- const query = Query(where => {
91
- const foo = where(Foo);
92
- const bar = where(Bar);
93
-
94
- where(bar.color).is(foo.color);
95
- where(foo.name).is(bar.name);
96
- });
97
-
98
- type Returns = Query<number>;
99
-
100
- expect<Returns>(query).toMatchInlineSnapshot(`
101
- SELECT
102
- COUNT(*)
103
- FROM
104
- foo
105
- INNER JOIN bar ON bar.color = foo.color
106
- WHERE
107
- foo.name = bar.name
108
- `);
109
- })
110
-
111
- it("will join a table with alias", async () => {
112
- class Baz extends Type {
113
- this = Table({ "schema": "other" });
114
-
115
- color = Str();
116
- rating = Num();
117
- }
118
-
119
- const query = Query(where => {
120
- const foo = where(Foo);
121
- const bar = where(Baz);
122
-
123
- where(bar.color).is(foo.color);
124
-
125
- return bar.rating;
126
- });
127
-
128
- expect(query).toMatchInlineSnapshot(`
129
- SELECT
130
- T1.rating
131
- FROM
132
- foo
133
- INNER JOIN other.baz T1 ON T1.color = foo.color
134
- `);
135
- });
136
-
137
- it.todo("will self join");
138
-
139
- it("will select left join", async () => {
140
- class Bar extends Type {
141
- name = Str();
142
- color = Str();
143
- rating = Num();
144
- }
145
-
146
- class Baz extends Type {
147
- rating = Num();
148
- name = Str();
149
- }
150
-
151
- const query = Query(where => {
152
- const foo = where(Foo);
153
- const bar = where(Bar);
154
- const baz = where(Baz, true);
155
-
156
- where(bar.color).is(foo.color);
157
- where(baz.rating).is(bar.rating);
158
-
159
- where(foo.name).not("Danny");
160
- where(bar.rating).over(50);
161
-
162
- return {
163
- fooValue: foo.name,
164
- barValue: bar.name,
165
- bazRating: baz.rating
166
- }
167
- });
168
-
169
- type Returns = Query.Selects<{
170
- fooValue: string;
171
- barValue: string;
172
- bazRating: number | undefined;
173
- }>
174
-
175
- expect<Returns>(query).toMatchInlineSnapshot(`
176
- SELECT
177
- foo.name AS "fooValue",
178
- bar.name AS "barValue",
179
- baz.rating AS "bazRating"
180
- FROM
181
- foo
182
- INNER JOIN bar ON bar.color = foo.color
183
- LEFT JOIN baz ON baz.rating = bar.rating
184
- WHERE
185
- foo.name <> 'Danny'
186
- AND bar.rating > 50
187
- `);
188
- })
189
-
190
- it("will assert a joined property's value", () => {
191
- const query = Query(where => {
192
- const foo = where(Foo);
193
- const bar = where(Bar);
194
-
195
- where(bar.color).is(foo.color);
196
- where(bar.rating).is(42);
197
- });
198
-
199
- expect(query).toMatchInlineSnapshot(`
200
- SELECT
201
- COUNT(*)
202
- FROM
203
- foo
204
- INNER JOIN bar ON bar.color = foo.color
205
- WHERE
206
- bar.rating = 42
207
- `);
208
- })
209
-
210
- it("will sort by joined table", async () => {
211
- class Test extends Type {
212
- name = Str();
213
- rating = Num();
214
- }
215
-
216
- class Other extends Type {
217
- name = Str();
218
- rank = Num();
219
- }
220
-
221
- const query = Query(where => {
222
- const test = where(Test);
223
- const other = where(Other);
224
-
225
- where(other.name).is(test.name);
226
- where(other.rank).asc();
227
-
228
- return other.name;
229
- });
230
-
231
- type Returns = Query.Selects<string>;
232
-
233
- expect<Returns>(query).toMatchInlineSnapshot(`
234
- SELECT
235
- other.name
236
- FROM
237
- test
238
- INNER JOIN other ON other.name = test.name
239
- ORDER BY
240
- other.rank asc
241
- `);
242
- })
@@ -1,69 +0,0 @@
1
- import { Num, Query, Type, math } from '..';
2
-
3
- class Item extends Type {
4
- number = Num();
5
- }
6
-
7
- describe("arithmetic", () => {
8
- it("will select equation", () => {
9
- const results = Query(where => {
10
- const { add } = math;
11
- const item = where(Item);
12
-
13
- return add(item.number, 2)
14
- });
15
-
16
- expect(results).toMatchInlineSnapshot(`
17
- SELECT
18
- item.number + 2
19
- FROM
20
- item
21
- `);
22
- })
23
-
24
- it("will select multiple equations", () => {
25
- const results = Query(where => {
26
- const { add, sub, mul, div } = math;
27
- const item = where(Item);
28
-
29
- return {
30
- add: add(item.number, 2),
31
- sub: sub(item.number, 2),
32
- mul: mul(item.number, 2),
33
- div: div(item.number, 2)
34
- }
35
- });
36
-
37
- expect(results).toMatchInlineSnapshot(`
38
- SELECT
39
- item.number + 2 AS "add",
40
- item.number - 2 AS "sub",
41
- item.number * 2 AS "mul",
42
- item.number / 2 AS "div"
43
- FROM
44
- item
45
- `);
46
- });
47
-
48
- it("will properly nest", async () => {
49
- const results = Query((where) => {
50
- const { add, mul, neg } = math;
51
- const { number } = where(Item);
52
-
53
- return {
54
- a: mul(number, add(number, 5)),
55
- b: add(mul(number, 5), number),
56
- c: neg(add(number, 100))
57
- }
58
- });
59
-
60
- expect(results).toMatchInlineSnapshot(`
61
- SELECT
62
- item.number * (item.number + 5) AS "a",
63
- item.number * 5 + item.number AS "b",
64
- - (item.number + 100) AS "c"
65
- FROM
66
- item
67
- `);
68
- });
69
- })