ovr 6.2.4 → 7.0.0-next.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 (136) hide show
  1. package/README.md +3 -1
  2. package/dist/app/index.d.ts +51 -7
  3. package/dist/app/index.d.ts.map +1 -1
  4. package/dist/app/index.js +163 -28
  5. package/dist/auth/auth-data.d.ts +26 -0
  6. package/dist/auth/auth-data.d.ts.map +1 -0
  7. package/dist/auth/auth-data.js +42 -0
  8. package/dist/auth/cbor.d.ts +50 -0
  9. package/dist/auth/cbor.d.ts.map +1 -0
  10. package/dist/auth/cbor.js +200 -0
  11. package/dist/auth/client-source.d.ts +3 -0
  12. package/dist/auth/client-source.d.ts.map +1 -0
  13. package/dist/auth/client-source.js +3 -0
  14. package/dist/auth/client.d.ts +3 -0
  15. package/dist/auth/client.d.ts.map +1 -0
  16. package/dist/auth/client.js +186 -0
  17. package/dist/auth/configure.d.ts +28 -0
  18. package/dist/auth/configure.d.ts.map +1 -0
  19. package/dist/auth/configure.js +228 -0
  20. package/dist/auth/der.d.ts +6 -0
  21. package/dist/auth/der.d.ts.map +1 -0
  22. package/dist/auth/der.js +36 -0
  23. package/dist/auth/index.d.ts +242 -0
  24. package/dist/auth/index.d.ts.map +1 -0
  25. package/dist/auth/index.js +152 -0
  26. package/dist/auth/issue.d.ts +36 -0
  27. package/dist/auth/issue.d.ts.map +1 -0
  28. package/dist/auth/issue.js +47 -0
  29. package/dist/auth/metadata.d.ts +22 -0
  30. package/dist/auth/metadata.d.ts.map +1 -0
  31. package/dist/auth/metadata.js +134 -0
  32. package/dist/auth/oauth.d.ts +29 -0
  33. package/dist/auth/oauth.d.ts.map +1 -0
  34. package/dist/auth/oauth.js +724 -0
  35. package/dist/auth/passkey.d.ts +101 -0
  36. package/dist/auth/passkey.d.ts.map +1 -0
  37. package/dist/auth/passkey.js +393 -0
  38. package/dist/auth/state.d.ts +49 -0
  39. package/dist/auth/state.d.ts.map +1 -0
  40. package/dist/auth/state.js +184 -0
  41. package/dist/auth/storage.d.ts +193 -0
  42. package/dist/auth/storage.d.ts.map +1 -0
  43. package/dist/auth/storage.js +410 -0
  44. package/dist/auth/token.d.ts +12 -0
  45. package/dist/auth/token.d.ts.map +1 -0
  46. package/dist/auth/token.js +39 -0
  47. package/dist/context/index.d.ts +86 -16
  48. package/dist/context/index.d.ts.map +1 -1
  49. package/dist/context/index.js +166 -42
  50. package/dist/cookie/index.d.ts +3 -0
  51. package/dist/cookie/index.d.ts.map +1 -1
  52. package/dist/cookie/index.js +1 -0
  53. package/dist/database/index.d.ts +262 -0
  54. package/dist/database/index.d.ts.map +1 -0
  55. package/dist/database/index.js +807 -0
  56. package/dist/form/index.d.ts +699 -0
  57. package/dist/form/index.d.ts.map +1 -0
  58. package/dist/form/index.js +901 -0
  59. package/dist/index.d.ts +10 -3
  60. package/dist/index.d.ts.map +1 -1
  61. package/dist/index.js +9 -3
  62. package/dist/jsx/elements.d.ts +28 -2
  63. package/dist/jsx/elements.d.ts.map +1 -1
  64. package/dist/jsx/index.d.ts +20 -4
  65. package/dist/jsx/index.d.ts.map +1 -1
  66. package/dist/jsx/index.js +6 -65
  67. package/dist/limiter/index.d.ts +65 -0
  68. package/dist/limiter/index.d.ts.map +1 -0
  69. package/dist/limiter/index.js +157 -0
  70. package/dist/markdown/index.d.ts +61 -0
  71. package/dist/markdown/index.d.ts.map +1 -0
  72. package/dist/markdown/index.js +1160 -0
  73. package/dist/markup/index.d.ts +188 -0
  74. package/dist/markup/index.d.ts.map +1 -0
  75. package/dist/markup/index.js +718 -0
  76. package/dist/mcp/index.d.ts +73 -0
  77. package/dist/mcp/index.d.ts.map +1 -0
  78. package/dist/mcp/index.js +988 -0
  79. package/dist/middleware/index.d.ts +3 -4
  80. package/dist/middleware/index.d.ts.map +1 -1
  81. package/dist/multipart/index.d.ts +53 -7
  82. package/dist/multipart/index.d.ts.map +1 -1
  83. package/dist/multipart/index.js +332 -124
  84. package/dist/route/index.d.ts +226 -80
  85. package/dist/route/index.d.ts.map +1 -1
  86. package/dist/route/index.js +239 -99
  87. package/dist/schema/index.d.ts +307 -734
  88. package/dist/schema/index.d.ts.map +1 -1
  89. package/dist/schema/index.js +783 -1050
  90. package/dist/table/index.d.ts +132 -0
  91. package/dist/table/index.d.ts.map +1 -0
  92. package/dist/table/index.js +188 -0
  93. package/dist/trie/index.js +4 -4
  94. package/dist/util/index.d.ts +37 -5
  95. package/dist/util/index.d.ts.map +1 -1
  96. package/dist/util/index.js +156 -41
  97. package/package.json +11 -4
  98. package/src/app/index.ts +230 -42
  99. package/src/auth/auth-data.ts +56 -0
  100. package/src/auth/cbor.ts +231 -0
  101. package/src/auth/client-source.ts +3 -0
  102. package/src/auth/client.ts +205 -0
  103. package/src/auth/configure.ts +279 -0
  104. package/src/auth/der.ts +35 -0
  105. package/src/auth/index.ts +387 -0
  106. package/src/auth/issue.ts +52 -0
  107. package/src/auth/metadata.ts +149 -0
  108. package/src/auth/oauth.ts +882 -0
  109. package/src/auth/passkey.ts +556 -0
  110. package/src/auth/state.ts +213 -0
  111. package/src/auth/storage.ts +572 -0
  112. package/src/auth/token.ts +67 -0
  113. package/src/context/index.ts +240 -65
  114. package/src/cookie/index.ts +3 -0
  115. package/src/database/index.ts +1193 -0
  116. package/src/form/index.ts +1720 -0
  117. package/src/index.ts +10 -3
  118. package/src/jsx/elements.ts +45 -25
  119. package/src/jsx/index.ts +24 -69
  120. package/src/limiter/index.ts +221 -0
  121. package/src/markdown/index.ts +1322 -0
  122. package/src/markup/index.ts +853 -0
  123. package/src/mcp/conformance.2025-11-25.yml +39 -0
  124. package/src/mcp/conformance.2026-07-28.yml +56 -0
  125. package/src/mcp/index.ts +1262 -0
  126. package/src/middleware/index.ts +5 -6
  127. package/src/multipart/index.ts +410 -158
  128. package/src/route/index.ts +559 -278
  129. package/src/schema/index.ts +1542 -2256
  130. package/src/table/index.ts +387 -0
  131. package/src/trie/index.ts +4 -4
  132. package/src/util/index.ts +163 -49
  133. package/dist/render/index.d.ts +0 -79
  134. package/dist/render/index.d.ts.map +0 -1
  135. package/dist/render/index.js +0 -257
  136. package/src/render/index.ts +0 -314
@@ -0,0 +1,1193 @@
1
+ import { Schema, append, exact } from "../schema/index.js";
2
+ import { Column, Table } from "../table/index.js";
3
+
4
+ export namespace Database {
5
+ /** Query capability of a pg-compatible client. */
6
+ export interface Client {
7
+ query(text: string, values?: unknown[]): Promise<Result>;
8
+ }
9
+
10
+ /** Query result of a pg-compatible client. */
11
+ export interface Result {
12
+ readonly rows: unknown[];
13
+
14
+ /** Returned columns, used to decode `int8`, `numeric`, and JSON values. */
15
+ readonly fields?: readonly Field[];
16
+ }
17
+
18
+ /** Returned column with its Postgres type ID. */
19
+ export interface Field {
20
+ readonly name: string;
21
+ readonly dataTypeID: number;
22
+ }
23
+
24
+ /** pg-compatible pool; `connect` checks out one client for a transaction, `sql(fn)`. */
25
+ export interface Pool extends Client {
26
+ connect(): Promise<Client & { release(error?: Error | boolean): void }>;
27
+ }
28
+
29
+ /** SQL migration applied by `migrate`. */
30
+ export interface Migration {
31
+ /** Unique ID, migrations are applied in ID order. */
32
+ readonly id: string;
33
+
34
+ /** Trusted SQL, may contain several statements but not `BEGIN`, `COMMIT`, or `ROLLBACK`, since it runs in a transaction. */
35
+ readonly sql: string;
36
+ }
37
+
38
+ /**
39
+ * Tables accessible by name on the database, none when names are unknown so any database is a `Database`.
40
+ *
41
+ * @template T Tables of the database
42
+ */
43
+ export type Tables<T extends readonly Table.Any[]> =
44
+ string extends T[number]["name"]
45
+ ? {}
46
+ : { readonly [K in T[number] as K["name"]]: K };
47
+
48
+ /** Names used by database members, tables cannot use them. */
49
+ export type Reserved = "sql" | "migrate" | "check";
50
+
51
+ /**
52
+ * Tables with reserved names, or a name another table has, are rejected.
53
+ *
54
+ * @template T Tables to check
55
+ */
56
+ export type Valid<T extends readonly Table.Any[]> = {
57
+ readonly [I in keyof T]: T[I] extends { name: Reserved }
58
+ ? never
59
+ : string extends T[I]["name"]
60
+ ? T[I]
61
+ : T[I]["name"] extends {
62
+ [J in keyof T]: J extends I ? never : T[J]["name"];
63
+ }[number]
64
+ ? never
65
+ : T[I];
66
+ };
67
+
68
+ /** SQL template tag and helpers bound to a pool or transaction. */
69
+ export interface Tag {
70
+ /**
71
+ * Build a query, run when awaited.
72
+ *
73
+ * Tables and columns become quoted identifiers, nested fragments are
74
+ * inlined, and every other value becomes a bound parameter.
75
+ */
76
+ (strings: TemplateStringsArray, ...values: unknown[]): Sql;
77
+
78
+ /**
79
+ * Validate rows and build the `(columns) VALUES (...)` of an insert.
80
+ * Omitted columns use their SQL default.
81
+ *
82
+ * @template T Table to insert into
83
+ * @param table Table to insert into
84
+ * @param rows One row or several, an empty list throws
85
+ * @returns Columns and values
86
+ */
87
+ values<T extends Table.Any>(
88
+ table: T,
89
+ rows: Insert<T> | readonly Insert<T>[],
90
+ ): Sql;
91
+
92
+ /**
93
+ * Validate values and build the assignments of an update.
94
+ *
95
+ * @template T Table to update
96
+ * @param table Table to update
97
+ * @param values Columns to change
98
+ * @returns Assignments
99
+ */
100
+ set<T extends Table.Any>(table: T, values: Update<T>): Sql;
101
+ }
102
+
103
+ /**
104
+ * Insert values of a table.
105
+ *
106
+ * @template T Table
107
+ */
108
+ export type Insert<T extends Table.Any> =
109
+ T extends Table<string, infer S, infer O> ? Table.Insert<S, O> : never;
110
+
111
+ /**
112
+ * Update values of a table.
113
+ *
114
+ * @template T Table
115
+ */
116
+ export type Update<T extends Table.Any> =
117
+ T extends Table<string, infer S, any> ? Table.Update<S> : never;
118
+
119
+ /** Scope passed to `database.sql(fn)`. */
120
+ export interface Transaction {
121
+ /** SQL tag that runs in the transaction. */
122
+ readonly sql: Tag;
123
+ }
124
+ }
125
+
126
+ /** Identifier quoting shared by `Sql` and `Database`, not exported. */
127
+ class Identifier {
128
+ /**
129
+ * @param name Identifier
130
+ * @returns Quoted identifier
131
+ */
132
+ static quote(name: string) {
133
+ // an empty name or a NUL in one is a type error, see `Table.Identifier`
134
+ return `"${name.replaceAll('"', '""')}"`;
135
+ }
136
+
137
+ /**
138
+ * @param table Table
139
+ * @returns Quoted, schema-qualified table name
140
+ */
141
+ static table(table: Table.Any) {
142
+ return (
143
+ (table.options.schema
144
+ ? `${Identifier.quote(table.options.schema)}.`
145
+ : "") + Identifier.quote(table.name)
146
+ );
147
+ }
148
+ }
149
+
150
+ /** Converts one driver value. */
151
+ type Convert = (value: unknown) => unknown;
152
+
153
+ /**
154
+ * SQL fragment, a lazy promise that runs once on its client when awaited.
155
+ *
156
+ * @template Row Row type
157
+ */
158
+ export class Sql<Row = unknown> implements Promise<Row[]> {
159
+ /** Text segments surrounding the values. */
160
+ readonly #strings: readonly string[];
161
+
162
+ /** Interpolated values. */
163
+ readonly #values: readonly unknown[];
164
+
165
+ /** Client used when awaited. */
166
+ readonly #client: Database.Client;
167
+
168
+ /** Schema validating each returned row. */
169
+ readonly #schema: Schema<Row> | undefined;
170
+
171
+ /** Query result, shared with the fragments `parse` returns so the query runs once. */
172
+ readonly #execution: { result?: Promise<Database.Result> };
173
+
174
+ /** Validated rows, started by the first `then`, `catch`, or `finally`. */
175
+ #result?: Promise<Row[]>;
176
+
177
+ readonly [Symbol.toStringTag] = "Sql";
178
+
179
+ /**
180
+ * @param strings Text segments, one more than values
181
+ * @param values Interpolated values
182
+ * @param client Client used when awaited
183
+ * @param schema Schema validating each returned row
184
+ * @param execution Query result shared with the source fragment
185
+ */
186
+ constructor(
187
+ strings: readonly string[],
188
+ values: readonly unknown[],
189
+ client: Database.Client,
190
+ schema?: Schema<Row>,
191
+ execution: { result?: Promise<Database.Result> } = {},
192
+ ) {
193
+ this.#strings = strings;
194
+ this.#values = values;
195
+ this.#client = client;
196
+ this.#schema = schema;
197
+ this.#execution = execution;
198
+ }
199
+
200
+ /**
201
+ * Parse each returned row with a schema, throwing the issues if any fail.
202
+ * The query still runs once, however many fragments `parse` returns.
203
+ *
204
+ * @template O Row type
205
+ * @param schema Row schema, for example a table
206
+ * @returns Fragment returning parsed rows
207
+ */
208
+ parse<O>(schema: Schema<O>) {
209
+ return new Sql<O>(
210
+ this.#strings,
211
+ this.#values,
212
+ this.#client,
213
+ schema,
214
+ this.#execution,
215
+ );
216
+ }
217
+
218
+ /**
219
+ * Compile to parameterized text.
220
+ *
221
+ * @returns Query text and parameter values
222
+ */
223
+ toQuery() {
224
+ const values: unknown[] = [];
225
+
226
+ return { text: this.#build(values), values };
227
+ }
228
+
229
+ /**
230
+ * Run the query once, the first time the result is requested.
231
+ *
232
+ * @template A Result of `resolve`
233
+ * @template B Result of `reject`
234
+ * @param resolve Receives the rows
235
+ * @param reject Receives the query or validation error
236
+ * @returns Promise of the callback result
237
+ */
238
+ then<A = Row[], B = never>(
239
+ resolve?: ((rows: Row[]) => A | PromiseLike<A>) | null,
240
+ reject?: ((reason: unknown) => B | PromiseLike<B>) | null,
241
+ ) {
242
+ return (this.#result ??= this.#run()).then(resolve, reject);
243
+ }
244
+
245
+ /**
246
+ * @template B Result of `reject`
247
+ * @param reject Receives the query or validation error
248
+ * @returns Promise of the rows or the callback result
249
+ */
250
+ catch<B = never>(reject?: ((reason: unknown) => B | PromiseLike<B>) | null) {
251
+ return this.then(undefined, reject);
252
+ }
253
+
254
+ /**
255
+ * @param fn Called when the query settles
256
+ * @returns Promise of the rows
257
+ */
258
+ finally(fn?: (() => void) | null) {
259
+ return this.then().finally(fn);
260
+ }
261
+
262
+ async #run() {
263
+ if (!this.#execution.result) {
264
+ const { text, values } = this.toQuery();
265
+
266
+ this.#execution.result = this.#client.query(text, values);
267
+ }
268
+
269
+ const { rows, fields } = await this.#execution.result;
270
+
271
+ if (!this.#schema) return rows as Row[];
272
+
273
+ const base = Sql.#base(this.#schema.def);
274
+ const decode =
275
+ base.type === "object" && fields
276
+ ? Sql.#decoder(base.shape, fields)
277
+ : undefined;
278
+ const data: Row[] = [];
279
+ const issues: Schema.Issue[] = [];
280
+
281
+ for (let i = 0; i < rows.length; i++) {
282
+ const result = this.#schema.parse(decode ? decode(rows[i]) : rows[i], [
283
+ i,
284
+ ]);
285
+
286
+ if (result.issues) append(issues, result.issues);
287
+ else data.push(result.data);
288
+ }
289
+
290
+ if (issues.length) throw new Schema.AggregateIssue(issues);
291
+
292
+ return data;
293
+ }
294
+
295
+ /**
296
+ * @param values Parameter values, appended to
297
+ * @returns Query text using `$n` placeholders
298
+ */
299
+ #build(values: unknown[]): string {
300
+ let text = this.#strings[0]!;
301
+
302
+ for (let i = 0; i < this.#values.length; i++) {
303
+ const value = this.#values[i];
304
+
305
+ text +=
306
+ (value instanceof Sql
307
+ ? value.#build(values)
308
+ : value instanceof Table
309
+ ? Identifier.table(value)
310
+ : value instanceof Column
311
+ ? `${Identifier.table(value.table)}.${Identifier.quote(value.name)}`
312
+ : `$${values.push(typeof value === "bigint" ? String(value) : value)}`) +
313
+ this.#strings[i + 1];
314
+ }
315
+
316
+ return text;
317
+ }
318
+
319
+ /**
320
+ * @param def Schema definition
321
+ * @returns Definition that validates the input, without modifiers
322
+ */
323
+ static #base(def: Schema.Def): Schema.Def {
324
+ switch (def.type) {
325
+ case "optional":
326
+ case "nullable":
327
+ case "nullish":
328
+ case "default":
329
+ case "check":
330
+ case "pipe":
331
+ case "transform":
332
+ return Sql.#base(def.inner.def);
333
+ }
334
+
335
+ return def;
336
+ }
337
+
338
+ /**
339
+ * Build the row decoder for one result, converting driver values into the
340
+ * types the row schema expects by each column's Postgres type.
341
+ *
342
+ * @param shape Row schema shape
343
+ * @param fields Returned columns
344
+ * @returns Decoder, or `undefined` when no column needs converting
345
+ */
346
+ static #decoder(
347
+ shape: Schema.Object.Shape,
348
+ fields: readonly Database.Field[],
349
+ ) {
350
+ const columns: [name: string, convert: Convert][] = [];
351
+
352
+ for (const { name, dataTypeID } of fields) {
353
+ if (!Object.hasOwn(shape, name)) continue;
354
+
355
+ const def = shape[name]!.def;
356
+ let convert: Convert | undefined;
357
+
358
+ switch (dataTypeID) {
359
+ case 20: // int8
360
+ case 1700: // numeric
361
+ convert = Sql.#number(def);
362
+ break;
363
+ case 1016: // int8[]
364
+ case 1231: // numeric[]
365
+ convert = Sql.#numbers(def);
366
+ break;
367
+ case 114: // json
368
+ case 3802: // jsonb
369
+ case 199: // json[]
370
+ case 3807: // jsonb[]
371
+ convert = Sql.#dates(def);
372
+ }
373
+
374
+ if (convert) columns.push([name, convert]);
375
+ }
376
+
377
+ return Sql.#keys(columns);
378
+ }
379
+
380
+ /**
381
+ * @param keys Converter for each key that needs one
382
+ * @returns Converter for an object, `undefined` when no key needs one
383
+ */
384
+ static #keys(keys: [key: string, convert: Convert][]): Convert | undefined {
385
+ if (!keys.length) return;
386
+
387
+ return (value) => {
388
+ if (value == null || typeof value !== "object" || Array.isArray(value))
389
+ return value;
390
+
391
+ // copied, a driver's row may be shared with other views
392
+ const decoded: Record<string, unknown> = { ...value };
393
+
394
+ for (const [key, convert] of keys) {
395
+ if (Object.hasOwn(decoded, key)) decoded[key] = convert(decoded[key]);
396
+ }
397
+
398
+ return decoded;
399
+ };
400
+ }
401
+
402
+ /**
403
+ * @param def Schema definition
404
+ * @returns Converter for a Postgres array, possibly multidimensional
405
+ */
406
+ static #numbers(def: Schema.Def): Convert | undefined {
407
+ const base = Sql.#base(def);
408
+
409
+ if (base.type !== "array") return Sql.#number(def);
410
+
411
+ return Sql.#each(Sql.#numbers(base.item.def));
412
+ }
413
+
414
+ /**
415
+ * @param item Converter for each item
416
+ * @returns Converter for an array, `undefined` when items need none
417
+ */
418
+ static #each(item: Convert | undefined): Convert | undefined {
419
+ return (
420
+ item && ((value) => (Array.isArray(value) ? value.map(item) : value))
421
+ );
422
+ }
423
+
424
+ /**
425
+ * Drivers return `int8` and `numeric` as strings or bigints, and pg
426
+ * returns `numeric[]` items as numbers.
427
+ *
428
+ * @param def Schema definition
429
+ * @returns Converter to a bigint or number, integers are never rounded
430
+ */
431
+ static #number(def: Schema.Def): Convert | undefined {
432
+ const base = Sql.#base(def);
433
+
434
+ // numbers beyond 2^53 were already rounded by the driver
435
+ if (base.type === "bigint")
436
+ return (value) =>
437
+ (typeof value === "string" && /^-?\d+$/.test(value)) ||
438
+ Number.isSafeInteger(value)
439
+ ? BigInt(value as string | number)
440
+ : value;
441
+
442
+ if (base.type !== "number") return;
443
+
444
+ return (value) => {
445
+ if (
446
+ typeof value !== "string" &&
447
+ typeof value !== "bigint" &&
448
+ typeof value !== "number"
449
+ )
450
+ return value;
451
+
452
+ // integers beyond 2^53 may already be rounded
453
+ return exact(value);
454
+ };
455
+ }
456
+
457
+ /**
458
+ * JSON has no dates, so they are returned as ISO strings.
459
+ *
460
+ * @param def Schema definition
461
+ * @returns Converter for the branches containing dates, `undefined` without any
462
+ */
463
+ static #dates(def: Schema.Def): Convert | undefined {
464
+ const base = Sql.#base(def);
465
+
466
+ switch (base.type) {
467
+ case "date":
468
+ return (value) => (typeof value === "string" ? new Date(value) : value);
469
+ case "array":
470
+ return Sql.#each(Sql.#dates(base.item.def));
471
+ case "object": {
472
+ const keys: [key: string, convert: Convert][] = [];
473
+
474
+ for (const [key, schema] of Object.entries(base.shape)) {
475
+ const convert = Sql.#dates(schema.def);
476
+
477
+ if (convert) keys.push([key, convert]);
478
+ }
479
+
480
+ return Sql.#keys(keys);
481
+ }
482
+ case "union": {
483
+ const options = base.options.map(
484
+ (option) => [option, Sql.#dates(option.def)] as const,
485
+ );
486
+
487
+ if (!options.some(([, convert]) => convert)) return;
488
+
489
+ // the first branch the converted value matches, so a string
490
+ // in a branch without a date stays a string
491
+ return (value) => {
492
+ for (const [option, convert] of options) {
493
+ const converted = convert ? convert(value) : value;
494
+ if (!option.parse(converted).issues) return converted;
495
+ }
496
+
497
+ return value;
498
+ };
499
+ }
500
+ }
501
+ }
502
+ }
503
+
504
+ /**
505
+ * Migrations a library's tables bring, by table. Tables of one library share
506
+ * one list, applied by `database.migrate` in the order it lists them, before the application's.
507
+ */
508
+ export const owned = new WeakMap<Table.Any, readonly Database.Migration[]>();
509
+
510
+ /**
511
+ * Columns of a library's tables that must reference the `id` of a table the
512
+ * application chooses, with `ON DELETE CASCADE`, and the library that chooses
513
+ * it, for `database.check`.
514
+ */
515
+ export const referenced = new WeakMap<
516
+ Table.Any,
517
+ { readonly column: string; readonly by: string }
518
+ >();
519
+
520
+ /**
521
+ * The table each such column references, per database, set by the library
522
+ * when it is configured with that database.
523
+ */
524
+ export const references = new WeakMap<object, Map<Table.Any, Table.Any>>();
525
+
526
+ /**
527
+ * Database members, tables are added by name.
528
+ *
529
+ * @template T Tables of the database
530
+ */
531
+ class Base<T extends readonly Table.Any[]> {
532
+ /** Names database members use. */
533
+ /** Postgres types able to store each kind of column value, preferred first. */
534
+ static readonly #types: Record<Table.Type, readonly string[]> = {
535
+ string: [
536
+ "text",
537
+ "character varying",
538
+ "character",
539
+ "citext",
540
+ "uuid",
541
+ "enum",
542
+ ],
543
+ number: [
544
+ "double precision",
545
+ "integer",
546
+ "bigint",
547
+ "numeric",
548
+ "real",
549
+ "smallint",
550
+ ],
551
+ bigint: ["bigint", "numeric"],
552
+ boolean: ["boolean"],
553
+ date: ["timestamp with time zone", "timestamp without time zone", "date"],
554
+ json: ["jsonb", "json"],
555
+ };
556
+
557
+ /** Insert and update schemas by table. */
558
+ static readonly #writes = new WeakMap<
559
+ Table.Any,
560
+ {
561
+ insert: Schema<Record<string, unknown>>;
562
+ update: Schema<Record<string, unknown>>;
563
+ }
564
+ >();
565
+
566
+ readonly #pool: Database.Pool;
567
+ readonly #tables: T;
568
+
569
+ /** SQL tag, queries run on the pool when awaited. */
570
+ readonly sql: Database.Tag & {
571
+ /**
572
+ * Run a callback's queries as one transaction, on one connection.
573
+ * Commits when the callback resolves and rolls back when it throws.
574
+ *
575
+ * @template R Callback result
576
+ * @param fn Callback, query with `t.sql`
577
+ * @returns Callback result
578
+ */
579
+ <R>(fn: (t: Database.Transaction) => Promise<R>): Promise<R>;
580
+ };
581
+
582
+ /**
583
+ * @param pool pg-compatible pool, owned by the application
584
+ * @param tables Tables, accessible by name
585
+ */
586
+ constructor(pool: Database.Pool, tables: T) {
587
+ this.#pool = pool;
588
+ this.#tables = tables;
589
+ this.sql = Base.#tag(pool, (fn) => this.#transaction(fn)) as Base<T>["sql"];
590
+
591
+ // reserved and repeated names are type errors
592
+ for (const table of tables) {
593
+ Object.defineProperty(this, table.name, {
594
+ value: table,
595
+ enumerable: true,
596
+ });
597
+ }
598
+ }
599
+
600
+ /**
601
+ * Run a callback in a transaction on one connection.
602
+ *
603
+ * @template R Callback result
604
+ * @param fn Callback receiving the transaction's client
605
+ * @returns Callback result
606
+ */
607
+ async #transaction<R>(fn: (client: Database.Client) => Promise<R>) {
608
+ const connection = await this.#pool.connect();
609
+ let open = true;
610
+ let failure: unknown;
611
+ let broken: Error | undefined;
612
+ /** Queries started and not yet finished */
613
+ const running = new Set<Promise<unknown>>();
614
+
615
+ // only valid until the transaction ends, the connection returns to the pool
616
+ const client: Database.Client = {
617
+ query: async (text, values) => {
618
+ if (!open) throw new Error("Transaction has ended");
619
+
620
+ const query = connection.query(text, values);
621
+ const settled = query.catch(() => {});
622
+ running.add(settled);
623
+ try {
624
+ return await query;
625
+ } catch (error) {
626
+ // queries after an aborted statement fail too, keep the cause
627
+ if ((error as { code?: unknown } | null)?.code !== "25P02")
628
+ failure = error;
629
+
630
+ throw error;
631
+ } finally {
632
+ running.delete(settled);
633
+ }
634
+ },
635
+ };
636
+
637
+ try {
638
+ await connection.query("BEGIN");
639
+ const result = await fn(client).finally(async () => {
640
+ open = false;
641
+ // one the callback did not wait for may still fail and abort it
642
+ await Promise.all(running);
643
+ });
644
+
645
+ // COMMIT of an aborted transaction rolls back without an error
646
+ if (failure !== undefined)
647
+ await connection.query("SELECT 1").catch(() => {
648
+ throw failure;
649
+ });
650
+
651
+ await connection.query("COMMIT");
652
+
653
+ return result;
654
+ } catch (error) {
655
+ open = false;
656
+ await connection.query("ROLLBACK").catch((reason: unknown) => {
657
+ broken = reason instanceof Error ? reason : new Error(String(reason));
658
+ });
659
+
660
+ throw error;
661
+ } finally {
662
+ // a connection that cannot roll back is destroyed instead of reused
663
+ connection.release(broken);
664
+ }
665
+ }
666
+
667
+ /**
668
+ * Apply pending migrations in ID order. Libraries' tables, such as
669
+ * `Auth.tables`, bring their own migrations, applied first in their own
670
+ * order, so a migration of yours can reference their tables.
671
+ *
672
+ * Each migration and its history record commit together while holding a
673
+ * transaction-level advisory lock, so concurrent runs apply each once.
674
+ *
675
+ * @param migrations Every migration of yours, including applied ones
676
+ * @returns IDs applied by this call
677
+ */
678
+ readonly migrate = async (migrations: readonly Database.Migration[]) => {
679
+ // each library's migrations, in the order their tables are listed, then yours
680
+ const groups = [
681
+ ...new Set(this.#tables.map((table) => owned.get(table))),
682
+ ].filter((group) => group !== undefined);
683
+ groups.push(migrations);
684
+
685
+ const checksums = new Map<string, string>();
686
+
687
+ for (const { id, sql } of groups.flat()) {
688
+ if (!id || checksums.has(id))
689
+ throw new TypeError(`Invalid or duplicate migration ID: ${id}`);
690
+
691
+ checksums.set(
692
+ id,
693
+ new Uint8Array(
694
+ await crypto.subtle.digest("SHA-256", new TextEncoder().encode(sql)),
695
+ ).toHex(),
696
+ );
697
+ }
698
+
699
+ // a library's in the order it lists them, so `auth:10` follows
700
+ // `auth:9`, and yours in ID order, as files are named
701
+ const ordered = groups.map((group, i) =>
702
+ i === groups.length - 1
703
+ ? [...group].sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0))
704
+ : group,
705
+ );
706
+ const applied: string[] = [];
707
+ const done = new Set<string>();
708
+ let last = 0;
709
+
710
+ // one migration per transaction, history added since the last read is verified every time
711
+ while (
712
+ await this.#transaction(async (client) => {
713
+ const sql = Base.#tag(client);
714
+
715
+ await sql`SELECT pg_advisory_xact_lock(hashtext('migrations'))`;
716
+ // applied in order under the lock, so `n` follows the history
717
+ await sql`CREATE TABLE IF NOT EXISTS migrations (n bigint GENERATED ALWAYS AS IDENTITY, id text PRIMARY KEY, checksum text NOT NULL, applied timestamptz NOT NULL DEFAULT now())`;
718
+
719
+ const history = await sql`
720
+ SELECT n, id, checksum FROM migrations WHERE n > ${last} ORDER BY n
721
+ `.parse(
722
+ Schema.object({
723
+ n: Schema.number().int(),
724
+ id: Schema.string(),
725
+ checksum: Schema.string(),
726
+ }),
727
+ );
728
+
729
+ for (const row of history) {
730
+ if (!checksums.has(row.id))
731
+ throw new Error(`Applied migration ${row.id} is missing`);
732
+ if (checksums.get(row.id) !== row.checksum)
733
+ throw new Error(`Applied migration ${row.id} has changed`);
734
+
735
+ done.add(row.id);
736
+ last = row.n;
737
+ }
738
+
739
+ for (const group of ordered) {
740
+ const index = group.findIndex((migration) => !done.has(migration.id));
741
+ if (index === -1) continue;
742
+
743
+ const later = group.findLastIndex((migration) =>
744
+ done.has(migration.id),
745
+ );
746
+ if (later > index)
747
+ throw new Error(
748
+ `Migration ${group[index]!.id} sorts before applied migration ${group[later]!.id}`,
749
+ );
750
+ const next = group[index]!;
751
+
752
+ // run by PL/pgSQL, where a COMMIT or ROLLBACK in the migration is an
753
+ // error, instead of ending this transaction and leaving changes
754
+ // applied but unrecorded
755
+ await sql`SELECT set_config('migrate.sql', ${next.sql}, true)`;
756
+ await sql`DO $$ BEGIN EXECUTE current_setting('migrate.sql'); END $$`.catch(
757
+ (error: unknown) => {
758
+ const { code, message } = (error ?? {}) as {
759
+ code?: unknown;
760
+ message?: unknown;
761
+ };
762
+ if (
763
+ code === "0A000" &&
764
+ typeof message === "string" &&
765
+ message.includes("transaction commands")
766
+ )
767
+ throw new Error(
768
+ `Migration ${next.id} cannot contain BEGIN, COMMIT, or ROLLBACK, it already runs in a transaction`,
769
+ { cause: error },
770
+ );
771
+ throw error;
772
+ },
773
+ );
774
+ const [row] = await sql`
775
+ INSERT INTO migrations (id, checksum) VALUES (${next.id}, ${checksums.get(next.id)})
776
+ RETURNING n
777
+ `.parse(Schema.object({ n: Schema.number().int() }));
778
+ applied.push(next.id);
779
+ done.add(next.id);
780
+ last = row!.n;
781
+
782
+ return true;
783
+ }
784
+
785
+ return false;
786
+ })
787
+ );
788
+
789
+ return applied;
790
+ };
791
+
792
+ /**
793
+ * Check that the live database can store and return the tables' rows.
794
+ *
795
+ * Reports missing tables and columns, incompatible types, nullability, and
796
+ * missing defaults, without changing anything. Keys, constraints, and indexes
797
+ * are left to migrations, except the foreign keys a library's tables need,
798
+ * such as Auth's to the users table.
799
+ *
800
+ * @returns One line per difference, empty when they match
801
+ */
802
+ readonly check = async () => {
803
+ const differences: string[] = [];
804
+
805
+ for (const table of this.#tables) {
806
+ const label = table.name;
807
+ const [{ regclass } = { regclass: null }] = await this
808
+ .sql`SELECT to_regclass(${Identifier.table(table)})::text AS regclass`.parse(
809
+ Schema.object({ regclass: Schema.string().nullable() }),
810
+ );
811
+
812
+ if (!regclass) {
813
+ differences.push(`${label}: missing table`);
814
+ continue;
815
+ }
816
+
817
+ // each column's type and the domains it is built on, which may add NOT NULL and defaults
818
+ const columns = await this.sql`
819
+ WITH RECURSIVE chain AS (
820
+ SELECT a.attnum, t.oid, t.typtype, t.typbasetype, t.typnotnull, t.typdefaultbin IS NOT NULL AS "default"
821
+ FROM pg_attribute a JOIN pg_type t ON t.oid = a.atttypid
822
+ WHERE a.attrelid = to_regclass(${regclass}) AND a.attnum > 0 AND NOT a.attisdropped
823
+ UNION ALL
824
+ SELECT c.attnum, t.oid, t.typtype, t.typbasetype, t.typnotnull, t.typdefaultbin IS NOT NULL
825
+ FROM chain c JOIN pg_type t ON t.oid = c.typbasetype
826
+ WHERE c.typtype = 'd'
827
+ )
828
+ SELECT a.attname::text AS name,
829
+ -- domains compare as their base type, enums as "enum"
830
+ (SELECT CASE WHEN c.typtype = 'e' THEN 'enum' ELSE format_type(c.oid, NULL) END
831
+ FROM chain c WHERE c.attnum = a.attnum AND c.typtype <> 'd') AS type,
832
+ NOT (a.attnotnull OR EXISTS (SELECT 1 FROM chain c WHERE c.attnum = a.attnum AND c.typnotnull)) AS nullable,
833
+ a.atthasdef OR a.attidentity <> '' OR a.attgenerated <> ''
834
+ OR EXISTS (SELECT 1 FROM chain c WHERE c.attnum = a.attnum AND c."default") AS "default"
835
+ FROM pg_attribute a
836
+ WHERE a.attrelid = to_regclass(${regclass}) AND a.attnum > 0 AND NOT a.attisdropped
837
+ `.parse(
838
+ Schema.object({
839
+ name: Schema.string(),
840
+ type: Schema.string(),
841
+ nullable: Schema.boolean(),
842
+ default: Schema.boolean(),
843
+ }),
844
+ );
845
+ const found = new Map(columns.map((column) => [column.name, column]));
846
+ const defaults = new Set<string>(table.options.default ?? []);
847
+
848
+ for (const column of Object.values<Column>(table.columns)) {
849
+ const name = `${label}.${column.name}`;
850
+ const actual = found.get(column.name);
851
+ const types = Base.#types[column.type];
852
+ const nullable = (value: boolean) => (value ? "NULL" : "NOT NULL");
853
+
854
+ if (!actual) {
855
+ differences.push(
856
+ `${name}: missing column (${types[0]} ${nullable(column.nullable)})`,
857
+ );
858
+ continue;
859
+ }
860
+
861
+ if (!types.includes(actual.type))
862
+ differences.push(
863
+ `${name}: ${actual.type} cannot store ${column.type} values, use ${types.join(", ")}`,
864
+ );
865
+ if (actual.nullable !== column.nullable)
866
+ differences.push(
867
+ `${name}: expected ${nullable(column.nullable)}, found ${nullable(actual.nullable)}`,
868
+ );
869
+ if (defaults.has(column.name) && !actual.default)
870
+ differences.push(`${name}: missing default`);
871
+ }
872
+
873
+ // other columns are fine unless inserts cannot omit them
874
+ for (const column of columns) {
875
+ if (
876
+ !Object.hasOwn(table.columns, column.name) &&
877
+ !column.nullable &&
878
+ !column.default
879
+ )
880
+ differences.push(
881
+ `${label}.${column.name}: unexpected NOT NULL column without a default`,
882
+ );
883
+ }
884
+
885
+ const reference = referenced.get(table);
886
+ if (reference)
887
+ differences.push(
888
+ ...(await this.#reference(table, regclass, reference)),
889
+ );
890
+ }
891
+
892
+ return differences;
893
+ };
894
+
895
+ /**
896
+ * Check the foreign key a library's table needs: from its column to the
897
+ * chosen table's `id`, cascading deletes, validated and enforced.
898
+ *
899
+ * @param table Library's table
900
+ * @param regclass Its resolved name
901
+ * @param reference Column that references, and the library choosing what
902
+ * @returns Differences
903
+ */
904
+ async #reference(
905
+ table: Table.Any,
906
+ regclass: string,
907
+ reference: { readonly column: string; readonly by: string },
908
+ ) {
909
+ const label = `${table.name}.${reference.column}`;
910
+ const target = references.get(this)?.get(table);
911
+ if (!target)
912
+ return [
913
+ `${label}: create ${reference.by} with this database before checking it, so it knows the table ${table.name} references`,
914
+ ];
915
+
916
+ const expected = `${target.name} (id) ON DELETE CASCADE`;
917
+ const keys = await this.sql`
918
+ SELECT con.confrelid = to_regclass(${Identifier.table(target)}) AS target,
919
+ (SELECT a.attname::text FROM pg_attribute a
920
+ WHERE a.attrelid = con.confrelid AND a.attnum = con.confkey[1]) AS "column",
921
+ con.confdeltype = 'c' AS cascade,
922
+ con.convalidated AS validated,
923
+ -- NOT ENFORCED is new in Postgres 18
924
+ coalesce((to_jsonb(con) ->> 'conenforced')::boolean, true) AS enforced
925
+ FROM pg_constraint con
926
+ WHERE con.contype = 'f' AND con.conrelid = to_regclass(${regclass})
927
+ AND cardinality(con.conkey) = 1
928
+ AND con.conkey[1] = (SELECT a.attnum FROM pg_attribute a
929
+ WHERE a.attrelid = con.conrelid AND a.attname = ${reference.column})
930
+ `.parse(
931
+ Schema.object({
932
+ target: Schema.boolean().nullable(),
933
+ column: Schema.string().nullable(),
934
+ cascade: Schema.boolean(),
935
+ validated: Schema.boolean(),
936
+ enforced: Schema.boolean(),
937
+ }),
938
+ );
939
+
940
+ if (
941
+ keys.some(
942
+ (key) =>
943
+ key.target &&
944
+ key.column === "id" &&
945
+ key.cascade &&
946
+ key.validated &&
947
+ key.enforced,
948
+ )
949
+ )
950
+ return [];
951
+
952
+ const [key] = keys;
953
+ if (!key) return [`${label}: missing foreign key to ${expected}`];
954
+
955
+ const problems = [
956
+ (!key.target || key.column !== "id") &&
957
+ "references another table or column",
958
+ !key.cascade && "does not cascade deletes",
959
+ !key.validated && "is NOT VALID, validate it",
960
+ !key.enforced && "is NOT ENFORCED",
961
+ ].filter(Boolean);
962
+
963
+ return [
964
+ `${label}: foreign key ${problems.join(", ")}, expected ${expected}`,
965
+ ];
966
+ }
967
+
968
+ /**
969
+ * @param table Table
970
+ * @returns Cached insert and update schemas
971
+ */
972
+ static #write(table: Table.Any) {
973
+ let write = Base.#writes.get(table);
974
+
975
+ if (!write) {
976
+ const insert: Schema.Object.Shape = {};
977
+ const update: Schema.Object.Shape = {};
978
+ const defaults = new Set<string>(table.options.default ?? []);
979
+
980
+ for (const [key, schema] of Object.entries<Schema<unknown>>(
981
+ table.shape,
982
+ )) {
983
+ // a schema accepting undefined, like unknown, cannot tell an omitted column
984
+ insert[key] =
985
+ defaults.has(key) ||
986
+ (table.columns[key]!.nullable && schema.parse(undefined).issues)
987
+ ? schema.optional()
988
+ : schema.refine((value) => value !== undefined, "Required");
989
+ update[key] = schema.optional();
990
+ }
991
+
992
+ write = {
993
+ insert: Schema.object(insert).strict(),
994
+ update: Schema.object(update).strict(),
995
+ };
996
+ Base.#writes.set(table, write);
997
+ }
998
+
999
+ return write;
1000
+ }
1001
+
1002
+ /**
1003
+ * @param schema Write schema
1004
+ * @param value Values to validate
1005
+ * @param path Issue path
1006
+ * @returns Validated values
1007
+ */
1008
+ static #parse(
1009
+ schema: Schema<Record<string, unknown>>,
1010
+ value: unknown,
1011
+ path: Schema.Issue.Path = [],
1012
+ ) {
1013
+ const result = schema.parse(value, path);
1014
+
1015
+ if (result.issues) throw result;
1016
+
1017
+ return result.data;
1018
+ }
1019
+
1020
+ /**
1021
+ * @param column Column receiving the value
1022
+ * @param value Validated value
1023
+ * @returns Driver parameter
1024
+ */
1025
+ static #encode(column: Column, value: unknown) {
1026
+ // drivers send arrays as Postgres arrays, so JSON is always serialized,
1027
+ // and null is SQL NULL only when the column allows it
1028
+ return column.type === "json" && (value !== null || !column.nullable)
1029
+ ? JSON.stringify(value)
1030
+ : value;
1031
+ }
1032
+
1033
+ /**
1034
+ * @param client Client queries run on
1035
+ * @param transaction Runs a callback in a transaction, only for the pool's tag
1036
+ * @returns SQL tag bound to the client
1037
+ */
1038
+ static #tag(
1039
+ client: Database.Client,
1040
+ transaction?: <R>(
1041
+ fn: (client: Database.Client) => Promise<R>,
1042
+ ) => Promise<R>,
1043
+ ) {
1044
+ const fragment = (strings: readonly string[], values: readonly unknown[]) =>
1045
+ new Sql(strings, values, client);
1046
+ const raw = (text: string) => fragment([text], []);
1047
+
1048
+ return Object.assign(
1049
+ (
1050
+ strings:
1051
+ | TemplateStringsArray
1052
+ | ((t: Database.Transaction) => Promise<unknown>),
1053
+ ...values: unknown[]
1054
+ ) => {
1055
+ // a transaction's own tag has none, transactions do not nest
1056
+ if (typeof strings === "function" && transaction) {
1057
+ const fn = strings;
1058
+ return transaction((inner) => fn({ sql: Base.#tag(inner) }));
1059
+ }
1060
+
1061
+ if (!Array.isArray(strings) || !Object.hasOwn(strings, "raw"))
1062
+ throw new TypeError(
1063
+ "sql is a template tag, write sql`...`, or pass a callback to run a transaction",
1064
+ );
1065
+
1066
+ return fragment(strings, values);
1067
+ },
1068
+ {
1069
+ values: (table: Table.Any, rows: unknown) => {
1070
+ const list = (Array.isArray(rows) ? rows : [rows]).map((row, i) =>
1071
+ Base.#parse(
1072
+ Base.#write(table).insert,
1073
+ row,
1074
+ Array.isArray(rows) ? [i] : [],
1075
+ ),
1076
+ );
1077
+ const keys = Object.keys(table.columns).filter((key) =>
1078
+ list.some((row) => Object.hasOwn(row, key)),
1079
+ );
1080
+
1081
+ if (!list.length) throw new TypeError("sql.values requires a row");
1082
+ if (!keys.length) {
1083
+ if (list.length > 1)
1084
+ throw new TypeError("sql.values requires a column");
1085
+
1086
+ return raw("DEFAULT VALUES");
1087
+ }
1088
+
1089
+ // one fragment for every row, text is added to the segment before the next value
1090
+ const strings = [
1091
+ `(${keys.map(Identifier.quote).join(", ")}) VALUES `,
1092
+ ];
1093
+ const params: unknown[] = [];
1094
+
1095
+ for (let r = 0; r < list.length; r++) {
1096
+ const row = list[r]!;
1097
+ let text = r ? ", (" : "(";
1098
+
1099
+ for (let k = 0; k < keys.length; k++) {
1100
+ const key = keys[k]!;
1101
+
1102
+ if (k) text += ", ";
1103
+
1104
+ if (Object.hasOwn(row, key)) {
1105
+ strings[strings.length - 1] += text;
1106
+ strings.push("");
1107
+ params.push(Base.#encode(table.columns[key]!, row[key]));
1108
+ text = "";
1109
+ } else {
1110
+ text += "DEFAULT";
1111
+ }
1112
+ }
1113
+
1114
+ strings[strings.length - 1] += text + ")";
1115
+ }
1116
+
1117
+ return fragment(strings, params);
1118
+ },
1119
+ set: (table: Table.Any, values: unknown) => {
1120
+ const data = Base.#parse(Base.#write(table).update, values);
1121
+ const keys = Object.keys(data);
1122
+
1123
+ if (!keys.length) throw new TypeError("sql.set requires a column");
1124
+
1125
+ return fragment(
1126
+ [
1127
+ ...keys.map(
1128
+ (key, i) => `${i ? ", " : ""}${Identifier.quote(key)} = `,
1129
+ ),
1130
+ "",
1131
+ ],
1132
+ keys.map((key) => Base.#encode(table.columns[key]!, data[key])),
1133
+ );
1134
+ },
1135
+ },
1136
+ ) as Database.Tag;
1137
+ }
1138
+
1139
+ /**
1140
+ * Check whether an error is a unique constraint violation, for example to
1141
+ * show it as a form error.
1142
+ *
1143
+ * ```ts
1144
+ * if (Database.unique(error, "users_email_key")) {
1145
+ * const invalid = result.invalid({ email: "Already registered" });
1146
+ * return c.redirect(invalid.url, 303);
1147
+ * }
1148
+ * ```
1149
+ *
1150
+ * @param error Caught error
1151
+ * @param constraint Constraint name, any unique constraint when omitted
1152
+ * @returns `true` for a matching unique violation
1153
+ */
1154
+ static unique(error: unknown, constraint?: string) {
1155
+ if (!(error instanceof Error)) return false;
1156
+
1157
+ const { code, constraint: name } = error as {
1158
+ code?: unknown;
1159
+ constraint?: unknown;
1160
+ };
1161
+
1162
+ // SQLSTATE unique_violation
1163
+ return (
1164
+ code === "23505" && (constraint === undefined || name === constraint)
1165
+ );
1166
+ }
1167
+ }
1168
+
1169
+ /**
1170
+ * Postgres database with tables, accessed through an application-owned,
1171
+ * pg-compatible pool.
1172
+ *
1173
+ * ```ts
1174
+ * const database = new Database(pool, [users, posts]);
1175
+ *
1176
+ * const rows = await database.sql`SELECT * FROM ${database.users}`.parse(database.users);
1177
+ * ```
1178
+ *
1179
+ * @template T Tables of the database, each available by name
1180
+ */
1181
+ export const Database = Base as Omit<typeof Base, "prototype"> &
1182
+ (new <const T extends readonly Table.Any[]>(
1183
+ pool: Database.Pool,
1184
+ tables: T & Database.Valid<T>,
1185
+ ) => Database<T>);
1186
+
1187
+ /**
1188
+ * Postgres database with its tables accessible by name.
1189
+ *
1190
+ * @template T Tables of the database
1191
+ */
1192
+ export type Database<T extends readonly Table.Any[] = readonly Table.Any[]> =
1193
+ Base<T> & Database.Tables<T>;