@forestfuture/active-record 0.8.1 → 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.
@@ -1,6 +1,6 @@
1
- import { i as attributeName, n as castDefault, s as listed, t as storageOverride, u as parseJsonc } from "./storage-override-0ZgeP2sc.mjs";
2
- import { a as migrationSql, i as withDigits, n as namesInList, o as quotedName, r as withGeneratedEnum, s as indexName, t as generatedSchema } from "./for-adapters-BbIMUNcz.mjs";
3
- import { E as underscore } from "./identifiers-Dh5DFACX.mjs";
1
+ import { i as attributeName, n as castDefault, s as listed, t as storageOverride, u as parseJsonc } from "./storage-override-yF2NT5ST.mjs";
2
+ import { a as migrationSql, 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 { D as underscore } from "./identifiers-CzqYL_nC.mjs";
4
4
  import { createRequire } from "node:module";
5
5
  import { existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
6
6
  import { basename, dirname, join, relative, resolve, sep } from "node:path";
@@ -479,7 +479,10 @@ function typeOfDeclared(column, declared, where) {
479
479
  function unmatchedNote(declared, where) {
480
480
  return `${where}: ${declared === "" ? "has no declared type" : `is declared ${declared}`}, so it's read as a string; a number in it fails when the record loads, so override it in its Model with the type it holds`;
481
481
  }
482
- /** A column declared exactly TEXT or INTEGER, refined by its name (Rails' conventions). */
482
+ /**
483
+ * A column declared exactly TEXT or INTEGER, refined by its name: `created_at` a datetime,
484
+ * `is_active` a boolean, and so on.
485
+ */
483
486
  function refinedByName(column, type, where) {
484
487
  if (type === "string" && column.name.endsWith("_at")) return { type: "datetime" };
485
488
  const prefix = /^(is|has)_/.exec(column.name)?.[1];
@@ -612,9 +615,9 @@ function applied(migrations) {
612
615
  */
613
616
  function ownTables(all, migrationsTable) {
614
617
  const virtual = [...all].filter(([, sql]) => /^CREATE\s+VIRTUAL\s+TABLE/i.test(sql)).map(([name]) => name);
615
- const shadow = (name) => virtual.some((table) => name === table || name.startsWith(`${table}_`));
616
- const internal = (name) => name.startsWith("sqlite_") || name.startsWith("_cf_") || name === migrationsTable;
617
- return [...all].filter(([name]) => !internal(name) && !shadow(name));
618
+ const isVirtualOrShadow = (name) => virtual.some((table) => name === table || name.startsWith(`${table}_`));
619
+ const isInternal = (name) => name.startsWith("sqlite_") || name.startsWith("_cf_") || name === migrationsTable;
620
+ return [...all].filter(([name]) => !isInternal(name) && !isVirtualOrShadow(name));
618
621
  }
619
622
  /** The columns `json_valid` checks in a table's definition: `CHECK (json_valid(settings))`. */
620
623
  function jsonChecked(definition) {
@@ -1,6 +1,6 @@
1
- import { i as attributeName, n as castDefault, p as byVersion, r as isCastDefaultType, u as parseJsonc } from "./storage-override-0ZgeP2sc.mjs";
2
- import { a as migrationSql, i as withDigits, n as namesInList, o as quotedName, r as withGeneratedEnum, t as generatedSchema } from "./for-adapters-BbIMUNcz.mjs";
3
- import { E as underscore } from "./identifiers-Dh5DFACX.mjs";
1
+ import { i as attributeName, n as castDefault, p as byVersion, r as isCastDefaultType, u as parseJsonc } from "./storage-override-yF2NT5ST.mjs";
2
+ import { a as migrationSql, i as withDigits, n as namesInList, o as quotedName, r as withGeneratedEnum, t as generatedSchema } from "./for-adapters-D35a5x3t.mjs";
3
+ import { D as underscore } from "./identifiers-CzqYL_nC.mjs";
4
4
  import { createRequire } from "node:module";
5
5
  import { existsSync, readFileSync, readdirSync } from "node:fs";
6
6
  import { basename, dirname, join } from "node:path";
@@ -106,7 +106,7 @@ function hyperdriveIn(dir) {
106
106
  };
107
107
  }
108
108
  // cli/adapters/postgresql/init.ts
109
- /** The local database a project's folder suggests, named as Rails names it: `shop_development`. */
109
+ /** The local database a project's folder suggests: `shop_development`. */
110
110
  function guessedUrl(dir) {
111
111
  return `postgres://localhost:5432/${basename(dir).toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_|_$/g, "") || "app"}_development`;
112
112
  }
@@ -283,13 +283,13 @@ function dollarEnd(sql, index) {
283
283
  return end < 0 ? sql.length : end + tag.length;
284
284
  }
285
285
  /** Whether a string starting at `index` is an escape string (`E'…'`). */
286
- const escapeString = (sql, index) => /[eE]/.test(sql[index - 1] ?? "") && !/\w/.test(sql[index - 2] ?? "");
286
+ const isEscapeString = (sql, index) => /[eE]/.test(sql[index - 1] ?? "") && !/\w/.test(sql[index - 2] ?? "");
287
287
  /** Where the quoted or commented text starting at `index` ends, or `index` when none starts there. */
288
288
  function skipped(sql, index) {
289
289
  if (sql.startsWith("--", index)) return lineEnd(sql, index);
290
290
  if (sql.startsWith("/*", index)) return blockEnd(sql, index);
291
291
  const char = sql[index];
292
- if (char === "'") return quoteEnd(sql, index, escapeString(sql, index));
292
+ if (char === "'") return quoteEnd(sql, index, isEscapeString(sql, index));
293
293
  if (char === "\"") return quoteEnd(sql, index, false);
294
294
  return char === "$" ? dollarEnd(sql, index) : index;
295
295
  }
@@ -364,7 +364,7 @@ function migrationFiles(dir) {
364
364
  sql
365
365
  }))) ?? files;
366
366
  }
367
- /** One lock per database and schema: a run while another holds it is refused, as Rails refuses it. */
367
+ /** One lock per database and schema: a run while another holds it is refused. */
368
368
  const lock = `hashtext('active-record migrate ' || current_database() || '.' || current_schema())`;
369
369
  /** The versions already applied, once the table that records them is there. */
370
370
  async function appliedVersions(client) {
@@ -1,4 +1,4 @@
1
- import { C as QueryEvent$1, D as SchemaAdapter, O as AnyDatabase, w as QueryListener$1 } from "./validations-BSZ5gVeI.mjs";
1
+ import { C as QueryEvent$1, D as SchemaAdapter, O as AnyDatabase, w as QueryListener$1 } from "./validations-CKPJoSj4.mjs";
2
2
  import pg from "pg";
3
3
  /** The Postgres database a generated schema's Models query: `adapter: postgresql({ binding: "HYPERDRIVE" })`. */
4
4
  export declare function postgresql({ binding }: {
@@ -1,7 +1,7 @@
1
- import { a as AnyDatabase, g as DatabaseExecutor, o as databaseExecutor } from "./batch-Ms5p9lKq.mjs";
2
- import { n as onlyRequested, t as workersEnv } from "./for-adapters-C-MQxaIx.mjs";
3
- import { z as NoDatabase } from "./identifiers-Dh5DFACX.mjs";
4
- import { U as boundValue } from "./generated-model-DJA8vmNE.mjs";
1
+ import { a as databaseExecutor, i as AnyDatabase, l as workersEnv, u as DatabaseExecutor } from "./batch-Ca1JtVcK.mjs";
2
+ import { t as onlyRequested } from "./for-adapters-Bl6BCiR1.mjs";
3
+ import { V as NoDatabase } from "./identifiers-CzqYL_nC.mjs";
4
+ import { w as boundValue } from "./generated-model-L4WAqgOZ.mjs";
5
5
  import pg from "pg";
6
6
  // src/adapters/postgresql/connect-timeout.ts
7
7
  /** The limit when the connection string sets none, in milliseconds. */
@@ -256,6 +256,17 @@ function withoutRefusedValue(error) {
256
256
  if (stack !== void 0) error.stack = stack.replace(message, filtered);
257
257
  }
258
258
  const enumRefusal = "invalid input value for enum ";
259
+ /**
260
+ * The value the dialect's stale guard refuses (#357): the library's marker, naming the stale
261
+ * record's write, not a value of the user's, so it's kept, in any language Postgres writes in.
262
+ */
263
+ const staleGuardMarker = /^active-record stale record [0-9a-f-]{36}$/;
264
+ /** Whether the refused value, from the message's first quote to its last, is the guard's marker. */
265
+ function isStaleGuardRefusal(message) {
266
+ const start = message.indexOf("\"");
267
+ const end = message.lastIndexOf("\"");
268
+ return start !== -1 && end > start && staleGuardMarker.test(message.slice(start + 1, end));
269
+ }
259
270
  /** Where the quoted identifier opening at `at` ends, past its closing quote; its own quotes are doubled. -1 if it never closes. */
260
271
  function quotedEnd(message, at) {
261
272
  let next = at + 1;
@@ -283,6 +294,7 @@ function enumNameEnd(message) {
283
294
  * not matched with a pattern that could backtrack, since the value is the user's.
284
295
  */
285
296
  function refusedValueFiltered(message) {
297
+ if (isStaleGuardRefusal(message)) return message;
286
298
  if (message.startsWith(enumRefusal)) {
287
299
  const end = enumNameEnd(message);
288
300
  if (end !== -1 && message.startsWith(": \"", end) && message.endsWith("\"")) return `${message.slice(0, end)}: "[FILTERED]"`;
@@ -535,6 +547,18 @@ const pgAdapter = {
535
547
  return `CASE WHEN ${key} ~ ${literal("^\\s*[+-]?[0-9]+\\s*$")} THEN CAST(${key} AS NUMERIC) END`;
536
548
  },
537
549
  /**
550
+ * The write returns a row if it changed one, and the statement casts the marker to an integer
551
+ * when it returned none, which fails the transaction with the marker in its message (#357).
552
+ * The cast is of the CASE, which reads the write's rows, so it can't be made before it runs.
553
+ */
554
+ staleGuard(write, marker) {
555
+ return [{
556
+ sql: `WITH locked AS (${write.sql} RETURNING 1) SELECT CAST(CASE WHEN NOT EXISTS (SELECT FROM locked) THEN CAST( AS TEXT) END AS INTEGER) AS stale`,
557
+ params: [...write.params, marker],
558
+ model: write.model
559
+ }];
560
+ },
561
+ /**
538
562
  * The removal returns a row for each row it removed, which the counters' UPDATEs count, and the
539
563
  * statement selects how many as `removed`: a COUNT sent before it could miss a row another
540
564
  * request commits in between, on a snapshot of its own (#61).
@@ -1,5 +1,5 @@
1
- import { n as readyModel, r as Model, s as isReservedScopeName } from "./batch-Ms5p9lKq.mjs";
2
- import { $ as modelNameOf, et as ownValueSetter, ot as ancestors, st as staticBelow } from "./generated-model-DJA8vmNE.mjs";
1
+ import { n as Model, o as readyModel, s as isReservedScopeName } from "./batch-Ca1JtVcK.mjs";
2
+ import { Mt as staticBelow, Tt as ownValueSetter, jt as ancestors, wt as modelNameOf } from "./generated-model-L4WAqgOZ.mjs";
3
3
  // src/define-schema.ts
4
4
  const listed = /* @__PURE__ */ new Set();
5
5
  /**
@@ -1,4 +1,4 @@
1
- import { E as underscore, T as camelize, c as castValue, d as uncastable, n as reservedWords, r as epochStorages } from "./identifiers-Dh5DFACX.mjs";
1
+ import { D as underscore, T as camelize, c as castValue, d as uncastable, n as reservedWords, r as epochStorages } from "./identifiers-CzqYL_nC.mjs";
2
2
  import { existsSync, readFileSync, readdirSync } from "node:fs";
3
3
  import { basename, dirname, join, relative, resolve, sep } from "node:path";
4
4
  // cli/project/paths.ts