@forestfuture/active-record 0.8.2 → 0.9.1
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/adapter.d.mts +2 -2
- package/dist/adapter.mjs +4 -4
- package/dist/{batch-D3nP3g83.mjs → batch-DpMoy3-7.mjs} +2566 -1706
- package/dist/cli.d.mts +4 -4
- package/dist/cli.mjs +3 -3
- package/dist/command.mjs +19 -18
- package/dist/d1.d.mts +2 -2
- package/dist/d1.mjs +9 -4
- package/dist/{for-adapters-CgEQfuyD.mjs → for-adapters-DSVRZL3n.mjs} +6 -3
- package/dist/{for-adapters-DAn1wSYz.d.mts → for-adapters-GQfwyuMl.d.mts} +1 -1
- package/dist/for-adapters-unqbZQM7.mjs +12 -0
- package/dist/{generated-model-FB7oT7V1.mjs → generated-model-CKIciUat.mjs} +1982 -1148
- package/dist/{epoch-storage-C7186hd1.mjs → identifiers-BP6aRwew.mjs} +285 -223
- package/dist/{index-BfX3Dgy_.d.mts → index-DkWlkGy2.d.mts} +139 -96
- package/dist/index.d.mts +4 -4
- package/dist/index.mjs +5 -5
- package/dist/metadata-nKZ_6DzA.d.mts +378 -0
- package/dist/{plugin-BY2QaRpq.mjs → plugin-A93qwqAh.mjs} +10 -7
- package/dist/{plugin-IHD0I6Rg.mjs → plugin-CsOOLZkx.mjs} +7 -7
- package/dist/postgresql.d.mts +1 -1
- package/dist/postgresql.mjs +28 -4
- package/dist/{src-DnuvSHF6.mjs → src-CB2AUq70.mjs} +2 -2
- package/dist/{storage-override-BFC-GSR0.mjs → storage-override-B7WTiA_U.mjs} +1 -1
- package/dist/{validations-DFLjJ203.d.mts → validations-C2-HKi1V.d.mts} +325 -118
- package/llms-full.txt +8489 -4094
- package/package.json +1 -1
- package/skills/active-record/SKILL.md +5 -3
- package/dist/for-adapters-l4rNitkK.mjs +0 -31
- package/dist/metadata-CzntpYzC.d.mts +0 -182
package/package.json
CHANGED
|
@@ -12,7 +12,7 @@ description: Active Record (`@forestfuture/active-record`, with its D1 and Postg
|
|
|
12
12
|
Active Record (`@forestfuture/active-record`) is a Rails-style Active Record for Cloudflare Workers, with an adapter per database inside it: `@forestfuture/active-record/d1` for D1, and `@forestfuture/active-record/postgresql` for Postgres, which needs the app's own `pg`. Import Models, Relations, and errors from the core, and what opens a database from its adapter's entry: `connect`, `withSession`, `NoSession`, and `d1` from `/d1`; `connect` and `postgresql` from `/postgresql`. Every `active-record` command reads `active-record.jsonc`, which names each database's adapter, so one project can hold a D1 database and a Postgres one: run `npx active-record init` to write it, never `--adapter` on another command (`init --adapter postgresql` adds Hyperdrive bindings to a file that names only D1 databases). Its guide for the installed version is `node_modules/@forestfuture/active-record/llms-full.txt`, one Markdown file with a `#` heading per page: read the part for the task before writing code with it.
|
|
13
13
|
|
|
14
14
|
- Create tables with the generators, never by hand-declaring attributes: `npx active-record g model Post user:references 'title:string!'` writes the migration and the Model; `npx active-record g migration AddSlugToPosts slug:string:unique` writes a change. Apply them with `npx active-record migrate`. After a hand-written migration, run `npx active-record schema`. Never edit the generated `src/db/schema.ts`.
|
|
15
|
-
- A Model extends the app's base class: `class Post extends ApplicationRecord {}`. Its table comes from its class name (`Post` → `posts`), or `static override table = "…"`, and its attributes from the schema, so it declares only behavior. With a bundler that renames classes (Wrangler keeps them by default), set `static override modelName = "Post"` on each Model, so its table, foreign keys and schema entry keep the name. Run `npx active-record schema` after adding or renaming a Model, as after a migration: a Model it hasn't seen throws `InvalidModel`. Change how a column is read with an override in the class, `static override attributes = { metadata: "json" } as const`, never by editing the schema. An `INTEGER` holding a Unix time (Drizzle's `timestamp` modes) is `{ type: "datetime", storage: "unixSeconds" }` or `"unixMilliseconds"`. Bytes are a `binary` attribute (a `Uint8Array`, in a `BLOB` or `bytea` column): assign a form's file as `new Uint8Array(await file.arrayBuffer())`. An exact number (a price, a quantity with a fraction) is a `decimal` attribute, held as text (`"12.5"`) in a `NUMERIC` or `DECIMAL` column, never a `real`, with `precision` and `scale` to round it as `NUMERIC(10, 2)` does; a day with no time is a `date` (`"2026-01-02"`) and a time of day a `time` (`"09:30:00"`), assigned as text, not a `Date`. A value no built-in type holds (money, a value object, a list kept as text) is a custom type: `const money = defineType({ storedAs: "integer", cast, serialize, deserialize })`, given as `priceCents: money` in the override or in `define`, rather than converting in getters, setters or callbacks; its `cast` throws for a value it can't hold. A column with a fixed set of values is an enum: `status: { enum: ["draft", "published"] }` (names stored as text) or `{ enum: { low: 0, high: 1 } }` (an integer column), which gives `post.isDraft()`, `await post.saveAsPublished()`, `Post.published()`, `Post.notPublished()` and `Post.enumValues("status")`; use those and `where({ status: "published" })` rather than a hand-written scope or a `declare status: …` narrowing. Run `npx active-record schema` after adding an enum, so its scopes are typed. A column the database restricts to a list (a Postgres enum type, `CHECK (state IN ('open', 'done'))`) already has the names in the schema, typed and checked but without methods: turn them on with `state: { enum: true }`, rather than listing the names again, or drop it with `enum: false`. An unlisted stored value reads as `null`; rename a name with `{ newName: "old_value" }`. A cell that isn't its attribute's type (a number in an ISO `datetime`, text in an `integer`) fails the load with a `TypeError` naming the attribute: correct the override, don't catch it.
|
|
15
|
+
- A Model extends the app's base class: `class Post extends ApplicationRecord {}`. Its table comes from its class name (`Post` → `posts`), or `static override table = "…"`, and its attributes from the schema, so it declares only behavior. With a bundler that renames classes (Wrangler keeps them by default), set `static override modelName = "Post"` on each Model, so its table, foreign keys and schema entry keep the name. Run `npx active-record schema` after adding or renaming a Model, as after a migration: a Model it hasn't seen throws `InvalidModel`. Change how a column is read with an override in the class, `static override attributes = { metadata: "json" } as const`, never by editing the schema. Normalize an attribute's values (trimming, lowercasing an email) with `this.normalizes("email", { with: (email) => email.trim().toLowerCase() })` in `static {}`, not in a setter, a `beforeValidation` callback or each query: it runs on every assigned value and on a query's values too, so `findBy` with the user's input finds the stored row. It doesn't change rows already stored: normalize those with `record.normalizeAttribute("email")` and `save()`. A value a form sends but the table doesn't keep (a terms checkbox, a confirmation) is a virtual attribute in the same object, `termsOfService: { type: "boolean", virtual: true }`, not a plain class field: it's cast, tracked and taken by `permit`, never saved, and a query can't name it. To give an attribute a second name, add `title: { aliasOf: "name" }` there, rather than a getter and setter: queries, writes and validations take either name. Keep a password as `password: { securePassword: true }` there, with a `password_digest` column, never by hashing in a callback or storing it: it's hashed with PBKDF2 when the record is saved, `await user.authenticate(password)` checks it, and sign in with `await User.authenticateBy({ email, password })`, which resolves to null for a wrong email or password alike, rather than `findBy` then `authenticate`. Ask for the current password before a change with `passwordChallenge`. For bcrypt or a stronger hash, give `{ securePassword: { algorithm } }` an object with `hash`, `verify` and `maxBytes`. The default costs 10–40 ms of CPU per hash, past the Workers Free plan's 10 ms. A random token for each new record (an API token, an invite code) is `authToken: { secureToken: true }` on a string column with a UNIQUE index, with `await user.regenerateAuthToken()` to replace it, rather than `crypto.randomUUID()` in a callback; `generateSecureToken()` makes one for anything else. For a password reset link, use `await user.passwordResetToken()` and `await User.findByPasswordResetToken(token)`, never a token column you store and clear: it lasts 15 minutes and stops working once the password changes. For any other link (confirming an email, unsubscribing), declare `this.generatesTokenFor("emailConfirmation", { expiresIn: { days: 1 }, dependsOn: (user) => user.email })` in `static {}`, then `await user.generateTokenFor(purpose)` and `User.findByTokenFor(purpose, token)`; or sign an id with `await user.signedId({ purpose, expiresIn })` and `User.findSigned(signedId, { purpose })`. Don't put a plain id in such a link, or sign one yourself. They're signed with the Worker's `SECRET_KEY_BASE` (`wrangler secret put SECRET_KEY_BASE`, at least 32 bytes; in tests, `process.env`); to rotate it, override `static signingSecret(env)` on the app's base class to return `[env.SECRET_KEY_BASE, env.PREVIOUS_SECRET_KEY_BASE]`. An `INTEGER` holding a Unix time (Drizzle's `timestamp` modes) is `{ type: "datetime", storage: "unixSeconds" }` or `"unixMilliseconds"`. Bytes are a `binary` attribute (a `Uint8Array`, in a `BLOB` or `bytea` column): assign a form's file as `new Uint8Array(await file.arrayBuffer())`. An exact number (a price, a quantity with a fraction) is a `decimal` attribute, held as text (`"12.5"`) in a `NUMERIC` or `DECIMAL` column, never a `real`, with `precision` and `scale` to round it as `NUMERIC(10, 2)` does; a day with no time is a `date` (`"2026-01-02"`) and a time of day a `time` (`"09:30:00"`), assigned as text, not a `Date`. A value no built-in type holds (money, a value object, a list kept as text) is a custom type: `const money = defineType({ storedAs: "integer", cast, serialize, deserialize })`, given as `priceCents: money` in the override or in `define`, rather than converting in getters, setters or callbacks; its `cast` throws for a value it can't hold. A column with a fixed set of values is an enum: `status: { enum: ["draft", "published"] }` (names stored as text) or `{ enum: { low: 0, high: 1 } }` (an integer column), which gives `post.isDraft()`, `await post.saveAsPublished()`, `Post.published()`, `Post.notPublished()` and `Post.enumValues("status")`; use those and `where({ status: "published" })` rather than a hand-written scope or a `declare status: …` narrowing. Run `npx active-record schema` after adding an enum, so its scopes are typed. A column the database restricts to a list (a Postgres enum type, `CHECK (state IN ('open', 'done'))`) already has the names in the schema, typed and checked but without methods: turn them on with `state: { enum: true }`, rather than listing the names again, or drop it with `enum: false`. An unlisted stored value reads as `null`; rename a name with `{ newName: "old_value" }`. A cell that isn't its attribute's type (a number in an ISO `datetime`, text in an `integer`) fails the load with a `TypeError` naming the attribute: correct the override, don't catch it.
|
|
16
16
|
- Start queries and new records from the Model, as in Rails: `User.find(id)`, `User.where(…)`, `User.build(…)`. Each Model queries the binding named in the generated schema its base class holds, during a request. For a D1 Session, wrap the handler in `withSession(request, env.DB, fn)`. For per-request `onQuery`, or tests and scripts outside a Worker, wrap the code once in `withDatabase(connect(env.DB, { … }), fn)`. Records keep the database they came from.
|
|
17
17
|
- Never pass a request's whole body, form or query string to a Model: name the fields, with destructuring or `User.permit(await request.json(), "email", "name")` (it reads `FormData` and `URLSearchParams` too). Assigned values are checked against the attribute's type, but that doesn't stop a user setting `role` or `isAdmin`. Check a request value's type before querying with it: `findBy({ token: null })` matches rows whose token is NULL, and a list matches any of its values. `findOrCreateBy`, `findOrInitializeBy` and `createOrFindBy` throw `TypeError` for a list, a comparison or a `sql` fragment.
|
|
18
18
|
- Name attributes in camelCase everywhere: `where`, `order`, `pluck`, `foreignKey`. Column names (snake_case) appear only inside `sql` fragments.
|
|
@@ -21,13 +21,15 @@ Active Record (`@forestfuture/active-record`) is a Rails-style Active Record for
|
|
|
21
21
|
- Bulk writes run when called, without callbacks: `await posts.deleteAll()`, `deleteBy({…})` and `updateAll(…)` resolve to how many rows; `insert(…)`, `insertAll`, `upsert` and `upsertAll` to `{ rowsAffected, rows }`, where `rows` holds each written row's primary key, or the attributes `returning: [...]` names (`returning: false` for none). Through a Relation they write its equality values and `createWith` over the attributes given (`Post.where({ userId: 1 }).insert({ userId: 2, … })` writes `userId: 1`), where `build` and `create` keep the given ones. Make several writes atomic by preparing them in one batch's callback: `batch((b) => [b.insert(Post, {…}), b.updateAll(Post.where(…), {…}), b.save(user), b.destroy(post)])`. The callback can't await, so load what the writes need first. D1 has no interactive transactions, so a read-then-write can't be atomic.
|
|
22
22
|
- Count with the database, not in memory: `post.incrementColumn("viewCount")` or `Post.updateCounters(id, { viewCount: 1 })` add to the row atomically, where `post.viewCount++` then `save()` loses another request's increment. The counter statics (`Post.updateCounters(ids, …)`, `incrementCounter`) skip the default scope, so with a key from a request, and a default scope that separates tenants or hides deleted rows, write `Post.where({ id }).updateCounters({ … })`, which keeps it. The `…Column` methods and `updateColumns` skip validations, callbacks and `updatedAt`, so use `update` for a change those should see; `increment` and `toggle` only change the record in memory. In an after-callback, `record.isPreviouslyNewRecord()` says whether the save created it.
|
|
23
23
|
- To mark a record changed without saving it (a cache key, a "last seen"), `await record.touch()` sets `updatedAt`, or `touch("lastSeenAt")` that attribute too, with no validation or save callback; `Post.where(…).touchAll()` touches many rows. A touch runs `afterTouch` and the update commit callbacks (`afterUpdateCommit` included), so code there that should run only on a save belongs in `afterUpdate` or `afterSave`. To keep a parent's `updatedAt` current as its children change (a cache key), declare `belongsTo(Article, { touch: true })` on the child rather than touching the parent in a callback: the parent is touched in the child's batch, runs its own touch callbacks, and touches its own parents in turn. A parent that isn't loaded costs one SELECT per level, so preload the chain (`includes({ article: "blog" })`) when saving many. `hasOne(Profile, { touch: true })` touches a user's profile the same way when the user is updated, destroyed or touched. For a bulk import, wrap it in `Article.noTouching(async () => { … })`, so no article is touched per comment, then touch each article once after it.
|
|
24
|
+
- To stop two edits of one record from overwriting each other, add a `lock_version INTEGER NOT NULL DEFAULT 0` column: every save, destroy and `touch()` then checks the row still has the record's `lockVersion`, and a stale copy's throws `StaleRecord` (from `save()` too, not `false`) and writes nothing in its batch (a destroy's dependents on another database are already gone). For edits across requests, put `lockVersion` in the form as a hidden field and permit it with the other fields, and answer `StaleRecord` with a 409; to retry in code, `await record.reload()` and make the change again. A child's `touch` on a locked parent raises the parent's version, so a parent its children touch often gets conflicts: drop the `touch` or write the children inside `noTouching`.
|
|
25
|
+
- For records a request reads but must not write (a public page, a report), load them with `readonly()` (`Article.readonly().where(…)`) or call `record.markReadonly()`: a save, update, destroy, `touch()` or column write then throws `ReadonlyRecord` before anything runs. Bulk writes (`updateAll`, `deleteAll`) ignore the mark. For an attribute set once on create, such as a slug, declare `slug: { readonly: true }` in the Model's `static attributes`: changing it on a saved record throws `ReadonlyAttribute`, and posting back the value it holds is fine, so an edit form needn't leave it out.
|
|
24
26
|
- To show how many records an association has, keep a counter cache rather than counting on each read: `article = belongsTo(Article, { counterCache: true })` with a `commentsCount` attribute, which `article.comments().size()` reads. Saves, destroys and the association's `delete`/`clear`/`deleteAll()` keep it; bulk writes (`insertAll`, `updateAll`, a Relation's `deleteAll`) don't, so follow them with `Article.resetCounters(id, "comments")`. Add one to existing rows with `{ active: false }`, reset each, then drop `active: false`.
|
|
25
27
|
- To work through more records than a request should hold (a backfill, an export, a cleanup), iterate in batches rather than `toArray()` or `offset` pages: `for await (const user of User.where(…).findEach())`, `findInBatches()` for arrays, and `inBatches()` for a Relation per batch to `updateAll`, `deleteAll` or `destroyAll`. Batches go in primary-key order, so `reorder()` a Relation that has an order (a default scope's too), and bound them with `start` and `finish`, not `offset`. On D1 a Worker invocation sends at most 1,000 queries (50 on Free), and each batch sends one (`inBatches` reads its keys, then sends the write, and a `destroyAll` adds a load and each record's dependent reads; a `db.batch` counts as one): split a larger job across invocations by `start` and `finish`.
|
|
26
28
|
- To destroy many records with their callbacks and `dependent:` strategies, use `posts.destroyAll()`, `Post.destroyBy({…})` or `Post.destroy(ids)`: they load the records and destroy them in one write, all or none (`RecordNotDestroyed` if one refuses). They hold every record in memory, so destroy a large set a batch at a time: `for await (const batch of posts.inBatches({ batchSize: 100 })) await batch.destroyAll()`.
|
|
27
29
|
- Keep the generators' `TEXT` keys, generated in code, for records saved together (`--id integer` gives a key D1 generates instead). An owner whose key is known before its INSERT (generated in code, or already saved) is written in one atomic batch with the records built through it on its database. A key D1 generates exists only after its own write, so each level is then written in a separate batch. Records on another database are always a separate write there, and a batch refuses them.
|
|
28
30
|
- To change how those keys are made (UUIDv7, ULID, a prefix), override `static generateId` once on the app's base class; don't give each Model's key a `default`. `generateId` sees only the attribute's name, so a value made from other attributes (a slug) goes in a callback.
|
|
29
31
|
- Declare associations as fields, passing the target class: `posts = hasMany(Post, { dependent: "destroy" })`, `author = belongsTo(User)`. The field's name is the association's name. Add and remove a `hasMany`'s records through it: `user.posts().push(post)`, `delete(post)` (by its `dependent:`, nullifying by default), `destroy(post)` and `clear()`, rather than writing the foreign key yourself, so a loaded collection stays in step. Saving requires a `belongsTo`'s record ("must exist"), so pass `optional: true` when its foreign key may be `null`. Its target may be on another database (a Model on another base class): reading, preloading (one more round trip), and writing through it go to the target's database, and a save or destroy writes each database separately, not atomically. A `hasOne`'s new record, through `set`, `build` or `create`, replaces the old one, which its `dependent:` strategy removes (without one, its foreign key is set to `null`). Await `user.profile.set(profile)`: on a saved owner it saves at once, unlike a `belongsTo`'s `set`. To save changes to associated records with their owner, declare the association `autosave: true` and change the records it loaded (`await user.posts().toArray()`), not ones found with a query of their own. `record.markForDestruction()` then destroys a record when its owner is saved. For a record that can belong to one of several Models, list them: `commentable = belongsTo([Post, Photo])`, with `commentableType` and `commentableId` attributes, and `comments = hasMany(Comment, { as: "commentable" })` on each listed Model. Point it with `comment.commentable.set(post)`, not by writing the type yourself: the type holds each Model's `modelName`, so set `static modelName` on the listed Models if a bundler renames classes. Reach records through a join Model with `through`: `projects = hasMany(Project, { through: "assignments" })` (`source:` names the join Model's association when it isn't `project`). It reads and preloads as any association, each record once. Write through it to make and remove join records: `user.projects().push(project)`, `build`, `create`, `delete(project)` and `clear()` (`destroy(project)` destroys the join records too, not the project). A built project is linked when the owner is saved, not the project. Don't narrow before `deleteAll` (`user.projects().where(…).deleteAll()`), which deletes the projects themselves. Only a join Model is written through (a `hasMany` to a `belongsTo`); `insert` and `upsert` through it throw. An upsert through a `hasMany` only updates the owner's records, and leaves another owner's clashing row as it is.
|
|
30
|
-
- Change the copy of validation messages with `this.errorMessages({...})` in the `static {}` block of the app's base class (every Model) or a Model (`attributes: { email: { taken: "…" } }` for one attribute), and attribute names with `this.humanAttributeNames({...})`, rather than a `message` on every `validates`. Compare one attribute with another with `comparison: { greaterThan: (event) => event.startsAt }`, not a callback. Validate an association's loaded records with `this.validatesAssociated("posts")`, not a callback. Run a rule only when creating or updating with `on: "create"` or `on: "update"` (or skip one with `exceptOn`), not `if: (record) => record.isNewRecord()`. For a step of the app's own, list its name in the Model's `static validationContexts = ["signup"] as const` and validate in it with `isValid("signup")` or `save({ context: "signup" })`; that replaces `"create"`, so pass `["create", "signup"]` to run both. For a custom error, `errors.add("startsAt", { type: "onTheHour" })` and give `onTheHour` a message there.
|
|
32
|
+
- Change the copy of validation messages with `this.errorMessages({...})` in the `static {}` block of the app's base class (every Model) or a Model (`attributes: { email: { taken: "…" } }` for one attribute), and attribute names with `this.humanAttributeNames({...})`, rather than a `message` on every `validates`. Check a value typed twice with `this.validates("email", { confirmation: true })` and a virtual `emailConfirmation: { type: "string", virtual: true }`; `toJSON()` leaves the confirmation out. Compare one attribute with another with `comparison: { greaterThan: (event) => event.startsAt }`, not a callback. Validate an association's loaded records with `this.validatesAssociated("posts")`, not a callback. Run a rule only when creating or updating with `on: "create"` or `on: "update"` (or skip one with `exceptOn`), not `if: (record) => record.isNewRecord()`. For a step of the app's own, list its name in the Model's `static validationContexts = ["signup"] as const` and validate in it with `isValid("signup")` or `save({ context: "signup" })`; that replaces `"create"`, so pass `["create", "signup"]` to run both. For a custom error, `errors.add("startsAt", { type: "onTheHour" })` and give `onTheHour` a message there.
|
|
31
33
|
- Check what writes return. `save()` and `update()` resolve to `false` when validation fails (reasons in `record.errors`) or a callback aborts (`record.abortReason`). `destroy()` resolves to `false` when a callback aborts, or a `restrictWithError` association refuses (reason in `record.errors`). The `…OrThrow` methods throw instead. Constraint errors, such as `RecordNotUnique`, always throw, and so does a rule declared `strict: true` (`StrictValidationFailed`), meant for values only a bug could set.
|
|
32
34
|
|
|
33
35
|
<!-- #endregion rules -->
|
|
@@ -83,7 +85,7 @@ export default {
|
|
|
83
85
|
|
|
84
86
|
- **`onQuery` listeners see filtered attributes' values as `"[FILTERED]"`**: passwords, tokens, keys and emails, by Rails' default list. Add names to `static filterAttributes` on the app's base class for other secrets. Values inside `sql` fragments aren't filtered.
|
|
85
87
|
- **`relation.toSql()` shows a query's `{ sql, params }` without sending it**, to inspect it while debugging. The params are real values, filtered attributes included, so don't log them where `onQuery` wouldn't. Bulk writes and batches have no `toSql()`; `onQuery` shows what they sent.
|
|
86
|
-
- **`toJSON()` sends every loaded attribute**, so `Response.json(user)` includes `
|
|
88
|
+
- **`toJSON()` sends every loaded attribute**, so `Response.json(user)` includes an `apiKey` column. List the names to leave out in `static hiddenAttributes` on the app's base class (exact names; a Model's own list replaces it). `attributes()` still has them. A secure password, its confirmation, challenge and digest, and a secure token, are left out already; send a token on purpose, as `Response.json({ token: user.authToken })`.
|
|
87
89
|
- **Uniqueness validation is a friendly check, not a guarantee.** Two requests can pass it at once; the table's UNIQUE index decides, and the save then throws `RecordNotUnique`. Declare both. To create a row once where requests race, use `createOrFindBy(attrs)` (insert, then find on `RecordNotUnique`) with the index alone: a `uniqueness` validation refuses first, so it finds nothing. `findOrCreateBy` races.
|
|
88
90
|
- **`record.loaded("posts")` reads what was preloaded or already read**, synchronously, and throws `AssociationNotLoaded` otherwise. `await user.posts().toArray()` loads when needed. A record loaded or built through `user.posts()` already has `user` loaded as its `author` (its inverse association), so don't preload or re-read the owner from a child; with a `scope:` on either side, name the inverse with `inverseOf: "author"`.
|
|
89
91
|
- **Page a list with `paginate()`, not a hand-built `limit` and `offset`**: `Post.published().paginate({ page: url.searchParams.get("page") })` casts the untrusted page, caps its size at `static maxPerPage`, and on D1 sends the count with the page in one round trip. `{ count: false }` skips the `COUNT`, which reads (and bills) every matching row.
|
|
@@ -1,31 +0,0 @@
|
|
|
1
|
-
import { z as NoDatabase } from "./epoch-storage-C7186hd1.mjs";
|
|
2
|
-
// 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
|
-
// src/workers-env.ts
|
|
13
|
-
/** Whether importing `cloudflare:workers` failed because this isn't a Worker (Node, scripts). */
|
|
14
|
-
function isOutsideWorker(error) {
|
|
15
|
-
const { code, message } = error;
|
|
16
|
-
return code === "ERR_UNSUPPORTED_ESM_URL_SCHEME" || code === "ERR_MODULE_NOT_FOUND" || /cloudflare:workers/.test(String(message));
|
|
17
|
-
}
|
|
18
|
-
/**
|
|
19
|
-
* The Worker's `env`, from `load`, or undefined outside a Worker (Node, scripts). An adapter
|
|
20
|
-
* passes `() => import("cloudflare:workers")` from its own module, with that literal specifier:
|
|
21
|
-
* Wrangler only bundles those, and a test that mocks the module with the adapter inlined reaches it.
|
|
22
|
-
*/
|
|
23
|
-
async function workersEnv(load) {
|
|
24
|
-
try {
|
|
25
|
-
return (await load()).env;
|
|
26
|
-
} catch (error) {
|
|
27
|
-
if (isOutsideWorker(error)) return void 0;
|
|
28
|
-
throw error;
|
|
29
|
-
}
|
|
30
|
-
}
|
|
31
|
-
export { onlyRequested as n, workersEnv as t };
|
|
@@ -1,182 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* A type an app defines: what its values are, and how each is kept as a value of the built-in
|
|
3
|
-
* type it's stored as. Made by `defineType`.
|
|
4
|
-
*/
|
|
5
|
-
interface CustomType<T = unknown, S extends AttributeType = AttributeType> {
|
|
6
|
-
/** The built-in type its values are stored as: `"integer"` for money kept as cents. */
|
|
7
|
-
readonly storedAs: S;
|
|
8
|
-
/**
|
|
9
|
-
* An assigned value or a condition's as the type's value. It throws for one it can't hold:
|
|
10
|
-
* assigning that value throws `TypeError`, with this error as its `cause`, and a condition
|
|
11
|
-
* matches nothing. Never called with `null`.
|
|
12
|
-
*/
|
|
13
|
-
cast(input: unknown): T;
|
|
14
|
-
/** A value as the stored type's value: `money.cents`. Never called with `null`. */
|
|
15
|
-
serialize(value: T): BuiltInValue<S>;
|
|
16
|
-
/** A stored type's value, read as the stored type reads a cell, as the type's value. */
|
|
17
|
-
deserialize(stored: BuiltInValue<S>): T;
|
|
18
|
-
}
|
|
19
|
-
/** Any custom type, whatever its values: what a spec takes. */
|
|
20
|
-
type AnyCustomType = CustomType<any, AttributeType>;
|
|
21
|
-
/**
|
|
22
|
-
* Defines an attribute type, used in a spec as a type name is: `price: money`, or
|
|
23
|
-
* `{ type: money, null: false }`. Its values are kept as `storedAs` keeps its own, so they're
|
|
24
|
-
* read strictly, compared and ordered as that type's are.
|
|
25
|
-
*/
|
|
26
|
-
declare function defineType<T, S extends AttributeType>(type: CustomType<T, S>): CustomType<T, S>;
|
|
27
|
-
/**
|
|
28
|
-
* An enum's values: its names, each stored as itself (a `string` attribute's only), or each name
|
|
29
|
-
* with the value it's stored as (`{ draft: 0, published: 1 }`).
|
|
30
|
-
*/
|
|
31
|
-
type EnumValues = readonly string[] | {
|
|
32
|
-
readonly [name: string]: string | number;
|
|
33
|
-
};
|
|
34
|
-
/** A `string` attribute's enum: names stored as themselves, or each with the text it's stored as. */
|
|
35
|
-
type TextEnum = readonly string[] | {
|
|
36
|
-
readonly [name: string]: string;
|
|
37
|
-
};
|
|
38
|
-
/** An `integer` attribute's enum: each name with the integer it's stored as. */
|
|
39
|
-
type IntegerEnum = {
|
|
40
|
-
readonly [name: string]: number;
|
|
41
|
-
};
|
|
42
|
-
/** The names an enum's values give its attribute: `"draft" | "published"`. */
|
|
43
|
-
type EnumNames<E> = E extends readonly (infer N extends string)[] ? N : keyof E & string;
|
|
44
|
-
/** An enum's names, each with the value it's stored as, as `enumValues` gives them. */
|
|
45
|
-
type EnumMapping<E> = E extends readonly string[] ? { readonly [N in E[number]]: N; } : Readonly<E>;
|
|
46
|
-
/** A datetime held in an `INTEGER` column as seconds or milliseconds since 1970. */
|
|
47
|
-
declare const epochStorages: readonly ["unixSeconds", "unixMilliseconds"];
|
|
48
|
-
type EpochStorage = (typeof epochStorages)[number];
|
|
49
|
-
type AttributeType = "string" | "integer" | "real" | "decimal" | "boolean" | "datetime" | "date" | "time" | "json" | "binary";
|
|
50
|
-
/** An attribute's spec written out: its type, and optionally nullability, column and default. */
|
|
51
|
-
interface SpecObject {
|
|
52
|
-
/** A built-in type's name, or a type `defineType` made (#20). */
|
|
53
|
-
type: AttributeType | AnyCustomType;
|
|
54
|
-
null?: boolean;
|
|
55
|
-
column?: string;
|
|
56
|
-
/** A `datetime` held as a Unix epoch integer, as Drizzle's timestamp modes write it (#73). */
|
|
57
|
-
storage?: EpochStorage;
|
|
58
|
-
/** A decimal's most digits in all, as `NUMERIC(10, 2)`'s 10; without a scale, its scale is 0 (#398). */
|
|
59
|
-
precision?: number;
|
|
60
|
-
/** A decimal's digits after the point, as `NUMERIC(10, 2)`'s 2: a cast value is rounded to them (#398). */
|
|
61
|
-
scale?: number;
|
|
62
|
-
/** Evaluated at `build()`, e.g. `() => new Date()`. */
|
|
63
|
-
default?: () => unknown;
|
|
64
|
-
/**
|
|
65
|
-
* Made by the Model's `generateId` when not given, where a default would run: an
|
|
66
|
-
* app-generated key (#99). Generated ids are strings, so only a string attribute has one.
|
|
67
|
-
*/
|
|
68
|
-
generateId?: boolean;
|
|
69
|
-
/** Its only values, by name, and what each is stored as (#340). */
|
|
70
|
-
enum?: EnumValues;
|
|
71
|
-
/** A word before each enum name in its methods' names: the attribute's name for `true` (#340). */
|
|
72
|
-
prefix?: boolean | string;
|
|
73
|
-
/** A word after each enum name in its methods' names: the attribute's name for `true` (#340). */
|
|
74
|
-
suffix?: boolean | string;
|
|
75
|
-
/** `false` to give the Model no scope for each enum name (#340). */
|
|
76
|
-
scopes?: boolean;
|
|
77
|
-
/** `false` to give records no predicate or `saveAs…` setter for each enum name (#340). */
|
|
78
|
-
instanceMethods?: boolean;
|
|
79
|
-
/**
|
|
80
|
-
* Validates an enum's value instead of refusing an unknown one when it's assigned, as Rails'
|
|
81
|
-
* `validate: true` does: a record holding another value, or null unless `allowNull`, is invalid.
|
|
82
|
-
*/
|
|
83
|
-
validate?: EnumValidation;
|
|
84
|
-
}
|
|
85
|
-
/** How an enum's value is validated: `true`, or `{ allowNull: true }` to let it be null. */
|
|
86
|
-
type EnumValidation = boolean | {
|
|
87
|
-
readonly allowNull?: boolean;
|
|
88
|
-
};
|
|
89
|
-
/** Where a string attribute's value comes from when it isn't given: a default or `generateId`, never both. */
|
|
90
|
-
type ValueSource = {
|
|
91
|
-
default?: () => unknown;
|
|
92
|
-
generateId?: false;
|
|
93
|
-
} | {
|
|
94
|
-
default?: never;
|
|
95
|
-
generateId: true;
|
|
96
|
-
};
|
|
97
|
-
/** An attribute that isn't an enum: no type but a string or an integer has one (#340). */
|
|
98
|
-
type NoEnum = {
|
|
99
|
-
enum?: never;
|
|
100
|
-
prefix?: never;
|
|
101
|
-
suffix?: never;
|
|
102
|
-
scopes?: never;
|
|
103
|
-
instanceMethods?: never;
|
|
104
|
-
validate?: never;
|
|
105
|
-
};
|
|
106
|
-
/** An attribute that isn't a decimal: only a decimal has a precision and a scale (#398). */
|
|
107
|
-
type NoDigits = {
|
|
108
|
-
precision?: never;
|
|
109
|
-
scale?: never;
|
|
110
|
-
};
|
|
111
|
-
/** The spec's keys that only some types have, each written by the type's own branch below. */
|
|
112
|
-
type PerTypeKeys = "type" | "generateId" | "storage" | "enum" | "precision" | "scale";
|
|
113
|
-
type AttributeSpec = AttributeType | AnyCustomType | (Omit<SpecObject, "default" | PerTypeKeys> & {
|
|
114
|
-
type: "string";
|
|
115
|
-
storage?: never;
|
|
116
|
-
enum?: TextEnum;
|
|
117
|
-
} & ValueSource & NoDigits) | (Omit<SpecObject, PerTypeKeys> & NoDigits & {
|
|
118
|
-
type: "integer";
|
|
119
|
-
generateId?: false;
|
|
120
|
-
storage?: never;
|
|
121
|
-
enum?: IntegerEnum;
|
|
122
|
-
}) | (Omit<SpecObject, PerTypeKeys> & NoEnum & NoDigits & {
|
|
123
|
-
type: Exclude<AttributeType, "string" | "integer" | "datetime" | "decimal">;
|
|
124
|
-
generateId?: false;
|
|
125
|
-
storage?: never;
|
|
126
|
-
}) | (Omit<SpecObject, PerTypeKeys> & NoEnum & {
|
|
127
|
-
type: "decimal";
|
|
128
|
-
generateId?: false;
|
|
129
|
-
storage?: never;
|
|
130
|
-
precision?: number;
|
|
131
|
-
scale?: number;
|
|
132
|
-
}) | (Omit<SpecObject, Exclude<PerTypeKeys, "storage">> & NoEnum & NoDigits & {
|
|
133
|
-
type: "datetime";
|
|
134
|
-
generateId?: false;
|
|
135
|
-
}) | (Omit<SpecObject, PerTypeKeys> & NoEnum & NoDigits & {
|
|
136
|
-
type: AnyCustomType;
|
|
137
|
-
generateId?: false;
|
|
138
|
-
storage?: never;
|
|
139
|
-
});
|
|
140
|
-
type AttributeSpecs = Record<string, AttributeSpec>;
|
|
141
|
-
/**
|
|
142
|
-
* `A`, with any key a spec doesn't have typed `never`, so a misspelled one (`nul: false`) is a
|
|
143
|
-
* compile error: a generic parameter skips TypeScript's own check for unknown keys (#102).
|
|
144
|
-
*/
|
|
145
|
-
type ExactSpecs<A> = { [K in keyof A]: A[K] extends AnyCustomType ? A[K] : A[K] extends object ? A[K] & Record<Exclude<keyof A[K], keyof SpecObject>, never> : A[K]; };
|
|
146
|
-
/** An attribute's resolved metadata. */
|
|
147
|
-
interface AttributeDefinition {
|
|
148
|
-
/** Its built-in type: for a custom type, the type it's stored as. */
|
|
149
|
-
type: AttributeType;
|
|
150
|
-
/** The type `defineType` made, whose values it holds, kept as `type`'s (#20). */
|
|
151
|
-
customType?: AnyCustomType;
|
|
152
|
-
column: string;
|
|
153
|
-
default?: () => unknown;
|
|
154
|
-
generateId?: true;
|
|
155
|
-
storage?: EpochStorage;
|
|
156
|
-
precision?: number;
|
|
157
|
-
scale?: number;
|
|
158
|
-
enum?: EnumValues;
|
|
159
|
-
prefix?: boolean | string;
|
|
160
|
-
suffix?: boolean | string;
|
|
161
|
-
scopes?: boolean;
|
|
162
|
-
instanceMethods?: boolean;
|
|
163
|
-
validate?: EnumValidation;
|
|
164
|
-
}
|
|
165
|
-
/** The JavaScript value an attribute of a built-in type holds: a `Date` for a `datetime`. */
|
|
166
|
-
type BuiltInValue<T extends AttributeType> = T extends "string" ? string : T extends "integer" | "real" ? number : T extends "boolean" ? boolean : T extends "datetime" ? Date : T extends "binary" ? Uint8Array : T extends "decimal" | "date" | "time" ? string : unknown;
|
|
167
|
-
/** A type's JavaScript value: a built-in type's, or a custom type's own (#20). */
|
|
168
|
-
type ValueOf<T> = T extends AttributeType ? BuiltInValue<T> : T extends CustomType<infer V, AttributeType> ? V : never;
|
|
169
|
-
/** A spec's value, not null: an enum's names (#340), or its type's JavaScript value. */
|
|
170
|
-
type SpecValue<S> = S extends {
|
|
171
|
-
enum: infer E extends EnumValues;
|
|
172
|
-
} ? EnumNames<E> : S extends {
|
|
173
|
-
type: infer T;
|
|
174
|
-
} ? ValueOf<T> : never;
|
|
175
|
-
type AttributeValue<S> = S extends AttributeType | AnyCustomType ? ValueOf<S> | null : S extends {
|
|
176
|
-
type: unknown;
|
|
177
|
-
null: false;
|
|
178
|
-
} ? SpecValue<S> : S extends {
|
|
179
|
-
type: unknown;
|
|
180
|
-
} ? SpecValue<S> | null : never;
|
|
181
|
-
type AttributeProperties<A extends AttributeSpecs> = { -readonly [K in keyof A]: AttributeValue<A[K]>; };
|
|
182
|
-
export { defineType as _, AttributeType as a, ValueSource as c, EnumNames as d, EnumValues as f, CustomType as g, AnyCustomType as h, AttributeSpecs as i, EpochStorage as l, TextEnum as m, AttributeProperties as n, ExactSpecs as o, IntegerEnum as p, AttributeSpec as r, SpecObject as s, AttributeDefinition as t, EnumMapping as u };
|