@sigil-dev/plugin-sql 0.9.20 → 0.9.22
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.
- package/README.md +324 -314
- package/package.json +2 -2
- package/src/bun.ts +292 -265
- package/src/contract.ts +249 -249
- package/src/database.ts +764 -750
- package/src/fragment.ts +304 -304
- package/src/index.ts +67 -66
- package/src/testing.ts +148 -148
package/src/fragment.ts
CHANGED
|
@@ -1,304 +1,304 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* A query that has been *described* but not run.
|
|
3
|
-
*
|
|
4
|
-
* A tagged template is usually a promise, and a promise is a result. This is
|
|
5
|
-
* the opposite: it holds the template and its values, and resolves the client
|
|
6
|
-
* only when you run it — `await`, or `run()`. That is what makes it safe to
|
|
7
|
-
* build at module scope, before a worker has opened a connection, and safe to
|
|
8
|
-
* reuse, since every run is a fresh execution rather than a shared settled
|
|
9
|
-
* promise.
|
|
10
|
-
*
|
|
11
|
-
* Fragments compose. Interpolating one splices its text and its values into
|
|
12
|
-
* the enclosing template, so a condition with a parameter inside it stays a
|
|
13
|
-
* parameter all the way down:
|
|
14
|
-
*
|
|
15
|
-
* ```ts
|
|
16
|
-
* const active = db.sql`deleted_at is null`;
|
|
17
|
-
* const byOwner = (id: number) => db.sql`owner_id = ${id} and ${active}`;
|
|
18
|
-
* const rows = await db.sql<User>`select * from t where ${byOwner(7)}`;
|
|
19
|
-
* // select * from t where owner_id = $1 and deleted_at is null
|
|
20
|
-
* ```
|
|
21
|
-
*/
|
|
22
|
-
|
|
23
|
-
/**
|
|
24
|
-
* A registered template, so two copies of this package still compose.
|
|
25
|
-
*
|
|
26
|
-
* A symbol from `Symbol.for` rather than a module-local one: `db.sql` from an
|
|
27
|
-
* older `@sigil-dev/plugin-sql` in a transitive dependency must be recognised
|
|
28
|
-
* as a fragment, and `in` also means a plain object literal carrying the
|
|
29
|
-
* marker works, which keeps tests from needing the real constructor.
|
|
30
|
-
*/
|
|
31
|
-
export const SQL_FRAGMENT = Symbol.for("sigil.sql.fragment");
|
|
32
|
-
|
|
33
|
-
/**
|
|
34
|
-
* `T` is the row type. It defaults to `any`, like `Bun.SQL`'s own results,
|
|
35
|
-
* so code that casts rows to its own interfaces — `(await q) as CardRow[]` —
|
|
36
|
-
* keeps compiling; `db.sql<CardRow>` is the typed spelling.
|
|
37
|
-
*/
|
|
38
|
-
// biome-ignore lint/suspicious/noExplicitAny: the default row, as in Bun.SQL
|
|
39
|
-
export interface Fragment<T = any> extends Promise<T[]> {
|
|
40
|
-
readonly [SQL_FRAGMENT]: true;
|
|
41
|
-
/**
|
|
42
|
-
* The static parts of the query with every nested fragment spliced in.
|
|
43
|
-
* Always one longer than `values`, like a `TemplateStringsArray`.
|
|
44
|
-
*
|
|
45
|
-
* This, not `text`, is what an adapter should execute: handing it to the
|
|
46
|
-
* driver's own tagged template lets the driver choose its placeholders,
|
|
47
|
-
* which is `$1` on postgres and `?` on MySQL. Choosing them here is the
|
|
48
|
-
* bug this package already had once.
|
|
49
|
-
*/
|
|
50
|
-
readonly strings: readonly string[];
|
|
51
|
-
/**
|
|
52
|
-
* The query with `$1`-style placeholders, for logs and error messages —
|
|
53
|
-
* and for an adapter over a postgres-only driver. Not portable: MySQL
|
|
54
|
-
* reads `$1` as a column name.
|
|
55
|
-
*/
|
|
56
|
-
readonly text: string;
|
|
57
|
-
/** Bound parameters, in order. Never interpolated into `strings`. */
|
|
58
|
-
readonly values: readonly unknown[];
|
|
59
|
-
|
|
60
|
-
/** The request's transaction if there is one, else the pool. */
|
|
61
|
-
run(): Promise<T[]>;
|
|
62
|
-
|
|
63
|
-
/** Inside a transaction, or throw. */
|
|
64
|
-
runTx(): Promise<T[]>;
|
|
65
|
-
|
|
66
|
-
/** Always the pool, deliberately outside any transaction. */
|
|
67
|
-
runPool(): Promise<T[]>;
|
|
68
|
-
|
|
69
|
-
/**
|
|
70
|
-
* So `await db.sql`...`` works, and reads like every other query in the
|
|
71
|
-
* app. The same as `run()`.
|
|
72
|
-
*
|
|
73
|
-
* The cost is the one every thenable has: anything that awaits a
|
|
74
|
-
* fragment runs it — returning one from an `async` function included.
|
|
75
|
-
* Return it from a plain function if the caller is meant to compose it.
|
|
76
|
-
*/
|
|
77
|
-
then<A = T[], B = never>(
|
|
78
|
-
onFulfilled?: ((value: T[]) => A | PromiseLike<A>) | null,
|
|
79
|
-
// biome-ignore lint/suspicious/noExplicitAny: matches Promise's own signature
|
|
80
|
-
onRejected?: ((reason: any) => B | PromiseLike<B>) | null,
|
|
81
|
-
): Promise<A | B>;
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
export function isFragment(v: unknown): v is Fragment<unknown> {
|
|
85
|
-
return (
|
|
86
|
-
(typeof v === "object" || typeof v === "function") &&
|
|
87
|
-
v !== null &&
|
|
88
|
-
SQL_FRAGMENT in v
|
|
89
|
-
);
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
/**
|
|
93
|
-
* The text and values a fragment contributes when spliced.
|
|
94
|
-
*
|
|
95
|
-
* A value may also carry them behind the marker itself, as a function:
|
|
96
|
-
* `{ [SQL_FRAGMENT]: () => ({ strings, values }) }`. That is how a table or
|
|
97
|
-
* a column object from a query builder interpolates as an identifier without
|
|
98
|
-
* reserving `strings` and `values` as property names, which would collide
|
|
99
|
-
* with the column names it exposes.
|
|
100
|
-
*/
|
|
101
|
-
export function fragmentParts(v: object): {
|
|
102
|
-
strings?: readonly string[];
|
|
103
|
-
values?: readonly unknown[];
|
|
104
|
-
} {
|
|
105
|
-
const marker = (v as Record<symbol, unknown>)[SQL_FRAGMENT];
|
|
106
|
-
if (typeof marker === "function") {
|
|
107
|
-
return (
|
|
108
|
-
marker as (this: object) => {
|
|
109
|
-
strings: readonly string[];
|
|
110
|
-
values: readonly unknown[];
|
|
111
|
-
}
|
|
112
|
-
).call(v);
|
|
113
|
-
}
|
|
114
|
-
return v as Partial<Fragment<unknown>>;
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
export const SQL_HELPER = Symbol.for("sigil.sql.helper");
|
|
118
|
-
|
|
119
|
-
/**
|
|
120
|
-
* A driver helper — an `IN` list, a postgres array, a row to insert — that
|
|
121
|
-
* has been described but not built.
|
|
122
|
-
*
|
|
123
|
-
* `Bun.SQL` builds these from a client: `sql(ids)`, `sql.array(xs, "text")`.
|
|
124
|
-
* A fragment at module scope has no client yet, so `db.sql(ids)` records the
|
|
125
|
-
* call and the adapter replays it on whichever client runs the query. It is a
|
|
126
|
-
* value, not a fragment: it sits in `values` and is bound, never spliced.
|
|
127
|
-
*/
|
|
128
|
-
export interface SqlHelper {
|
|
129
|
-
readonly [SQL_HELPER]: true;
|
|
130
|
-
/** The helper to call on the client; undefined for the client itself. */
|
|
131
|
-
readonly method: string | undefined;
|
|
132
|
-
readonly args: readonly unknown[];
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
export function isHelper(v: unknown): v is SqlHelper {
|
|
136
|
-
return typeof v === "object" && v !== null && SQL_HELPER in v;
|
|
137
|
-
}
|
|
138
|
-
|
|
139
|
-
export function createHelper(
|
|
140
|
-
method: string | undefined,
|
|
141
|
-
args: readonly unknown[],
|
|
142
|
-
): SqlHelper {
|
|
143
|
-
return {
|
|
144
|
-
[SQL_HELPER]: true,
|
|
145
|
-
method,
|
|
146
|
-
args,
|
|
147
|
-
toString(): never {
|
|
148
|
-
throw new Error(
|
|
149
|
-
"This sql helper was used as a string. Interpolate it into a " +
|
|
150
|
-
"sql`` template instead.",
|
|
151
|
-
);
|
|
152
|
-
},
|
|
153
|
-
} as SqlHelper;
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
/**
|
|
157
|
-
* Splice a template and everything nested in it into one list of static
|
|
158
|
-
* parts and one list of values.
|
|
159
|
-
*
|
|
160
|
-
* A nested fragment's first part is joined onto the current last part, its
|
|
161
|
-
* middle parts are appended, and the enclosing template's next part is
|
|
162
|
-
* joined onto its last one. Keeping that as one accumulating array rather
|
|
163
|
-
* than a parallel string is what stops the trailing text being emitted twice,
|
|
164
|
-
* or lost — `ART_KIND` spliced into a `SELECT` list is the case that matters.
|
|
165
|
-
*/
|
|
166
|
-
export function splice(
|
|
167
|
-
strings: readonly string[],
|
|
168
|
-
values: readonly unknown[],
|
|
169
|
-
): { strings: string[]; values: unknown[] } {
|
|
170
|
-
const parts: string[] = [];
|
|
171
|
-
const out: unknown[] = [];
|
|
172
|
-
// The part still being built; pushed when a value closes it.
|
|
173
|
-
let tail = strings[0] ?? "";
|
|
174
|
-
for (let i = 0; i < values.length; i++) {
|
|
175
|
-
const v = values[i];
|
|
176
|
-
if (isFragment(v)) {
|
|
177
|
-
const f = fragmentParts(v);
|
|
178
|
-
if (!f.strings) {
|
|
179
|
-
throw new Error(
|
|
180
|
-
"This sql fragment has no `strings`, so it cannot be spliced " +
|
|
181
|
-
"into another query. It most likely comes from an older copy " +
|
|
182
|
-
"of @sigil-dev/plugin-sql; deduplicate the package.",
|
|
183
|
-
);
|
|
184
|
-
}
|
|
185
|
-
const inner = splice(f.strings, f.values ?? []);
|
|
186
|
-
const [first = "", ...rest] = inner.strings;
|
|
187
|
-
tail += first;
|
|
188
|
-
if (rest.length > 0) {
|
|
189
|
-
parts.push(tail, ...rest.slice(0, -1));
|
|
190
|
-
tail = rest[rest.length - 1] ?? "";
|
|
191
|
-
}
|
|
192
|
-
out.push(...inner.values);
|
|
193
|
-
} else {
|
|
194
|
-
parts.push(tail);
|
|
195
|
-
tail = "";
|
|
196
|
-
out.push(v);
|
|
197
|
-
}
|
|
198
|
-
tail += strings[i + 1] ?? "";
|
|
199
|
-
}
|
|
200
|
-
parts.push(tail);
|
|
201
|
-
return { strings: parts, values: out };
|
|
202
|
-
}
|
|
203
|
-
|
|
204
|
-
/**
|
|
205
|
-
* `splice`, rendered as one string with `$n` placeholders.
|
|
206
|
-
*
|
|
207
|
-
* Kept for display and for postgres-only drivers. The placeholder style is a
|
|
208
|
-
* parameter so a caller that knows its dialect can ask for another.
|
|
209
|
-
*/
|
|
210
|
-
export function flatten(
|
|
211
|
-
strings: readonly string[],
|
|
212
|
-
values: readonly unknown[],
|
|
213
|
-
placeholder: (index: number) => string = (i) => `$${i + 1}`,
|
|
214
|
-
): { text: string; values: unknown[] } {
|
|
215
|
-
const s = splice(strings, values);
|
|
216
|
-
let text = s.strings[0] ?? "";
|
|
217
|
-
for (let i = 1; i < s.strings.length; i++) {
|
|
218
|
-
text += placeholder(i - 1) + s.strings[i];
|
|
219
|
-
}
|
|
220
|
-
return { text, values: s.values };
|
|
221
|
-
}
|
|
222
|
-
|
|
223
|
-
/** What a fragment needs from its database to run. */
|
|
224
|
-
export interface FragmentRunner {
|
|
225
|
-
run: () => unknown;
|
|
226
|
-
runTx: () => unknown;
|
|
227
|
-
runPool: () => unknown;
|
|
228
|
-
query: (
|
|
229
|
-
target: unknown,
|
|
230
|
-
text: string,
|
|
231
|
-
values: readonly unknown[],
|
|
232
|
-
strings: readonly string[],
|
|
233
|
-
) => Promise<unknown[]>;
|
|
234
|
-
}
|
|
235
|
-
|
|
236
|
-
/**
|
|
237
|
-
* Build a fragment from a template.
|
|
238
|
-
*
|
|
239
|
-
* `resolve` is supplied by the database and picks the client, which is the
|
|
240
|
-
* only reason this can be called before a worker exists.
|
|
241
|
-
*/
|
|
242
|
-
// biome-ignore lint/suspicious/noExplicitAny: the default row, as in Bun.SQL
|
|
243
|
-
export function createFragment<T = any>(
|
|
244
|
-
strings: TemplateStringsArray | readonly string[],
|
|
245
|
-
values: readonly unknown[],
|
|
246
|
-
resolve: FragmentRunner,
|
|
247
|
-
): Fragment<T> {
|
|
248
|
-
// Spliced once, at construction. It is pure string work with no client
|
|
249
|
-
// involved, so a module-scope fragment costs nothing and cannot fail for
|
|
250
|
-
// want of a connection.
|
|
251
|
-
const s = splice(strings, values);
|
|
252
|
-
const { text } = flatten(s.strings, s.values);
|
|
253
|
-
|
|
254
|
-
// `pick` is called inside the promise, so a throwing accessor — tx()
|
|
255
|
-
// outside a transaction — is a rejection like any other query error.
|
|
256
|
-
// runTx() used to throw synchronously, which `await x.runTx()` hides but
|
|
257
|
-
// `x.runTx().catch()` does not.
|
|
258
|
-
const exec = (pick: () => unknown): Promise<T[]> =>
|
|
259
|
-
Promise.resolve().then(
|
|
260
|
-
() =>
|
|
261
|
-
resolve.query(pick(), text, s.values, s.strings) as Promise<T[]>,
|
|
262
|
-
);
|
|
263
|
-
|
|
264
|
-
const frag: Fragment<T> = {
|
|
265
|
-
[SQL_FRAGMENT]: true,
|
|
266
|
-
strings: s.strings,
|
|
267
|
-
text,
|
|
268
|
-
values: s.values,
|
|
269
|
-
|
|
270
|
-
run: () => exec(resolve.run),
|
|
271
|
-
runTx: () => exec(resolve.runTx),
|
|
272
|
-
runPool: () => exec(resolve.runPool),
|
|
273
|
-
|
|
274
|
-
then(onFulfilled, onRejected) {
|
|
275
|
-
return exec(resolve.run).then(onFulfilled, onRejected);
|
|
276
|
-
},
|
|
277
|
-
// The rest of Promise, so a fragment goes wherever a Promise does:
|
|
278
|
-
// Promise.all, a `() => Promise<T>` parameter, an `as Promise<Row[]>`.
|
|
279
|
-
catch(onRejected) {
|
|
280
|
-
return exec(resolve.run).catch(onRejected);
|
|
281
|
-
},
|
|
282
|
-
finally(onFinally) {
|
|
283
|
-
return exec(resolve.run).finally(onFinally);
|
|
284
|
-
},
|
|
285
|
-
[Symbol.toStringTag]: "SqlFragment",
|
|
286
|
-
|
|
287
|
-
/**
|
|
288
|
-
* Refuses rather than returning text.
|
|
289
|
-
*
|
|
290
|
-
* The tempting alternative is `text`, and it is wrong: this object
|
|
291
|
-
* holds bound values that `text` does not contain, so stringifying it
|
|
292
|
-
* either drops the parameters or inlines them unescaped. Failing here
|
|
293
|
-
* is the difference between a wrong query and a broken build.
|
|
294
|
-
*/
|
|
295
|
-
toString(): never {
|
|
296
|
-
throw new Error(
|
|
297
|
-
"This sql fragment was used as a string. Interpolate it into " +
|
|
298
|
-
"another sql`` template instead, so its values stay bound.",
|
|
299
|
-
);
|
|
300
|
-
},
|
|
301
|
-
} as Fragment<T>;
|
|
302
|
-
|
|
303
|
-
return frag;
|
|
304
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* A query that has been *described* but not run.
|
|
3
|
+
*
|
|
4
|
+
* A tagged template is usually a promise, and a promise is a result. This is
|
|
5
|
+
* the opposite: it holds the template and its values, and resolves the client
|
|
6
|
+
* only when you run it — `await`, or `run()`. That is what makes it safe to
|
|
7
|
+
* build at module scope, before a worker has opened a connection, and safe to
|
|
8
|
+
* reuse, since every run is a fresh execution rather than a shared settled
|
|
9
|
+
* promise.
|
|
10
|
+
*
|
|
11
|
+
* Fragments compose. Interpolating one splices its text and its values into
|
|
12
|
+
* the enclosing template, so a condition with a parameter inside it stays a
|
|
13
|
+
* parameter all the way down:
|
|
14
|
+
*
|
|
15
|
+
* ```ts
|
|
16
|
+
* const active = db.sql`deleted_at is null`;
|
|
17
|
+
* const byOwner = (id: number) => db.sql`owner_id = ${id} and ${active}`;
|
|
18
|
+
* const rows = await db.sql<User>`select * from t where ${byOwner(7)}`;
|
|
19
|
+
* // select * from t where owner_id = $1 and deleted_at is null
|
|
20
|
+
* ```
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* A registered template, so two copies of this package still compose.
|
|
25
|
+
*
|
|
26
|
+
* A symbol from `Symbol.for` rather than a module-local one: `db.sql` from an
|
|
27
|
+
* older `@sigil-dev/plugin-sql` in a transitive dependency must be recognised
|
|
28
|
+
* as a fragment, and `in` also means a plain object literal carrying the
|
|
29
|
+
* marker works, which keeps tests from needing the real constructor.
|
|
30
|
+
*/
|
|
31
|
+
export const SQL_FRAGMENT = Symbol.for("sigil.sql.fragment");
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* `T` is the row type. It defaults to `any`, like `Bun.SQL`'s own results,
|
|
35
|
+
* so code that casts rows to its own interfaces — `(await q) as CardRow[]` —
|
|
36
|
+
* keeps compiling; `db.sql<CardRow>` is the typed spelling.
|
|
37
|
+
*/
|
|
38
|
+
// biome-ignore lint/suspicious/noExplicitAny: the default row, as in Bun.SQL
|
|
39
|
+
export interface Fragment<T = any> extends Promise<T[]> {
|
|
40
|
+
readonly [SQL_FRAGMENT]: true;
|
|
41
|
+
/**
|
|
42
|
+
* The static parts of the query with every nested fragment spliced in.
|
|
43
|
+
* Always one longer than `values`, like a `TemplateStringsArray`.
|
|
44
|
+
*
|
|
45
|
+
* This, not `text`, is what an adapter should execute: handing it to the
|
|
46
|
+
* driver's own tagged template lets the driver choose its placeholders,
|
|
47
|
+
* which is `$1` on postgres and `?` on MySQL. Choosing them here is the
|
|
48
|
+
* bug this package already had once.
|
|
49
|
+
*/
|
|
50
|
+
readonly strings: readonly string[];
|
|
51
|
+
/**
|
|
52
|
+
* The query with `$1`-style placeholders, for logs and error messages —
|
|
53
|
+
* and for an adapter over a postgres-only driver. Not portable: MySQL
|
|
54
|
+
* reads `$1` as a column name.
|
|
55
|
+
*/
|
|
56
|
+
readonly text: string;
|
|
57
|
+
/** Bound parameters, in order. Never interpolated into `strings`. */
|
|
58
|
+
readonly values: readonly unknown[];
|
|
59
|
+
|
|
60
|
+
/** The request's transaction if there is one, else the pool. */
|
|
61
|
+
run(): Promise<T[]>;
|
|
62
|
+
|
|
63
|
+
/** Inside a transaction, or throw. */
|
|
64
|
+
runTx(): Promise<T[]>;
|
|
65
|
+
|
|
66
|
+
/** Always the pool, deliberately outside any transaction. */
|
|
67
|
+
runPool(): Promise<T[]>;
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* So `await db.sql`...`` works, and reads like every other query in the
|
|
71
|
+
* app. The same as `run()`.
|
|
72
|
+
*
|
|
73
|
+
* The cost is the one every thenable has: anything that awaits a
|
|
74
|
+
* fragment runs it — returning one from an `async` function included.
|
|
75
|
+
* Return it from a plain function if the caller is meant to compose it.
|
|
76
|
+
*/
|
|
77
|
+
then<A = T[], B = never>(
|
|
78
|
+
onFulfilled?: ((value: T[]) => A | PromiseLike<A>) | null,
|
|
79
|
+
// biome-ignore lint/suspicious/noExplicitAny: matches Promise's own signature
|
|
80
|
+
onRejected?: ((reason: any) => B | PromiseLike<B>) | null,
|
|
81
|
+
): Promise<A | B>;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export function isFragment(v: unknown): v is Fragment<unknown> {
|
|
85
|
+
return (
|
|
86
|
+
(typeof v === "object" || typeof v === "function") &&
|
|
87
|
+
v !== null &&
|
|
88
|
+
SQL_FRAGMENT in v
|
|
89
|
+
);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* The text and values a fragment contributes when spliced.
|
|
94
|
+
*
|
|
95
|
+
* A value may also carry them behind the marker itself, as a function:
|
|
96
|
+
* `{ [SQL_FRAGMENT]: () => ({ strings, values }) }`. That is how a table or
|
|
97
|
+
* a column object from a query builder interpolates as an identifier without
|
|
98
|
+
* reserving `strings` and `values` as property names, which would collide
|
|
99
|
+
* with the column names it exposes.
|
|
100
|
+
*/
|
|
101
|
+
export function fragmentParts(v: object): {
|
|
102
|
+
strings?: readonly string[];
|
|
103
|
+
values?: readonly unknown[];
|
|
104
|
+
} {
|
|
105
|
+
const marker = (v as Record<symbol, unknown>)[SQL_FRAGMENT];
|
|
106
|
+
if (typeof marker === "function") {
|
|
107
|
+
return (
|
|
108
|
+
marker as (this: object) => {
|
|
109
|
+
strings: readonly string[];
|
|
110
|
+
values: readonly unknown[];
|
|
111
|
+
}
|
|
112
|
+
).call(v);
|
|
113
|
+
}
|
|
114
|
+
return v as Partial<Fragment<unknown>>;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export const SQL_HELPER = Symbol.for("sigil.sql.helper");
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* A driver helper — an `IN` list, a postgres array, a row to insert — that
|
|
121
|
+
* has been described but not built.
|
|
122
|
+
*
|
|
123
|
+
* `Bun.SQL` builds these from a client: `sql(ids)`, `sql.array(xs, "text")`.
|
|
124
|
+
* A fragment at module scope has no client yet, so `db.sql(ids)` records the
|
|
125
|
+
* call and the adapter replays it on whichever client runs the query. It is a
|
|
126
|
+
* value, not a fragment: it sits in `values` and is bound, never spliced.
|
|
127
|
+
*/
|
|
128
|
+
export interface SqlHelper {
|
|
129
|
+
readonly [SQL_HELPER]: true;
|
|
130
|
+
/** The helper to call on the client; undefined for the client itself. */
|
|
131
|
+
readonly method: string | undefined;
|
|
132
|
+
readonly args: readonly unknown[];
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export function isHelper(v: unknown): v is SqlHelper {
|
|
136
|
+
return typeof v === "object" && v !== null && SQL_HELPER in v;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export function createHelper(
|
|
140
|
+
method: string | undefined,
|
|
141
|
+
args: readonly unknown[],
|
|
142
|
+
): SqlHelper {
|
|
143
|
+
return {
|
|
144
|
+
[SQL_HELPER]: true,
|
|
145
|
+
method,
|
|
146
|
+
args,
|
|
147
|
+
toString(): never {
|
|
148
|
+
throw new Error(
|
|
149
|
+
"This sql helper was used as a string. Interpolate it into a " +
|
|
150
|
+
"sql`` template instead.",
|
|
151
|
+
);
|
|
152
|
+
},
|
|
153
|
+
} as SqlHelper;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Splice a template and everything nested in it into one list of static
|
|
158
|
+
* parts and one list of values.
|
|
159
|
+
*
|
|
160
|
+
* A nested fragment's first part is joined onto the current last part, its
|
|
161
|
+
* middle parts are appended, and the enclosing template's next part is
|
|
162
|
+
* joined onto its last one. Keeping that as one accumulating array rather
|
|
163
|
+
* than a parallel string is what stops the trailing text being emitted twice,
|
|
164
|
+
* or lost — `ART_KIND` spliced into a `SELECT` list is the case that matters.
|
|
165
|
+
*/
|
|
166
|
+
export function splice(
|
|
167
|
+
strings: readonly string[],
|
|
168
|
+
values: readonly unknown[],
|
|
169
|
+
): { strings: string[]; values: unknown[] } {
|
|
170
|
+
const parts: string[] = [];
|
|
171
|
+
const out: unknown[] = [];
|
|
172
|
+
// The part still being built; pushed when a value closes it.
|
|
173
|
+
let tail = strings[0] ?? "";
|
|
174
|
+
for (let i = 0; i < values.length; i++) {
|
|
175
|
+
const v = values[i];
|
|
176
|
+
if (isFragment(v)) {
|
|
177
|
+
const f = fragmentParts(v);
|
|
178
|
+
if (!f.strings) {
|
|
179
|
+
throw new Error(
|
|
180
|
+
"This sql fragment has no `strings`, so it cannot be spliced " +
|
|
181
|
+
"into another query. It most likely comes from an older copy " +
|
|
182
|
+
"of @sigil-dev/plugin-sql; deduplicate the package.",
|
|
183
|
+
);
|
|
184
|
+
}
|
|
185
|
+
const inner = splice(f.strings, f.values ?? []);
|
|
186
|
+
const [first = "", ...rest] = inner.strings;
|
|
187
|
+
tail += first;
|
|
188
|
+
if (rest.length > 0) {
|
|
189
|
+
parts.push(tail, ...rest.slice(0, -1));
|
|
190
|
+
tail = rest[rest.length - 1] ?? "";
|
|
191
|
+
}
|
|
192
|
+
out.push(...inner.values);
|
|
193
|
+
} else {
|
|
194
|
+
parts.push(tail);
|
|
195
|
+
tail = "";
|
|
196
|
+
out.push(v);
|
|
197
|
+
}
|
|
198
|
+
tail += strings[i + 1] ?? "";
|
|
199
|
+
}
|
|
200
|
+
parts.push(tail);
|
|
201
|
+
return { strings: parts, values: out };
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* `splice`, rendered as one string with `$n` placeholders.
|
|
206
|
+
*
|
|
207
|
+
* Kept for display and for postgres-only drivers. The placeholder style is a
|
|
208
|
+
* parameter so a caller that knows its dialect can ask for another.
|
|
209
|
+
*/
|
|
210
|
+
export function flatten(
|
|
211
|
+
strings: readonly string[],
|
|
212
|
+
values: readonly unknown[],
|
|
213
|
+
placeholder: (index: number) => string = (i) => `$${i + 1}`,
|
|
214
|
+
): { text: string; values: unknown[] } {
|
|
215
|
+
const s = splice(strings, values);
|
|
216
|
+
let text = s.strings[0] ?? "";
|
|
217
|
+
for (let i = 1; i < s.strings.length; i++) {
|
|
218
|
+
text += placeholder(i - 1) + s.strings[i];
|
|
219
|
+
}
|
|
220
|
+
return { text, values: s.values };
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** What a fragment needs from its database to run. */
|
|
224
|
+
export interface FragmentRunner {
|
|
225
|
+
run: () => unknown;
|
|
226
|
+
runTx: () => unknown;
|
|
227
|
+
runPool: () => unknown;
|
|
228
|
+
query: (
|
|
229
|
+
target: unknown,
|
|
230
|
+
text: string,
|
|
231
|
+
values: readonly unknown[],
|
|
232
|
+
strings: readonly string[],
|
|
233
|
+
) => Promise<unknown[]>;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* Build a fragment from a template.
|
|
238
|
+
*
|
|
239
|
+
* `resolve` is supplied by the database and picks the client, which is the
|
|
240
|
+
* only reason this can be called before a worker exists.
|
|
241
|
+
*/
|
|
242
|
+
// biome-ignore lint/suspicious/noExplicitAny: the default row, as in Bun.SQL
|
|
243
|
+
export function createFragment<T = any>(
|
|
244
|
+
strings: TemplateStringsArray | readonly string[],
|
|
245
|
+
values: readonly unknown[],
|
|
246
|
+
resolve: FragmentRunner,
|
|
247
|
+
): Fragment<T> {
|
|
248
|
+
// Spliced once, at construction. It is pure string work with no client
|
|
249
|
+
// involved, so a module-scope fragment costs nothing and cannot fail for
|
|
250
|
+
// want of a connection.
|
|
251
|
+
const s = splice(strings, values);
|
|
252
|
+
const { text } = flatten(s.strings, s.values);
|
|
253
|
+
|
|
254
|
+
// `pick` is called inside the promise, so a throwing accessor — tx()
|
|
255
|
+
// outside a transaction — is a rejection like any other query error.
|
|
256
|
+
// runTx() used to throw synchronously, which `await x.runTx()` hides but
|
|
257
|
+
// `x.runTx().catch()` does not.
|
|
258
|
+
const exec = (pick: () => unknown): Promise<T[]> =>
|
|
259
|
+
Promise.resolve().then(
|
|
260
|
+
() =>
|
|
261
|
+
resolve.query(pick(), text, s.values, s.strings) as Promise<T[]>,
|
|
262
|
+
);
|
|
263
|
+
|
|
264
|
+
const frag: Fragment<T> = {
|
|
265
|
+
[SQL_FRAGMENT]: true,
|
|
266
|
+
strings: s.strings,
|
|
267
|
+
text,
|
|
268
|
+
values: s.values,
|
|
269
|
+
|
|
270
|
+
run: () => exec(resolve.run),
|
|
271
|
+
runTx: () => exec(resolve.runTx),
|
|
272
|
+
runPool: () => exec(resolve.runPool),
|
|
273
|
+
|
|
274
|
+
then(onFulfilled, onRejected) {
|
|
275
|
+
return exec(resolve.run).then(onFulfilled, onRejected);
|
|
276
|
+
},
|
|
277
|
+
// The rest of Promise, so a fragment goes wherever a Promise does:
|
|
278
|
+
// Promise.all, a `() => Promise<T>` parameter, an `as Promise<Row[]>`.
|
|
279
|
+
catch(onRejected) {
|
|
280
|
+
return exec(resolve.run).catch(onRejected);
|
|
281
|
+
},
|
|
282
|
+
finally(onFinally) {
|
|
283
|
+
return exec(resolve.run).finally(onFinally);
|
|
284
|
+
},
|
|
285
|
+
[Symbol.toStringTag]: "SqlFragment",
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* Refuses rather than returning text.
|
|
289
|
+
*
|
|
290
|
+
* The tempting alternative is `text`, and it is wrong: this object
|
|
291
|
+
* holds bound values that `text` does not contain, so stringifying it
|
|
292
|
+
* either drops the parameters or inlines them unescaped. Failing here
|
|
293
|
+
* is the difference between a wrong query and a broken build.
|
|
294
|
+
*/
|
|
295
|
+
toString(): never {
|
|
296
|
+
throw new Error(
|
|
297
|
+
"This sql fragment was used as a string. Interpolate it into " +
|
|
298
|
+
"another sql`` template instead, so its values stay bound.",
|
|
299
|
+
);
|
|
300
|
+
},
|
|
301
|
+
} as Fragment<T>;
|
|
302
|
+
|
|
303
|
+
return frag;
|
|
304
|
+
}
|