@forestfuture/active-record 0.7.0 → 0.8.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.
Files changed (33) hide show
  1. package/config-schema.json +6 -2
  2. package/dist/adapter.d.mts +3 -3
  3. package/dist/adapter.mjs +5 -4
  4. package/dist/batch-Ms5p9lKq.mjs +9777 -0
  5. package/dist/cli.d.mts +55 -33
  6. package/dist/cli.mjs +4 -4
  7. package/dist/command.mjs +530 -271
  8. package/dist/d1.d.mts +2 -10
  9. package/dist/d1.mjs +0 -0
  10. package/dist/{for-adapters-t3-LukJQ.d.mts → for-adapters-BT2GDjIA.d.mts} +8 -6
  11. package/dist/{for-adapters-Ch6CoHD4.mjs → for-adapters-BbIMUNcz.mjs} +46 -10
  12. package/dist/{for-adapters-D_Iu0gS_.mjs → for-adapters-C-MQxaIx.mjs} +3 -5
  13. package/dist/{generated-model-Cnt0Ot9q.mjs → generated-model-DJA8vmNE.mjs} +705 -508
  14. package/dist/identifiers-Dh5DFACX.mjs +989 -0
  15. package/dist/index-D5getfHx.d.mts +242 -0
  16. package/dist/index.d.mts +4 -3
  17. package/dist/index.mjs +5 -4
  18. package/dist/metadata-CzntpYzC.d.mts +182 -0
  19. package/dist/{plugin-Cyoej7qV.mjs → plugin-CZPDqguF.mjs} +211 -112
  20. package/dist/{plugin-XOHYndhP.mjs → plugin-Cf-5Z0_h.mjs} +148 -52
  21. package/dist/postgresql.d.mts +1 -9
  22. package/dist/postgresql.mjs +42 -26
  23. package/dist/src-BAVZKQ7J.mjs +46 -0
  24. package/dist/{storage-override-CpbkdIqE.mjs → storage-override-0ZgeP2sc.mjs} +61 -28
  25. package/dist/validations-BSZ5gVeI.d.mts +2024 -0
  26. package/llms-full.txt +2326 -229
  27. package/package.json +1 -1
  28. package/skills/active-record/SKILL.md +24 -15
  29. package/dist/adapter-AGKp6wfO.d.mts +0 -1326
  30. package/dist/batch-BS_WseLf.mjs +0 -4255
  31. package/dist/epoch-storage-o2aoOH7H.mjs +0 -112
  32. package/dist/index-CyCJuM96.d.mts +0 -149
  33. package/dist/src-la_KkjCS.mjs +0 -1
@@ -1,11 +1,11 @@
1
- import { a as underscore } from "./epoch-storage-o2aoOH7H.mjs";
2
- import { n as migrationSql, r as quotedName, t as generatedSchema } from "./for-adapters-Ch6CoHD4.mjs";
3
- import { f as byVersion, l as parseJsonc, n as attributeName } from "./storage-override-CpbkdIqE.mjs";
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";
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";
7
7
  import { randomUUID } from "node:crypto";
8
- //#region cli/adapters/postgresql/config.ts
8
+ // cli/adapters/postgresql/config.ts
9
9
  /** The table the runner records applied migrations in, left out of the schema. */
10
10
  const migrationsTable = "schema_migrations";
11
11
  /** The settings a database's entry may have, each a string. */
@@ -50,8 +50,7 @@ function readDatabases(project) {
50
50
  databases: entries.map(([binding, entry]) => databaseOf(binding, entry))
51
51
  };
52
52
  }
53
- //#endregion
54
- //#region cli/adapters/postgresql/wrangler.ts
53
+ // cli/adapters/postgresql/wrangler.ts
55
54
  const candidates = [
56
55
  "wrangler.jsonc",
57
56
  "wrangler.json",
@@ -106,8 +105,7 @@ function hyperdriveIn(dir) {
106
105
  bindings: entries.filter((entry) => typeof entry?.binding === "string")
107
106
  };
108
107
  }
109
- //#endregion
110
- //#region cli/adapters/postgresql/init.ts
108
+ // cli/adapters/postgresql/init.ts
111
109
  /** The local database a project's folder suggests, named as Rails names it: `shop_development`. */
112
110
  function guessedUrl(dir) {
113
111
  return `postgres://localhost:5432/${basename(dir).toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_|_$/g, "") || "app"}_development`;
@@ -147,8 +145,7 @@ function init(dir, named) {
147
145
  notes: { DATABASE_URL: note }
148
146
  };
149
147
  }
150
- //#endregion
151
- //#region cli/adapters/postgresql/drivers.ts
148
+ // cli/adapters/postgresql/drivers.ts
152
149
  /** Whether Node's error is for the package `name` itself missing, from `require` or `import`. */
153
150
  function isMissing(error, name) {
154
151
  const { code, message } = error;
@@ -175,8 +172,7 @@ async function pgliteModule(load = () => import("@electric-sql/pglite")) {
175
172
  return "Reading a PostgreSQL schema needs PGlite, which isn't installed here: run `npm install --save-dev @electric-sql/pglite`";
176
173
  }
177
174
  }
178
- //#endregion
179
- //#region cli/adapters/postgresql/urls.ts
175
+ // cli/adapters/postgresql/urls.ts
180
176
  /** `${NAME}`: a variable's value, put in its place. */
181
177
  const variable = /\$\{(\w+)\}/g;
182
178
  /**
@@ -212,8 +208,7 @@ function hostOf(url) {
212
208
  function databaseNameOf(url) {
213
209
  return parsed(url)?.database ?? "postgres";
214
210
  }
215
- //#endregion
216
- //#region cli/adapters/postgresql/targets.ts
211
+ // cli/adapters/postgresql/targets.ts
217
212
  /** A database, named for a person: its binding, its database's name and its host. */
218
213
  const described = (kind, binding, url) => `${kind} database ${binding} (${databaseNameOf(url)} on ${hostOf(url)})`;
219
214
  /** The real database the entry's `remoteUrl` names, or why there's none. */
@@ -242,8 +237,7 @@ function target(chosen, remote, needs = "migrate needs") {
242
237
  description: described(remote ? "Remote" : "Local", chosen.binding, url)
243
238
  };
244
239
  }
245
- //#endregion
246
- //#region cli/adapters/postgresql/client.ts
240
+ // cli/adapters/postgresql/client.ts
247
241
  /** A client on the connection string's database, connected, or the reason it couldn't be. */
248
242
  async function connected(connectionString) {
249
243
  const pg = pgDriver();
@@ -260,8 +254,7 @@ async function connected(connectionString) {
260
254
  return error.message;
261
255
  }
262
256
  }
263
- //#endregion
264
- //#region cli/adapters/postgresql/transaction-control.ts
257
+ // cli/adapters/postgresql/transaction-control.ts
265
258
  /** Where a `--` comment starting at `index` ends: at the end of its line. */
266
259
  function lineEnd(sql, index) {
267
260
  const end = sql.indexOf("\n", index);
@@ -331,8 +324,7 @@ function ownTransactions(migrations) {
331
324
  if (found !== void 0) return `${name} has its own ${found}; leave out BEGIN, COMMIT and ROLLBACK, since migrate runs each migration in a transaction of its own`;
332
325
  }
333
326
  }
334
- //#endregion
335
- //#region cli/adapters/postgresql/versions.ts
327
+ // cli/adapters/postgresql/versions.ts
336
328
  /**
337
329
  * Each migration's version, by its file, in the order they're applied; or why one has none, or
338
330
  * shares its version with another, which `migrate` and the schema both refuse.
@@ -351,8 +343,7 @@ function versionsOf(files) {
351
343
  }
352
344
  return versions;
353
345
  }
354
- //#endregion
355
- //#region cli/adapters/postgresql/runner.ts
346
+ // cli/adapters/postgresql/runner.ts
356
347
  /** The migrations folder's files in the order they're applied (by version), or why they can't be. */
357
348
  function migrationFiles(dir) {
358
349
  let names;
@@ -440,8 +431,7 @@ async function runMigrations(url, files, say) {
440
431
  await client.end();
441
432
  }
442
433
  }
443
- //#endregion
444
- //#region cli/adapters/postgresql/migrate.ts
434
+ // cli/adapters/postgresql/migrate.ts
445
435
  /** Applies the chosen database's pending migrations, locally or remotely; the exit code. */
446
436
  async function migrate(_cwd, chosen, { remote }, io) {
447
437
  const say = (line) => io.output(`${line}\n`);
@@ -456,8 +446,7 @@ async function migrate(_cwd, chosen, { remote }, io) {
456
446
  say(reached.description);
457
447
  return runMigrations(reached.url, files, say);
458
448
  }
459
- //#endregion
460
- //#region cli/adapters/postgresql/migration.ts
449
+ // cli/adapters/postgresql/migration.ts
461
450
  /** Postgres's SQL for a generated migration. */
462
451
  const postgres = {
463
452
  reserved: new Set("all analyse analyze and any array as asc asymmetric authorization binary both case cast check collate collation column concurrently constraint create cross current_catalog current_date current_role current_schema current_time current_timestamp current_user default deferrable desc distinct do else end except false fetch for foreign freeze from full grant group having ilike in initially inner intersect into is isnull join lateral leading left like limit localtime localtimestamp natural not notnull null offset on only or order outer overlaps placing primary references returning right select session_user similar some symmetric system_user table tablesample then to trailing true union unique user using variadic verbose when where window with".split(" ")),
@@ -465,9 +454,13 @@ const postgres = {
465
454
  string: "TEXT",
466
455
  integer: "BIGINT",
467
456
  real: "DOUBLE PRECISION",
457
+ decimal: "NUMERIC",
468
458
  boolean: "BOOLEAN",
469
459
  datetime: "TIMESTAMPTZ",
470
- json: "JSONB"
460
+ date: "DATE",
461
+ time: "TIME",
462
+ json: "JSONB",
463
+ binary: "BYTEA"
471
464
  },
472
465
  key: (integerId) => integerId ? "id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY" : "id UUID PRIMARY KEY",
473
466
  timestampType: "TIMESTAMPTZ",
@@ -478,8 +471,7 @@ const postgres = {
478
471
  function migration(change) {
479
472
  return migrationSql(change, postgres);
480
473
  }
481
- //#endregion
482
- //#region cli/adapters/postgresql/open.ts
474
+ // cli/adapters/postgresql/open.ts
483
475
  /**
484
476
  * A Pool on the chosen database, for the project's `connect`: the `pg` this plugin imports is the
485
477
  * one the project's PostgreSQL adapter imports, from the same install. It's ended when the console closes.
@@ -497,25 +489,120 @@ async function openDatabase(chosen, { remote }) {
497
489
  dispose: () => pool.end()
498
490
  };
499
491
  }
500
- //#endregion
501
- //#region cli/adapters/postgresql/catalog.ts
492
+ // cli/adapters/postgresql/checks.ts
493
+ /** A column as Postgres writes it back: bare in lower case, or double-quoted. */
494
+ const columnName = String.raw`"(?:[^"]|"")+"|[a-z_][a-z0-9_$]*`;
495
+ /** A list of string literals, once their casts are gone: `'draft', 'it''s'`. */
496
+ const stringList = String.raw`'(?:[^']|'')*'(?:, '(?:[^']|'')*')*`;
497
+ /**
498
+ * `status = ANY ARRAY['draft', 'published']`, alone or with `status IS NULL OR` before it or
499
+ * `OR status IS NULL` after it, as a definition reads with its parentheses and casts taken out.
500
+ */
501
+ const inList = new RegExp(String.raw`^CHECK (?:(${columnName}) IS NULL OR )?(${columnName}) = ANY ARRAY\[(${stringList})\](?: OR (${columnName}) IS NULL)?$`);
502
+ /**
503
+ * A definition without its parentheses and casts, outside its string literals, with its spaces
504
+ * collapsed: `CHECK (((b)::text = ANY ((ARRAY['a'::character varying])::text[])))` →
505
+ * `CHECK b = ANY ARRAY['a']`.
506
+ */
507
+ function bare(definition) {
508
+ return definition.split(/('(?:[^']|'')*')/).map((part, index) => index % 2 === 1 ? part : bareCode(part)).join("").trim();
509
+ }
510
+ /** A part of a definition outside its literals, without parentheses or casts, its spaces collapsed. */
511
+ function bareCode(part) {
512
+ return part.replace(/::(?:character varying|[a-z_]+)(?:\[\])?|[()]/g, "").replace(/\s+/g, " ");
513
+ }
514
+ /** A column name without its quotes: `"Dee"` → `Dee`. */
515
+ function unquoted(name) {
516
+ return name.startsWith("\"") ? name.slice(1, -1).replaceAll("\"\"", "\"") : name;
517
+ }
518
+ /**
519
+ * `status = 'draft'`, as Postgres writes back a one-name `IN ('draft')`: a restriction that
520
+ * counts against a list on the same column, though it isn't read as one.
521
+ */
522
+ const oneName = new RegExp(String.raw`^CHECK (?:(${columnName}) IS NULL OR )?(${columnName}) = '(?:[^']|'')*'(?: OR (${columnName}) IS NULL)?$`);
523
+ /** The column a list or a single name restricts, unless its `IS NULL` names another one. */
524
+ function restrictedColumn(match) {
525
+ const column = unquoted(match[2]);
526
+ return [match[1], match[match.length - 1]].filter((name) => name !== void 0).map(unquoted).every((name) => name === column) ? column : void 0;
527
+ }
528
+ /** The column a constraint restricts to a list of strings, or to one, if it's that and on that column. */
529
+ function restriction({ columns, definition }) {
530
+ const text = bare(definition);
531
+ const list = inList.exec(text);
532
+ const match = list ?? oneName.exec(text);
533
+ const column = match === null ? void 0 : restrictedColumn(match);
534
+ const found = column === void 0 ? void 0 : onItsColumn(column, columns);
535
+ if (found === void 0 || list === null) return found;
536
+ return {
537
+ ...found,
538
+ names: namesInList(list[3])
539
+ };
540
+ }
541
+ /** A restriction of `column`, if that's the only column the constraint names. */
542
+ function onItsColumn(column, columns) {
543
+ return columns.length === 1 && columns[0] === column ? { column } : void 0;
544
+ }
545
+ /**
546
+ * Each column of a table that one CHECK restricts to a list of strings, with the list. A column
547
+ * a second list (or a single name) also restricts isn't one, as on D1: which of them holds isn't
548
+ * the schema's to say. Other CHECKs on it, such as `length(status) > 0`, don't count.
549
+ */
550
+ function checkedNames(constraints) {
551
+ const byColumn = /* @__PURE__ */ new Map();
552
+ for (const constraint of constraints) {
553
+ const found = restriction(constraint);
554
+ if (found !== void 0) byColumn.set(found.column, [...byColumn.get(found.column) ?? [], found]);
555
+ }
556
+ const lists = /* @__PURE__ */ new Map();
557
+ for (const [column, [only, ...others]] of byColumn) if (others.length === 0 && only.names !== void 0) lists.set(column, only.names);
558
+ return lists;
559
+ }
560
+ // cli/adapters/postgresql/catalog.ts
502
561
  /** The current schema's own tables: ordinary and partitioned ones, not a partition or a view. */
503
562
  const ownTables = `c.relnamespace = current_schema()::regnamespace
504
563
  AND c.relkind IN ('r', 'p') AND NOT c.relispartition`;
564
+ /** A numeric's precision or scale, read from its type modifier, or NULL for a numeric without one. */
565
+ function numericDigits(name, fromTypmod) {
566
+ return `CASE WHEN b.typname = 'numeric' AND m.typmod >= 4 THEN ${fromTypmod} END AS "${name}"`;
567
+ }
505
568
  const columnsQuery = `
506
569
  SELECT c.relname AS "table", a.attname AS "name",
507
570
  format_type(a.atttypid, a.atttypmod) AS "declared",
508
571
  b.typname AS "base", b.typtype AS "kind", b.typcategory AS "category",
572
+ (SELECT array_agg(e.enumlabel::text ORDER BY e.enumsortorder) FROM pg_enum e
573
+ WHERE e.enumtypid = b.oid) AS "restrictedTo",
574
+ ${numericDigits("precision", "((m.typmod - 4) >> 16) & 65535")},
575
+ ${numericDigits("scale", "(m.typmod - 4) & 65535")},
509
576
  a.attnotnull AS "notNull", pg_get_expr(d.adbin, d.adrelid) AS "defaultValue",
510
577
  COALESCE(a.attnum = ANY (k.conkey), false) AS "primaryKey"
511
578
  FROM pg_class c
512
579
  JOIN pg_attribute a ON a.attrelid = c.oid AND a.attnum > 0 AND NOT a.attisdropped
513
580
  JOIN pg_type t ON t.oid = a.atttypid
514
581
  JOIN pg_type b ON b.oid = CASE WHEN t.typtype = 'd' THEN t.typbasetype ELSE t.oid END
582
+ -- A numeric's precision and scale are in its type modifier: the column's, or a domain's.
583
+ CROSS JOIN LATERAL (SELECT CASE WHEN a.atttypmod >= 0 THEN a.atttypmod ELSE t.typtypmod END AS typmod) m
515
584
  LEFT JOIN pg_attrdef d ON d.adrelid = c.oid AND d.adnum = a.attnum
516
585
  LEFT JOIN pg_constraint k ON k.conrelid = c.oid AND k.contype = 'p'
517
586
  WHERE ${ownTables}
518
587
  ORDER BY c.relname, a.attnum`;
588
+ /** Each CHECK constraint of the current schema's tables: its table, its columns, its definition. */
589
+ const checksQuery = `
590
+ SELECT c.relname AS "table", pg_get_constraintdef(k.oid) AS "definition",
591
+ ARRAY(SELECT a.attname::text FROM pg_attribute a
592
+ WHERE a.attrelid = k.conrelid AND a.attnum = ANY (k.conkey)) AS "columns"
593
+ FROM pg_constraint k
594
+ JOIN pg_class c ON c.oid = k.conrelid
595
+ WHERE k.contype = 'c' AND ${ownTables}`;
596
+ /** Each table's CHECK constraints, by table. */
597
+ async function checksByTable(query) {
598
+ const byTable = /* @__PURE__ */ new Map();
599
+ for (const row of await query(checksQuery)) {
600
+ const checks = byTable.get(String(row.table)) ?? [];
601
+ checks.push(row);
602
+ byTable.set(String(row.table), checks);
603
+ }
604
+ return byTable;
605
+ }
519
606
  /** Each table's columns and constraints as one line of text, to tell when a migration changed it. */
520
607
  const definitionsQuery = `
521
608
  SELECT c.relname AS "table",
@@ -536,16 +623,18 @@ async function definitions(query) {
536
623
  /** Every column of the current schema's tables, by table, in column order. */
537
624
  async function columnsByTable(query) {
538
625
  const byTable = /* @__PURE__ */ new Map();
626
+ const checks = await checksByTable(query);
627
+ const listsByTable = new Map([...checks].map(([table, constraints]) => [table, checkedNames(constraints)]));
539
628
  for (const row of await query(columnsQuery)) {
540
629
  const column = row;
630
+ column.restrictedTo = column.restrictedTo ?? listsByTable.get(column.table)?.get(column.name) ?? void 0;
541
631
  const columns = byTable.get(column.table) ?? [];
542
632
  columns.push(column);
543
633
  byTable.set(column.table, columns);
544
634
  }
545
635
  return byTable;
546
636
  }
547
- //#endregion
548
- //#region cli/adapters/postgresql/conventions.ts
637
+ // cli/adapters/postgresql/conventions.ts
549
638
  /** Each base type an attribute holds, by its catalog name. */
550
639
  const attributeTypes = {
551
640
  int2: "integer",
@@ -554,11 +643,14 @@ const attributeTypes = {
554
643
  float4: "real",
555
644
  float8: "real",
556
645
  bool: "boolean",
557
- date: "datetime",
646
+ date: "date",
647
+ time: "time",
648
+ numeric: "decimal",
558
649
  timestamp: "datetime",
559
650
  timestamptz: "datetime",
560
651
  json: "json",
561
652
  jsonb: "json",
653
+ bytea: "binary",
562
654
  text: "string",
563
655
  varchar: "string",
564
656
  bpchar: "string",
@@ -568,9 +660,7 @@ const attributeTypes = {
568
660
  };
569
661
  /** Why a column's type can't be an attribute, if it can't. */
570
662
  function refusal(column, where) {
571
- if (column.category === "A") return `${where}: arrays (${column.declared}) aren't supported; use a jsonb column, or a table`;
572
- if (column.base === "numeric") return `${where}: numeric loses precision as a number; store money as integer cents (${column.name}_cents BIGINT)`;
573
- return column.base === "bytea" ? `${where}: bytea columns aren't supported yet (#20)` : void 0;
663
+ return column.category === "A" ? `${where}: arrays (${column.declared}) aren't supported; use a jsonb column, or a table` : void 0;
574
664
  }
575
665
  /** A column's attribute type, and a note when it's a string for want of a better one. */
576
666
  function typeOf(column, where) {
@@ -606,22 +696,33 @@ function parsedDefault(text, type) {
606
696
  }
607
697
  }
608
698
  /** A literal default as a value of the attribute's type; undefined for a function or anything else. */
609
- function literalDefault(sql, type) {
610
- const text = sql === null ? void 0 : literalText(sql.trim());
611
- if (text === void 0) return void 0;
699
+ function literalDefault(sql, spec) {
700
+ if (sql === null || spec.type === "binary") return void 0;
701
+ const text = literalText(sql.trim());
702
+ return text === void 0 ? void 0 : defaultOf(text, {
703
+ ...spec,
704
+ type: spec.type
705
+ });
706
+ }
707
+ /** A literal's text, its casts taken off, as a value of the attribute's type. */
708
+ function defaultOf(text, { type, precision, scale }) {
612
709
  if (type === "boolean") return /^(true|false)$/i.test(text) ? { literal: /^true$/i.test(text) } : void 0;
613
710
  if (type === "integer" || type === "real") return numberDefault(text, type);
711
+ if (isCastDefaultType(type)) return castDefault(type, text, {
712
+ precision,
713
+ scale
714
+ });
614
715
  return type === "string" ? { literal: text } : parsedDefault(text, type);
615
716
  }
616
717
  /** A column's spec: nullability, a mapped column name, and its default or a key made in code. */
617
718
  function specOf(column, type, attribute) {
618
- const spec = { type };
719
+ const spec = withDigits({ type }, column.precision, column.scale);
619
720
  if (column.notNull || column.primaryKey) spec.null = false;
620
721
  if (underscore(attribute) !== column.name) spec.column = column.name;
621
- const defaultValue = literalDefault(column.defaultValue, type);
722
+ const defaultValue = literalDefault(column.defaultValue, spec);
622
723
  if (defaultValue !== void 0) spec.default = defaultValue;
623
724
  else if (column.primaryKey && type === "string") spec.generateId = true;
624
- return spec;
725
+ return withGeneratedEnum(spec, column.restrictedTo);
625
726
  }
626
727
  /** A column as an attribute: its type, nullability and literal default, or why it can't be one. */
627
728
  function convert(column) {
@@ -645,8 +746,7 @@ function convert(column) {
645
746
  note
646
747
  };
647
748
  }
648
- //#endregion
649
- //#region cli/adapters/postgresql/extensions.ts
749
+ // cli/adapters/postgresql/extensions.ts
650
750
  /** The contrib extensions PGlite has its own build of, by the module it exports each from. */
651
751
  const contrib = new Set("amcheck auto_explain bloom btree_gin btree_gist citext cube dict_int dict_xsyn earthdistance file_fdw fuzzystrmatch hstore intarray isn lo ltree moddatetime pageinspect pg_buffercache pg_freespacemap pg_stat_statements pg_surgery pg_trgm pg_visibility pg_walinspect pgcrypto seg tablefunc tcn tsm_system_rows tsm_system_time unaccent uuid_ossp".split(" "));
652
752
  /** `CREATE EXTENSION [IF NOT EXISTS] name`, its name quoted or not. */
@@ -671,8 +771,7 @@ async function pgliteExtensions(migrations) {
671
771
  }
672
772
  return loaded;
673
773
  }
674
- //#endregion
675
- //#region cli/adapters/postgresql/server-schema.ts
774
+ // cli/adapters/postgresql/server-schema.ts
676
775
  /**
677
776
  * The same server's connection string, for another database on it; undefined when Node can't read
678
777
  * it as a URL (a socket's `postgres://app@/shop`), whose message would show it, password and all.
@@ -783,8 +882,7 @@ async function temporaryDatabase(url) {
783
882
  }
784
883
  };
785
884
  }
786
- //#endregion
787
- //#region cli/adapters/postgresql/schema.ts
885
+ // cli/adapters/postgresql/schema.ts
788
886
  /**
789
887
  * An in-memory PGlite, loaded when a schema is first read, with the extensions it has builds of;
790
888
  * or what to install.
@@ -921,8 +1019,7 @@ async function schemaOf(migrations, options = {}) {
921
1019
  const read = await readOn(scratch, migrations, table);
922
1020
  return "ok" in read ? read : readOnServer(migrations, options, read);
923
1021
  }
924
- //#endregion
925
- //#region cli/adapters/postgresql/plugin.ts
1022
+ // cli/adapters/postgresql/plugin.ts
926
1023
  /** Postgres, as the command line sees it: `active-record.jsonc`'s databases, PGlite's schema, and `pg`. */
927
1024
  const cli = {
928
1025
  name: "postgresql",
@@ -935,5 +1032,4 @@ const cli = {
935
1032
  open: (_cwd, chosen, options) => openDatabase(chosen, options),
936
1033
  migrate
937
1034
  };
938
- //#endregion
939
1035
  export { cli };
@@ -1,12 +1,9 @@
1
- import { i as AnyDatabase, lt as QueryEvent$1, r as SchemaAdapter, ut as QueryListener$1 } from "./adapter-AGKp6wfO.mjs";
1
+ import { C as QueryEvent$1, D as SchemaAdapter, O as AnyDatabase, w as QueryListener$1 } from "./validations-BSZ5gVeI.mjs";
2
2
  import pg from "pg";
3
- //#region src/adapters/postgresql/adapter.d.ts
4
3
  /** The Postgres database a generated schema's Models query: `adapter: postgresql({ binding: "HYPERDRIVE" })`. */
5
4
  export declare function postgresql({ binding }: {
6
5
  binding: string;
7
6
  }): SchemaAdapter;
8
- //#endregion
9
- //#region src/adapters/postgresql/clients.d.ts
10
7
  /** Reads a column's text, by its type's OID, as a JavaScript value: `pg`'s `types` option. */
11
8
  interface TypeParsers {
12
9
  getTypeParser(oid: number, format?: string): (text: string) => unknown;
@@ -39,16 +36,12 @@ interface Pool {
39
36
  readonly connectionString?: string | undefined;
40
37
  };
41
38
  }
42
- //#endregion
43
- //#region src/adapters/postgresql/driver.d.ts
44
39
  /** What `onQuery` hears from Postgres about a statement: its command and the rows it counted. */
45
40
  interface PostgreSQLMeta {
46
41
  /** `SELECT`, `INSERT`, `UPDATE`, `DELETE`, … */
47
42
  command: string;
48
43
  rowCount: number | null;
49
44
  }
50
- //#endregion
51
- //#region src/adapters/postgresql/database.d.ts
52
45
  /** What `onQuery` hears about a statement: its Model, SQL, bound values, timing, and Postgres's `meta`. */
53
46
  type QueryEvent = QueryEvent$1<PostgreSQLMeta>;
54
47
  /** Hears each statement's `QueryEvent`, with Postgres's `meta`. */
@@ -68,5 +61,4 @@ export declare class Database extends AnyDatabase {
68
61
  constructor(source: PostgreSQLSource, options?: ConnectOptions);
69
62
  }
70
63
  export declare function connect(source: PostgreSQLSource, options?: ConnectOptions): Database;
71
- //#endregion
72
64
  export type { ConnectOptions, Pool, PostgreSQLMeta, PostgreSQLSource, QueryEvent, QueryListener };
@@ -1,8 +1,9 @@
1
- import { L as boundValue, ct as NoDatabase } from "./generated-model-Cnt0Ot9q.mjs";
2
- import { a as databaseExecutor, i as AnyDatabase, s as DatabaseExecutor } from "./batch-BS_WseLf.mjs";
3
- import { n as onlyRequested, t as workersEnv } from "./for-adapters-D_Iu0gS_.mjs";
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";
4
5
  import pg from "pg";
5
- //#region src/adapters/postgresql/connect-timeout.ts
6
+ // src/adapters/postgresql/connect-timeout.ts
6
7
  /** The limit when the connection string sets none, in milliseconds. */
7
8
  const defaultTimeoutMs = 1e4;
8
9
  /** The longest a timer waits, in milliseconds (about 24 days): it fires at once for longer. */
@@ -60,8 +61,7 @@ async function openClient(connectionString, timeoutMs) {
60
61
  clearTimeout(timer);
61
62
  }
62
63
  }
63
- //#endregion
64
- //#region src/adapters/postgresql/clients.ts
64
+ // src/adapters/postgresql/clients.ts
65
65
  /**
66
66
  * The connection string a source opens its clients from: a Hyperdrive binding's, or the source
67
67
  * itself when it's one. Undefined for anything else, such as a Pool.
@@ -205,12 +205,10 @@ function isSessionEnding(error) {
205
205
  async function closed(client) {
206
206
  await client.end().catch(() => {});
207
207
  }
208
- //#endregion
209
- //#region src/adapters/postgresql/is-object.ts
208
+ // src/adapters/postgresql/is-object.ts
210
209
  /** Whether `value` is an object, one a WeakMap can key. */
211
210
  const isObject = (value) => typeof value === "object" && value !== null;
212
- //#endregion
213
- //#region src/adapters/postgresql/errors.ts
211
+ // src/adapters/postgresql/errors.ts
214
212
  const kinds = {
215
213
  "23505": "unique",
216
214
  "23502": "notNull",
@@ -314,8 +312,7 @@ function missingTable(error) {
314
312
  if (code !== "42P01") return void 0;
315
313
  return /relation "(.+?)" does not exist/.exec(text(message) ?? "")?.[1];
316
314
  }
317
- //#endregion
318
- //#region src/adapters/postgresql/type-parsers.ts
315
+ // src/adapters/postgresql/type-parsers.ts
319
316
  /** Postgres's type OIDs this adapter reads its own way. */
320
317
  const oids = {
321
318
  bool: 16,
@@ -356,8 +353,7 @@ const parsers = {
356
353
  const typeParsers = { getTypeParser(oid, format) {
357
354
  return (format === void 0 || format === "text" ? parsers[oid] : void 0) ?? pg.types.getTypeParser(oid, format);
358
355
  } };
359
- //#endregion
360
- //#region src/adapters/postgresql/driver.ts
356
+ // src/adapters/postgresql/driver.ts
361
357
  /** Every query the driver sends: its error, if it fails, without the row values Postgres wrote in it. */
362
358
  function queried(client, query) {
363
359
  return client.query(query).catch((error) => {
@@ -437,8 +433,7 @@ var PgDriver = class {
437
433
  async function rolledBack(client) {
438
434
  await client.query({ text: "ROLLBACK" }).catch(() => {});
439
435
  }
440
- //#endregion
441
- //#region src/adapters/postgresql/current-database.ts
436
+ // src/adapters/postgresql/current-database.ts
442
437
  /** The Worker's bindings, from `cloudflare:workers`, read once; undefined outside a Worker. */
443
438
  let bindings;
444
439
  /** The `env` a test mocks with the PostgreSQL adapter inlined is this module's import, so it's imported here. */
@@ -476,8 +471,7 @@ async function databaseFor(name, requested) {
476
471
  if (connectionString === void 0) throw new NoDatabase(`The binding ${name} isn't in this Worker's env as a Hyperdrive binding or a connection string; check hyperdrive in your Wrangler config`);
477
472
  return requested.find((db) => dbConnectionString(db) === connectionString) ?? defaultDatabase(binding, connectionString, name);
478
473
  }
479
- //#endregion
480
- //#region src/adapters/postgresql/dialect.ts
474
+ // src/adapters/postgresql/dialect.ts
481
475
  /** A text literal, as an escape string, so it reads the same whatever `standard_conforming_strings` is. */
482
476
  const literal = (text) => `E'${text.replaceAll("\\", "\\\\").replaceAll("'", "''")}'`;
483
477
  /** A quoted identifier; embedded double quotes are doubled. */
@@ -491,14 +485,21 @@ function jsonObject(pairs) {
491
485
  return parts.join(" || ");
492
486
  }
493
487
  /**
488
+ * An attribute's cell in a bulk row: bytes are hex text in the JSON (#20), read as `bytea`,
489
+ * whose JSON form (`"\\x0102"`) the row reads back as bytes.
490
+ */
491
+ function rowCell(table, { column, isJson, isBinary }, index) {
492
+ if (isBinary) return `to_jsonb(decode(cells ->> ${index}, 'hex'))`;
493
+ return isJson ? jsonCell(table, column, index) : `cells -> ${index}`;
494
+ }
495
+ /**
494
496
  * A json attribute's cell, which is its JSON's text: read as JSON for a json or jsonb column,
495
497
  * which would otherwise keep it as a JSON string, and kept as that text for any other column.
496
498
  */
497
499
  function jsonCell(table, column, index) {
498
500
  return `CASE WHEN ${`pg_typeof((NULL::${table}).${quoted(column)})`} IN ('json'::regtype, 'jsonb'::regtype) THEN (cells ->> ${index})::jsonb ELSE cells -> ${index} END`;
499
501
  }
500
- //#endregion
501
- //#region src/adapters/postgresql/adapter.ts
502
+ // src/adapters/postgresql/adapter.ts
502
503
  const pgAdapter = {
503
504
  name: "Postgres",
504
505
  dialect: {
@@ -507,6 +508,10 @@ const pgAdapter = {
507
508
  sql: `${column} = ANY()`,
508
509
  value: [...cells]
509
510
  }),
511
+ placeInList: (column, cells) => ({
512
+ sql: `array_position(, ${column})`,
513
+ value: [...cells]
514
+ }),
510
515
  pagination(limit, offset, params) {
511
516
  let text = "";
512
517
  if (limit !== void 0) {
@@ -530,13 +535,26 @@ const pgAdapter = {
530
535
  return `CASE WHEN ${key} ~ ${literal("^\\s*[+-]?[0-9]+\\s*$")} THEN CAST(${key} AS NUMERIC) END`;
531
536
  },
532
537
  /**
538
+ * The removal returns a row for each row it removed, which the counters' UPDATEs count, and the
539
+ * statement selects how many as `removed`: a COUNT sent before it could miss a row another
540
+ * request commits in between, on a snapshot of its own (#61).
541
+ */
542
+ countedRemoval(removal, decrements) {
543
+ const counted = decrements("(SELECT COUNT(*) FROM removed)");
544
+ const ctes = counted.map(({ sql }, index) => `counted${index} AS (${sql})`);
545
+ return {
546
+ sql: `WITH removed AS (${removal.sql} RETURNING 1), ${ctes.join(", ")} SELECT COUNT(*) AS removed FROM removed`,
547
+ params: [...removal.params, ...counted.flatMap(({ params }) => params)],
548
+ model: removal.model
549
+ };
550
+ },
551
+ /**
533
552
  * Each row's cells become an object of its columns, read into a record of `table`, so every
534
553
  * value converts to its column's own type as an insert's would.
535
554
  */
536
555
  bulkRows(table, attributes) {
537
- const pairs = attributes.map(({ column, isJson }, index) => {
538
- const cell = isJson ? jsonCell(table, column, index) : `cells -> ${index}`;
539
- return `${literal(column)}, ${cell}`;
556
+ const pairs = attributes.map((attribute, index) => {
557
+ return `${literal(attribute.column)}, ${rowCell(table, attribute, index)}`;
540
558
  });
541
559
  return {
542
560
  select: attributes.map(({ column }) => `row.${quoted(column)}`).join(", "),
@@ -557,8 +575,7 @@ function postgresql({ binding }) {
557
575
  binding
558
576
  };
559
577
  }
560
- //#endregion
561
- //#region src/adapters/postgresql/database.ts
578
+ // src/adapters/postgresql/database.ts
562
579
  function clientsFor(source) {
563
580
  const connectionString = connectionStringOf(source);
564
581
  return connectionString === void 0 ? new PoolClients(source) : new UrlClients(connectionString);
@@ -584,5 +601,4 @@ var Database = class extends AnyDatabase {
584
601
  function connect(source, options) {
585
602
  return new Database(source, options);
586
603
  }
587
- //#endregion
588
604
  export { Database, connect, postgresql };
@@ -0,0 +1,46 @@
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";
3
+ // src/define-schema.ts
4
+ const listed = /* @__PURE__ */ new Set();
5
+ /**
6
+ * A generated schema, as `schema.ts` declares it: `export const schema = defineSchema({ … })`.
7
+ * A generated Model's attributes are settled when it's first used, so its enum scopes would
8
+ * only appear then; `Post.published()` is often that first use. So each scope the schema lists
9
+ * is a static of every Model now: on a Model it's listed for, reading it readies the Model,
10
+ * which defines the scope on it; on any other, it's `undefined`.
11
+ */
12
+ function defineSchema(schema) {
13
+ for (const names of Object.values(schema.enumScopes ?? {})) for (const name of names) listScope(name);
14
+ return schema;
15
+ }
16
+ function listScope(name) {
17
+ if (listed.has(name) || isReservedScopeName(name) || name in Model) return;
18
+ listed.add(name);
19
+ Object.defineProperty(Model, name, {
20
+ configurable: true,
21
+ get() {
22
+ return enumScopeOf(this, name);
23
+ },
24
+ set: ownValueSetter(name)
25
+ });
26
+ }
27
+ /** The scope `name` of `model`, once it's ready, if its schema lists it; else `undefined`. */
28
+ function enumScopeOf(model, name) {
29
+ if (!isListedFor(model, name)) return void 0;
30
+ readyModel(model);
31
+ return staticBelow(model, Model, name)?.value;
32
+ }
33
+ /**
34
+ * Whether the schema `model`'s base holds lists `name` among the enum scopes of `model`, or of a
35
+ * class it extends: a subclass of a generated Model has its scopes, by the Model's `modelName`.
36
+ */
37
+ function isListedFor(model, name) {
38
+ const holder = ancestors(model).find((each) => Object.hasOwn(each, "schema"));
39
+ const scopes = holder?.schema?.enumScopes;
40
+ if (scopes === void 0) return false;
41
+ return ancestors(model).filter((each) => each !== holder).some((each) => {
42
+ const modelName = modelNameOf(each);
43
+ return Object.hasOwn(scopes, modelName) && scopes[modelName].includes(name);
44
+ });
45
+ }
46
+ export { defineSchema as t };