@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/dist/d1.d.mts ADDED
@@ -0,0 +1,68 @@
1
+ import { i as AnyDatabase, lt as QueryEvent$1, r as SchemaAdapter, ut as QueryListener$1 } from "./adapter-AGKp6wfO.mjs";
2
+ import { r as ActiveRecordError } from "./index-CyCJuM96.mjs";
3
+ //#region src/adapters/d1/adapter.d.ts
4
+ /** The D1 database a generated schema's Models query: `adapter: d1({ binding: "DB" })`. */
5
+ export declare function d1({ binding }: {
6
+ binding: string;
7
+ }): SchemaAdapter;
8
+ //#endregion
9
+ //#region src/adapters/d1/database.d.ts
10
+ /** What `onQuery` hears about a statement: its Model, SQL, bound values, timing, and D1's `meta`. */
11
+ type QueryEvent = QueryEvent$1<D1Meta>;
12
+ /** Hears each statement's `QueryEvent`, with D1's `meta`. */
13
+ type QueryListener = QueryListener$1<D1Meta>;
14
+ interface ConnectOptions {
15
+ /** Called once for every statement sent to D1, with D1's `meta`. */
16
+ onQuery?: QueryListener;
17
+ /**
18
+ * Sends every query through one D1 Session, so the request reads its own writes even when
19
+ * reads are served by replicas: `"first-primary"`, `"first-unconstrained"`, or a bookmark
20
+ * from an earlier request's `db.bookmark()`.
21
+ */
22
+ session?: D1SessionConstraint | (D1SessionBookmark & {});
23
+ }
24
+ /**
25
+ * A per-request wrapper around a D1 binding; every query goes through it. `db.batch` uses D1's
26
+ * `batch()`. There's no interactive `transaction()`, because D1 can't hold one open across awaits.
27
+ */
28
+ export declare class Database extends AnyDatabase {
29
+ #private;
30
+ constructor(binding: D1Database, options?: ConnectOptions);
31
+ /**
32
+ * The Session's latest bookmark (null before its first query). Pass it to the next request's
33
+ * `connect(env.DB, { session: bookmark })` to read at least as new as this request wrote.
34
+ */
35
+ bookmark(): D1SessionBookmark | null;
36
+ }
37
+ export declare function connect(binding: D1Database, options?: ConnectOptions): Database;
38
+ //#endregion
39
+ //#region src/adapters/d1/errors.d.ts
40
+ /** `bookmark()` was called on a Database opened without a `session`. */
41
+ export declare class NoSession extends ActiveRecordError {
42
+ name: string;
43
+ }
44
+ //#endregion
45
+ //#region src/adapters/d1/with-session.d.ts
46
+ /** How `withSession` opens the request's Database, and where its bookmark travels. */
47
+ type SessionOptions = Omit<ConnectOptions, "session"> & {
48
+ /** Where a request with no bookmark starts its Session: `"first-unconstrained"` unless set. */
49
+ start?: D1SessionConstraint;
50
+ } & ({
51
+ /** The cookie the bookmark travels in: `"d1-bookmark"` unless set. */
52
+ cookie?: string;
53
+ header?: never;
54
+ } | {
55
+ cookie?: never;
56
+ /** The header the bookmark travels in, on the request and the response, instead of a cookie. */
57
+ header: string;
58
+ });
59
+ type Handler = (db: Database) => Response | Promise<Response>;
60
+ /**
61
+ * Runs `fn` with a Database whose Session starts from the request's bookmark, so the request
62
+ * reads at least as new as the user's last write, from any replica, and sets the Session's
63
+ * latest bookmark on the response it returns. An error from `fn` reaches the caller unchanged.
64
+ */
65
+ export declare function withSession(request: Request, binding: D1Database, fn: Handler): Promise<Response>;
66
+ export declare function withSession(request: Request, binding: D1Database, options: SessionOptions, fn: Handler): Promise<Response>;
67
+ //#endregion
68
+ export type { ConnectOptions, QueryEvent, QueryListener, SessionOptions };
package/dist/d1.mjs ADDED
Binary file
@@ -0,0 +1,240 @@
1
+ import { a as underscore, n as pluralize } from "./epoch-storage-o2aoOH7H.mjs";
2
+ import { d as byName, i as exportName } from "./storage-override-CpbkdIqE.mjs";
3
+ //#region cli/generate/migration-plan.ts
4
+ /** What to do, read from a migration's name: `create_products`, `add_sku_to_products`, …; else empty. */
5
+ function migrationPlan(name) {
6
+ const words = underscore(name);
7
+ const create = /^create_(\w+)$/.exec(words);
8
+ if (create) return {
9
+ kind: "create",
10
+ table: pluralize(create[1])
11
+ };
12
+ const add = /^add_\w+?_to_(\w+)$/.exec(words);
13
+ if (add) return {
14
+ kind: "add",
15
+ table: pluralize(add[1])
16
+ };
17
+ const remove = /^remove_\w+?_from_(\w+)$/.exec(words);
18
+ return remove ? {
19
+ kind: "remove",
20
+ table: pluralize(remove[1])
21
+ } : { kind: "empty" };
22
+ }
23
+ /** The index the generators name a column's index by: `index_products_on_sku`. */
24
+ function indexName(table, column) {
25
+ return `index_${table}_on_${column}`;
26
+ }
27
+ //#endregion
28
+ //#region cli/generate/migration-sql.ts
29
+ /** A name as SQL: quoted only when the database reserves it, so migrations stay readable. */
30
+ function quotedName(dialect, name) {
31
+ return dialect.reserved.has(name) ? `"${name}"` : name;
32
+ }
33
+ /** A default as a SQL literal: `TRUE`, `1.5`, `'it''s'`. */
34
+ function literal(value) {
35
+ if (typeof value === "boolean") return value ? "TRUE" : "FALSE";
36
+ return typeof value === "number" ? String(value) : `'${value.replaceAll("'", "''")}'`;
37
+ }
38
+ /** A column's definition, as `CREATE TABLE` and `ADD COLUMN` write it. */
39
+ function definition(column, { dialect, keys }, notNull) {
40
+ const name = quotedName(dialect, column.name);
41
+ if (column.type === "references") {
42
+ const type = (keys.get(column.references) ?? dialect.guessedKeyType).toUpperCase();
43
+ const target = quotedName(dialect, column.references);
44
+ return `${name} ${type}${notNull ? " NOT NULL" : ""} REFERENCES ${target} (id)`;
45
+ }
46
+ const parts = [name, dialect.types[column.type]];
47
+ if (notNull) parts.push("NOT NULL");
48
+ if (column.default !== void 0) parts.push(`DEFAULT ${literal(column.default)}`);
49
+ const check = dialect.check?.(column, name);
50
+ if (check !== void 0) parts.push(check);
51
+ return parts.join(" ");
52
+ }
53
+ /** `CREATE [UNIQUE] INDEX` for each indexed column. */
54
+ function indexes(dialect, table, columns) {
55
+ return columns.filter((column) => column.index !== "none").map((column) => {
56
+ const unique = column.index === "unique" ? "UNIQUE " : "";
57
+ const on = `${quotedName(dialect, table)} (${quotedName(dialect, column.name)})`;
58
+ return `CREATE ${unique}INDEX ${indexName(table, column.name)} ON ${on};\n`;
59
+ }).join("");
60
+ }
61
+ /** `CREATE TABLE`, with its key, columns, timestamps and indexes. */
62
+ function createTable(table, change, writing) {
63
+ const { dialect } = writing;
64
+ const lines = [dialect.key(change.options.integerId === true)];
65
+ for (const column of change.columns) lines.push(definition(column, writing, column.notNull));
66
+ if (change.options.timestamps !== false) {
67
+ const type = dialect.timestampType;
68
+ lines.push(`created_at ${type} NOT NULL`, `updated_at ${type} NOT NULL`);
69
+ }
70
+ const body = lines.join(",\n ");
71
+ return `CREATE TABLE ${quotedName(dialect, table)} (\n ${body}\n);\n${indexes(dialect, table, change.columns)}`;
72
+ }
73
+ /** `ADD COLUMN` for each column; a reference added later can be null, as Rails' `add_reference`. */
74
+ function addColumns(table, columns, writing) {
75
+ const { dialect } = writing;
76
+ for (const column of columns) {
77
+ const error = dialect.addRefusal?.(table, column);
78
+ if (error !== void 0) return {
79
+ ok: false,
80
+ error
81
+ };
82
+ }
83
+ return {
84
+ ok: true,
85
+ sql: columns.map((column) => {
86
+ const notNull = column.type !== "references" && column.notNull;
87
+ return `ALTER TABLE ${quotedName(dialect, table)} ADD COLUMN ${definition(column, writing, notNull)};\n`;
88
+ }).join("") + indexes(dialect, table, columns)
89
+ };
90
+ }
91
+ /** The SQL for the migration the change names, or why it can't be written. */
92
+ function migrationFor(change, writing) {
93
+ const { name, columns } = change;
94
+ const plan = migrationPlan(name);
95
+ if (plan.kind === "empty") return columns.length > 0 ? {
96
+ ok: false,
97
+ error: `${name}: columns only go with Create…, Add…To… or Remove…From… migrations`
98
+ } : {
99
+ ok: true,
100
+ sql: "-- Write the migration's SQL here.\n"
101
+ };
102
+ if (columns.length === 0 && plan.kind !== "create") return {
103
+ ok: false,
104
+ error: `${name}: name the columns to ${plan.kind} (sku:string)`
105
+ };
106
+ if (plan.kind === "create") return {
107
+ ok: true,
108
+ sql: createTable(plan.table, change, writing)
109
+ };
110
+ if (plan.kind === "add") return addColumns(plan.table, columns, writing);
111
+ return {
112
+ ok: true,
113
+ sql: columns.map((column) => writing.dialect.dropColumn(plan.table, column.name)).join("")
114
+ };
115
+ }
116
+ /** Notes for references to tables the migrations don't make yet: their key type is a guess. */
117
+ function referenceNotes(change, dialect) {
118
+ if (migrationPlan(change.name).kind === "remove") return [];
119
+ return change.columns.filter((column) => column.type === "references" && !change.keys.has(column.references)).map((column) => `${column.references} isn't in the migrations yet, so ${column.name} is ${dialect.guessedKeyType}`);
120
+ }
121
+ /**
122
+ * A migration's SQL in the dialect given: a table created, columns added or removed, or an empty
123
+ * migration, as its name says (`CreateProducts`, `AddSkuToProducts`, …), with a note for each key
124
+ * type it guessed.
125
+ */
126
+ function migrationSql(change, dialect) {
127
+ const result = migrationFor(change, {
128
+ dialect,
129
+ keys: change.keys
130
+ });
131
+ if (!result.ok) return result;
132
+ const notes = referenceNotes(change, dialect);
133
+ return notes.length === 0 ? result : {
134
+ ...result,
135
+ notes
136
+ };
137
+ }
138
+ //#endregion
139
+ //#region cli/schema/tables.ts
140
+ const noFindings = () => ({
141
+ errors: [],
142
+ notes: [],
143
+ textDates: []
144
+ });
145
+ function merge(into, from) {
146
+ into.errors.push(...from.errors);
147
+ into.notes.push(...from.notes);
148
+ into.textDates.push(...from.textDates);
149
+ }
150
+ /** A table's attributes, in column order, with what their columns turn up. */
151
+ function attributesOf(columns, convert) {
152
+ const attributes = {};
153
+ const found = noFindings();
154
+ const columnOf = /* @__PURE__ */ new Map();
155
+ for (const column of columns) {
156
+ const converted = convert(column);
157
+ if (!converted.ok) {
158
+ found.errors.push(converted.error);
159
+ continue;
160
+ }
161
+ const { attribute, spec, note, textDate } = converted;
162
+ const taken = columnOf.get(attribute);
163
+ if (taken !== void 0) found.errors.push(`${column.table}: columns ${taken} and ${column.name} would both be the attribute ${attribute}; rename one`);
164
+ columnOf.set(attribute, column.name);
165
+ attributes[attribute] = spec;
166
+ if (note !== void 0) found.notes.push(note);
167
+ if (textDate) found.textDates.push(`${column.table}.${column.name}`);
168
+ }
169
+ return {
170
+ attributes,
171
+ ...found
172
+ };
173
+ }
174
+ /** One table's schema, or the errors that stop it from being generated. */
175
+ function tableSchema(table, reading) {
176
+ const { name, columns, lastChangedBy, keyType } = table;
177
+ const keys = columns.filter((column) => column.primaryKey).map((column) => column.name);
178
+ if (keys.length !== 1) {
179
+ const error = keys.length === 0 ? reading.missingKey(name) : `${name}: a composite primary key (${keys.join(", ")}) isn't supported; give the table a single key`;
180
+ return {
181
+ ...noFindings(),
182
+ errors: [error]
183
+ };
184
+ }
185
+ const { attributes, ...found } = attributesOf(columns, reading.convert);
186
+ const generated = {
187
+ name,
188
+ exportName: exportName(name),
189
+ primaryKey: keys[0],
190
+ lastChangedBy
191
+ };
192
+ const withKeyType = keyType === void 0 ? {} : { keyType };
193
+ return {
194
+ table: {
195
+ ...generated,
196
+ attributes,
197
+ ...withKeyType
198
+ },
199
+ ...found
200
+ };
201
+ }
202
+ /** Tables whose names become the same export (`line_items`, `line-items` → `lineItems`). */
203
+ function exportCollisions(names) {
204
+ const seen = /* @__PURE__ */ new Map();
205
+ const errors = [];
206
+ for (const name of names) {
207
+ const as = exportName(name);
208
+ const other = seen.get(as);
209
+ if (other !== void 0) errors.push(`${other} and ${name} would both be exported as ${as}; rename one of the tables`);
210
+ seen.set(as, name);
211
+ }
212
+ return errors;
213
+ }
214
+ /**
215
+ * The generated schema's tables, from the tables an adapter read, in alphabetical order (so the
216
+ * result only changes with the schema), or every error that stops them.
217
+ */
218
+ function generatedSchema(read, reading) {
219
+ const sorted = [...read].sort((a, b) => byName(a.name, b.name));
220
+ const found = noFindings();
221
+ found.errors.push(...exportCollisions(sorted.map((table) => table.name)));
222
+ const tables = [];
223
+ for (const table of sorted) {
224
+ const result = tableSchema(table, reading);
225
+ merge(found, result);
226
+ if (result.table !== void 0) tables.push(result.table);
227
+ }
228
+ const { errors, notes, textDates } = found;
229
+ return errors.length > 0 ? {
230
+ ok: false,
231
+ errors
232
+ } : {
233
+ ok: true,
234
+ tables,
235
+ notes,
236
+ textDates
237
+ };
238
+ }
239
+ //#endregion
240
+ export { migrationPlan as a, indexName as i, migrationSql as n, quotedName as r, generatedSchema as t };
@@ -0,0 +1,33 @@
1
+ import { ct as NoDatabase } from "./generated-model-Cnt0Ot9q.mjs";
2
+ //#region src/request-database.ts
3
+ /**
4
+ * The request's database for a query on `binding` outside a Worker, or a `NoDatabase` saying what
5
+ * to do. `connect` is how the adapter's docs open one, such as `connect(env.DB)`.
6
+ */
7
+ function onlyRequested(requested, binding, connect) {
8
+ if (requested.length === 1) return requested[0];
9
+ const reason = requested.length > 1 ? "withDatabase was given several, and outside a Worker a binding can't tell which" : binding === void 0 ? "its Model's base class holds no generated schema, which names its binding" : `the binding ${binding} is only there inside a Worker`;
10
+ throw new NoDatabase(`No database for this query: ${reason}. Wrap the code in withDatabase(${connect}, …), or use db.model(Model)`);
11
+ }
12
+ //#endregion
13
+ //#region src/workers-env.ts
14
+ /** Whether importing `cloudflare:workers` failed because this isn't a Worker (Node, scripts). */
15
+ function isOutsideWorker(error) {
16
+ const { code, message } = error;
17
+ return code === "ERR_UNSUPPORTED_ESM_URL_SCHEME" || code === "ERR_MODULE_NOT_FOUND" || /cloudflare:workers/.test(String(message));
18
+ }
19
+ /**
20
+ * The Worker's `env`, from `load`, or undefined outside a Worker (Node, scripts). An adapter
21
+ * passes `() => import("cloudflare:workers")` from its own module, with that literal specifier:
22
+ * Wrangler only bundles those, and a test that mocks the module with the adapter inlined reaches it.
23
+ */
24
+ async function workersEnv(load) {
25
+ try {
26
+ return (await load()).env;
27
+ } catch (error) {
28
+ if (isOutsideWorker(error)) return void 0;
29
+ throw error;
30
+ }
31
+ }
32
+ //#endregion
33
+ export { onlyRequested as n, workersEnv as t };
@@ -0,0 +1,21 @@
1
+ import { i as AnyDatabase } from "./adapter-AGKp6wfO.mjs";
2
+ //#region src/request-database.d.ts
3
+ /**
4
+ * The request's database for a query on `binding` outside a Worker, or a `NoDatabase` saying what
5
+ * to do. `connect` is how the adapter's docs open one, such as `connect(env.DB)`.
6
+ */
7
+ declare function onlyRequested(requested: readonly AnyDatabase[], binding: string | undefined, connect: string): AnyDatabase;
8
+ //#endregion
9
+ //#region src/workers-env.d.ts
10
+ /** A Worker's `env`: its bindings and variables, by name. */
11
+ type WorkersEnv = Record<string, unknown>;
12
+ /**
13
+ * The Worker's `env`, from `load`, or undefined outside a Worker (Node, scripts). An adapter
14
+ * passes `() => import("cloudflare:workers")` from its own module, with that literal specifier:
15
+ * Wrangler only bundles those, and a test that mocks the module with the adapter inlined reaches it.
16
+ */
17
+ declare function workersEnv(load: () => Promise<{
18
+ env: unknown;
19
+ }>): Promise<WorkersEnv | undefined>;
20
+ //#endregion
21
+ export { workersEnv as n, onlyRequested as r, WorkersEnv as t };
@@ -762,6 +762,10 @@ var Attribute = class {
762
762
  get isText() {
763
763
  return this.#definition.type === "string";
764
764
  }
765
+ /** Whether it's a `json` attribute, whose stored text is JSON itself. */
766
+ get isJson() {
767
+ return this.#definition.type === "json";
768
+ }
765
769
  /**
766
770
  * An assigned value (a setter, `build`, `update`, `insert`, `permit`) as the attribute's type:
767
771
  * only what's unambiguous for it (#81). `undefined` throws, as it would store NULL silently;
@@ -0,0 +1,149 @@
1
+ import { C as HasOne, S as HasManyDependent, b as BelongsTo, d as Model, f as ModelClass, i as AnyDatabase, w as HasOneDependent, x as HasMany, y as AssociationOptions } from "./adapter-AGKp6wfO.mjs";
2
+ //#region src/association-fields.d.ts
3
+ /** This record points at one `target` record through `foreignKey` (its own attribute). */
4
+ declare function belongsTo<C extends ModelClass>(target: C, options?: Omit<AssociationOptions<C>, "dependent">): BelongsTo<C>;
5
+ /** Many `target` records point at this record through `foreignKey` (theirs). */
6
+ declare function hasMany<C extends ModelClass>(target: C, options?: AssociationOptions<C> & {
7
+ dependent?: HasManyDependent;
8
+ }): HasMany<C>;
9
+ /** One `target` record points at this record through `foreignKey` (its own). */
10
+ declare function hasOne<C extends ModelClass>(target: C, options?: AssociationOptions<C> & {
11
+ dependent?: HasOneDependent;
12
+ }): HasOne<C>;
13
+ //#endregion
14
+ //#region src/errors.d.ts
15
+ /** Base class for every error the library throws on purpose. */
16
+ declare class ActiveRecordError extends Error {
17
+ name: string;
18
+ }
19
+ /** A Model's declaration is invalid, e.g. an association's foreign key isn't an attribute. */
20
+ declare class InvalidModel extends ActiveRecordError {
21
+ name: string;
22
+ }
23
+ /** A key that isn't a declared attribute of the Model. */
24
+ declare class UnknownAttribute extends ActiveRecordError {
25
+ name: string;
26
+ }
27
+ /** A record constructed directly (`new User()`) was used for something that needs D1. */
28
+ declare class NoDatabase extends ActiveRecordError {
29
+ name: string;
30
+ }
31
+ /** No record matched a lookup that requires one (`find`, `findByOrThrow`). */
32
+ declare class RecordNotFound extends ActiveRecordError {
33
+ name: string;
34
+ }
35
+ /** Reading an attribute that wasn't loaded, e.g. one left out of `select(...)`. */
36
+ declare class MissingAttribute extends ActiveRecordError {
37
+ name: string;
38
+ }
39
+ /** Destroying a record whose `dependent: "restrictWithException"` association still has records. */
40
+ declare class DeleteRestriction extends ActiveRecordError {
41
+ name: string;
42
+ }
43
+ /** `last()` can't reverse an order given as an `sql` fragment (Rails' IrreversibleOrderError). */
44
+ declare class IrreversibleOrder extends ActiveRecordError {
45
+ name: string;
46
+ }
47
+ /**
48
+ * Things that can't be combined: relations in `or`/`merge` (e.g. of different Models),
49
+ * `includes` or a write statement with `distinct()`, or statements of two Databases in a batch.
50
+ */
51
+ declare class IncompatibleRelation extends ActiveRecordError {
52
+ name: string;
53
+ }
54
+ /** Using a destroyed record as a live one: `save`, `update`, `destroy` or `reload` after `destroy()`. */
55
+ declare class RecordDestroyed extends ActiveRecordError {
56
+ name: string;
57
+ }
58
+ /**
59
+ * D1 rejected a write because of a database constraint. `table`, `columns` and `attributes`
60
+ * are filled in when D1's message names them. `table` is null only for a batch writing to
61
+ * several tables, when D1 doesn't say which one failed. The original D1 error is the `cause`.
62
+ */
63
+ declare class ConstraintViolation extends ActiveRecordError {
64
+ name: string;
65
+ readonly table: string | null;
66
+ readonly columns: readonly string[];
67
+ readonly attributes: readonly string[];
68
+ constructor(message: string, details: {
69
+ table: string | null;
70
+ columns: readonly string[];
71
+ attributes: readonly string[];
72
+ cause: unknown;
73
+ });
74
+ }
75
+ /** A UNIQUE constraint failed, e.g. another request won the race after validation passed. */
76
+ declare class RecordNotUnique extends ConstraintViolation {
77
+ name: string;
78
+ }
79
+ /** A FOREIGN KEY constraint failed. SQLite's message doesn't name the column. */
80
+ declare class InvalidForeignKey extends ConstraintViolation {
81
+ name: string;
82
+ }
83
+ /** A NOT NULL constraint failed. */
84
+ declare class NotNullViolation extends ConstraintViolation {
85
+ name: string;
86
+ }
87
+ /** A CHECK constraint failed. */
88
+ declare class CheckViolation extends ConstraintViolation {
89
+ name: string;
90
+ }
91
+ /** A `…OrThrow` save was refused because the record is invalid; `record.errors` says why. */
92
+ declare class RecordInvalid extends ActiveRecordError {
93
+ name: string;
94
+ readonly record: Model;
95
+ constructor(record: Model);
96
+ }
97
+ /**
98
+ * Thrown by a callback to refuse a save or destroy: `throw abort("Account is suspended")`.
99
+ * Only this exact class halts a lifecycle; returning `false` never does.
100
+ */
101
+ declare class CallbackAbort extends ActiveRecordError {
102
+ name: string;
103
+ readonly reason: string;
104
+ constructor(reason: string);
105
+ }
106
+ /** Makes the sentinel a pre-write callback throws to refuse: `throw abort("reason")`. */
107
+ declare function abort(reason?: string): CallbackAbort;
108
+ /** A `…OrThrow` save was refused by a callback's `abort(reason)`. */
109
+ declare class RecordNotSaved extends ActiveRecordError {
110
+ name: string;
111
+ }
112
+ /**
113
+ * `abort()` was thrown from an after-write callback (`afterSave`, `afterCreate`, `afterUpdate`,
114
+ * `afterDestroy`). That's a mistake: the save or destroy already succeeded and nothing rolls back.
115
+ */
116
+ declare class AbortAfterPersistence extends ActiveRecordError {
117
+ name: string;
118
+ readonly callback: string;
119
+ readonly reason: string;
120
+ constructor(callback: string, lifecycle: "save" | "destroy", abortion: CallbackAbort);
121
+ }
122
+ /** A `destroyOrThrow()` was refused by a `beforeDestroy` callback's `abort(reason)`. */
123
+ declare class RecordNotDestroyed extends ActiveRecordError {
124
+ name: string;
125
+ }
126
+ /** A name passed to `includes()` or `loaded()` that isn't one of the Model's associations. */
127
+ declare class UnknownAssociation extends ActiveRecordError {
128
+ name: string;
129
+ }
130
+ /** `record.loaded(name)` for an association that wasn't preloaded or read yet. */
131
+ declare class AssociationNotLoaded extends ActiveRecordError {
132
+ name: string;
133
+ }
134
+ //#endregion
135
+ //#region src/current-database.d.ts
136
+ /**
137
+ * Runs `fn` with `databases` as the request's own: queries started from a Model inside it (and
138
+ * everything it awaits) use the one on that Model's binding, with its Session and `onQuery`.
139
+ * Usually called once per request, in middleware. Nested calls add to the outer ones.
140
+ *
141
+ * Each call is a scope of its own, even with a Database another request shares. An adapter may
142
+ * hold a connection for the scope (the PostgreSQL adapter does, from a connection string). A nested call with
143
+ * the same Database shares the outer call's scope while that call is running. When `fn` settles,
144
+ * the scope ends, and the adapter lets its connection go once the queries still running on it
145
+ * finish. Work that outlives the scope, such as a `waitUntil` save, gets a connection of its own.
146
+ */
147
+ declare function withDatabase<R>(databases: AnyDatabase | readonly AnyDatabase[], fn: () => R | Promise<R>): Promise<R>;
148
+ //#endregion
149
+ export { UnknownAttribute as C, hasOne as D, hasMany as E, UnknownAssociation as S, belongsTo as T, RecordInvalid as _, CallbackAbort as a, RecordNotSaved as b, DeleteRestriction as c, InvalidModel as d, IrreversibleOrder as f, RecordDestroyed as g, NotNullViolation as h, AssociationNotLoaded as i, IncompatibleRelation as l, NoDatabase as m, AbortAfterPersistence as n, CheckViolation as o, MissingAttribute as p, ActiveRecordError as r, ConstraintViolation as s, withDatabase as t, InvalidForeignKey as u, RecordNotDestroyed as v, abort as w, RecordNotUnique as x, RecordNotFound as y };