@forestfuture/active-record 0.6.0 → 0.7.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 +5 -4
- package/config-schema.json +56 -0
- package/dist/{adapter-BSvFhTDf.d.mts → adapter-AGKp6wfO.d.mts} +42 -9
- package/dist/adapter.d.mts +3 -2
- package/dist/adapter.mjs +4 -3
- package/dist/{batch-DBeYk5wx.mjs → batch-BS_WseLf.mjs} +128 -44
- package/dist/cli.d.mts +176 -28
- package/dist/cli.mjs +3 -2
- package/dist/command.mjs +746 -432
- package/dist/d1.d.mts +68 -0
- package/dist/d1.mjs +0 -0
- package/dist/for-adapters-Ch6CoHD4.mjs +240 -0
- package/dist/for-adapters-D_Iu0gS_.mjs +33 -0
- package/dist/for-adapters-t3-LukJQ.d.mts +21 -0
- package/dist/{generated-model-CfDggoVN.mjs → generated-model-Cnt0Ot9q.mjs} +4 -0
- package/dist/index-CyCJuM96.d.mts +149 -0
- package/dist/index.d.mts +3 -143
- package/dist/index.mjs +3 -2
- package/dist/plugin-Cyoej7qV.mjs +600 -0
- package/dist/plugin-XOHYndhP.mjs +939 -0
- package/dist/postgresql.d.mts +72 -0
- package/dist/postgresql.mjs +588 -0
- package/dist/src-la_KkjCS.mjs +1 -0
- package/dist/storage-override-CpbkdIqE.mjs +187 -0
- package/llms-full.txt +837 -201
- package/package.json +25 -2
- package/skills/active-record/SKILL.md +4 -4
- package/dist/storage-override-BYBYP8Mj.mjs +0 -91
package/README.md
CHANGED
|
@@ -1,14 +1,15 @@
|
|
|
1
1
|
# @forestfuture/active-record
|
|
2
2
|
|
|
3
|
-
A Rails-inspired Active Record for [Cloudflare Workers](https://developers.cloudflare.com/workers/): Models with validations, callbacks, associations, and change tracking; lazy, composable queries; and a predictable save lifecycle. It talks to a database through an adapter
|
|
3
|
+
A Rails-inspired Active Record for [Cloudflare Workers](https://developers.cloudflare.com/workers/): Models with validations, callbacks, associations, and change tracking; lazy, composable queries; and a predictable save lifecycle. It talks to a database through an adapter it ships with: `@forestfuture/active-record/d1` for [D1](https://developers.cloudflare.com/d1/), and `@forestfuture/active-record/postgresql` for Postgres, with your own `pg`.
|
|
4
4
|
|
|
5
5
|
```sh
|
|
6
|
-
npm install @forestfuture/active-record
|
|
6
|
+
npm install @forestfuture/active-record
|
|
7
7
|
```
|
|
8
8
|
|
|
9
|
-
|
|
9
|
+
Name your database, generate a Model and its table, then use it in your Worker:
|
|
10
10
|
|
|
11
11
|
```sh
|
|
12
|
+
npx active-record init
|
|
12
13
|
npx active-record g model Post 'title:string!' publishedAt:datetime
|
|
13
14
|
npx active-record migrate
|
|
14
15
|
```
|
|
@@ -24,4 +25,4 @@ const drafts = await Post.where({ publishedAt: null })
|
|
|
24
25
|
|
|
25
26
|
The package also installs the `active-record` command (`ffar` for short), which generates the schema, Models and migrations, applies migrations, and opens a console. It ships the guide for its own version as `llms-full.txt`, and an agent skill in `skills/active-record/`.
|
|
26
27
|
|
|
27
|
-
The guide is at [
|
|
28
|
+
The guide is at [active-record.forestfuture.dev](https://active-record.forestfuture.dev). Coming from an earlier release? See [Upgrading](https://active-record.forestfuture.dev/upgrading). The source is on [GitHub](https://github.com/forestfuture/active-record).
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "http://json-schema.org/draft-07/schema#",
|
|
3
|
+
"title": "active-record.jsonc",
|
|
4
|
+
"description": "The project's databases and their adapter, which the active-record command reads. `npx active-record init` writes it.",
|
|
5
|
+
"type": "object",
|
|
6
|
+
"properties": {
|
|
7
|
+
"$schema": {
|
|
8
|
+
"description": "This schema, for an editor to complete and check the file's keys.",
|
|
9
|
+
"type": "string"
|
|
10
|
+
},
|
|
11
|
+
"databases": {
|
|
12
|
+
"description": "Each database by its binding: the name the Worker's env, and the generated schema, give it.",
|
|
13
|
+
"type": "object",
|
|
14
|
+
"minProperties": 1,
|
|
15
|
+
"additionalProperties": {
|
|
16
|
+
"oneOf": [{ "$ref": "#/definitions/d1" }, { "$ref": "#/definitions/postgresql" }]
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
},
|
|
20
|
+
"required": ["databases"],
|
|
21
|
+
"additionalProperties": false,
|
|
22
|
+
"definitions": {
|
|
23
|
+
"d1": {
|
|
24
|
+
"description": "A D1 database. Its migrations folder and the rest come from its d1_databases entry in the Wrangler config beside this file.",
|
|
25
|
+
"type": "object",
|
|
26
|
+
"properties": {
|
|
27
|
+
"adapter": { "description": "The database's adapter.", "const": "d1" }
|
|
28
|
+
},
|
|
29
|
+
"required": ["adapter"],
|
|
30
|
+
"additionalProperties": false
|
|
31
|
+
},
|
|
32
|
+
"postgresql": {
|
|
33
|
+
"description": "A Postgres database. `${NAME}` in a connection string reads the variable NAME from the environment.",
|
|
34
|
+
"type": "object",
|
|
35
|
+
"properties": {
|
|
36
|
+
"adapter": { "description": "The database's adapter.", "const": "postgresql" },
|
|
37
|
+
"migrationsDir": {
|
|
38
|
+
"description": "Its migrations folder, relative to this file.",
|
|
39
|
+
"type": "string",
|
|
40
|
+
"default": "migrations"
|
|
41
|
+
},
|
|
42
|
+
"url": {
|
|
43
|
+
"description": "The local database: what migrate and the console use.",
|
|
44
|
+
"type": "string"
|
|
45
|
+
},
|
|
46
|
+
"remoteUrl": { "description": "The real database, for --remote.", "type": "string" },
|
|
47
|
+
"schemaUrl": {
|
|
48
|
+
"description": "A server the schema may be read on, for an extension PGlite doesn't have.",
|
|
49
|
+
"type": "string"
|
|
50
|
+
}
|
|
51
|
+
},
|
|
52
|
+
"required": ["adapter"],
|
|
53
|
+
"additionalProperties": false
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
@@ -44,6 +44,8 @@ declare class Attribute {
|
|
|
44
44
|
readonly column: string;
|
|
45
45
|
/** Whether it's a `string` attribute, which D1 compares as text, not by number. */
|
|
46
46
|
get isText(): boolean;
|
|
47
|
+
/** Whether it's a `json` attribute, whose stored text is JSON itself. */
|
|
48
|
+
get isJson(): boolean;
|
|
47
49
|
/**
|
|
48
50
|
* An assigned value (a setter, `build`, `update`, `insert`, `permit`) as the attribute's type:
|
|
49
51
|
* only what's unambiguous for it (#81). `undefined` throws, as it would store NULL silently;
|
|
@@ -92,8 +94,16 @@ declare class Attribute {
|
|
|
92
94
|
}
|
|
93
95
|
//#endregion
|
|
94
96
|
//#region src/dialect.d.ts
|
|
97
|
+
/**
|
|
98
|
+
* Where compiled SQL binds a value, in its own order. A dialect writes each as its database's
|
|
99
|
+
* placeholder once the SQL is complete, so a `?` in a raw `sql` fragment's text (Postgres's jsonb
|
|
100
|
+
* operator) is never read as one. NUL, since no database accepts it in a statement's text.
|
|
101
|
+
*/
|
|
102
|
+
declare const valueMark = "\0";
|
|
95
103
|
/** The SQL a database needs in its own form. Everything else in the compiler is shared. */
|
|
96
104
|
interface Dialect {
|
|
105
|
+
/** The placeholder for the `index`th bound value, from 1: `?`, or `$1`. */
|
|
106
|
+
placeholder(index: number): string;
|
|
97
107
|
/** `column` in a list of `cells` bound as one value, so any length fits a statement's limits. */
|
|
98
108
|
inList(column: string, cells: readonly unknown[]): {
|
|
99
109
|
sql: string;
|
|
@@ -101,11 +111,19 @@ interface Dialect {
|
|
|
101
111
|
};
|
|
102
112
|
/** `limit` and `offset`, at least one of them set, as this database writes them, their values added to `params`. */
|
|
103
113
|
pagination(limit: number | undefined, offset: number | undefined, params: unknown[]): string;
|
|
104
|
-
/**
|
|
105
|
-
|
|
114
|
+
/**
|
|
115
|
+
* Where a bulk insert into `table` (quoted) reads its rows of `attributes`, from one bound JSON
|
|
116
|
+
* value: its SELECT list and FROM.
|
|
117
|
+
*/
|
|
118
|
+
bulkRows(table: string, attributes: readonly Attribute[]): {
|
|
106
119
|
select: string;
|
|
107
120
|
from: string;
|
|
108
121
|
};
|
|
122
|
+
/**
|
|
123
|
+
* The owners' `key` (a quoted column, of `keyAttribute`) as a linked condition selects it, so
|
|
124
|
+
* it matches `linked`'s column as a condition on `linked` would: by text for a text attribute.
|
|
125
|
+
*/
|
|
126
|
+
linkedKey(key: string, keyAttribute: Attribute, linked: Attribute): string;
|
|
109
127
|
}
|
|
110
128
|
//#endregion
|
|
111
129
|
//#region src/compiler.d.ts
|
|
@@ -133,16 +151,31 @@ interface StatementResult {
|
|
|
133
151
|
/** The database's own detail about it, for `onQuery` (D1's `meta`). */
|
|
134
152
|
meta?: unknown;
|
|
135
153
|
}
|
|
136
|
-
/**
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
154
|
+
/**
|
|
155
|
+
* Sends statements to one database. It knows nothing of Models, `onQuery` or error classes.
|
|
156
|
+
* `Scope` is what it holds for a `withDatabase` scope, handed back with each statement sent inside it.
|
|
157
|
+
*/
|
|
158
|
+
interface Driver<Scope = unknown> {
|
|
159
|
+
/** Sends one statement, inside `scope` when one was opened. */
|
|
160
|
+
send(statement: CompiledSql, scope?: Scope): Promise<StatementResult>;
|
|
140
161
|
/** Sends reads at once where it can, resolving to each one's result. They needn't be atomic. */
|
|
141
|
-
read(statements: readonly CompiledSql[]): Promise<StatementResult[]>;
|
|
162
|
+
read(statements: readonly CompiledSql[], scope?: Scope): Promise<StatementResult[]>;
|
|
142
163
|
/** Sends writes atomically, all or none, resolving to each one's result. */
|
|
143
|
-
write(statements: readonly CompiledSql[]): Promise<StatementResult[]>;
|
|
164
|
+
write(statements: readonly CompiledSql[], scope?: Scope): Promise<StatementResult[]>;
|
|
144
165
|
/** Whether sending again can succeed after `error`, having readied the connection for it. */
|
|
145
166
|
recover(error: unknown): boolean;
|
|
167
|
+
/**
|
|
168
|
+
* A `withDatabase` call with this database has begun: what the driver holds for it, such as a
|
|
169
|
+
* connection, until `closeScope`. Each call opens its own, so overlapping requests sharing a
|
|
170
|
+
* Database never share one; a call nested in a running one with the same database shares the
|
|
171
|
+
* outer's. Statements sent after it ended (a `waitUntil` save) are still handed it.
|
|
172
|
+
*/
|
|
173
|
+
openScope?(): Scope;
|
|
174
|
+
/**
|
|
175
|
+
* The scope `openScope` returned has ended: what it holds can be let go once its statements
|
|
176
|
+
* finish. `withDatabase` waits for it, so it shouldn't wait for them.
|
|
177
|
+
*/
|
|
178
|
+
closeScope?(scope: Scope): Promise<void>;
|
|
146
179
|
}
|
|
147
180
|
//#endregion
|
|
148
181
|
//#region src/executor.d.ts
|
|
@@ -1290,4 +1323,4 @@ interface Adapter {
|
|
|
1290
1323
|
databaseFor(binding: string | undefined, requested: readonly AnyDatabase[]): Promise<AnyDatabase>;
|
|
1291
1324
|
}
|
|
1292
1325
|
//#endregion
|
|
1293
|
-
export { ErrorMessages as $, Page as A, Comparison as B, HasOne as C, ScopeMethods as D, Scope as E, Conditions as F, lte as G, gt as H, InsertOptions as I, TableSchemas as J, DatabaseSchema as K, OrderSpec as L, ReturnedRow as M, Statement as N, Scoped as O, WriteResult as P, ErrorMessage as Q, Returning as R, HasManyDependent as S, Relation as T, gte as U, between as V, lt as W, ValidationError as X, Errors as Y, AttributeErrorMessages as Z, UniquenessOptions as _,
|
|
1326
|
+
export { ErrorMessages as $, Page as A, Comparison as B, HasOne as C, ScopeMethods as D, Scope as E, Conditions as F, lte as G, gt as H, InsertOptions as I, TableSchemas as J, DatabaseSchema as K, OrderSpec as L, ReturnedRow as M, Statement as N, Scoped as O, WriteResult as P, ErrorMessage as Q, Returning as R, HasManyDependent as S, Relation as T, gte as U, between as V, lt as W, ValidationError as X, Errors as Y, AttributeErrorMessages as Z, UniquenessOptions as _, ColumnReference as _t, RelationsFor as a, AttributeSpecs as at, BelongsTo as b, column as bt, BatchResults as c, DatabaseExecutor as ct, Model as d, Driver as dt, RestrictMessages as et, ModelClass as f, StatementResult as ft, NumericalityOptions as g, valueMark as gt, LengthOptions as h, Dialect as ht, AnyDatabase as i, AttributeSpec as it, PageOptions as j, CountlessPage as k, batch as l, QueryEvent as lt, TableAttributes as m, QuerySql as mt, ConstraintFailure as n, boundValue as nt, databaseExecutor as o, AttributeType as ot, ScopeStatic as p, CompiledSql as pt, TableSchema as q, SchemaAdapter as r, AttributeConversions as rt, BatchEntry as s, EpochStorage as st, Adapter as t, FilterAttribute as tt, RecordStatement as u, QueryListener as ut, ValidationOptions as v, ColumnValue as vt, HasOneDependent as w, HasMany as x, sql$1 as xt, AssociationOptions as y, SafeSql as yt, UpsertOptions as z };
|
package/dist/adapter.d.mts
CHANGED
|
@@ -1,2 +1,3 @@
|
|
|
1
|
-
import { ct as DatabaseExecutor, dt as Driver, ft as StatementResult, ht as Dialect, i as AnyDatabase, lt as QueryEvent, n as ConstraintFailure, nt as boundValue, o as databaseExecutor, pt as CompiledSql, r as SchemaAdapter, t as Adapter, ut as QueryListener } from "./adapter-
|
|
2
|
-
|
|
1
|
+
import { ct as DatabaseExecutor, dt as Driver, ft as StatementResult, gt as valueMark, ht as Dialect, i as AnyDatabase, lt as QueryEvent, n as ConstraintFailure, nt as boundValue, o as databaseExecutor, pt as CompiledSql, r as SchemaAdapter, t as Adapter, ut as QueryListener } from "./adapter-AGKp6wfO.mjs";
|
|
2
|
+
import { n as workersEnv, r as onlyRequested, t as WorkersEnv } from "./for-adapters-t3-LukJQ.mjs";
|
|
3
|
+
export { type Adapter, AnyDatabase, type CompiledSql, type ConstraintFailure, DatabaseExecutor, type Dialect, type Driver, type QueryEvent, type QueryListener, type SchemaAdapter, type StatementResult, type WorkersEnv, boundValue, databaseExecutor, onlyRequested, valueMark, workersEnv };
|
package/dist/adapter.mjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
-
import { L as boundValue } from "./generated-model-
|
|
2
|
-
import { a as databaseExecutor, i as AnyDatabase, s as DatabaseExecutor } from "./batch-
|
|
3
|
-
|
|
1
|
+
import { L as boundValue } from "./generated-model-Cnt0Ot9q.mjs";
|
|
2
|
+
import { a as databaseExecutor, c as valueMark, i as AnyDatabase, s as DatabaseExecutor } from "./batch-BS_WseLf.mjs";
|
|
3
|
+
import { n as onlyRequested, t as workersEnv } from "./for-adapters-D_Iu0gS_.mjs";
|
|
4
|
+
export { AnyDatabase, DatabaseExecutor, boundValue, databaseExecutor, onlyRequested, valueMark, workersEnv };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { $ as CallbackAbort, A as requireDefined, B as shownKey, C as castInherited, D as attributesForColumn, E as attributeOf, F as zonelessDateTime, G as modelClassName, H as explainMissingTable, I as Filtered, K as rejectAbstract, L as boundValue, M as castValue, N as uncastable, O as define, P as writeUntypedValue, Q as AssociationNotLoaded, R as defaultFilterAttributes, S as attributeFor, T as storedRows, U as ignoresColumns, V as shownValue, W as inferTableNames, X as AbortAfterPersistence, Y as ancestors, _ as attributesNamedInMessages, a as isGenerated, at as InvalidModel, b as declared, c as RecordState, ct as NoDatabase, dt as RecordInvalid, et as CheckViolation, f as addFailure, ft as RecordNotDestroyed, g as printed, gt as UnknownAssociation, h as inspectCustom, ht as RecordNotUnique, it as InvalidForeignKey, j as specProblem, k as initialValues, l as linksOf, lt as NotNullViolation, m as FilteredMark, mt as RecordNotSaved, n as defineAttributeAccessors, nt as DeleteRestriction, o as schemaAdapter, ot as IrreversibleOrder, p as clearErrors, pt as RecordNotFound, q as requireTableName, r as defineGeneratedStatics, rt as IncompatibleRelation, s as settleGenerated, t as attributesSettled, u as state, v as humanAttributeName, w as noMatch, x as seal, y as declare, z as isFiltered } from "./generated-model-
|
|
1
|
+
import { $ as CallbackAbort, A as requireDefined, B as shownKey, C as castInherited, D as attributesForColumn, E as attributeOf, F as zonelessDateTime, G as modelClassName, H as explainMissingTable, I as Filtered, K as rejectAbstract, L as boundValue, M as castValue, N as uncastable, O as define, P as writeUntypedValue, Q as AssociationNotLoaded, R as defaultFilterAttributes, S as attributeFor, T as storedRows, U as ignoresColumns, V as shownValue, W as inferTableNames, X as AbortAfterPersistence, Y as ancestors, _ as attributesNamedInMessages, a as isGenerated, at as InvalidModel, b as declared, c as RecordState, ct as NoDatabase, dt as RecordInvalid, et as CheckViolation, f as addFailure, ft as RecordNotDestroyed, g as printed, gt as UnknownAssociation, h as inspectCustom, ht as RecordNotUnique, it as InvalidForeignKey, j as specProblem, k as initialValues, l as linksOf, lt as NotNullViolation, m as FilteredMark, mt as RecordNotSaved, n as defineAttributeAccessors, nt as DeleteRestriction, o as schemaAdapter, ot as IrreversibleOrder, p as clearErrors, pt as RecordNotFound, q as requireTableName, r as defineGeneratedStatics, rt as IncompatibleRelation, s as settleGenerated, t as attributesSettled, u as state, v as humanAttributeName, w as noMatch, x as seal, y as declare, z as isFiltered } from "./generated-model-Cnt0Ot9q.mjs";
|
|
2
2
|
import { a as underscore, i as camelize } from "./epoch-storage-o2aoOH7H.mjs";
|
|
3
3
|
//#region src/foreign-keys.ts
|
|
4
4
|
/**
|
|
@@ -413,6 +413,24 @@ function sameTree(a, b) {
|
|
|
413
413
|
return names.every((name) => b[name] !== void 0 && sameTree(a[name], b[name]));
|
|
414
414
|
}
|
|
415
415
|
//#endregion
|
|
416
|
+
//#region src/dialect.ts
|
|
417
|
+
/**
|
|
418
|
+
* Where compiled SQL binds a value, in its own order. A dialect writes each as its database's
|
|
419
|
+
* placeholder once the SQL is complete, so a `?` in a raw `sql` fragment's text (Postgres's jsonb
|
|
420
|
+
* operator) is never read as one. NUL, since no database accepts it in a statement's text.
|
|
421
|
+
*/
|
|
422
|
+
const valueMark = "\0";
|
|
423
|
+
/** `compiled` with each `valueMark` written as `dialect`'s placeholder: the SQL as it's sent. */
|
|
424
|
+
function withPlaceholders(dialect, compiled) {
|
|
425
|
+
if (!compiled.sql.includes("\0")) return compiled;
|
|
426
|
+
let index = 0;
|
|
427
|
+
const sql = compiled.sql.replaceAll("\0", () => dialect.placeholder(++index));
|
|
428
|
+
return {
|
|
429
|
+
...compiled,
|
|
430
|
+
sql
|
|
431
|
+
};
|
|
432
|
+
}
|
|
433
|
+
//#endregion
|
|
416
434
|
//#region src/compiler.ts
|
|
417
435
|
/** `compiled` as `toSql()` shows it: the values D1 binds, and not the Model it is for. */
|
|
418
436
|
function querySql({ sql, params }) {
|
|
@@ -462,15 +480,14 @@ function compileCondition(dialect, condition, model, params) {
|
|
|
462
480
|
/**
|
|
463
481
|
* `attr IN (SELECT key FROM … WHERE …)`: the keys of the records `owners` finds. With a limit
|
|
464
482
|
* or offset, its order picks those records; without, it's left out, as it can't change them.
|
|
465
|
-
*
|
|
466
|
-
* by number, which can't search `attr`'s index, and which `'09'` matches.
|
|
483
|
+
* The dialect selects the key so it compares with `attr` as a condition would, across key types.
|
|
467
484
|
*/
|
|
468
485
|
function compileLinkedTo(dialect, { attribute, owners, ownerKey }, model, params) {
|
|
469
486
|
const linked = attributeFor(model, attribute);
|
|
470
487
|
const keyAttribute = attributeFor(owners.model, ownerKey);
|
|
471
488
|
const column = quoteIdentifier(linked.column);
|
|
472
489
|
const keyColumn = quoteIdentifier(keyAttribute.column);
|
|
473
|
-
const selected =
|
|
490
|
+
const selected = dialect.linkedKey(keyColumn, keyAttribute, linked);
|
|
474
491
|
const order = owners.limit !== void 0 || owners.offset !== void 0 ? owners.order : [];
|
|
475
492
|
const inner = compileSelect(dialect, {
|
|
476
493
|
...owners,
|
|
@@ -494,7 +511,7 @@ function compileInsert(model, assignments, returning) {
|
|
|
494
511
|
model
|
|
495
512
|
};
|
|
496
513
|
const columns = assignments.map(([name]) => quoteIdentifier(attributeFor(model, name).column)).join(", ");
|
|
497
|
-
const placeholders = assignments.map(() => "
|
|
514
|
+
const placeholders = assignments.map(() => "\0").join(", ");
|
|
498
515
|
const params = [];
|
|
499
516
|
for (const [name, value] of assignments) attributeFor(model, name).bind(params, value);
|
|
500
517
|
return {
|
|
@@ -516,10 +533,11 @@ function compileReturning(model, attributes) {
|
|
|
516
533
|
function compileInsertRows(dialect, model, { names, rows, conflict, returning }) {
|
|
517
534
|
const attributes = names.map((name) => attributeFor(model, name));
|
|
518
535
|
const columns = attributes.map(({ column }) => quoteIdentifier(column)).join(", ");
|
|
519
|
-
const
|
|
536
|
+
const table = quoteIdentifier(model.table);
|
|
537
|
+
const { select, from } = dialect.bulkRows(table, attributes);
|
|
520
538
|
const json = storedRows(model, names, rows);
|
|
521
539
|
return {
|
|
522
|
-
sql: `INSERT INTO ${
|
|
540
|
+
sql: `INSERT INTO ${table} (${columns}) SELECT ${select} FROM ${from} WHERE true${compileConflict(model, names, conflict)}` + compileReturning(model, returning),
|
|
523
541
|
params: [json],
|
|
524
542
|
model
|
|
525
543
|
};
|
|
@@ -547,7 +565,7 @@ function compileUpdate(model, assignments, storedKey) {
|
|
|
547
565
|
const primaryKey = attributeFor(model, model.primaryKey);
|
|
548
566
|
attributeFor(model, model.primaryKey).bindCells(params, storedKey);
|
|
549
567
|
return {
|
|
550
|
-
sql: `UPDATE ${quoteIdentifier(model.table)} SET ${sets} WHERE ${quoteIdentifier(primaryKey.column)} =
|
|
568
|
+
sql: `UPDATE ${quoteIdentifier(model.table)} SET ${sets} WHERE ${quoteIdentifier(primaryKey.column)} = `,
|
|
551
569
|
params,
|
|
552
570
|
model
|
|
553
571
|
};
|
|
@@ -558,7 +576,7 @@ function compileSets(model, changes, params) {
|
|
|
558
576
|
return changes.map(([name, value]) => {
|
|
559
577
|
const attribute = attributeFor(model, name);
|
|
560
578
|
attribute.bind(params, value);
|
|
561
|
-
return `${quoteIdentifier(attribute.column)} =
|
|
579
|
+
return `${quoteIdentifier(attribute.column)} = `;
|
|
562
580
|
}).join(", ");
|
|
563
581
|
}
|
|
564
582
|
/**
|
|
@@ -604,7 +622,7 @@ function compileDelete(model, storedKey) {
|
|
|
604
622
|
const params = [];
|
|
605
623
|
attributeFor(model, model.primaryKey).bindCells(params, storedKey);
|
|
606
624
|
return {
|
|
607
|
-
sql: `DELETE FROM ${quoteIdentifier(model.table)} WHERE ${quoteIdentifier(column)} =
|
|
625
|
+
sql: `DELETE FROM ${quoteIdentifier(model.table)} WHERE ${quoteIdentifier(column)} = `,
|
|
608
626
|
params,
|
|
609
627
|
model
|
|
610
628
|
};
|
|
@@ -684,12 +702,12 @@ function compileComparison(attribute, comparison, params) {
|
|
|
684
702
|
const NOTHING = "1 = 0";
|
|
685
703
|
/** Each comparison's SQL for a quoted column; values are bound in order. */
|
|
686
704
|
const COMPARISON_SQL = {
|
|
687
|
-
">": (column) => `${column} >
|
|
688
|
-
">=": (column) => `${column} >=
|
|
689
|
-
"<": (column) => `${column} <
|
|
690
|
-
"<=": (column) => `${column} <=
|
|
691
|
-
between: (column) => `${column} BETWEEN
|
|
692
|
-
betweenExcludingEnd: (column) => `(${column} >=
|
|
705
|
+
">": (column) => `${column} > `,
|
|
706
|
+
">=": (column) => `${column} >= `,
|
|
707
|
+
"<": (column) => `${column} < `,
|
|
708
|
+
"<=": (column) => `${column} <= `,
|
|
709
|
+
between: (column) => `${column} BETWEEN AND `,
|
|
710
|
+
betweenExcludingEnd: (column) => `(${column} >= AND ${column} < )`
|
|
693
711
|
};
|
|
694
712
|
/** `attr = value`, with NULL and arrays (IN) handled the way the contract specifies. */
|
|
695
713
|
function compileEquality(dialect, attribute, value, params) {
|
|
@@ -699,7 +717,7 @@ function compileEquality(dialect, attribute, value, params) {
|
|
|
699
717
|
const stored = attribute.conditionCell(value);
|
|
700
718
|
if (stored === noMatch) return NOTHING;
|
|
701
719
|
attribute.bindCells(params, stored);
|
|
702
|
-
return `${column} =
|
|
720
|
+
return `${column} = `;
|
|
703
721
|
}
|
|
704
722
|
const present = value.filter((item) => item !== null).map((item) => attribute.conditionCell(item)).filter((item) => item !== noMatch);
|
|
705
723
|
const parts = [];
|
|
@@ -730,10 +748,10 @@ function compileFragment(fragment, model, params) {
|
|
|
730
748
|
if (value instanceof ColumnReference) text += quoteIdentifier(attributeFor(model, value.attribute).column);
|
|
731
749
|
else if (value instanceof ColumnValue) {
|
|
732
750
|
attributeFor(model, value.attribute).bind(params, value.assigned);
|
|
733
|
-
text += "
|
|
751
|
+
text += "\0";
|
|
734
752
|
} else {
|
|
735
753
|
params.push(writeUntypedValue(value));
|
|
736
|
-
text += "
|
|
754
|
+
text += "\0";
|
|
737
755
|
}
|
|
738
756
|
text += fragment.strings[index + 1] ?? "";
|
|
739
757
|
});
|
|
@@ -1272,6 +1290,25 @@ function violation({ kind, table, columns }, models, cause) {
|
|
|
1272
1290
|
});
|
|
1273
1291
|
}
|
|
1274
1292
|
//#endregion
|
|
1293
|
+
//#region src/request-store.ts
|
|
1294
|
+
/** The storage, once `withDatabase` has been called. */
|
|
1295
|
+
let storage;
|
|
1296
|
+
/** Node's AsyncLocalStorage, loaded when it's first needed, so Workers without Node.js compatibility still build. */
|
|
1297
|
+
function newStorage() {
|
|
1298
|
+
const hooks = globalThis.process?.getBuiltinModule?.("node:async_hooks");
|
|
1299
|
+
if (hooks === void 0) throw new NoDatabase("withDatabase needs Node.js compatibility: a compatibility_date of 2026-08-04 or later, or the nodejs_compat flag, in your Wrangler config");
|
|
1300
|
+
return new hooks.AsyncLocalStorage();
|
|
1301
|
+
}
|
|
1302
|
+
/** What the current `withDatabase` keeps, if code runs inside one. */
|
|
1303
|
+
function requestStore() {
|
|
1304
|
+
return storage?.getStore();
|
|
1305
|
+
}
|
|
1306
|
+
/** Runs `fn` with `store` as the request's. */
|
|
1307
|
+
function runWithStore(store, fn) {
|
|
1308
|
+
storage ??= newStorage();
|
|
1309
|
+
return storage.run(store, fn);
|
|
1310
|
+
}
|
|
1311
|
+
//#endregion
|
|
1275
1312
|
//#region src/executor.ts
|
|
1276
1313
|
/**
|
|
1277
1314
|
* Calls a query listener, which never changes the query's outcome: a listener that throws is
|
|
@@ -1331,17 +1368,34 @@ var DatabaseExecutor = class {
|
|
|
1331
1368
|
setOrigin(origin) {
|
|
1332
1369
|
this.#origin = origin;
|
|
1333
1370
|
}
|
|
1371
|
+
/** @internal A `withDatabase` scope with this database has begun: what its driver holds for it. */
|
|
1372
|
+
openScope() {
|
|
1373
|
+
return this.#driver.openScope?.();
|
|
1374
|
+
}
|
|
1375
|
+
/** @internal The scope `openScope` began has ended. */
|
|
1376
|
+
async closeScope(scope) {
|
|
1377
|
+
await this.#driver.closeScope?.(scope);
|
|
1378
|
+
}
|
|
1379
|
+
/** What the driver opened for the `withDatabase` scope a statement is sent in, if any. */
|
|
1380
|
+
#scope() {
|
|
1381
|
+
return requestStore()?.scopes.get(this)?.held;
|
|
1382
|
+
}
|
|
1334
1383
|
/** Runs one statement and resolves to its rows. */
|
|
1335
1384
|
async all(query) {
|
|
1336
|
-
return (await this.#one(query)).rows;
|
|
1385
|
+
return (await this.#one(this.#sendable(query))).rows;
|
|
1337
1386
|
}
|
|
1338
1387
|
/** Runs one statement for its effect and resolves to its result. */
|
|
1339
1388
|
async run(query) {
|
|
1340
|
-
return this.#one(query);
|
|
1389
|
+
return this.#one(this.#sendable(query));
|
|
1341
1390
|
}
|
|
1342
1391
|
/** Runs reads together and resolves to each one's result. */
|
|
1343
1392
|
async read(statements) {
|
|
1344
|
-
|
|
1393
|
+
const sent = statements.map((statement) => this.#sendable(statement));
|
|
1394
|
+
return this.#together(sent, () => this.#driver.read(sent, this.#scope()));
|
|
1395
|
+
}
|
|
1396
|
+
/** `query` as it's sent and reported: with its database's placeholders. */
|
|
1397
|
+
#sendable(query) {
|
|
1398
|
+
return withPlaceholders(this.dialect, query);
|
|
1345
1399
|
}
|
|
1346
1400
|
/** `statements`, sent by `send`, unless there are none. On failure every one is reported. */
|
|
1347
1401
|
async #together(statements, send, mayRetry = true) {
|
|
@@ -1371,15 +1425,16 @@ var DatabaseExecutor = class {
|
|
|
1371
1425
|
}
|
|
1372
1426
|
/** Runs statements atomically: one on its own, several all or none. Resolves to each result. */
|
|
1373
1427
|
async write(statements) {
|
|
1374
|
-
const
|
|
1375
|
-
|
|
1376
|
-
|
|
1428
|
+
const sent = statements.map((statement) => this.#sendable(statement));
|
|
1429
|
+
const [only] = sent;
|
|
1430
|
+
if (sent.length === 1 && only !== void 0) return [await this.#one(only)];
|
|
1431
|
+
return this.#together(sent, () => this.#driver.write(sent, this.#scope()));
|
|
1377
1432
|
}
|
|
1378
1433
|
async #one(query, mayRetry = true) {
|
|
1379
1434
|
const started = performance.now();
|
|
1380
1435
|
let result;
|
|
1381
1436
|
try {
|
|
1382
|
-
result = await this.#driver.send(query);
|
|
1437
|
+
result = await this.#driver.send(query, this.#scope());
|
|
1383
1438
|
} catch (error) {
|
|
1384
1439
|
this.#report(query, {
|
|
1385
1440
|
durationMs: performance.now() - started,
|
|
@@ -1656,10 +1711,10 @@ function selectFor(dialect, model, query) {
|
|
|
1656
1711
|
*/
|
|
1657
1712
|
function selectForToSql(dialect, model, query) {
|
|
1658
1713
|
const never = sql`1 = 0`;
|
|
1659
|
-
return selectFor(dialect, model, query.none ? {
|
|
1714
|
+
return withPlaceholders(dialect, selectFor(dialect, model, query.none ? {
|
|
1660
1715
|
...query,
|
|
1661
1716
|
conditions: [...query.conditions, never]
|
|
1662
|
-
} : query);
|
|
1717
|
+
} : query));
|
|
1663
1718
|
}
|
|
1664
1719
|
/**
|
|
1665
1720
|
* The primary keys `find(...)` looks up: each cast to the key's type as a condition is, then
|
|
@@ -2313,7 +2368,7 @@ var Statement = class {
|
|
|
2313
2368
|
}
|
|
2314
2369
|
/** The SQL this Statement sends and its bound values, unsent: see `Relation#toSql`. */
|
|
2315
2370
|
toSql() {
|
|
2316
|
-
return querySql(this.#query);
|
|
2371
|
+
return querySql(withPlaceholders(this.#executor.dialect, this.#query));
|
|
2317
2372
|
}
|
|
2318
2373
|
/**
|
|
2319
2374
|
* @internal The Database's Executor it runs on, its compiled SQL, what runs once written, and
|
|
@@ -3228,25 +3283,54 @@ var AnyDatabase = class {
|
|
|
3228
3283
|
};
|
|
3229
3284
|
//#endregion
|
|
3230
3285
|
//#region src/current-database.ts
|
|
3231
|
-
/** The databases `withDatabase` set for the current request, once it's been called. */
|
|
3232
|
-
let requests;
|
|
3233
|
-
/** Node's AsyncLocalStorage, loaded when it's first needed, so Workers without Node.js compatibility still build. */
|
|
3234
|
-
function newStorage() {
|
|
3235
|
-
const hooks = globalThis.process?.getBuiltinModule?.("node:async_hooks");
|
|
3236
|
-
if (hooks === void 0) throw new NoDatabase("withDatabase needs Node.js compatibility: a compatibility_date of 2026-08-04 or later, or the nodejs_compat flag, in your Wrangler config");
|
|
3237
|
-
return new hooks.AsyncLocalStorage();
|
|
3238
|
-
}
|
|
3239
3286
|
/**
|
|
3240
3287
|
* Runs `fn` with `databases` as the request's own: queries started from a Model inside it (and
|
|
3241
3288
|
* everything it awaits) use the one on that Model's binding, with its Session and `onQuery`.
|
|
3242
3289
|
* Usually called once per request, in middleware. Nested calls add to the outer ones.
|
|
3290
|
+
*
|
|
3291
|
+
* Each call is a scope of its own, even with a Database another request shares. An adapter may
|
|
3292
|
+
* hold a connection for the scope (the PostgreSQL adapter does, from a connection string). A nested call with
|
|
3293
|
+
* the same Database shares the outer call's scope while that call is running. When `fn` settles,
|
|
3294
|
+
* the scope ends, and the adapter lets its connection go once the queries still running on it
|
|
3295
|
+
* finish. Work that outlives the scope, such as a `waitUntil` save, gets a connection of its own.
|
|
3243
3296
|
*/
|
|
3244
3297
|
async function withDatabase(databases, fn) {
|
|
3245
|
-
|
|
3246
|
-
const outer = requests.getStore() ?? [];
|
|
3298
|
+
const outer = requestStore();
|
|
3247
3299
|
const inner = Array.isArray(databases) ? databases : [databases];
|
|
3248
|
-
|
|
3249
|
-
|
|
3300
|
+
const scopes = new Map(outer?.scopes);
|
|
3301
|
+
const opened = [];
|
|
3302
|
+
try {
|
|
3303
|
+
openScopes(inner, scopes, opened);
|
|
3304
|
+
return await runWithStore({
|
|
3305
|
+
databases: [.../* @__PURE__ */ new Set([...inner, ...outer?.databases ?? []])],
|
|
3306
|
+
scopes
|
|
3307
|
+
}, fn);
|
|
3308
|
+
} finally {
|
|
3309
|
+
await Promise.all(opened.map(({ executor, scope }) => {
|
|
3310
|
+
scope.hasEnded = true;
|
|
3311
|
+
return executor.closeScope(scope.held);
|
|
3312
|
+
}));
|
|
3313
|
+
}
|
|
3314
|
+
}
|
|
3315
|
+
/**
|
|
3316
|
+
* Opens a scope for each of `databases` not already in a running one, added to `scopes` and to `opened` as
|
|
3317
|
+
* it opens, so the ones opened before a driver throws are still closed.
|
|
3318
|
+
*/
|
|
3319
|
+
function openScopes(databases, scopes, opened) {
|
|
3320
|
+
for (const db of databases) {
|
|
3321
|
+
const executor = db[databaseExecutor];
|
|
3322
|
+
executor.setOrigin("request");
|
|
3323
|
+
if (scopes.get(executor)?.hasEnded === false) continue;
|
|
3324
|
+
const scope = {
|
|
3325
|
+
held: executor.openScope(),
|
|
3326
|
+
hasEnded: false
|
|
3327
|
+
};
|
|
3328
|
+
scopes.set(executor, scope);
|
|
3329
|
+
opened.push({
|
|
3330
|
+
executor,
|
|
3331
|
+
scope
|
|
3332
|
+
});
|
|
3333
|
+
}
|
|
3250
3334
|
}
|
|
3251
3335
|
/**
|
|
3252
3336
|
* The adapter a statement compiles for. Statements compile when they're built, before their
|
|
@@ -3255,7 +3339,7 @@ async function withDatabase(databases, fn) {
|
|
|
3255
3339
|
*/
|
|
3256
3340
|
function adapterFor(named) {
|
|
3257
3341
|
if (named !== void 0) return named.adapter;
|
|
3258
|
-
const [first] =
|
|
3342
|
+
const [first] = requestStore()?.databases ?? [];
|
|
3259
3343
|
if (first === void 0) throw noSchemaOrDatabase();
|
|
3260
3344
|
return first[databaseExecutor].adapter;
|
|
3261
3345
|
}
|
|
@@ -3264,7 +3348,7 @@ function noSchemaOrDatabase() {
|
|
|
3264
3348
|
}
|
|
3265
3349
|
/** The database a query uses now, on the adapter its Model's schema names. */
|
|
3266
3350
|
function databaseFor(named) {
|
|
3267
|
-
return adapterFor(named).databaseFor(named?.binding,
|
|
3351
|
+
return adapterFor(named).databaseFor(named?.binding, requestStore()?.databases ?? []);
|
|
3268
3352
|
}
|
|
3269
3353
|
/**
|
|
3270
3354
|
* One Executor per adapter and binding (from a Model's schema), finding the current database each
|
|
@@ -4168,4 +4252,4 @@ async function recordEntry(statement, claimed) {
|
|
|
4168
4252
|
};
|
|
4169
4253
|
}
|
|
4170
4254
|
//#endregion
|
|
4171
|
-
export {
|
|
4255
|
+
export { hasMany as _, databaseExecutor as a, valueMark as c, between as d, gt as f, belongsTo as g, lte as h, AnyDatabase as i, column as l, lt as m, Model as n, Relation as o, gte as p, withDatabase as r, DatabaseExecutor as s, batch as t, sql as u, hasOne as v };
|