@forestfuture/active-record 0.8.2 → 0.9.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/cli.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { a as AttributeType } from "./metadata-CzntpYzC.mjs";
1
+ import { a as AttributeType } from "./metadata-BIUbGJlS.mjs";
2
2
  type ColumnType = "string" | "integer" | "real" | "decimal" | "boolean" | "datetime" | "date" | "time" | "json" | "binary" | "references";
3
3
  /** One column as the generators' syntax gives it: `email:string!:unique`, `user:references`. */
4
4
  interface ColumnArg {
@@ -128,7 +128,7 @@ interface SchemaOptions {
128
128
  }
129
129
  /** What `g model` and `g migration` ask an adapter for: a migration's SQL. */
130
130
  interface MigrationChange {
131
- /** The migration's name, as Rails reads it (`CreateProducts`, `AddSkuToProducts`, …). */
131
+ /** The migration's name, which says what it does (`CreateProducts`, `AddSkuToProducts`, …). */
132
132
  name: string;
133
133
  columns: readonly ColumnArg[];
134
134
  /**
@@ -356,11 +356,11 @@ interface Reading<C extends ReadColumn> {
356
356
  * result only changes with the schema), or every error that stops them.
357
357
  */
358
358
  export declare function generatedSchema<C extends ReadColumn>(read: readonly ReadTable<C>[], reading: Reading<C>): SchemaResult;
359
- /** Rails' `pluralize`: `category` → `categories`, `person` → `people`, `sheep` → `sheep`. */
359
+ /** A word's plural: `category` → `categories`, `person` → `people`, `sheep` → `sheep`. */
360
360
  export declare function pluralize(word: string): string;
361
361
  /**
362
362
  * Converts a camelCase attribute name to its snake_case column name, treating
363
- * a run of capitals as one word (Rails' `underscore`): `htmlURL` → `html_url`,
363
+ * a run of capitals as one word: `htmlURL` → `html_url`,
364
364
  * `userID` → `user_id`, `sha256Hash` → `sha256_hash`.
365
365
  */
366
366
  export declare function underscore(name: string): string;
package/dist/cli.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { C as pluralize, E as underscore } from "./epoch-storage-C7186hd1.mjs";
2
- import { a as migrationSql, c as migrationPlan, i as withDigits, n as namesInList, o as quotedName, r as withGeneratedEnum, s as indexName, t as generatedSchema } from "./for-adapters-CgEQfuyD.mjs";
3
- import { f as byName, i as attributeName, l as configFileName, n as castDefault, o as exportName, p as byVersion, r as isCastDefaultType, s as listed, t as storageOverride, u as parseJsonc } from "./storage-override-BFC-GSR0.mjs";
1
+ import { C as pluralize, D as underscore } from "./identifiers-CzqYL_nC.mjs";
2
+ import { a as migrationSql, c as migrationPlan, i as withDigits, n as namesInList, o as quotedName, r as withGeneratedEnum, s as indexName, t as generatedSchema } from "./for-adapters-D35a5x3t.mjs";
3
+ import { f as byName, i as attributeName, l as configFileName, n as castDefault, o as exportName, p as byVersion, r as isCastDefaultType, s as listed, t as storageOverride, u as parseJsonc } from "./storage-override-yF2NT5ST.mjs";
4
4
  export { attributeName, byName, byVersion, castDefault, configFileName, exportName, generatedSchema, indexName, isCastDefaultType, listed, migrationPlan, migrationSql, namesInList, parseJsonc, pluralize, quotedName, storageOverride, underscore, withDigits, withGeneratedEnum };
package/dist/command.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
- import { _ as importPath, a as classify, c as moduleName, d as projectDatabases, g as migrationsOf, h as leadingNumber, m as hasNestedMigrations, n as castDefault, p as byVersion, s as listed, t as storageOverride, u as parseJsonc, v as shown$1, y as slashed } from "./storage-override-BFC-GSR0.mjs";
3
- import { U as enumNameProblem, W as enumScopeNames, at as tableize, c as methodsOffFixes, i as isBase, ot as ancestors, st as staticBelow } from "./generated-model-FB7oT7V1.mjs";
4
- import { C as pluralize, E as underscore, T as camelize, h as isIdentifier, n as digitsProblem, w as singularize } from "./epoch-storage-C7186hd1.mjs";
2
+ import { _ as importPath, a as classify, c as moduleName, d as projectDatabases, g as migrationsOf, h as leadingNumber, m as hasNestedMigrations, n as castDefault, p as byVersion, s as listed, t as storageOverride, u as parseJsonc, v as shown$1, y as slashed } from "./storage-override-yF2NT5ST.mjs";
3
+ import { At as tableize, Mt as staticBelow, c as methodsOffFixes, d as enumNameProblem, f as enumScopeNames, i as isBase, jt as ancestors } from "./generated-model-L4WAqgOZ.mjs";
4
+ import { C as pluralize, D as underscore, T as camelize, h as digitsProblem, t as isIdentifier, w as singularize } from "./identifiers-CzqYL_nC.mjs";
5
5
  import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync, statSync, watch, writeFileSync } from "node:fs";
6
6
  import { basename, dirname, join, relative, resolve, sep } from "node:path";
7
7
  import { inspect, parseArgs, types } from "node:util";
@@ -68,11 +68,11 @@ function helpFor(subcommands) {
68
68
  const adapters = {
69
69
  d1: {
70
70
  entry: "@forestfuture/active-record/d1",
71
- plugin: async () => (await import("./plugin-BY2QaRpq.mjs")).cli
71
+ plugin: async () => (await import("./plugin-BHUP4ssD.mjs")).cli
72
72
  },
73
73
  postgresql: {
74
74
  entry: "@forestfuture/active-record/postgresql",
75
- plugin: async () => (await import("./plugin-IHD0I6Rg.mjs")).cli
75
+ plugin: async () => (await import("./plugin-BMAJKgj6.mjs")).cli
76
76
  }
77
77
  };
78
78
  /** The adapters' names, in the registry's order. */
@@ -343,8 +343,8 @@ async function confirmRemote({ input, output, target, consequence = "What you ch
343
343
  }
344
344
  // cli/project/targets.ts
345
345
  /**
346
- * A database's base class: `ApplicationRecord` when there's one database, as in Rails, and one
347
- * per binding when there are several (`LOGS` → `LogsRecord`), as Rails names them.
346
+ * A database's base class: `ApplicationRecord` when there's one database, and one
347
+ * per binding when there are several (`LOGS` → `LogsRecord`).
348
348
  */
349
349
  function baseFor(modelsDir, binding, several) {
350
350
  if (!several) return {
@@ -1312,8 +1312,8 @@ function declarationsSource({ tables, models }) {
1312
1312
  }
1313
1313
  /**
1314
1314
  * The generated `schema.ts`: each table's attributes, the binding with every table and Model,
1315
- * and each Model's attributes added to its class. It's the schema as a document, like Rails'
1316
- * `schema.rb`; the app's base class (`renderBase`) holds it.
1315
+ * and each Model's attributes added to its class. It's the schema as a document; the app's
1316
+ * base class (`renderBase`) holds it.
1317
1317
  */
1318
1318
  function renderSchema(schema, source) {
1319
1319
  const hasModels = schema.models.length > 0;
@@ -1332,8 +1332,8 @@ ${schemaValueSource(schema)}${declarations}
1332
1332
  `;
1333
1333
  }
1334
1334
  /**
1335
- * The app's base class for a database's Models, written once and then the app's own, as Rails'
1336
- * `ApplicationRecord` is: `class Product extends ApplicationRecord {}`.
1335
+ * The app's base class for a database's Models, written once and then the app's own:
1336
+ * `class Product extends ApplicationRecord {}`.
1337
1337
  */
1338
1338
  function renderBase(className, schemaImport) {
1339
1339
  return `import { Model } from "@forestfuture/active-record";
@@ -1341,7 +1341,7 @@ import { schema } from ${stringLiteral(schemaImport)};
1341
1341
 
1342
1342
  /**
1343
1343
  * The base class for this app's Models: \`class Product extends ${className} {}\`. Methods,
1344
- * callbacks and scopes written here are shared by every Model, as in Rails' ApplicationRecord.
1344
+ * callbacks and scopes written here are shared by every Model.
1345
1345
  * It's abstract: it has no table of its own.
1346
1346
  */
1347
1347
  export abstract class ${className} extends Model {
@@ -1363,7 +1363,7 @@ export abstract class ${className} extends Model {
1363
1363
  // console.log(\`\${model} \${durationMs.toFixed(1)}ms \${sql}\`);
1364
1364
 
1365
1365
  // Values of attributes named like these show as "[FILTERED]" to onQuery and in errors. These
1366
- // are Rails' defaults (passwords, tokens, keys, emails…); add yours, or leave one out:
1366
+ // are the defaults (passwords, tokens, keys, emails…); add yours, or leave one out:
1367
1367
  // static override filterAttributes = [...Model.filterAttributes, "iban"];
1368
1368
 
1369
1369
  // Attributes toJSON() leaves out, so Response.json(record) never sends them (exact names;
@@ -1871,7 +1871,8 @@ function classSource({ className, associations, base }) {
1871
1871
  }
1872
1872
  /**
1873
1873
  * A Model's source, with its imports: the library's `belongsTo` when it has one, the app's
1874
- * base class (`ApplicationRecord`), and, in a file of its own, each target's file (`./order`), as Rails assumes it exists.
1874
+ * base class (`ApplicationRecord`), and, in a file of its own, each target's file (`./order`),
1875
+ * assumed to exist.
1875
1876
  */
1876
1877
  function modelSource(model, { separateFiles }) {
1877
1878
  const imports = [];
@@ -1929,8 +1930,8 @@ function stamp(now) {
1929
1930
  }
1930
1931
  /**
1931
1932
  * The next migration's file name: the current UTC second as its version, or one past the highest
1932
- * version there when that's later, as Rails numbers them, so two written in one second stay in
1933
- * order. Files numbered `0001_…` sort before it, on every adapter.
1933
+ * version there when that's later, so two written in one second stay in order. Files numbered
1934
+ * `0001_…` sort before it, on every adapter.
1934
1935
  */
1935
1936
  function migrationFileName(existing, name, now) {
1936
1937
  const highest = Math.max(0, ...existing.map(leadingNumber).filter(Number.isFinite));
@@ -1941,7 +1942,7 @@ function migrationFileName(existing, name, now) {
1941
1942
  /** A name the generators accept: letters, digits and `_`, starting with a letter. */
1942
1943
  const allowed$1 = /^[A-Za-z][A-Za-z0-9_]*$/;
1943
1944
  /**
1944
- * The class a `g model` name asks for, singular as Rails makes it (`line_items` → `LineItem`),
1945
+ * The class a `g model` name asks for, made singular (`line_items` → `LineItem`),
1945
1946
  * with a note when it was plural; or why the name won't do.
1946
1947
  */
1947
1948
  function modelName(given) {
@@ -1956,7 +1957,7 @@ function modelName(given) {
1956
1957
  } : {
1957
1958
  ok: true,
1958
1959
  className,
1959
- note: `${given} looks plural, so the Model is ${className}, as Rails names it`
1960
+ note: `${given} looks plural, so the Model is ${className}`
1960
1961
  };
1961
1962
  }
1962
1963
  /** Whether a migration's name is usable as its file's name, or why not. */
package/dist/d1.d.mts CHANGED
@@ -1,5 +1,5 @@
1
- import { C as QueryEvent$1, D as SchemaAdapter, O as AnyDatabase, w as QueryListener$1 } from "./validations-DFLjJ203.mjs";
2
- import { i as ActiveRecordError } from "./index-BfX3Dgy_.mjs";
1
+ import { C as QueryEvent$1, D as SchemaAdapter, O as AnyDatabase, w as QueryListener$1 } from "./validations-CKPJoSj4.mjs";
2
+ import { c as ActiveRecordError } from "./index-Fq4gT3c8.mjs";
3
3
  /** The D1 database a generated schema's Models query: `adapter: d1({ binding: "DB" })`. */
4
4
  export declare function d1({ binding }: {
5
5
  binding: string;
package/dist/d1.mjs CHANGED
@@ -1,7 +1,7 @@
1
- import { a as databaseExecutor, i as AnyDatabase, l as DatabaseExecutor, r as withDatabase } from "./batch-D3nP3g83.mjs";
2
- import { n as onlyRequested, t as workersEnv } from "./for-adapters-l4rNitkK.mjs";
3
- import { O as ActiveRecordError, p as hexOf, z as NoDatabase } from "./epoch-storage-C7186hd1.mjs";
4
- import { O as boundValue } from "./generated-model-FB7oT7V1.mjs";
1
+ import { a as databaseExecutor, i as AnyDatabase, l as workersEnv, r as withDatabase, u as DatabaseExecutor } from "./batch-Ca1JtVcK.mjs";
2
+ import { t as onlyRequested } from "./for-adapters-Bl6BCiR1.mjs";
3
+ import { V as NoDatabase, i as hexOf, k as ActiveRecordError } from "./identifiers-CzqYL_nC.mjs";
4
+ import { w as boundValue } from "./generated-model-L4WAqgOZ.mjs";
5
5
  // src/adapters/d1/errors.ts
6
6
  /** D1's error for a Session's bookmark it can't use, and the bookmark it repeats (#237). */
7
7
  const rejectedBookmark = /invalid commitToken bookmark provided: (.*)$/s;
@@ -217,6 +217,11 @@ const d1Adapter = {
217
217
  from: `json_each()`
218
218
  }),
219
219
  maxValueBytes: 2e6,
220
+ staleGuard: (write, marker) => [write, {
221
+ sql: `SELECT json_extract('{}', CASE WHEN changes() = 0 THEN ELSE '$' END) AS stale`,
222
+ params: [marker],
223
+ model: write.model
224
+ }],
220
225
  linkedKey: (key, keyAttribute, linked) => linked.isText && !keyAttribute.isText ? `CAST(${key} AS TEXT)` : key
221
226
  },
222
227
  maxBoundValues: 100,
@@ -0,0 +1,12 @@
1
+ import { V as NoDatabase } from "./identifiers-CzqYL_nC.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
+ export { onlyRequested as t };
@@ -1,5 +1,5 @@
1
- import { C as pluralize, E as underscore, n as digitsProblem } from "./epoch-storage-C7186hd1.mjs";
2
- import { f as byName, o as exportName } from "./storage-override-BFC-GSR0.mjs";
1
+ import { C as pluralize, D as underscore, h as digitsProblem } from "./identifiers-CzqYL_nC.mjs";
2
+ import { f as byName, o as exportName } from "./storage-override-yF2NT5ST.mjs";
3
3
  // cli/generate/migration-plan.ts
4
4
  /** What to do, read from a migration's name: `create_products`, `add_sku_to_products`, …; else empty. */
5
5
  function migrationPlan(name) {
@@ -75,7 +75,10 @@ function createTable(table, change, writing) {
75
75
  const body = lines.join(",\n ");
76
76
  return `CREATE TABLE ${quotedName(dialect, table)} (\n ${body}\n);\n${indexes(dialect, table, change.columns)}`;
77
77
  }
78
- /** `ADD COLUMN` for each column; a reference added later can be null, as Rails' `add_reference`. */
78
+ /**
79
+ * `ADD COLUMN` for each column; a reference added later can be null, since the table may already
80
+ * have rows.
81
+ */
79
82
  function addColumns(table, columns, writing) {
80
83
  const { dialect } = writing;
81
84
  for (const column of columns) {
@@ -1,4 +1,4 @@
1
- import { O as AnyDatabase } from "./validations-DFLjJ203.mjs";
1
+ import { O as AnyDatabase } from "./validations-CKPJoSj4.mjs";
2
2
  /**
3
3
  * Bytes as hex text, two digits each, for SQL that reads bytes from JSON (`unhex`, `\\x…`). The
4
4
  * digits' character codes are written into one array and decoded once: mapping each byte to a