vite-plugin-postgres-import 0.9.0 → 0.10.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.
- package/README.md +84 -42
- package/describe.js +2 -1
- package/package.json +3 -2
- package/parse.js +77 -15
- package/runtime.js +94 -0
package/README.md
CHANGED
|
@@ -73,25 +73,25 @@ const rowsUpdated = await UpdateQuery({ id: 1, newFoo: "baz" }, { db: tx });
|
|
|
73
73
|
|
|
74
74
|
The only 4 sqlc annotations that are available are the following:
|
|
75
75
|
|
|
76
|
-
-
|
|
76
|
+
- `:execresult` - default if neither of the 3 below are provided, returns `QueryResult`.
|
|
77
77
|
|
|
78
78
|
ex.: `Query<R extends QueryResultRow = { ... }>(params?, config?): Promise<QueryResult<R>>`
|
|
79
79
|
|
|
80
|
-
-
|
|
80
|
+
- `:one` - returns template argument, or the default-parsed ones from the select/returning clause.
|
|
81
81
|
|
|
82
82
|
ex.: `Query<R extends QueryResultRow = { ... }>(params?, config?): Promise<R>`
|
|
83
83
|
|
|
84
|
-
-
|
|
84
|
+
- `:many` - returns template argument as an array, or the default-parsed ones from the select/returning clause.
|
|
85
85
|
|
|
86
86
|
ex.: `Query<R extends QueryResultRow = { ... }>(params?, config?): Promise<R[]>`
|
|
87
87
|
|
|
88
|
-
-
|
|
88
|
+
- `:execrows` - returns number of affected rows.
|
|
89
89
|
|
|
90
90
|
ex.: `Query(params?, config?): Promise<number>`
|
|
91
91
|
|
|
92
92
|
4 additional annotations not found in sqlc are available:
|
|
93
93
|
|
|
94
|
-
-
|
|
94
|
+
- `:prepare` - prepares the statement by passing query's name to query config.
|
|
95
95
|
|
|
96
96
|
> [!Warning]
|
|
97
97
|
>
|
|
@@ -131,7 +131,7 @@ The only 4 sqlc annotations that are available are the following:
|
|
|
131
131
|
>
|
|
132
132
|
> At best, you'd get an error in the provided example, due to mismatch in provided values, and at worst, assuming different examples, you'd be getting obscure bugs related to incorrect data.
|
|
133
133
|
|
|
134
|
-
-
|
|
134
|
+
- `:array` - sets `rowMode` to `'array'`. Modifies to type declarations accordingly:
|
|
135
135
|
|
|
136
136
|
ex. `:execresult`: `Query<R extends any[] = [ ... ]>(params?, config?): Promise<QueryArrayResult<R>>`
|
|
137
137
|
|
|
@@ -139,8 +139,8 @@ The only 4 sqlc annotations that are available are the following:
|
|
|
139
139
|
|
|
140
140
|
ex. `:many`: `Query<R extends any[] = [ ... ]>(params?, config?): Promise<R[]>`
|
|
141
141
|
|
|
142
|
-
-
|
|
143
|
-
|
|
142
|
+
- `:iterable` - returns an `AsyncGenerator`. Once [Async Iterator Helpers](https://github.com/tc39/proposal-async-iterator-helpers)
|
|
143
|
+
are in the standard, you can use crazy piping as following:
|
|
144
144
|
|
|
145
145
|
```js
|
|
146
146
|
const result = await IterableQuery<{ ... }>({ foo: 'bar' })
|
|
@@ -152,7 +152,7 @@ const result = await IterableQuery<{ ... }>({ foo: 'bar' })
|
|
|
152
152
|
Well maybe that didn't look too crazy, but if some filtering forces your squeel to become convoluted, and you're fine with moving
|
|
153
153
|
some of that computation to JS, you can finally do that! Or at least when that proposal is in the language, that is.
|
|
154
154
|
|
|
155
|
-
-
|
|
155
|
+
- `:cursor` - returns an `Cursor`
|
|
156
156
|
|
|
157
157
|
ex.: `Query<R extends QueryResultRow = { ... }>(params?, config?): Promise<Cursor<R>>`
|
|
158
158
|
|
|
@@ -178,19 +178,19 @@ _default:_ `process.cwd()`
|
|
|
178
178
|
|
|
179
179
|
Where the default runtime comes from:
|
|
180
180
|
|
|
181
|
-
-
|
|
182
|
-
|
|
183
|
-
-
|
|
184
|
-
-
|
|
185
|
-
|
|
181
|
+
- `module` - specifier every generated module imports the runtime from. Point it at a module of yours
|
|
182
|
+
(typically via a subpath import) that provides the database connection. _default:_ `'#db-runtime'`
|
|
183
|
+
- `export` - named export of `module` holding the runtime. _default:_ `'db'`
|
|
184
|
+
- `type` - either `'object'` — the export is a `Queryable` (or a promise of one) — or `'function'` — the export
|
|
185
|
+
is called on each query invocation and returns a `Queryable` (or a promise of one). _default:_ `'object'`
|
|
186
186
|
|
|
187
187
|
### `describe`
|
|
188
188
|
|
|
189
189
|
Types params and result columns from a live database instead of guessing them from the query text.
|
|
190
190
|
Every query is parsed and described the way psql's `\gdesc` does it - nothing gets executed.
|
|
191
191
|
|
|
192
|
-
-
|
|
193
|
-
-
|
|
192
|
+
- `true` - connect using the standard `PG*` environment variables
|
|
193
|
+
- a connection string or a `pg` client config
|
|
194
194
|
|
|
195
195
|
```js
|
|
196
196
|
postgres({ describe: process.env.DATABASE_URL ?? false });
|
|
@@ -204,22 +204,24 @@ where id = :id!;
|
|
|
204
204
|
```
|
|
205
205
|
|
|
206
206
|
```ts
|
|
207
|
-
function GetUser<
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
207
|
+
function GetUser<
|
|
208
|
+
R1 extends QueryResultRow = {
|
|
209
|
+
id: string;
|
|
210
|
+
name: string;
|
|
211
|
+
bio: string | null;
|
|
212
|
+
mood: "sad" | "ok" | "happy";
|
|
213
|
+
},
|
|
214
|
+
>(params: { id: number | bigint | string }, config?): Promise<R1>;
|
|
213
215
|
```
|
|
214
216
|
|
|
215
|
-
-
|
|
216
|
-
|
|
217
|
-
-
|
|
218
|
-
|
|
219
|
-
-
|
|
220
|
-
-
|
|
221
|
-
-
|
|
222
|
-
|
|
217
|
+
- column types follow `pg`'s default type parsers (`int8` and `numeric` are strings, `timestamptz` is a `Date`, etc.),
|
|
218
|
+
enums become unions of their labels, `json` and `jsonb` are `unknown`
|
|
219
|
+
- columns are non-null only when they come straight from a `not null` table column and the query has no outer joins
|
|
220
|
+
nor `rollup`, `cube` or `grouping sets`, unless [hinted](#column-nullability)
|
|
221
|
+
- params of multi-statement queries are always required `string`s, as they're embedded into sql string
|
|
222
|
+
- queries that fail to describe are reported as warnings and fall back to the naive types
|
|
223
|
+
- connecting times out after 5 seconds unless `connectionTimeoutMillis` is set, after which describing is skipped
|
|
224
|
+
for 10 seconds
|
|
223
225
|
|
|
224
226
|
Only the generated `.d.ts` files depend on it, the generated JS stays the same. Hence the database is only ever
|
|
225
227
|
connected to by the dev server, `vite build` and vitest don't connect, nor do they touch the `.d.ts` files
|
|
@@ -245,11 +247,11 @@ postgres({
|
|
|
245
247
|
});
|
|
246
248
|
```
|
|
247
249
|
|
|
248
|
-
-
|
|
249
|
-
-
|
|
250
|
-
|
|
251
|
-
-
|
|
252
|
-
-
|
|
250
|
+
- builtins, enums, composites and domains can be overridden
|
|
251
|
+
- `pg` parses arrays separately from their elements, so array columns need their own `name[]` entry,
|
|
252
|
+
array params fall back to the element's override
|
|
253
|
+
- domain columns pick up their override only when selected straight from a table, otherwise the base type's applies
|
|
254
|
+
- types are inserted verbatim into the generated `.d.ts`, so don't use relative paths in `import()`
|
|
253
255
|
|
|
254
256
|
_default:_ `{}`
|
|
255
257
|
|
|
@@ -270,6 +272,49 @@ where id = :id!;
|
|
|
270
272
|
function UpdateBio(params: { bio?: string | null; id: number | bigint | string }, config?): Promise<number>;
|
|
271
273
|
```
|
|
272
274
|
|
|
275
|
+
## Slots
|
|
276
|
+
|
|
277
|
+
`@` symbol turns parameter into a slot, which is injected into the sql string directly. Slots may reference
|
|
278
|
+
params with the same `:name` syntax, these have to be declared in braces after the slot:
|
|
279
|
+
|
|
280
|
+
```sql
|
|
281
|
+
-- name: ListUsers :many
|
|
282
|
+
select *
|
|
283
|
+
from users
|
|
284
|
+
where org = :org! and @filter{status?, since?}
|
|
285
|
+
order by @orderBy;
|
|
286
|
+
```
|
|
287
|
+
|
|
288
|
+
```js
|
|
289
|
+
await ListUsers({
|
|
290
|
+
org,
|
|
291
|
+
filter: [status && "status = :status", since && "created_at > :since"].filter(Boolean).join(" and ") || "true",
|
|
292
|
+
orderBy: desc ? "id desc" : "id",
|
|
293
|
+
status,
|
|
294
|
+
since,
|
|
295
|
+
});
|
|
296
|
+
```
|
|
297
|
+
|
|
298
|
+
```ts
|
|
299
|
+
function ListUsers<R1 extends QueryResultRow = { [column: string]: unknown }>(
|
|
300
|
+
params: { org: {}; filter: string; orderBy: string; status?: unknown; since?: unknown },
|
|
301
|
+
config?,
|
|
302
|
+
): Promise<R1[]>;
|
|
303
|
+
```
|
|
304
|
+
|
|
305
|
+
- slot params are bound as positional params, numbered after the query's own ones and only when referenced.
|
|
306
|
+
params outside the slot's can be referenced by the slot string without explicit enumeration
|
|
307
|
+
- undeclared `:names` are left as is, you must declare all slots' possible params,
|
|
308
|
+
not all of them must be present in the slot string
|
|
309
|
+
- slots are inserted verbatim, never pass user input into them
|
|
310
|
+
- declared params are typed like undescribed params: required `unknown`, `{}` with a `!`,
|
|
311
|
+
and `?` makes them optional. they're not validated at runtime
|
|
312
|
+
- queries with slots can't be `:prepare`d, nor described
|
|
313
|
+
|
|
314
|
+
> [!Warning]
|
|
315
|
+
>
|
|
316
|
+
> Postgres has a prefix `@` operator for absolute values, write it as `@ x` or `abs(x)` instead.
|
|
317
|
+
|
|
273
318
|
## Column nullability
|
|
274
319
|
|
|
275
320
|
When `describe` can't tell whether a column is nullable, e.g. for `count(*)` or columns behind an outer join you know
|
|
@@ -310,8 +355,7 @@ Exact and conditional (`{ "node": ..., "default": ... }`) targets are supported
|
|
|
310
355
|
|
|
311
356
|
With the `'function'` runtime type, the runtime is re-evaluated on every query call — which means it can
|
|
312
357
|
consult [`AsyncLocalStorage`](https://nodejs.org/api/async_context.html#class-asynclocalstorage) and pick up
|
|
313
|
-
an _ambient_ transaction
|
|
314
|
-
no threading of `{ db }` through your functions. Combined with
|
|
358
|
+
an _ambient_ transaction which queries are going to run on down the call stack. Combined with
|
|
315
359
|
[explicit resource management](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/await_using)
|
|
316
360
|
you get commit-explicitly, rollback-on-dispose semantics without any callback wrapping.
|
|
317
361
|
|
|
@@ -392,12 +436,10 @@ await InsertAudit({ id: 1 }); // same transaction, however deep the call stack
|
|
|
392
436
|
await tx.commit(); // anything thrown before this point rolls back on scope exit
|
|
393
437
|
```
|
|
394
438
|
|
|
395
|
-
##
|
|
439
|
+
## Go to Defintion
|
|
396
440
|
|
|
397
|
-
Generated `.d.ts` files
|
|
398
|
-
|
|
399
|
-
on the query source itself. The vite transform also emits a sourcemap, so runtime stack traces
|
|
400
|
-
and debugger stepping map back to the `.sql` source.
|
|
441
|
+
Generated `.d.ts` files contain source maps that point to query start in `.sql` files. Triggering
|
|
442
|
+
"Go to Definition" on a query function takes you straight to the source `.sql` file.
|
|
401
443
|
|
|
402
444
|
## What this plugin does NOT do
|
|
403
445
|
|
package/describe.js
CHANGED
|
@@ -236,7 +236,8 @@ export function describer(config, typesOverrides = {}) {
|
|
|
236
236
|
* @param {string} filename
|
|
237
237
|
*/
|
|
238
238
|
async annotate(modules, filename) {
|
|
239
|
-
|
|
239
|
+
// slots' sql is only known at runtime
|
|
240
|
+
const statements = modules.flat().filter((s) => !s.slots.size);
|
|
240
241
|
if (!statements.length) return;
|
|
241
242
|
const texts = statements.map((s) => bindParams(stripHints(s.query), s.params));
|
|
242
243
|
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "vite-plugin-postgres-import",
|
|
3
3
|
"description": "Vite plugin for importing SQL files as JS modules with sqlc-style annotations",
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.10.0",
|
|
5
5
|
"main": "plugin.js",
|
|
6
6
|
"types": "plugin.d.ts",
|
|
7
7
|
"type": "module",
|
|
@@ -14,6 +14,7 @@
|
|
|
14
14
|
"files": [
|
|
15
15
|
"describe.js",
|
|
16
16
|
"parse.js",
|
|
17
|
+
"runtime.js",
|
|
17
18
|
"plugin.d.ts",
|
|
18
19
|
"plugin.d.ts.map"
|
|
19
20
|
],
|
|
@@ -45,4 +46,4 @@
|
|
|
45
46
|
"engines": {
|
|
46
47
|
"node": ">=22.0.0"
|
|
47
48
|
}
|
|
48
|
-
}
|
|
49
|
+
}
|
package/parse.js
CHANGED
|
@@ -1,5 +1,13 @@
|
|
|
1
1
|
const annotationRegex = /--\s*name:\s*(?<name>[a-zA-Z][\w_]*)\s*(?<tags>(:\w+\s*)*)?\r?\n/g;
|
|
2
2
|
const paramRegex = /(?<![\w\\:]):(\w+)(!(?![=~]))?/g;
|
|
3
|
+
const slotRegex = /(?<![\w\\@<])@(\w+)(?:\{([\w\s,!?]*)\})?/g;
|
|
4
|
+
const markerRank = { "?": 0, "": 1, "!": 2 };
|
|
5
|
+
|
|
6
|
+
/** Sets a slot param's `!`/`?` marker, the stricter of conflicting ones wins. */
|
|
7
|
+
function mergeMarker(/** @type {Map<string, string>} */ map, /** @type {string} */ param, /** @type {string} */ marker) {
|
|
8
|
+
const prev = map.get(param);
|
|
9
|
+
if (prev === undefined || markerRank[marker] > markerRank[prev]) map.set(param, marker);
|
|
10
|
+
}
|
|
3
11
|
const hintRegex = /\bas\s+"([^"]+?)([!?])"/gi;
|
|
4
12
|
|
|
5
13
|
/** Strips `!` and `?` nullability hints off of `as "alias!"` column aliases and all references to them. */
|
|
@@ -124,6 +132,15 @@ function metadata(/** @type {string} */ s, /** @type {ReturnType<typeof metadata
|
|
|
124
132
|
const query = s.substring(match?.[0]?.length ?? 0).trim();
|
|
125
133
|
const stripped = stripHints(query);
|
|
126
134
|
const params = query.matchAll(paramRegex).toArray();
|
|
135
|
+
/** @type {Map<string, Map<string, string>>} */
|
|
136
|
+
const slots = new Map();
|
|
137
|
+
for (const [, slot, declared] of query.matchAll(slotRegex)) {
|
|
138
|
+
const declarations = slots.get(slot) ?? slots.set(slot, new Map()).get(slot);
|
|
139
|
+
for (const d of declared?.matchAll(/(\w+)([!?]?)/g) ?? []) mergeMarker(declarations, d[1], d[2]);
|
|
140
|
+
}
|
|
141
|
+
for (const [, p] of params) {
|
|
142
|
+
if (slots.has(p)) throw new Error(`${meta?.name ?? firstMeta?.name}: @${p} slot shares its name with a param`);
|
|
143
|
+
}
|
|
127
144
|
|
|
128
145
|
return {
|
|
129
146
|
name: firstMeta?.name || meta?.name,
|
|
@@ -134,6 +151,7 @@ function metadata(/** @type {string} */ s, /** @type {ReturnType<typeof metadata
|
|
|
134
151
|
query,
|
|
135
152
|
params: new Set(params.map((m) => m[1])),
|
|
136
153
|
required: new Set(params.filter((m) => m[2]).map((m) => m[1])),
|
|
154
|
+
slots,
|
|
137
155
|
/** @type {[key: string, type: string][] | undefined} */
|
|
138
156
|
columns: undefined,
|
|
139
157
|
/** @type {Map<string, string> | undefined} */
|
|
@@ -149,6 +167,8 @@ function metadata(/** @type {string} */ s, /** @type {ReturnType<typeof metadata
|
|
|
149
167
|
|
|
150
168
|
function parseResultSymbol(/** @type {string} */ s) {
|
|
151
169
|
s = s.trim();
|
|
170
|
+
slotRegex.lastIndex = 0;
|
|
171
|
+
if (slotRegex.test(s)) return "[column: string]";
|
|
152
172
|
while (s.startsWith("(") && s.endsWith(")")) {
|
|
153
173
|
// unwrap
|
|
154
174
|
s = s.substring(1, s.length - 1).trim();
|
|
@@ -217,6 +237,13 @@ export function codegen(
|
|
|
217
237
|
query: module.flatMap((m) => m.query).join(";\n\n"),
|
|
218
238
|
params: new Set(module.flatMap((m) => [...m.params])),
|
|
219
239
|
required: new Set(module.flatMap((m) => [...m.required])),
|
|
240
|
+
slots: module.reduce((acc, m) => {
|
|
241
|
+
for (const [slot, declarations] of m.slots) {
|
|
242
|
+
const merged = acc.get(slot) ?? acc.set(slot, new Map()).get(slot);
|
|
243
|
+
for (const [p, marker] of declarations) mergeMarker(merged, p, marker);
|
|
244
|
+
}
|
|
245
|
+
return acc;
|
|
246
|
+
}, new Map()),
|
|
220
247
|
// values are inlined with escapeLiteral, which only accepts strings
|
|
221
248
|
paramTypes: module.some((m) => m.paramTypes)
|
|
222
249
|
? new Map(module.flatMap((m) => [...m.params]).map((p) => [p, "string"]))
|
|
@@ -243,17 +270,22 @@ export function codegen(
|
|
|
243
270
|
js[0] += `\nimport Cursor from 'pg-cursor';`;
|
|
244
271
|
}
|
|
245
272
|
|
|
246
|
-
|
|
247
|
-
const
|
|
248
|
-
|
|
249
|
-
.
|
|
273
|
+
/** @type {Map<string, string>} */
|
|
274
|
+
const slotParams = new Map();
|
|
275
|
+
for (const declarations of module.slots.values()) {
|
|
276
|
+
for (const [p, marker] of declarations) if (!module.params.has(p)) mergeMarker(slotParams, p, marker);
|
|
277
|
+
}
|
|
278
|
+
let optionalParams = !module.slots.size;
|
|
279
|
+
const keys = [
|
|
280
|
+
...module.params.values().map((p) => {
|
|
250
281
|
const type = module.paramTypes?.get(p) ?? "unknown";
|
|
251
282
|
if (type !== "unknown" && !module.required.has(p) && !module.multiStatement) return `${p}?: ${type} | null`;
|
|
252
283
|
optionalParams = false;
|
|
253
284
|
return `${p}: ${type === "unknown" && module.required.has(p) ? "{}" : type}`;
|
|
254
|
-
})
|
|
255
|
-
.
|
|
256
|
-
.
|
|
285
|
+
}),
|
|
286
|
+
...module.slots.keys().map((s) => `${s}: string`),
|
|
287
|
+
...slotParams.entries().map(([p, marker]) => `${p}${marker === "?" ? "?: unknown" : marker ? ": {}" : ": unknown"}`),
|
|
288
|
+
].join("; ");
|
|
257
289
|
|
|
258
290
|
dts.push(`/**
|
|
259
291
|
* ${"```"}sql
|
|
@@ -305,6 +337,34 @@ export function ${module.name}<${module.returnSymbols
|
|
|
305
337
|
module.multiStatement ? `\${escapeLiteral(${param})}` : `$${i + 1}` // the escapists
|
|
306
338
|
);
|
|
307
339
|
|
|
340
|
+
const slotted = module.slots.size > 0;
|
|
341
|
+
let args = `{ ${paramsString} } = {}`;
|
|
342
|
+
let values = `[ ${paramsString} ]`;
|
|
343
|
+
let pre = "";
|
|
344
|
+
if (slotted) {
|
|
345
|
+
if (module.prepared) throw new Error(`${module.name}: queries with slots can't be prepared`);
|
|
346
|
+
if (!js[0].includes("__slots")) {
|
|
347
|
+
js[0] += `\nimport { slot as __slot, slots as __slots } from 'vite-plugin-postgres-import/runtime.js';`;
|
|
348
|
+
}
|
|
349
|
+
const state = `__${module.name}`;
|
|
350
|
+
js.push(
|
|
351
|
+
`const ${state} = __slots(${JSON.stringify([...module.params])}, ${JSON.stringify([...slotParams.keys()])}${
|
|
352
|
+
module.multiStatement ? ", escapeLiteral" : ""
|
|
353
|
+
});`,
|
|
354
|
+
);
|
|
355
|
+
module.query = module.query.replaceAll(
|
|
356
|
+
slotRegex,
|
|
357
|
+
(_, slot) => `\${__slot(${slot}, ${module.multiStatement ? "null" : "__v"}, __p, ${state})}`,
|
|
358
|
+
);
|
|
359
|
+
args = "__p = {}";
|
|
360
|
+
values = "__v";
|
|
361
|
+
pre = `const { ${[...module.params, ...module.slots.keys()].join()} } = __p${
|
|
362
|
+
module.multiStatement ? "" : `, __v = [ ${paramsString} ]`
|
|
363
|
+
};`;
|
|
364
|
+
}
|
|
365
|
+
const body = (/** @type {string} */ expr) => (slotted ? `{\n\t${pre}\n\treturn ${expr};\n}` : expr);
|
|
366
|
+
const valuesArg = slotted ? (module.multiStatement ? "" : ", __v") : paramsString && `, ${values}`;
|
|
367
|
+
|
|
308
368
|
if (module.prepared && module.execution.size > 1) {
|
|
309
369
|
console.warn(
|
|
310
370
|
"Postgres does not support preparing multi-statement queries. You will get an error, just sayin'"
|
|
@@ -313,12 +373,14 @@ export function ${module.name}<${module.returnSymbols
|
|
|
313
373
|
|
|
314
374
|
js.push(
|
|
315
375
|
module.mode === ":cursor"
|
|
316
|
-
? `export const ${module.name} = async (
|
|
317
|
-
module.query
|
|
318
|
-
|
|
376
|
+
? `export const ${module.name} = async (${args}, { db: __db = ${rt} } = {}) => ${body(
|
|
377
|
+
`(await __db).query(new Cursor(\`${module.query}\`${valuesArg}${
|
|
378
|
+
module.rowArray ? `, { rowMode: "array" }` : ""
|
|
379
|
+
}))`,
|
|
380
|
+
)};`
|
|
319
381
|
: module.mode === ":iterable"
|
|
320
|
-
? `export async function* ${module.name}(
|
|
321
|
-
const cursor = (await __db).query(new Cursor(\`${module.query}\`${
|
|
382
|
+
? `export async function* ${module.name}(${args}, { db: __db = ${rt}, read = 10 } = {}) {${pre && `\n\t${pre}`}
|
|
383
|
+
const cursor = (await __db).query(new Cursor(\`${module.query}\`${valuesArg}${
|
|
322
384
|
module.rowArray ? `, { rowMode: "array" }` : ""
|
|
323
385
|
}));
|
|
324
386
|
try {
|
|
@@ -331,10 +393,10 @@ export function ${module.name}<${module.returnSymbols
|
|
|
331
393
|
await cursor.close();
|
|
332
394
|
}
|
|
333
395
|
}`
|
|
334
|
-
: `export const ${module.name} = async (
|
|
396
|
+
: `export const ${module.name} = async (${args}, { db: __db = ${rt} } = {}) => ${body(`(await __db).query({
|
|
335
397
|
${module.prepared ? `name: "${module.name}",` : ""}
|
|
336
398
|
text: \`${module.query}\`,
|
|
337
|
-
${module.multiStatement ? "" : `values:
|
|
399
|
+
${module.multiStatement ? "" : `values: ${values},`}
|
|
338
400
|
${module.rowArray ? `rowMode: "array",` : ""}
|
|
339
401
|
}).then((${module.multiStatement && "["}${module.returnSymbols.map((_, i) => `r${i + 1}`).join()}${
|
|
340
402
|
module.multiStatement && "]"
|
|
@@ -350,7 +412,7 @@ export function ${module.name}<${module.returnSymbols
|
|
|
350
412
|
? `.rowCount`
|
|
351
413
|
: "")
|
|
352
414
|
)
|
|
353
|
-
.join()}${module.multiStatement && "]"});`
|
|
415
|
+
.join()}${module.multiStatement && "]"})`)};`
|
|
354
416
|
);
|
|
355
417
|
}
|
|
356
418
|
|
package/runtime.js
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @typedef {{
|
|
3
|
+
* index: Map<string, number>,
|
|
4
|
+
* k: number,
|
|
5
|
+
* ph: string[],
|
|
6
|
+
* pos: Int32Array,
|
|
7
|
+
* mark: Float64Array,
|
|
8
|
+
* epoch: number,
|
|
9
|
+
* cur: unknown[] | null,
|
|
10
|
+
* esc: ((value: string) => string) | undefined,
|
|
11
|
+
* }} Slots
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Static binding state of a query with slots. Own params map to their `$N`, slot params to `~j`.
|
|
16
|
+
* @param {string[]} own
|
|
17
|
+
* @param {string[]} extra
|
|
18
|
+
* @param {(value: string) => string} [esc] inlines values instead of binding them, for multi-statement queries
|
|
19
|
+
* @returns {Slots}
|
|
20
|
+
*/
|
|
21
|
+
export function slots(own, extra, esc) {
|
|
22
|
+
const index = new Map(own.map((p, i) => [p, i + 1]));
|
|
23
|
+
for (let j = 0; j < extra.length; ++j) if (!index.has(extra[j])) index.set(extra[j], ~j);
|
|
24
|
+
const ph = [];
|
|
25
|
+
for (let i = 1; i <= own.length + extra.length; ++i) ph.push("$" + i);
|
|
26
|
+
return {
|
|
27
|
+
index,
|
|
28
|
+
k: own.length,
|
|
29
|
+
ph,
|
|
30
|
+
pos: new Int32Array(extra.length),
|
|
31
|
+
mark: new Float64Array(extra.length),
|
|
32
|
+
epoch: 0,
|
|
33
|
+
cur: null,
|
|
34
|
+
esc,
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const word = (/** @type {number} */ c) => (c >= 48 && c <= 57) || (c >= 65 && c <= 90) || (c >= 97 && c <= 122) || c === 95;
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Binds `:param` placeholders of a slot's text, appending slot params to `values` on first use.
|
|
42
|
+
*
|
|
43
|
+
* A call is identified by its `values` array, a different one starts a new epoch.
|
|
44
|
+
* `pos[j]` is only trusted when `mark[j]` was set in the current epoch.
|
|
45
|
+
* @param {string} s
|
|
46
|
+
* @param {unknown[] | null} values
|
|
47
|
+
* @param {Record<string, unknown>} params
|
|
48
|
+
* @param {Slots} q
|
|
49
|
+
*/
|
|
50
|
+
export function slot(s, values, params, q) {
|
|
51
|
+
let i = s.indexOf(":");
|
|
52
|
+
if (i < 0) return s;
|
|
53
|
+
let out = "";
|
|
54
|
+
let last = 0;
|
|
55
|
+
for (; i >= 0; i = s.indexOf(":", i + 1)) {
|
|
56
|
+
const prev = i ? s.charCodeAt(i - 1) : 0;
|
|
57
|
+
if (prev === 58 || prev === 92 || word(prev)) continue;
|
|
58
|
+
let end = i + 1;
|
|
59
|
+
while (end < s.length && word(s.charCodeAt(end))) ++end;
|
|
60
|
+
if (end === i + 1) continue;
|
|
61
|
+
const name = s.slice(i + 1, end);
|
|
62
|
+
const n = q.index.get(name);
|
|
63
|
+
if (n === undefined) {
|
|
64
|
+
i = end - 1;
|
|
65
|
+
continue;
|
|
66
|
+
}
|
|
67
|
+
let p;
|
|
68
|
+
if (q.esc) {
|
|
69
|
+
p = q.esc(/** @type {string} */ (params[name]));
|
|
70
|
+
} else if (n > 0) {
|
|
71
|
+
p = q.ph[n - 1];
|
|
72
|
+
} else {
|
|
73
|
+
const j = ~n;
|
|
74
|
+
if (q.cur !== values) {
|
|
75
|
+
q.cur = values;
|
|
76
|
+
++q.epoch;
|
|
77
|
+
}
|
|
78
|
+
let N = q.pos[j];
|
|
79
|
+
if (q.mark[j] !== q.epoch) {
|
|
80
|
+
N = q.pos[j] = /** @type {unknown[]} */ (values).push(params[name]);
|
|
81
|
+
q.mark[j] = q.epoch;
|
|
82
|
+
}
|
|
83
|
+
p = q.ph[N - 1] ?? "$" + N;
|
|
84
|
+
}
|
|
85
|
+
if (s.charCodeAt(end) === 33) {
|
|
86
|
+
const c = s.charCodeAt(end + 1);
|
|
87
|
+
if (c !== 61 && c !== 126) ++end;
|
|
88
|
+
}
|
|
89
|
+
out += s.slice(last, i) + p;
|
|
90
|
+
last = end;
|
|
91
|
+
i = end - 1;
|
|
92
|
+
}
|
|
93
|
+
return last ? out + s.slice(last) : s;
|
|
94
|
+
}
|