@forestfuture/active-record 0.0.0 → 0.6.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/LICENSE +21 -0
- package/README.md +26 -2
- package/dist/adapter-BSvFhTDf.d.mts +1293 -0
- package/dist/adapter.d.mts +2 -0
- package/dist/adapter.mjs +3 -0
- package/dist/batch-DBeYk5wx.mjs +4171 -0
- package/dist/cli.d.mts +197 -0
- package/dist/cli.mjs +3 -0
- package/dist/command.d.mts +1 -0
- package/dist/command.mjs +2157 -0
- package/dist/epoch-storage-o2aoOH7H.mjs +112 -0
- package/dist/generated-model-CfDggoVN.mjs +1853 -0
- package/dist/index.d.mts +143 -0
- package/dist/index.mjs +3 -0
- package/dist/storage-override-BYBYP8Mj.mjs +91 -0
- package/llms-full.txt +4397 -0
- package/package.json +42 -4
- package/skills/active-record/SKILL.md +88 -0
package/package.json
CHANGED
|
@@ -1,10 +1,48 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@forestfuture/active-record",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "0.6.0",
|
|
4
|
+
"description": "A Rails-inspired Active Record for Cloudflare Workers, with an adapter per database.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"active-record",
|
|
7
|
+
"cloudflare",
|
|
8
|
+
"orm",
|
|
9
|
+
"workers"
|
|
10
|
+
],
|
|
11
|
+
"homepage": "https://d1-record.forestfuture.dev",
|
|
12
|
+
"bugs": {
|
|
13
|
+
"url": "https://github.com/forestfuture/active-record/issues"
|
|
14
|
+
},
|
|
5
15
|
"license": "MIT",
|
|
16
|
+
"author": "ForestFuture (https://forestfuture.dev)",
|
|
6
17
|
"repository": {
|
|
7
18
|
"type": "git",
|
|
8
|
-
"url": "git+https://github.com/forestfuture/active-record.git"
|
|
19
|
+
"url": "git+https://github.com/forestfuture/active-record.git",
|
|
20
|
+
"directory": "packages/active-record"
|
|
21
|
+
},
|
|
22
|
+
"bin": {
|
|
23
|
+
"active-record": "./dist/command.mjs",
|
|
24
|
+
"ffar": "./dist/command.mjs"
|
|
25
|
+
},
|
|
26
|
+
"files": [
|
|
27
|
+
"dist",
|
|
28
|
+
"llms-full.txt",
|
|
29
|
+
"skills"
|
|
30
|
+
],
|
|
31
|
+
"type": "module",
|
|
32
|
+
"sideEffects": false,
|
|
33
|
+
"exports": {
|
|
34
|
+
".": "./dist/index.mjs",
|
|
35
|
+
"./adapter": "./dist/adapter.mjs",
|
|
36
|
+
"./cli": "./dist/cli.mjs",
|
|
37
|
+
"./package.json": "./package.json"
|
|
38
|
+
},
|
|
39
|
+
"publishConfig": {
|
|
40
|
+
"access": "public"
|
|
41
|
+
},
|
|
42
|
+
"dependencies": {
|
|
43
|
+
"jiti": "^2.7.0"
|
|
44
|
+
},
|
|
45
|
+
"scripts": {
|
|
46
|
+
"build": "vp pack"
|
|
9
47
|
}
|
|
10
|
-
}
|
|
48
|
+
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: active-record
|
|
3
|
+
description: Active Record (`@forestfuture/active-record`, with its D1 adapter `@forestfuture/d1-record`), a Rails-style Active Record for Cloudflare Workers. Use when writing code with either package, or deciding how to model D1 data in a Worker.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Active Record
|
|
7
|
+
|
|
8
|
+
## Rules
|
|
9
|
+
|
|
10
|
+
<!-- #region rules -->
|
|
11
|
+
|
|
12
|
+
Active Record (`@forestfuture/active-record`) is a Rails-style Active Record for Cloudflare Workers, with an adapter per database: `@forestfuture/d1-record` for D1. Import Models, Relations, and errors from the core, and `connect`, `withSession`, `NoSession`, and `d1` from the adapter. 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
|
+
|
|
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. 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"`. 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
|
+
- 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
|
+
- 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.
|
|
18
|
+
- Name attributes in camelCase everywhere: `where`, `order`, `pluck`, `foreignKey`. Column names (snake_case) appear only inside `sql` fragments.
|
|
19
|
+
- Write custom SQL as an `sql` tagged template, which binds every value: ``where(sql`lower(${column("email")}) = ${email}`)``. Interpolate an attribute's value with `column("publishedAt").value(date)`, not the bare `Date`, when the attribute is stored as a Unix time: a bare `Date` is ISO text, and it throws `TypeError` when it's compared directly with that column.
|
|
20
|
+
- For a raw `env.DB.prepare(…).bind(…)` statement, bind `Post.typeForAttribute("publishedAt").serialize(date)`, which writes the value as the attribute stores it, and read a cell with `.deserialize(cell)`. A value the attribute can't hold throws `TypeError`.
|
|
21
|
+
- Bulk writes run when called: `await posts.deleteAll()` 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). Make several writes atomic with one `batch([...])` of their `to…` forms (`toInsert`, `toUpdateAll`, `toDeleteAll`, …) and records' `toSave()`/`toDestroy()`. D1 has no interactive transactions, so a read-then-write can't be atomic.
|
|
22
|
+
- 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. A key D1 generates exists only after its own write, so each level is then written in a separate batch.
|
|
23
|
+
- 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.
|
|
24
|
+
- 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.
|
|
25
|
+
- 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`. For a custom error, `errors.add("endsAt", { type: "afterStart" })` and give `afterStart` a message there.
|
|
26
|
+
- 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.
|
|
27
|
+
|
|
28
|
+
<!-- #endregion rules -->
|
|
29
|
+
|
|
30
|
+
## Shapes to follow
|
|
31
|
+
|
|
32
|
+
Generated Models extend `ApplicationRecord`, with their attributes from the schema. Associations are fields, scopes are statics, and validations and callbacks go in the `static {}` block:
|
|
33
|
+
|
|
34
|
+
```ts
|
|
35
|
+
import { belongsTo, hasMany } from "@forestfuture/active-record";
|
|
36
|
+
import { ApplicationRecord } from "./application-record";
|
|
37
|
+
|
|
38
|
+
export class User extends ApplicationRecord {
|
|
39
|
+
posts = hasMany(Post, { dependent: "destroy" }); // foreign key inferred: Post's userId
|
|
40
|
+
|
|
41
|
+
static active = this.scope((q) => q.where({ isActive: true }));
|
|
42
|
+
|
|
43
|
+
static {
|
|
44
|
+
this.validates("email", { presence: true, uniqueness: true });
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export class Post extends ApplicationRecord {
|
|
49
|
+
user = belongsTo(User); // foreign key inferred: userId
|
|
50
|
+
}
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
A Worker queries from its Models, preloads associations with `includes`, and saves a new graph in one call:
|
|
54
|
+
|
|
55
|
+
```ts
|
|
56
|
+
import { User } from "./models";
|
|
57
|
+
|
|
58
|
+
export default {
|
|
59
|
+
async fetch(request: Request): Promise<Response> {
|
|
60
|
+
if (request.method === "GET") {
|
|
61
|
+
// One query for the users, and one for all their posts.
|
|
62
|
+
const users = await User.includes("posts").order({ createdAt: "desc" }).toArray();
|
|
63
|
+
return Response.json(users);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const { email } = await request.json<{ email: string }>();
|
|
67
|
+
const user = User.build({ email });
|
|
68
|
+
user.posts().build({ title: "Hello" }); // saved with the user, in one atomic batch
|
|
69
|
+
if (!(await user.save())) {
|
|
70
|
+
return Response.json({ errors: user.errors.fullMessages() }, { status: 422 });
|
|
71
|
+
}
|
|
72
|
+
return Response.json(user, { status: 201 });
|
|
73
|
+
},
|
|
74
|
+
} satisfies ExportedHandler<Env>;
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
## Where code goes wrong
|
|
78
|
+
|
|
79
|
+
- **`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.
|
|
80
|
+
- **`relation.toSql()` and `statement.toSql()` show 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. A record's `toSave()`/`toDestroy()` have no `toSql()`.
|
|
81
|
+
- **`toJSON()` sends every loaded attribute**, so `Response.json(user)` includes `passwordDigest`. 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.
|
|
82
|
+
- **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.
|
|
83
|
+
- **`record.loaded("posts")` reads what was preloaded or already read**, synchronously, and throws `AssociationNotLoaded` otherwise. `await user.posts().toArray()` loads when needed.
|
|
84
|
+
- **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 sends the count with the page in one round trip. `{ count: false }` skips the `COUNT`, which reads (and bills) every matching row.
|
|
85
|
+
- **`find(id)` throws `RecordNotFound`**; `findBy(conditions)` resolves to `null`.
|
|
86
|
+
- **After-callbacks run once D1 has committed the write.** An error there reaches the caller with the record already saved: nothing rolls back.
|
|
87
|
+
- **Read replicas:** wrap the handler in `withSession(request, env.DB, fn)`. Every query in `fn` goes through one D1 Session, and its bookmark is set on `fn`'s Response as a `d1-bookmark` cookie, so the user's next request reads at least as new as their last write. For APIs, pass `{ header: "x-d1-bookmark" }` before `fn`; `start: "first-primary"` starts a request with no bookmark on the primary. Don't read or set the bookmark by hand.
|
|
88
|
+
- **Outside a Worker** (tests, scripts) there's no binding to find: run the code in `withDatabase(connect(binding), fn)`, or a query throws `NoDatabase` saying so. With several databases, `withDatabase` can't tell them apart outside a Worker: mock `cloudflare:workers` with the bindings instead (Vitest needs `test.server.deps.inline: ["@forestfuture/d1-record"]`), assigning them onto the mocked `env` object. A query at a module's top level fails too: Workers only allow D1 calls during a request.
|