@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/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@forestfuture/active-record",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.0",
|
|
4
4
|
"description": "A Rails-inspired Active Record for Cloudflare Workers, with an adapter per database.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"active-record",
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
"orm",
|
|
9
9
|
"workers"
|
|
10
10
|
],
|
|
11
|
-
"homepage": "https://
|
|
11
|
+
"homepage": "https://active-record.forestfuture.dev",
|
|
12
12
|
"bugs": {
|
|
13
13
|
"url": "https://github.com/forestfuture/active-record/issues"
|
|
14
14
|
},
|
|
@@ -24,6 +24,7 @@
|
|
|
24
24
|
"ffar": "./dist/command.mjs"
|
|
25
25
|
},
|
|
26
26
|
"files": [
|
|
27
|
+
"config-schema.json",
|
|
27
28
|
"dist",
|
|
28
29
|
"llms-full.txt",
|
|
29
30
|
"skills"
|
|
@@ -34,6 +35,8 @@
|
|
|
34
35
|
".": "./dist/index.mjs",
|
|
35
36
|
"./adapter": "./dist/adapter.mjs",
|
|
36
37
|
"./cli": "./dist/cli.mjs",
|
|
38
|
+
"./d1": "./dist/d1.mjs",
|
|
39
|
+
"./postgresql": "./dist/postgresql.mjs",
|
|
37
40
|
"./package.json": "./package.json"
|
|
38
41
|
},
|
|
39
42
|
"publishConfig": {
|
|
@@ -42,6 +45,26 @@
|
|
|
42
45
|
"dependencies": {
|
|
43
46
|
"jiti": "^2.7.0"
|
|
44
47
|
},
|
|
48
|
+
"devDependencies": {
|
|
49
|
+
"@electric-sql/pglite": "^0.5.14",
|
|
50
|
+
"pg": "^8.23.1"
|
|
51
|
+
},
|
|
52
|
+
"peerDependencies": {
|
|
53
|
+
"@cloudflare/workers-types": ">=4",
|
|
54
|
+
"@electric-sql/pglite": "^0.5.14",
|
|
55
|
+
"pg": "^8.23.1"
|
|
56
|
+
},
|
|
57
|
+
"peerDependenciesMeta": {
|
|
58
|
+
"@cloudflare/workers-types": {
|
|
59
|
+
"optional": true
|
|
60
|
+
},
|
|
61
|
+
"@electric-sql/pglite": {
|
|
62
|
+
"optional": true
|
|
63
|
+
},
|
|
64
|
+
"pg": {
|
|
65
|
+
"optional": true
|
|
66
|
+
}
|
|
67
|
+
},
|
|
45
68
|
"scripts": {
|
|
46
69
|
"build": "vp pack"
|
|
47
70
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: active-record
|
|
3
|
-
description: Active Record (`@forestfuture/active-record`, with its D1
|
|
3
|
+
description: Active Record (`@forestfuture/active-record`, with its D1 and PostgreSQL adapters as its `/d1` and `/postgresql` entries), a Rails-style Active Record for Cloudflare Workers. Use when writing code with the package, or deciding how to model D1 or Postgres data in a Worker.
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# Active Record
|
|
@@ -9,7 +9,7 @@ description: Active Record (`@forestfuture/active-record`, with its D1 adapter `
|
|
|
9
9
|
|
|
10
10
|
<!-- #region rules -->
|
|
11
11
|
|
|
12
|
-
Active Record (`@forestfuture/active-record`) is a Rails-style Active Record for Cloudflare Workers, with an adapter per database: `@forestfuture/
|
|
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: run `npx active-record init` to write it, never `--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
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
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.
|
|
@@ -81,8 +81,8 @@ export default {
|
|
|
81
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
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
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.
|
|
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 on D1 sends the count with the page in one round trip. `{ count: false }` skips the `COUNT`, which reads (and bills) every matching row.
|
|
85
85
|
- **`find(id)` throws `RecordNotFound`**; `findBy(conditions)` resolves to `null`.
|
|
86
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
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/
|
|
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/active-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.
|
|
@@ -1,91 +0,0 @@
|
|
|
1
|
-
import { a as underscore, i as camelize, t as epochStorages } from "./epoch-storage-o2aoOH7H.mjs";
|
|
2
|
-
import { existsSync, readFileSync, readdirSync } from "node:fs";
|
|
3
|
-
import { join, relative, sep } from "node:path";
|
|
4
|
-
//#region cli/project/paths.ts
|
|
5
|
-
/** A relative path with forward slashes, as Wrangler names migrations on every system. */
|
|
6
|
-
function slashed(path) {
|
|
7
|
-
return path.split(sep).join("/");
|
|
8
|
-
}
|
|
9
|
-
/** A module path from one file's folder to another file, as an import writes it (`../db/schema`). */
|
|
10
|
-
function importPath(fromDir, to) {
|
|
11
|
-
const path = slashed(relative(fromDir, to)).replace(/\.ts$/, "");
|
|
12
|
-
return path.startsWith(".") ? path : `./${path}`;
|
|
13
|
-
}
|
|
14
|
-
/** A path as printed: relative to the project, with forward slashes. */
|
|
15
|
-
function shown(cwd, path) {
|
|
16
|
-
return slashed(relative(cwd, path)) || ".";
|
|
17
|
-
}
|
|
18
|
-
//#endregion
|
|
19
|
-
//#region cli/project/migrations.ts
|
|
20
|
-
/** Plain character order, the same on every machine (unlike `localeCompare`). */
|
|
21
|
-
function byName(a, b) {
|
|
22
|
-
return a < b ? -1 : a > b ? 1 : 0;
|
|
23
|
-
}
|
|
24
|
-
/** A database's migrations, in the order Wrangler applies them: by file name. */
|
|
25
|
-
function migrationsOf(target) {
|
|
26
|
-
const { migrationsPattern } = target.database;
|
|
27
|
-
return (migrationsPattern === void 0 ? readdirSync(target.migrationsDir).filter((name) => name.endsWith(".sql")) : process.getBuiltinModule("node:fs").globSync(migrationsPattern, { cwd: target.configDir }).map((path) => slashed(relative(target.migrationsDir, join(target.configDir, path))))).sort(byName).map((name) => ({
|
|
28
|
-
name,
|
|
29
|
-
sql: readFileSync(join(target.migrationsDir, name), "utf8")
|
|
30
|
-
}));
|
|
31
|
-
}
|
|
32
|
-
/**
|
|
33
|
-
* Whether a database's migrations are in folders (`migrations/0000_init/migration.sql`, as
|
|
34
|
-
* Drizzle writes them) with no `migrations_pattern` in the config to find them.
|
|
35
|
-
*/
|
|
36
|
-
function hasNestedMigrations(target) {
|
|
37
|
-
const dir = target.migrationsDir;
|
|
38
|
-
if (target.database.migrationsPattern !== void 0 || !existsSync(dir)) return false;
|
|
39
|
-
const entries = readdirSync(dir, { withFileTypes: true });
|
|
40
|
-
if (entries.some((entry) => entry.isFile() && entry.name.endsWith(".sql"))) return false;
|
|
41
|
-
return entries.some((entry) => entry.isDirectory() && existsSync(join(dir, entry.name, "migration.sql")));
|
|
42
|
-
}
|
|
43
|
-
//#endregion
|
|
44
|
-
//#region cli/project/names.ts
|
|
45
|
-
/** Whether a name can be written bare: as a `const`, or as an object key without quotes. */
|
|
46
|
-
function isIdentifier(name) {
|
|
47
|
-
return /^[\p{L}_$][\p{L}\p{N}_$]*$/u.test(name);
|
|
48
|
-
}
|
|
49
|
-
/** A column's attribute: camelCase, keeping any leading underscores (`_secret` stays). */
|
|
50
|
-
function attributeName(column) {
|
|
51
|
-
const lead = /^_*/.exec(column)[0];
|
|
52
|
-
return lead + camelize(column.slice(lead.length));
|
|
53
|
-
}
|
|
54
|
-
/** Words JavaScript doesn't allow as a `const` name, and the generated file's own names. */
|
|
55
|
-
const reserved = new Set("break case catch class const continue debugger default delete do else enum export extends false finally for function if import in instanceof new null return super switch this throw true try typeof var void while with yield let static implements interface package private protected public await arguments eval tables".split(" "));
|
|
56
|
-
/**
|
|
57
|
-
* The `const` a table is exported as: its words in camelCase (`line_items` → `lineItems`),
|
|
58
|
-
* never a reserved word (`default` → `defaultTable`) or starting with a digit (`2fa` →
|
|
59
|
-
* `table2fa`).
|
|
60
|
-
*/
|
|
61
|
-
function exportName(table) {
|
|
62
|
-
const name = table.split(/[^\p{L}\p{N}]+/u).filter(Boolean).map((word, index) => index === 0 ? word : word[0].toUpperCase() + word.slice(1)).join("");
|
|
63
|
-
if (name === "" || /^\p{N}/u.test(name)) return `table${name}`;
|
|
64
|
-
return reserved.has(name) ? `${name}Table` : name;
|
|
65
|
-
}
|
|
66
|
-
/** A class name from any spelling: `line_item`, `lineItem` → `LineItem`. */
|
|
67
|
-
function classify(name) {
|
|
68
|
-
const camel = camelize(underscore(name));
|
|
69
|
-
return camel.charAt(0).toUpperCase() + camel.slice(1);
|
|
70
|
-
}
|
|
71
|
-
/** A Model's module, in kebab-case: `LineItem` → `line-item` (its file is `line-item.ts`). */
|
|
72
|
-
function moduleName(className) {
|
|
73
|
-
return underscore(className).replaceAll("_", "-");
|
|
74
|
-
}
|
|
75
|
-
/** `"A"`, `"A or B"`, `"A, B or C"`. */
|
|
76
|
-
function listed(names) {
|
|
77
|
-
return names.length < 2 ? names.join("") : `${names.slice(0, -1).join(", ")} or ${names.at(-1)}`;
|
|
78
|
-
}
|
|
79
|
-
//#endregion
|
|
80
|
-
//#region cli/schema/storage-override.ts
|
|
81
|
-
/** Drizzle's `mode` for each epoch storage, which a note names for a reader with its schema open. */
|
|
82
|
-
const drizzleModes = {
|
|
83
|
-
unixSeconds: "\"timestamp\"",
|
|
84
|
-
unixMilliseconds: "\"timestamp_ms\""
|
|
85
|
-
};
|
|
86
|
-
/** The override that reads a Unix time as a `Date`, for a note; with Drizzle's modes named if asked. */
|
|
87
|
-
function storageOverride(withDrizzleModes) {
|
|
88
|
-
return `{ type: "datetime", storage: ${epochStorages.map((storage) => withDrizzleModes ? `"${storage}" (${drizzleModes[storage]})` : `"${storage}"`).join(" or ")} }`;
|
|
89
|
-
}
|
|
90
|
-
//#endregion
|
|
91
|
-
export { isIdentifier as a, byName as c, importPath as d, shown as f, exportName as i, hasNestedMigrations as l, attributeName as n, listed as o, slashed as p, classify as r, moduleName as s, storageOverride as t, migrationsOf as u };
|