@rebasepro/server-postgres 0.16.1-canary.gef08a6e → 0.17.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.
Files changed (33) hide show
  1. package/dist/{backup-service-BL5x6Fj5.js → backup-service-BtgHxfFm.js} +2 -1
  2. package/dist/{backup-service-BL5x6Fj5.js.map → backup-service-BtgHxfFm.js.map} +1 -1
  3. package/dist/cli-helpers.d.ts +41 -0
  4. package/dist/{ensure-collection-tables-DpGX_25A.js → collection-index-DxJBvVTH.js} +240 -1913
  5. package/dist/collection-index-DxJBvVTH.js.map +1 -0
  6. package/dist/{ensure-collection-policies-RK8-SFLs.js → ensure-collection-policies-DFpOl8SM.js} +3 -3
  7. package/dist/{ensure-collection-policies-RK8-SFLs.js.map → ensure-collection-policies-DFpOl8SM.js.map} +1 -1
  8. package/dist/ensure-collection-tables-DMjOkeRy.js +1952 -0
  9. package/dist/ensure-collection-tables-DMjOkeRy.js.map +1 -0
  10. package/dist/index.es.js +10 -9
  11. package/dist/index.es.js.map +1 -1
  12. package/dist/{rls-enforcement-da7ekLw-.js → rls-enforcement-CInuYj1-.js} +2 -2
  13. package/dist/{rls-enforcement-da7ekLw-.js.map → rls-enforcement-CInuYj1-.js.map} +1 -1
  14. package/dist/schema/collection-index.d.ts +182 -0
  15. package/dist/schema/introspect-db-inference.d.ts +1 -1
  16. package/dist/schema/introspect-db-logic.d.ts +4 -4
  17. package/dist/schema/introspect-db-project.d.ts +2 -2
  18. package/dist/src-DiDgtX8P.js.map +1 -1
  19. package/dist/{websocket-6b7Iy4TP.js → websocket-HcyLl1ZM.js} +5 -4
  20. package/dist/{websocket-6b7Iy4TP.js.map → websocket-HcyLl1ZM.js.map} +1 -1
  21. package/package.json +6 -6
  22. package/src/cli-helpers.ts +114 -0
  23. package/src/cli.ts +22 -0
  24. package/src/schema/collection-index.ts +427 -0
  25. package/src/schema/ensure-collection-tables.ts +21 -0
  26. package/src/schema/generate-postgres-ddl-logic.ts +17 -5
  27. package/src/schema/introspect-db-inference.ts +1 -1
  28. package/src/schema/introspect-db-logic.ts +4 -4
  29. package/src/schema/introspect-db-project.ts +2 -2
  30. package/src/schema/introspect-db.ts +2 -2
  31. package/src/services/realtimeService.ts +17 -4
  32. package/src/websocket.ts +1 -1
  33. package/dist/ensure-collection-tables-DpGX_25A.js.map +0 -1
@@ -1,10 +1,8 @@
1
1
  import { createRequire as __createRequire } from "module";
2
2
  import "process";
3
3
  __createRequire(import.meta.url);
4
- import { d as __require, l as __commonJSMin, u as __exportAll } from "./connection-GOKU3Hu5.js";
5
- import { _ as isRelationAggregateSort, a as rewriteLegacyRlsFunctions, b as toCanonicalOp, c as isPostgresCollectionConfig, d as getDataSourceCapabilities, f as ALL_WHERE_FILTER_OPS, h as REST_TO_CANONICAL, i as RLS_UID_SQL, l as isRelationalCollectionConfig, m as NULL_OPS, n as REBASE_SCHEMA, p as CANONICAL_TO_REST, r as RLS_ROLES_SQL, s as getDeclaredSubcollections, y as sortKeyToString } from "./src-DiDgtX8P.js";
6
- import { isConcurrentDdlRace, isDuplicateObjectRace, logger } from "@rebasepro/server";
7
- import { createHash } from "node:crypto";
4
+ import { d as __require, l as __commonJSMin } from "./connection-GOKU3Hu5.js";
5
+ import { _ as isRelationAggregateSort, a as rewriteLegacyRlsFunctions, b as toCanonicalOp, c as isPostgresCollectionConfig, d as getDataSourceCapabilities, f as ALL_WHERE_FILTER_OPS, h as REST_TO_CANONICAL, i as RLS_UID_SQL, l as isRelationalCollectionConfig, m as NULL_OPS, p as CANONICAL_TO_REST, r as RLS_ROLES_SQL, s as getDeclaredSubcollections, y as sortKeyToString } from "./src-DiDgtX8P.js";
8
6
  //#region ../types/src/errors.ts
9
7
  /**
10
8
  * The single error type thrown across the entire Rebase client surface —
@@ -1595,9 +1593,28 @@ function legacyForeignKeyName(name) {
1595
1593
  * and `TextDecoder` are standard in both runtimes and need no ambient types.
1596
1594
  */
1597
1595
  function toPostgresIdentifier(name) {
1596
+ return truncateToBytes(name, 63);
1597
+ }
1598
+ /**
1599
+ * {@link toPostgresIdentifier} with the bound lifted to a parameter.
1600
+ *
1601
+ * Exists for names that end in something load-bearing. Truncating at 63 keeps
1602
+ * the *head* of a name and discards the tail, which is right for a descriptive
1603
+ * identifier and wrong for a hashed one: the hash is the part that makes it
1604
+ * unique, and it is at the end. A caller that appends a fingerprint truncates
1605
+ * the readable head to `63 - <tail>` itself and then appends, so the bound is
1606
+ * still 63 and the hash always survives.
1607
+ *
1608
+ * `contracts/derived-names.txt` records what the alternative costs — a foreign
1609
+ * key frozen as `..._corres`, its `_fkey` suffix truncated away, so a second
1610
+ * foreign key on that table would derive a byte-identical name.
1611
+ *
1612
+ * One truncation rule, in one function, so the two cannot drift.
1613
+ */
1614
+ function truncateToBytes(name, maxBytes) {
1598
1615
  const bytes = new TextEncoder().encode(name);
1599
- if (bytes.byteLength <= 63) return name;
1600
- return new TextDecoder("utf-8").decode(bytes.subarray(0, 63)).replace(/�+$/, "");
1616
+ if (bytes.byteLength <= maxBytes) return name;
1617
+ return new TextDecoder("utf-8").decode(bytes.subarray(0, maxBytes)).replace(/�+$/, "");
1601
1618
  }
1602
1619
  /**
1603
1620
  * The API name a database column is served under.
@@ -2703,10 +2720,10 @@ function compile(expr, scope) {
2703
2720
  }
2704
2721
  case "rolesOverlap": return `string_to_array(${RLS_ROLES_SQL}, ',') && ${rolesArraySql(expr.roles)}`;
2705
2722
  case "rolesContain": return `string_to_array(${RLS_ROLES_SQL}, ',') @> ${rolesArraySql(expr.roles)}`;
2706
- case "authenticated": return `${RLS_UID_SQL} IS NOT NULL AND ${RLS_UID_SQL} NOT IN (${ANONYMOUS_USER_IDS.map(quoteLiteral).join(", ")})`;
2723
+ case "authenticated": return `${RLS_UID_SQL} IS NOT NULL AND ${RLS_UID_SQL} NOT IN (${ANONYMOUS_USER_IDS.map(quoteLiteral$1).join(", ")})`;
2707
2724
  case "serverContext": return `${RLS_UID_SQL} IS NULL`;
2708
2725
  case "existsIn": return compileExistsIn(expr, scope);
2709
- case "raw": return rewriteLegacyRlsFunctions(expr.sql).replace(/\{(\w+)\}/g, (_, col) => `${outerQualifier(scope)}${resolveColumnName$1(col, scope.outerCollection)}`);
2726
+ case "raw": return rewriteLegacyRlsFunctions(expr.sql).replace(/\{(\w+)\}/g, (_, col) => `${outerQualifier(scope)}${resolveColumnName(col, scope.outerCollection)}`);
2710
2727
  }
2711
2728
  }
2712
2729
  /**
@@ -2717,7 +2734,7 @@ function compile(expr, scope) {
2717
2734
  function compileExistsIn(expr, scope) {
2718
2735
  const join = scope.resolveCollection?.(expr.collection);
2719
2736
  const joinTable = join ? getTableName(join) : toSnakeCase(expr.collection);
2720
- const joinSchema = schemaOf$1(join) ?? schemaOf$1(scope.outerCollection) ?? "public";
2737
+ const joinSchema = schemaOf(join) ?? schemaOf(scope.outerCollection) ?? "public";
2721
2738
  const alias = `_ex${scope.alias.n++}`;
2722
2739
  const outerPrefix = outerQualifier(scope);
2723
2740
  const innerScope = {
@@ -2740,9 +2757,9 @@ var COMPARE_SQL = {
2740
2757
  };
2741
2758
  function operandToSql(operand, scope) {
2742
2759
  switch (operand.kind) {
2743
- case "field": return `${scope.fieldPrefix}${resolveColumnName$1(operand.name, scope.fieldCollection)}`;
2744
- case "outerField": return `${scope.outerPrefix}${resolveColumnName$1(operand.name, scope.outerCollection)}`;
2745
- case "literal": return quoteLiteral(operand.value);
2760
+ case "field": return `${scope.fieldPrefix}${resolveColumnName(operand.name, scope.fieldCollection)}`;
2761
+ case "outerField": return `${scope.outerPrefix}${resolveColumnName(operand.name, scope.outerCollection)}`;
2762
+ case "literal": return quoteLiteral$1(operand.value);
2746
2763
  case "authUid": return RLS_UID_SQL;
2747
2764
  case "authRoles": return `string_to_array(${RLS_ROLES_SQL}, ',')`;
2748
2765
  }
@@ -2754,12 +2771,12 @@ function operandToSql(operand, scope) {
2754
2771
  function outerQualifier(scope) {
2755
2772
  const table = scope.outerCollection ? getTableName(scope.outerCollection) : void 0;
2756
2773
  if (!table) return "";
2757
- return `"${schemaOf$1(scope.outerCollection) ?? "public"}"."${table}".`;
2774
+ return `"${schemaOf(scope.outerCollection) ?? "public"}"."${table}".`;
2758
2775
  }
2759
- function schemaOf$1(collection) {
2776
+ function schemaOf(collection) {
2760
2777
  return collection?.schema || void 0;
2761
2778
  }
2762
- function resolveColumnName$1(propName, collection) {
2779
+ function resolveColumnName(propName, collection) {
2763
2780
  const prop = collection?.properties?.[propName];
2764
2781
  if (prop && "columnName" in prop && typeof prop.columnName === "string") return quoteColumnIdentifier(prop.columnName);
2765
2782
  return quoteColumnIdentifier(toSnakeCase(propName));
@@ -2903,7 +2920,7 @@ function quoteColumnIdentifier(name) {
2903
2920
  if (BARE_IDENTIFIER.test(name) && !RESERVED_SQL_WORDS.has(name)) return name;
2904
2921
  return `"${name.replace(/"/g, "\"\"")}"`;
2905
2922
  }
2906
- function quoteLiteral(value) {
2923
+ function quoteLiteral$1(value) {
2907
2924
  if (value === null) return "NULL";
2908
2925
  if (typeof value === "boolean") return value ? "true" : "false";
2909
2926
  if (typeof value === "number") return String(value);
@@ -2969,7 +2986,7 @@ var DEFAULT_GUARDED_OPS = [
2969
2986
  "delete"
2970
2987
  ];
2971
2988
  /** Whether a collection is flagged as an authentication collection. */
2972
- function isAuthCollection$1(collection) {
2989
+ function isAuthCollection(collection) {
2973
2990
  const auth = collection.auth;
2974
2991
  return auth === true || typeof auth === "object" && auth?.enabled === true;
2975
2992
  }
@@ -3007,7 +3024,7 @@ function getEffectiveSecurityRules(collection) {
3007
3024
  const explicit = [...collection.securityRules ?? []];
3008
3025
  const tableName = getTableName(collection);
3009
3026
  const injected = [];
3010
- if (isPostgresCollectionConfig(collection) && collection.disableDefaultPolicies) return isAuthCollection$1(collection) ? [...explicit, adminWriteGate(tableName)] : explicit;
3027
+ if (isPostgresCollectionConfig(collection) && collection.disableDefaultPolicies) return isAuthCollection(collection) ? [...explicit, adminWriteGate(tableName)] : explicit;
3011
3028
  injected.push({
3012
3029
  name: `${tableName}_default_admin_read`,
3013
3030
  operations: ["select"],
@@ -3019,7 +3036,7 @@ function getEffectiveSecurityRules(collection) {
3019
3036
  condition: SERVER_OR_ADMIN_EXPR$1,
3020
3037
  check: SERVER_OR_ADMIN_EXPR$1
3021
3038
  });
3022
- if (isAuthCollection$1(collection)) {
3039
+ if (isAuthCollection(collection)) {
3023
3040
  injected.push({
3024
3041
  name: `${tableName}_default_self_read`,
3025
3042
  operations: ["select"],
@@ -3041,7 +3058,7 @@ function getEffectiveSecurityRules(collection) {
3041
3058
  * DDL, which policies are injected and how to take them off.
3042
3059
  */
3043
3060
  function getInjectedSecurityRules(collection) {
3044
- if (isPostgresCollectionConfig(collection) && collection.disableDefaultPolicies) return isAuthCollection$1(collection) ? [adminWriteGate(getTableName(collection))] : [];
3061
+ if (isPostgresCollectionConfig(collection) && collection.disableDefaultPolicies) return isAuthCollection(collection) ? [adminWriteGate(getTableName(collection))] : [];
3045
3062
  const explicitCount = (collection.securityRules ?? []).length;
3046
3063
  return getEffectiveSecurityRules(collection).slice(explicitCount);
3047
3064
  }
@@ -3521,25 +3538,8 @@ function getJunctionSecurityRules(spec) {
3521
3538
  });
3522
3539
  })))();
3523
3540
  /**
3524
- * How wide a `varchar`/`char` column should be for a given property.
3525
- *
3526
- * One definition, three call sites, because they used to disagree. For the same
3527
- * `columnType: "varchar"` property the DDL generator emitted `VARCHAR(255)`
3528
- * while the Drizzle generator emitted a bare `varchar("col")` — which Postgres
3529
- * reads as *unbounded* — so which of the two you ran decided whether the column
3530
- * had a limit at all. Introspection then dropped the length entirely, so reading
3531
- * an existing `character varying(500)` column back and regenerating it produced
3532
- * a `VARCHAR(255)`: a silent narrowing of a column with data already in it.
3533
- *
3534
- * `validation.max` is the property's own statement about how long the value may
3535
- * be, so it is the only sensible source for the column's width — and it keeps
3536
- * the constraint the database enforces in step with the one the app enforces,
3537
- * rather than inventing a second, different limit underneath it.
3541
+ * Apply PropertyConditions to a resolved property, evaluating all JSON Logic rules.
3538
3542
  */
3539
- function resolveStringColumnLength(prop) {
3540
- const max = prop.validation?.max;
3541
- return typeof max === "number" && Number.isInteger(max) && max > 0 ? max : 255;
3542
- }
3543
3543
  //#endregion
3544
3544
  //#region ../../node_modules/.pnpm/fast-equals@6.0.2/node_modules/fast-equals/dist/es/index.mjs
3545
3545
  var { getOwnPropertyNames, getOwnPropertySymbols } = Object;
@@ -5447,1917 +5447,244 @@ function buildSdkData(driver) {
5447
5447
  return wrapAsSdkData(buildRebaseData(driver));
5448
5448
  }
5449
5449
  //#endregion
5450
- //#region src/schema/search-column.ts
5451
- /**
5452
- * The one place a collection's `search` block becomes SQL.
5453
- *
5454
- * Four things describe a Postgres table in this codebase — the DDL generator,
5455
- * the Drizzle schema generator, the runtime table builder for BaaS mode, and
5456
- * the boot-time schema ensure — and each of them has, at some point, described
5457
- * a column differently from the others. The `varchar(255)` note in
5458
- * `generate-postgres-ddl-logic` is one such scar: the same property produced a
5459
- * capped column down one path and an uncapped one down the other, and nothing
5460
- * failed until a user hit the cap.
5461
- *
5462
- * So the search column is not implemented four times. It is computed once,
5463
- * here, and every generator renders the same {@link SearchColumnSpec}. There is
5464
- * a test asserting exactly that (`search-column-contract.test.ts`); the point of
5465
- * this module is that the test has something to assert *about*.
5466
- *
5467
- * ## Why the expressions look the way they do
5468
- *
5469
- * A `GENERATED ALWAYS AS … STORED` expression must be strictly IMMUTABLE, and
5470
- * Postgres is stricter here than intuition. Verified against PostgreSQL 18:
5471
- *
5472
- * | expression | immutable |
5473
- * |-----------------------------------------|-----------|
5474
- * | `to_tsvector('spanish', col)` | yes |
5475
- * | `to_tsvector(col)` (1-arg) | **no** — depends on `default_text_search_config` |
5476
- * | `array_to_string(col, ' ')` | **no** |
5477
- * | `col::text` on `text[]` | **no** |
5478
- * | `to_jsonb(col)` | **no** |
5479
- * | `unaccent(col)` | **no** — dictionary lookup is STABLE |
5480
- * | `jsonb_to_tsvector('spanish', j, '["string"]')` | yes |
5481
- * | `setweight(...) || setweight(...)` | yes |
5482
- *
5483
- * Three of the four things a real search column needs are therefore unavailable
5484
- * directly, which is why {@link searchHelperFunctions} exists: each wraps a
5485
- * stable built-in in an SQL function declared IMMUTABLE. That declaration is a
5486
- * promise, and it is a true one for these three — array joining, JSON string
5487
- * extraction and accent folding are all deterministic for a given input; the
5488
- * built-ins are marked stable only because they must account for element types
5489
- * and dictionaries in general.
5490
- *
5491
- * The alternative was to skip `unaccent` and text arrays entirely. That is not
5492
- * a real option in an accented language: Postgres stems `auditoría` to
5493
- * `auditor` and `auditoria` to `auditori` — *different lexemes* — so a query
5494
- * typed without accents misses every row that carries them.
5495
- */
5496
- /** Schema-qualified so a collection outside `public` still resolves them. */
5497
- var HELPER_SCHEMA = "public";
5498
- /**
5499
- * Names of the helper functions. Frozen: they are recorded in the stored
5500
- * generation expression of every search column ever created, so renaming one
5501
- * orphans every table that already has a search column.
5502
- */
5503
- var SEARCH_TEXT_FN = `${HELPER_SCHEMA}.rebase_search_text`;
5504
- var SEARCH_UNACCENT_FN = `${HELPER_SCHEMA}.rebase_search_unaccent`;
5505
- /** Raised when a `search` block names something that cannot be searched. */
5506
- var SearchConfigError = class extends Error {
5507
- constructor(message) {
5508
- super(message);
5509
- this.name = "SearchConfigError";
5510
- }
5511
- };
5512
- /** The `search` block of a collection, or undefined when it has none. */
5513
- var getSearchConfig = (collection) => isPostgresCollectionConfig(collection) ? collection.search : void 0;
5450
+ //#region src/schema/collection-index.ts
5514
5451
  /**
5515
- * Refuse a `search` block on a collection this engine does not store.
5516
- *
5517
- * The type only permits one on a `PostgresCollectionConfig`, so TypeScript
5518
- * already stops the ordinary case. This catches the rest — a JS config, a cast,
5519
- * a collection whose `engine` was changed after the block was written — because
5520
- * the alternative is the exact failure the block exists to prevent: a developer
5521
- * who declared what to index, saw no error, and got the substring fallback.
5452
+ * A declaration that cannot become an index.
5522
5453
  *
5523
- * Called with *every* collection, before the Postgres ones are filtered out.
5454
+ * Thrown at build time, naming the collection and the array position, because
5455
+ * the alternative is a `CREATE INDEX` that fails during a push with a Postgres
5456
+ * error mentioning a column the author never wrote.
5524
5457
  */
5525
- var assertSearchIsPostgresOnly = (collections) => {
5526
- for (const collection of collections) {
5527
- if (isPostgresCollectionConfig(collection)) continue;
5528
- if (!collection.search) continue;
5529
- const engine = collection.engine ?? "non-postgres";
5530
- throw new SearchConfigError(`${collection.slug}.search: full-text search is a Postgres feature, and this collection is served by \`${engine}\`. Remove the block — it would otherwise look configured while \`.search()\` kept using the default substring match.`);
5458
+ var CollectionIndexConfigError = class extends Error {
5459
+ collectionSlug;
5460
+ position;
5461
+ constructor(collectionSlug, position, message) {
5462
+ super(`${collectionSlug}.indexes[${position}]: ${message}`);
5463
+ this.name = "CollectionIndexConfigError";
5464
+ this.collectionSlug = collectionSlug;
5465
+ this.position = position;
5531
5466
  }
5532
5467
  };
5533
- var columnNameOf = (propName, prop) => prop && "columnName" in prop && typeof prop.columnName === "string" ? prop.columnName : toSnakeCase(propName);
5534
5468
  /**
5535
- * Classify a property for search purposes.
5536
- *
5537
- * Deliberately narrower than `getSqlColumnType`: search only cares whether a
5538
- * value reaches text, and the mapping from property to *physical* type is
5539
- * asserted against `getSqlColumnType` in the contract test rather than
5540
- * duplicated here.
5541
- *
5542
- * Returns null for anything that is not text-bearing, which the caller turns
5543
- * into a boot error naming the property.
5544
- */
5545
- var classify = (prop) => {
5546
- switch (prop.type) {
5547
- case "string": {
5548
- const sp = prop;
5549
- if (sp.enum) return {
5550
- kind: "text",
5551
- reason: "enum"
5552
- };
5553
- if (sp.isId === "uuid" || sp.columnType === "uuid") return {
5554
- kind: "text",
5555
- reason: "uuid"
5556
- };
5557
- return { kind: "text" };
5558
- }
5559
- case "map":
5560
- if (prop.columnType === "json") return {
5561
- kind: "jsonb",
5562
- reason: "json"
5563
- };
5564
- return { kind: "jsonb" };
5565
- case "array": {
5566
- const ap = prop;
5567
- let colType = ap.columnType;
5568
- if (!colType && ap.of && !Array.isArray(ap.of)) {
5569
- const of = ap.of;
5570
- if (of.type === "string") colType = "text[]";
5571
- else if (of.type === "number") colType = of.validation?.integer ? "integer[]" : "numeric[]";
5572
- else if (of.type === "boolean") colType = "boolean[]";
5573
- }
5574
- if (colType === "text[]") return { kind: "text_array" };
5575
- if (colType === "json") return {
5576
- kind: "jsonb",
5577
- reason: "json"
5578
- };
5579
- if (colType === "integer[]" || colType === "boolean[]" || colType === "numeric[]") return {
5580
- kind: "text_array",
5581
- reason: "non_text_array"
5582
- };
5583
- return { kind: "jsonb" };
5584
- }
5585
- default: return null;
5586
- }
5587
- };
5588
- var normalize = (inner, unaccent) => unaccent ? `${SEARCH_UNACCENT_FN}(${inner})` : inner;
5589
- /** SQL reading one field as plain text, before normalization. */
5590
- var rawTextSql = (field) => {
5591
- const col = `"${field.column}"`;
5592
- if (field.kind === "text") return `coalesce(${col}, '')`;
5593
- if (field.kind === "text_array") return `${SEARCH_TEXT_FN}(coalesce(${col}, '{}'::text[]))`;
5594
- return `${SEARCH_TEXT_FN}(coalesce(${field.jsonPath.length === 0 ? col : field.jsonPath.length === 1 ? `${col} -> ${quote(field.jsonPath[0])}` : `${col} #> ${quote(`{${field.jsonPath.join(",")}}`)}`}, '{}'::jsonb))`;
5595
- };
5596
- var quote = (v) => `'${v.replace(/'/g, "''")}'`;
5597
- /**
5598
- * Resolve and validate one declared field path.
5599
- *
5600
- * A path that does not resolve throws. The whole point of an explicit block is
5601
- * that the author knows what is indexed; a silently dropped field would make it
5602
- * a guess again, and the failure — a search that returns nothing for content
5603
- * that is plainly in the row — is invisible from the outside.
5604
- */
5605
- var resolveField = (entry, collection, cfg) => {
5606
- const path = typeof entry === "string" ? entry : entry.path;
5607
- const weight = (typeof entry === "string" ? void 0 : entry.weight) ?? "B";
5608
- const where = `${collection.slug}.search`;
5609
- if (!path || typeof path !== "string") throw new SearchConfigError(`${where}: every entry in \`fields\` needs a property path.`);
5610
- const [head, ...rest] = path.split(".");
5611
- const prop = collection.properties?.[head];
5612
- if (!prop) throw new SearchConfigError(`${where}: "${path}" starts at property "${head}", which this collection does not declare. Known properties: ${Object.keys(collection.properties ?? {}).join(", ")}.`);
5613
- const classified = classify(prop);
5614
- if (!classified) throw new SearchConfigError(`${where}: "${path}" is a \`${prop.type}\` property, which holds no text to search. Searchable kinds are \`string\`, \`string[]\` and \`map\` (or a path inside one).`);
5615
- if (classified.reason === "enum") throw new SearchConfigError(`${where}: "${path}" is an enum. Enums are a fixed vocabulary — filter on them with \`where\` instead, which is exact and uses an index.`);
5616
- if (classified.reason === "uuid") throw new SearchConfigError(`${where}: "${path}" is a UUID column. Look it up by id rather than searching it.`);
5617
- if (classified.reason === "json") throw new SearchConfigError(`${where}: "${path}" is a \`json\` column, and the cast from \`json\` to \`jsonb\` is not immutable, so it cannot feed a generated column. Declare the property as \`jsonb\` (the default) to search it.`);
5618
- if (classified.reason === "non_text_array") throw new SearchConfigError(`${where}: "${path}" is an array of numbers or booleans. Only \`string[]\` carries text to search.`);
5619
- if (rest.length > 0 && classified.kind !== "jsonb") throw new SearchConfigError(`${where}: "${path}" addresses a path inside "${head}", but "${head}" is a \`${prop.type}\` property, not a \`map\`. Only map properties have paths inside them.`);
5620
- const column = columnNameOf(head, prop);
5621
- const textSql = normalize(rawTextSql({
5622
- column,
5623
- jsonPath: rest,
5624
- kind: classified.kind
5625
- }), cfg.unaccent === true);
5626
- const language = cfg.language ?? "simple";
5627
- return {
5628
- path,
5629
- column,
5630
- jsonPath: rest,
5631
- kind: classified.kind,
5632
- weight,
5633
- sql: `setweight(to_tsvector(${quote(language)}, ${textSql}), ${quote(weight)})`,
5634
- textSql
5635
- };
5636
- };
5637
- /**
5638
- * Build the full spec for a collection, or undefined when it has not opted in.
5639
- *
5640
- * Throws {@link SearchConfigError} on a config that cannot be honoured. Callers
5641
- * at boot surface that as a startup failure — a search block that half-works is
5642
- * worse than one that refuses.
5643
- */
5644
- var buildSearchColumnSpec = (collection) => {
5645
- const cfg = getSearchConfig(collection);
5646
- if (!cfg) return void 0;
5647
- if (!Array.isArray(cfg.fields) || cfg.fields.length === 0) throw new SearchConfigError(`${collection.slug}.search: \`fields\` is empty. Name the properties to index, or remove the \`search\` block to keep the default ILIKE behaviour.`);
5648
- const table = getTableName(collection);
5649
- const schema = isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : "public";
5650
- const column = cfg.column ?? "search_vector";
5651
- if (collection.properties?.[column]) throw new SearchConfigError(`${collection.slug}.search: the generated column "${column}" collides with a declared property of the same name. Set \`search.column\` to something else.`);
5652
- const fields = cfg.fields.map((entry) => resolveField(entry, collection, cfg));
5653
- const seen = /* @__PURE__ */ new Set();
5654
- for (const f of fields) {
5655
- if (seen.has(f.path)) throw new SearchConfigError(`${collection.slug}.search: "${f.path}" is listed twice.`);
5656
- seen.add(f.path);
5657
- }
5658
- const extensions = [];
5659
- if (cfg.unaccent) extensions.push("unaccent");
5660
- if (cfg.fuzzy) extensions.push("pg_trgm");
5661
- const spec = {
5662
- schema,
5663
- table,
5664
- column,
5665
- language: cfg.language ?? "simple",
5666
- unaccent: cfg.unaccent === true,
5667
- fields,
5668
- expression: fields.map((f) => f.sql).join(" || "),
5669
- indexName: toPostgresIdentifier(`${table}_${column}_gin`),
5670
- extensions
5671
- };
5672
- if (cfg.fuzzy) {
5673
- const fuzzyColumn = `${column}_text`;
5674
- if (collection.properties?.[fuzzyColumn]) throw new SearchConfigError(`${collection.slug}.search: \`fuzzy\` needs the column "${fuzzyColumn}", which collides with a declared property. Set \`search.column\` to something else.`);
5675
- spec.fuzzy = {
5676
- column: fuzzyColumn,
5677
- expression: fields.map((f) => f.textSql).join(" || ' ' || "),
5678
- indexName: toPostgresIdentifier(`${table}_${fuzzyColumn}_trgm`),
5679
- threshold: cfg.fuzzyThreshold ?? .3
5680
- };
5681
- }
5682
- return spec;
5469
+ * `_ix`/`_ux` plus `_` plus 7 hex — the part of the name that must always
5470
+ * survive truncation, and therefore is never inside the truncated portion.
5471
+ */
5472
+ var NAME_SUFFIX_BYTES = 11;
5473
+ var isOrderedMethod = (method) => method === "btree";
5474
+ /**
5475
+ * The parts of an index that decide what it *is*.
5476
+ *
5477
+ * A semantic projection, not the rendered statement — the same arrangement as
5478
+ * `getPolicyNameHash`, and for the same reason. A change to how this file
5479
+ * formats SQL (eliding a default `USING btree`, quoting differently, emitting
5480
+ * `NULLS LAST` explicitly) must not silently rename every index in every
5481
+ * deployed database. Hashing generator output would make every cosmetic edit a
5482
+ * fleet-wide DROP + CREATE.
5483
+ *
5484
+ * `reason` is deliberately absent: rewording a comment must not rebuild an
5485
+ * index. `nulls` is the *effective* placement, so writing Postgres's own
5486
+ * default down is a no-op rather than a redefinition.
5487
+ *
5488
+ * `v` is the only escape hatch, and it is expensive on purpose: bumping it
5489
+ * renames every index in the field.
5490
+ */
5491
+ var indexFingerprint = (spec) => sha1Hex(JSON.stringify({
5492
+ v: 1,
5493
+ s: spec.schema,
5494
+ t: spec.table,
5495
+ m: spec.method,
5496
+ u: spec.unique,
5497
+ k: spec.keys.map((k) => [
5498
+ k.column,
5499
+ k.direction,
5500
+ k.nulls
5501
+ ]),
5502
+ i: spec.include,
5503
+ w: spec.predicate
5504
+ })).substring(0, 7);
5505
+ /**
5506
+ * `<table>_<columns>_ix_<hash>`, or `_ux_` when unique.
5507
+ *
5508
+ * Truncation eats the readable head and never the hash. `toPostgresIdentifier`
5509
+ * truncates the whole string at 63 bytes, which on a hashed name would cut off
5510
+ * the one part that makes it unique — the failure already frozen into
5511
+ * `contracts/derived-names.txt`, where a foreign key is recorded with its
5512
+ * `_fkey` suffix truncated away, so a second foreign key on that table would
5513
+ * derive a byte-identical name.
5514
+ */
5515
+ var deriveIndexName = (spec) => {
5516
+ const suffix = `_${spec.unique ? "ux" : "ix"}_${indexFingerprint(spec)}`;
5517
+ return `${truncateToBytes(`${spec.table}_${spec.keys.map((k) => k.column).join("_")}`, 63 - NAME_SUFFIX_BYTES)}${suffix}`;
5683
5518
  };
5684
- /**
5685
- * The IMMUTABLE wrappers the generated expressions call.
5686
- *
5687
- * `CREATE OR REPLACE` so a boot against an existing database is a no-op rather
5688
- * than an error, and idempotent for the same reason every other boot-time DDL
5689
- * statement here is.
5690
- *
5691
- * The bodies are stable built-ins wrapped in an immutable promise — see the
5692
- * module comment for why that promise is sound. `STRICT` matters: it makes NULL
5693
- * in mean NULL out without executing the body, which is what the `coalesce` at
5694
- * each call site then absorbs.
5695
- */
5696
- var searchHelperFunctions = (spec) => {
5697
- const statements = [`CREATE OR REPLACE FUNCTION ${SEARCH_TEXT_FN}(text[]) RETURNS text\n LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE AS\n $$ SELECT array_to_string($1, ' ') $$;`, `CREATE OR REPLACE FUNCTION ${SEARCH_TEXT_FN}(jsonb) RETURNS text\n LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE AS\n $$ SELECT coalesce(string_agg(v, ' '), '')\n FROM jsonb_array_elements_text(jsonb_path_query_array($1, 'strict $.**?(@.type() == "string")')) AS v $$;`];
5698
- if (spec.unaccent) statements.push(`CREATE OR REPLACE FUNCTION ${SEARCH_UNACCENT_FN}(text) RETURNS text\n LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE AS\n $$ SELECT ${HELPER_SCHEMA}.unaccent('${HELPER_SCHEMA}.unaccent'::regdictionary, $1) $$;`);
5699
- return statements;
5700
- };
5701
- /**
5702
- * `CREATE EXTENSION` statements the spec's expressions depend on.
5703
- *
5704
- * `WITH SCHEMA public` is load-bearing, not tidiness. An unqualified
5705
- * `CREATE EXTENSION` installs into the first schema on `search_path`, which
5706
- * defaults to `"$user", public` — and the scaffold's database role is named
5707
- * `rebase`, the same as the schema the generator creates one statement earlier.
5708
- * So the moment that schema exists, `CREATE EXTENSION unaccent` puts the
5709
- * dictionary in `rebase`, and every reference to `public.unaccent` below fails
5710
- * with "text search dictionary does not exist". Observed, not theorised.
5711
- */
5712
- var searchExtensionStatements = (spec) => spec.extensions.map((e) => `CREATE EXTENSION IF NOT EXISTS ${e} WITH SCHEMA ${HELPER_SCHEMA};`);
5713
- /** The column definition as it appears inside `CREATE TABLE`. */
5714
- var searchColumnDefinition = (spec) => `"${spec.column}" tsvector GENERATED ALWAYS AS (${spec.expression}) STORED`;
5715
- /** The fuzzy column definition, when the spec asks for one. */
5716
- var fuzzyColumnDefinition = (spec) => spec.fuzzy ? `"${spec.fuzzy.column}" text GENERATED ALWAYS AS (${spec.fuzzy.expression}) STORED` : void 0;
5717
- /**
5718
- * Index statements for the spec.
5719
- *
5720
- * `CONCURRENTLY` is deliberately *not* used here. This form is emitted into a
5721
- * SQL file replayed as one unit — a migration, or `search.sql` — where a
5722
- * concurrent build is not allowed. The boot-time ensure path runs statement by
5723
- * statement against tables that are live and populated, and uses the
5724
- * concurrent form instead; see `ensureSearchColumns`.
5725
- */
5726
- var searchIndexStatements = (spec) => {
5727
- const statements = [`CREATE INDEX IF NOT EXISTS "${spec.indexName}" ON "${spec.schema}"."${spec.table}" USING GIN ("${spec.column}");`];
5728
- if (spec.fuzzy) statements.push(`CREATE INDEX IF NOT EXISTS "${spec.fuzzy.indexName}" ON "${spec.schema}"."${spec.table}" USING GIN ("${spec.fuzzy.column}" ${HELPER_SCHEMA}.gin_trgm_ops);`);
5729
- return statements;
5730
- };
5731
- /**
5732
- * Marker on the comment of every generated search column this module creates.
5733
- *
5734
- * Versioned because the fingerprint below is only comparable against itself: a
5735
- * future change to how it is computed has to read as "not stamped by this
5736
- * version" rather than as drift on every existing column.
5737
- */
5738
- var SEARCH_STAMP_PREFIX = "rebase:search:v1:";
5739
- /**
5740
- * A stable fingerprint of one generated column's expression.
5741
- *
5742
- * Why a stamp rather than reading the expression back: Postgres stores a
5743
- * generated column's expression *parsed*, and hands it back deparsed — casts
5744
- * made explicit, identifiers requoted, schema qualifications added or dropped
5745
- * according to `search_path`. Comparing that text to the text we generated
5746
- * would report drift on wording, and this comparison decides whether a boot
5747
- * refuses, so a false positive is an outage. The stamp is written by the same
5748
- * code that writes the column, so equality means what it says.
5749
- */
5750
- var searchExpressionFingerprint = (expression) => `${SEARCH_STAMP_PREFIX}${createHash("sha256").update(expression).digest("hex").slice(0, 16)}`;
5751
- /**
5752
- * The stamps for a spec's generated columns — one per column, never shared.
5753
- *
5754
- * Per column on purpose: turning `fuzzy` on adds a second column and changes
5755
- * nothing about the first, and a spec-wide fingerprint would report the
5756
- * untouched `tsvector` column as drifted and refuse a boot over a change that
5757
- * is purely additive.
5758
- */
5759
- var searchColumnStamps = (spec) => {
5760
- const stamp = (column, expression) => {
5761
- const fingerprint = searchExpressionFingerprint(expression);
5762
- return {
5763
- column,
5764
- expression,
5765
- fingerprint,
5766
- sql: `COMMENT ON COLUMN "${spec.schema}"."${spec.table}"."${column}" IS ${quote(fingerprint)};`
5767
- };
5768
- };
5769
- const stamps = [stamp(spec.column, spec.expression)];
5770
- if (spec.fuzzy) stamps.push(stamp(spec.fuzzy.column, spec.fuzzy.expression));
5771
- return stamps;
5519
+ var quoteLiteral = (value) => {
5520
+ if (typeof value === "number") return String(value);
5521
+ if (typeof value === "boolean") return value ? "TRUE" : "FALSE";
5522
+ return `'${value.replace(/'/g, "''")}'`;
5772
5523
  };
5773
- /**
5774
- * The same drift check as the boot ensure, for the SQL file.
5775
- *
5776
- * Needed because {@link searchColumnStamps} would otherwise *launder* drift on
5777
- * the migration path: `ADD COLUMN IF NOT EXISTS` does nothing to a column that
5778
- * exists, so a re-generated `search.sql` would stamp a stale column with the
5779
- * new block's fingerprint and the next boot would find them in agreement.
5780
- * Guarding first means the file refuses instead — `rebase db push` is attended,
5781
- * and the operator reading the failure is the person who changed the block.
5782
- */
5783
- var searchStampGuards = (spec) => searchColumnStamps(spec).map((stamp) => {
5784
- const relation = quote(`"${spec.schema}"."${spec.table}"`);
5785
- return `DO $rebase_search$
5786
- DECLARE recorded text;
5787
- BEGIN
5788
- SELECT col_description(a.attrelid, a.attnum) INTO recorded
5789
- FROM pg_attribute a
5790
- WHERE a.attrelid = ${relation}::regclass AND a.attname = ${quote(stamp.column)} AND NOT a.attisdropped;
5791
- IF recorded LIKE ${quote(`${SEARCH_STAMP_PREFIX}%`)} AND recorded <> ${quote(stamp.fingerprint)} THEN
5792
- RAISE EXCEPTION 'Rebase: the search block for ${spec.schema}.${spec.table} changed after the generated column "${stamp.column}" was built (recorded %, expected ${stamp.fingerprint}). Postgres cannot alter a generated expression in place. Drop the column and re-apply this file — it rewrites the table and rebuilds the index: ALTER TABLE ${relation.slice(1, -1)} DROP COLUMN "${stamp.column}";', recorded;
5793
- END IF;
5794
- END
5795
- $rebase_search$;`;
5796
- });
5797
- /**
5798
- * The generated column names a collection's search block adds, if any.
5799
- *
5800
- * These are physical columns on the table, so `SELECT *` returns them. They are
5801
- * an index in column form — a list of lexeme positions, or a concatenation of
5802
- * every searchable field on the row — and nothing outside the query planner has
5803
- * any use for them. Left in, every list response carries a second, larger copy
5804
- * of the row's text.
5805
- */
5806
- var searchColumnNames = (collection) => {
5807
- let spec;
5808
- try {
5809
- spec = buildSearchColumnSpec(collection);
5810
- } catch {
5811
- return [];
5524
+ /** Render a resolved predicate as the body of a `WHERE` clause. */
5525
+ var renderPredicate = (predicate) => {
5526
+ if ("and" in predicate) return predicate.and.map(renderPredicate).join(" AND ");
5527
+ switch (predicate.op) {
5528
+ case "is null":
5529
+ case "is not null": return `"${predicate.column}" ${predicate.op.toUpperCase()}`;
5530
+ case "in": return `"${predicate.column}" IN (${predicate.value.map(quoteLiteral).join(", ")})`;
5531
+ default: return `"${predicate.column}" ${predicate.op} ${quoteLiteral(predicate.value)}`;
5812
5532
  }
5813
- if (!spec) return [];
5814
- return spec.fuzzy ? [spec.column, spec.fuzzy.column] : [spec.column];
5815
- };
5816
- /**
5817
- * True for a column whose type only ever holds a search index.
5818
- *
5819
- * Independent of any collection config on purpose: an introspected database
5820
- * (BaaS mode) can carry a `tsvector` column this framework never created —
5821
- * Pagila's `film.fulltext` is the canonical one — and it should not be returned
5822
- * to callers either. `isDerivedIndexColumn` already keeps such a column out of
5823
- * the *properties*; this keeps it out of the *rows*.
5824
- */
5825
- var isSearchIndexColumn = (column) => {
5826
- const sqlType = typeof column?.getSQLType === "function" ? column.getSQLType().toLowerCase() : "";
5827
- return sqlType === "tsvector" || sqlType === "tsquery";
5828
- };
5829
- /**
5830
- * A drizzle select projection over `table` with the search columns dropped.
5831
- *
5832
- * Returns undefined when nothing needs dropping, so the common case keeps using
5833
- * a plain `select()` and this stays invisible in the generated SQL.
5834
- */
5835
- var visibleColumnProjection = (tableColumns, collection) => {
5836
- const excluded = excludedColumnNames(tableColumns, collection);
5837
- if (!tableColumns || excluded.length === 0) return void 0;
5838
- const projection = {};
5839
- for (const [name, column] of Object.entries(tableColumns)) if (!excluded.includes(name)) projection[name] = column;
5840
- return projection;
5841
- };
5842
- /** The same exclusion as a drizzle `db.query` `columns` denylist. */
5843
- var hiddenColumnsOption = (tableColumns, collection) => {
5844
- const excluded = excludedColumnNames(tableColumns, collection);
5845
- if (excluded.length === 0) return void 0;
5846
- return Object.fromEntries(excluded.map((name) => [name, false]));
5847
5533
  };
5848
5534
  /**
5849
- * The columns to keep out of a response, by name.
5535
+ * The `CREATE INDEX` for one spec.
5850
5536
  *
5851
- * `tableColumns` is whatever `getTableColumns` returned, which is `undefined`
5852
- * for anything that is not a real drizzle table — a stub in a test, a derived
5853
- * or nested path with no table behind it. Nothing to exclude is the right
5854
- * answer there, and it has to be an answer rather than a throw: this runs on
5855
- * the read path of every collection, opted in or not.
5856
- */
5857
- var excludedColumnNames = (tableColumns, collection) => {
5858
- if (!tableColumns || typeof tableColumns !== "object") return [];
5859
- const byName = new Set(collection ? searchColumnNames(collection) : []);
5860
- return Object.keys(tableColumns).filter((name) => byName.has(name) || isSearchIndexColumn(tableColumns[name]));
5537
+ * `concurrently` is a parameter rather than a string replacement on the way
5538
+ * out. `search-column.ts` and `vector-index.ts` both reach for
5539
+ * `.replace("CREATE INDEX IF NOT EXISTS", …)` instead, which silently does
5540
+ * nothing for a UNIQUE index the rendered text is `CREATE UNIQUE INDEX …`
5541
+ * and the pattern never matches.
5542
+ */
5543
+ var collectionIndexStatement = (spec, options = {}) => {
5544
+ const unique = spec.unique ? "UNIQUE " : "";
5545
+ const concurrently = options.concurrently ? "CONCURRENTLY " : "";
5546
+ const ifNotExists = options.ifNotExists ? "IF NOT EXISTS " : "";
5547
+ const using = spec.method === "btree" ? "" : ` USING ${spec.method}`;
5548
+ const keys = spec.keys.map((k) => {
5549
+ if (!isOrderedMethod(spec.method)) return `"${k.column}"`;
5550
+ const direction = k.direction === "desc" ? " DESC" : "";
5551
+ const impliedNulls = k.direction === "desc" ? "first" : "last";
5552
+ const nulls = k.nulls === impliedNulls ? "" : ` NULLS ${k.nulls.toUpperCase()}`;
5553
+ return `"${k.column}"${direction}${nulls}`;
5554
+ }).join(", ");
5555
+ const include = spec.include.length > 0 ? ` INCLUDE (${spec.include.map((c) => `"${c}"`).join(", ")})` : "";
5556
+ const where = spec.predicate ? ` WHERE ${renderPredicate(spec.predicate)}` : "";
5557
+ return `CREATE ${unique}INDEX ${concurrently}${ifNotExists}"${spec.indexName}" ON "${spec.schema}"."${spec.table}"${using} (${keys})${include}${where};`;
5861
5558
  };
5862
- //#endregion
5863
- //#region src/schema/auth-users-columns.ts
5864
- /**
5865
- * `email` is NOT NULL on purpose, and the anonymous sign-in route depends on it
5866
- * — it synthesizes `anon_<32 hex>@anonymous.local` rather than inserting NULL.
5867
- * The 320-char bound (RFC 5321) is a CHECK rather than a `VARCHAR(n)`, added
5868
- * separately by `ensureAuthTablesExist` so it can be `NOT VALID` on an adopted
5869
- * table that already holds a longer row.
5870
- */
5871
- var AUTH_USERS_COLUMNS = [
5872
- {
5873
- column: "email",
5874
- type: "TEXT",
5875
- notNull: true
5876
- },
5877
- {
5878
- column: "display_name",
5879
- type: "TEXT"
5880
- },
5881
- {
5882
- column: "photo_url",
5883
- type: "TEXT"
5884
- },
5885
- {
5886
- column: "roles",
5887
- type: "TEXT[]",
5888
- default: "'{}'",
5889
- notNull: true
5890
- },
5891
- {
5892
- column: "password_hash",
5893
- type: "TEXT"
5894
- },
5895
- {
5896
- column: "email_verified",
5897
- type: "BOOLEAN",
5898
- default: "FALSE",
5899
- notNull: true
5900
- },
5901
- {
5902
- column: "email_verification_token",
5903
- type: "TEXT"
5904
- },
5905
- {
5906
- column: "email_verification_sent_at",
5907
- type: "TIMESTAMP WITH TIME ZONE"
5908
- },
5909
- {
5910
- column: "is_anonymous",
5911
- type: "BOOLEAN",
5912
- default: "FALSE",
5913
- notNull: true
5914
- },
5915
- {
5916
- column: "metadata",
5917
- type: "JSONB",
5918
- default: "'{}'",
5919
- notNull: true
5920
- },
5921
- {
5922
- column: "tokens_valid_after",
5923
- type: "TIMESTAMP WITH TIME ZONE"
5924
- },
5925
- {
5926
- column: "created_at",
5927
- type: "TIMESTAMP WITH TIME ZONE",
5928
- default: "NOW()",
5929
- notNull: true
5930
- },
5931
- {
5932
- column: "updated_at",
5933
- type: "TIMESTAMP WITH TIME ZONE",
5934
- default: "NOW()",
5935
- notNull: true
5936
- }
5937
- ];
5938
- var BY_COLUMN = new Map(AUTH_USERS_COLUMNS.map((c) => [c.column, c]));
5939
- /** Type + inline constraints, as they appear after the column name. */
5940
- function authUsersColumnSql(spec) {
5941
- return [
5942
- spec.type,
5943
- spec.default !== void 0 ? `DEFAULT ${spec.default}` : "",
5944
- spec.notNull ? "NOT NULL" : ""
5945
- ].filter(Boolean).join(" ");
5946
- }
5559
+ var collectionIndexStatements = (specs, options = {}) => specs.map((spec) => collectionIndexStatement(spec, options));
5560
+ var relationOf = (collection, propKey) => resolveCollectionRelations(collection)[propKey];
5947
5561
  /**
5948
- * The auth-owned definition for a physical column name, or `undefined` when
5949
- * auth does not own it.
5562
+ * The column a property key indexes.
5950
5563
  *
5951
- * Callers pass the RESOLVED column name (after `columnName` mapping), because
5952
- * that is the only name the three creators agree on: the scaffold's users
5953
- * collection spells the property `displayName` and the column `display_name`.
5954
- */
5955
- function authUsersColumnDefinition(column) {
5956
- const spec = BY_COLUMN.get(column);
5957
- return spec ? authUsersColumnSql(spec) : void 0;
5958
- }
5959
- /**
5960
- * Whether a collection is an auth collection, i.e. whether the definitions in
5961
- * this module apply to its table at all.
5564
+ * A `belongsTo` resolves to its `localKey` `primaryCategory` becomes
5565
+ * `primary_category_id` — which is the case an index is most often wanted for
5566
+ * and the case where the property key and the column differ. Everything else
5567
+ * goes through `resolveColumnName`.
5962
5568
  *
5963
- * Duplicated in shape from `@rebasepro/common`'s policy defaults on purpose:
5964
- * that one takes a `CollectionConfig`, this one is called from DDL code paths
5965
- * that hold looser objects, and both spellings must accept `auth: true` as well
5966
- * as `auth: { enabled: true }`.
5967
- */
5968
- function isAuthCollection(collection) {
5969
- const auth = collection?.auth;
5970
- if (auth === true) return true;
5971
- return typeof auth === "object" && auth !== null && auth.enabled === true;
5972
- }
5973
- //#endregion
5974
- //#region src/schema/vector-index.ts
5975
- /**
5976
- * The widest `vector` pgvector will build an HNSW or IVFFlat index over.
5977
- * Storage and exact search are unaffected by this limit.
5978
- */
5979
- var MAX_INDEXABLE_VECTOR_DIMENSIONS = 2e3;
5980
- /**
5981
- * Operator class per distance. These strings are part of the database contract:
5982
- * they appear in `CREATE INDEX`, so renaming one renames an index.
5569
+ * The other relation kinds have no local column at all: the foreign key lives
5570
+ * on the target's table, or in a junction. Indexing them here is refused
5571
+ * rather than resolved to a column that does not exist.
5983
5572
  */
5984
- var OPERATOR_CLASS = {
5985
- cosine: "vector_cosine_ops",
5986
- l2: "vector_l2_ops",
5987
- inner_product: "vector_ip_ops"
5988
- };
5989
- /** Short, stable tag per distance, used to name the index. */
5990
- var DISTANCE_TAG = {
5991
- cosine: "cosine",
5992
- l2: "l2",
5993
- inner_product: "ip"
5994
- };
5995
- var VectorIndexConfigError = class extends Error {
5996
- constructor(message) {
5997
- super(message);
5998
- this.name = "VectorIndexConfigError";
5573
+ var resolveIndexableColumn = (collection, propKey, resolveColumnName, fail) => {
5574
+ const relation = relationOf(collection, propKey);
5575
+ if (relation) {
5576
+ if (relation.kind === "belongsTo") return relation.localKey;
5577
+ fail(`"${propKey}" is a ${relation.kind} relation, which has no column on this table — the foreign key lives on "${relation.targetSlug}". Declare the index there.`);
5999
5578
  }
5579
+ const property = collection.properties?.[propKey];
5580
+ if (!property) fail(`"${propKey}" is not a property of this collection.`);
5581
+ return resolveColumnName(propKey, property);
6000
5582
  };
6001
- var isVectorProperty = (prop) => !!prop && typeof prop === "object" && prop.type === "vector";
6002
- var asDistances = (config, label) => {
6003
- const raw = config.distance ?? "cosine";
6004
- const list = Array.isArray(raw) ? raw : [raw];
6005
- if (list.length === 0) throw new VectorIndexConfigError(`${label}: \`index.distance\` is an empty array. Name at least one distance, or set \`index: false\` to create no index.`);
6006
- const seen = /* @__PURE__ */ new Set();
6007
- for (const distance of list) {
6008
- if (!(distance in OPERATOR_CLASS)) throw new VectorIndexConfigError(`${label}: \`index.distance\` is "${distance}", which is not a pgvector distance. Use ${Object.keys(OPERATOR_CLASS).map((d) => `"${d}"`).join(", ")}.`);
6009
- if (seen.has(distance)) throw new VectorIndexConfigError(`${label}: \`index.distance\` lists "${distance}" twice.`);
6010
- seen.add(distance);
6011
- }
6012
- return list;
6013
- };
6014
- var assertPositiveInteger = (value, key, label) => {
6015
- if (value === void 0) return;
6016
- if (!Number.isInteger(value) || value <= 0) throw new VectorIndexConfigError(`${label}: \`index.${key}\` is ${JSON.stringify(value)}. It must be a positive integer.`);
6017
- };
6018
- /**
6019
- * Index parameters for one method. Parameters belonging to the *other* method
6020
- * are rejected rather than ignored, because a silently dropped `lists` on an
6021
- * HNSW index reads, from the config, exactly like a tuned index.
6022
- */
6023
- var parametersFor = (method, config, label) => {
6024
- assertPositiveInteger(config.m, "m", label);
6025
- assertPositiveInteger(config.efConstruction, "efConstruction", label);
6026
- assertPositiveInteger(config.lists, "lists", label);
6027
- if (method === "hnsw") {
6028
- if (config.lists !== void 0) throw new VectorIndexConfigError(`${label}: \`index.lists\` only applies to \`method: "ivfflat"\`. Remove it, or switch the method.`);
6029
- const params = [];
6030
- if (config.m !== void 0) params.push(["m", config.m]);
6031
- if (config.efConstruction !== void 0) params.push(["ef_construction", config.efConstruction]);
6032
- return params;
6033
- }
6034
- for (const key of ["m", "efConstruction"]) if (config[key] !== void 0) throw new VectorIndexConfigError(`${label}: \`index.${key}\` only applies to \`method: "hnsw"\`. Remove it, or switch the method.`);
6035
- return config.lists !== void 0 ? [["lists", config.lists]] : [];
6036
- };
6037
- /**
6038
- * Every ANN index a collection's vector properties call for.
6039
- *
6040
- * `resolveColumn` is passed in rather than imported so that this module stays
6041
- * free of the DDL generator, which imports *it*. Both callers hand it the same
6042
- * `resolveColumnName`, and a contract test asserts the names agree.
6043
- */
6044
- var buildVectorIndexPlan = (collection, resolveColumn) => {
6045
- const specs = [];
6046
- const skipped = [];
6047
- const properties = collection.properties ?? {};
6048
- const table = getTableName(collection);
6049
- const schema = isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : "public";
6050
- for (const [propName, prop] of Object.entries(properties)) {
6051
- if (!isVectorProperty(prop)) continue;
6052
- if (prop.index === false) continue;
6053
- const label = `${collection.slug}.${propName}`;
6054
- const column = resolveColumn(propName, prop);
6055
- const config = prop.index ?? {};
6056
- const method = config.method ?? "hnsw";
6057
- if (method !== "hnsw" && method !== "ivfflat") throw new VectorIndexConfigError(`${label}: \`index.method\` is "${method}". Use "hnsw" or "ivfflat".`);
6058
- const distances = asDistances(config, label);
6059
- const parameters = parametersFor(method, config, label);
6060
- if (!Number.isInteger(prop.dimensions) || prop.dimensions <= 0) throw new VectorIndexConfigError(`${label}: \`dimensions\` is ${JSON.stringify(prop.dimensions)}. It must be a positive integer.`);
6061
- if (prop.dimensions > 2e3) {
6062
- skipped.push({
6063
- schema,
6064
- table,
6065
- column,
6066
- dimensions: prop.dimensions,
6067
- reason: `pgvector cannot index a vector wider than ${MAX_INDEXABLE_VECTOR_DIMENSIONS} dimensions, and ${label} declares ${prop.dimensions}. The column works and \`vectorSearch\` still answers, as an exact scan. To index it, reduce the dimensions (many embedding models support a shorter output) or set \`index: false\` to state that the scan is intended.`
6068
- });
6069
- continue;
6070
- }
6071
- for (const distance of distances) specs.push({
6072
- schema,
6073
- table,
5583
+ var resolvePredicate = (collection, predicate, resolveColumnName, fail) => {
5584
+ if ("and" in predicate) return { and: predicate.and.map((p) => resolvePredicate(collection, p, resolveColumnName, fail)) };
5585
+ const column = resolveIndexableColumn(collection, predicate.prop, resolveColumnName, fail);
5586
+ switch (predicate.op) {
5587
+ case "is null":
5588
+ case "is not null": return {
6074
5589
  column,
6075
- indexName: toPostgresIdentifier(`${table}_${column}_${method}_${DISTANCE_TAG[distance]}`),
6076
- method,
6077
- distance,
6078
- operatorClass: OPERATOR_CLASS[distance],
6079
- parameters
6080
- });
6081
- }
6082
- return {
6083
- specs,
6084
- skipped
6085
- };
6086
- };
6087
- /**
6088
- * The `CREATE INDEX` for one spec.
6089
- *
6090
- * `CONCURRENTLY` is deliberately absent, for the same reason it is absent from
6091
- * `searchIndexStatements`: this form is replayed as part of a migration, where
6092
- * a concurrent build is not allowed. The boot-time ensure rewrites it — see
6093
- * `ensureCollectionTables`.
6094
- */
6095
- var vectorIndexStatement = (spec) => {
6096
- const params = spec.parameters.length ? ` WITH (${spec.parameters.map(([key, value]) => `${key} = ${value}`).join(", ")})` : "";
6097
- return `CREATE INDEX IF NOT EXISTS "${spec.indexName}" ON "${spec.schema}"."${spec.table}" USING ${spec.method} ("${spec.column}" ${spec.operatorClass})${params};`;
6098
- };
6099
- /** Every statement for a plan, in a stable order. */
6100
- var vectorIndexStatements = (plan) => plan.specs.map(vectorIndexStatement);
6101
- //#endregion
6102
- //#region src/schema/generate-postgres-ddl-logic.ts
6103
- var resolveColumnName = (propName, prop) => {
6104
- if (prop && "columnName" in prop && typeof prop.columnName === "string") return prop.columnName;
6105
- return toSnakeCase(propName);
6106
- };
6107
- var getPrimaryKeyProp = (collection) => {
6108
- if (collection.properties) {
6109
- const idPropEntry = Object.entries(collection.properties).find(([_, prop]) => "isId" in prop && Boolean(prop.isId));
6110
- if (idPropEntry) {
6111
- const prop = idPropEntry[1];
6112
- const isUuid = prop.type === "string" && "isId" in prop && prop.isId === "uuid";
5590
+ op: predicate.op
5591
+ };
5592
+ case "in":
5593
+ if (new Set(predicate.value).size !== predicate.value.length) fail(`the \`in\` list for "${predicate.prop}" repeats a value, which changes nothing.`);
6113
5594
  return {
6114
- name: idPropEntry[0],
6115
- type: prop.type === "number" ? "number" : "string",
6116
- isUuid
5595
+ column,
5596
+ op: "in",
5597
+ value: [...predicate.value]
6117
5598
  };
6118
- }
6119
- }
6120
- const idProp = collection.properties?.["id"];
6121
- if (idProp?.type === "number") return {
6122
- name: "id",
6123
- type: "number",
6124
- isUuid: false
6125
- };
6126
- return {
6127
- name: "id",
6128
- type: "string",
6129
- isUuid: idProp?.type === "string" && "isId" in idProp && idProp.isId === "uuid"
6130
- };
6131
- };
6132
- var isNumericId = (collection) => {
6133
- return getPrimaryKeyProp(collection).type === "number";
6134
- };
6135
- var getPrimaryKeyName = (collection) => {
6136
- return getPrimaryKeyProp(collection).name;
6137
- };
6138
- /** The column type a junction holds for one endpoint's primary key. */
6139
- var junctionKeyType = (collection) => isNumericId(collection) ? "INTEGER" : getPrimaryKeyProp(collection).isUuid ? "UUID" : "TEXT";
6140
- var isIdProperty = (propName, prop, collection) => {
6141
- if ("isId" in prop && Boolean(prop.isId)) return true;
6142
- return !Object.values(collection.properties ?? {}).some((p) => "isId" in p && Boolean(p.isId)) && propName === "id";
6143
- };
6144
- /**
6145
- * Render statements produced by {@link generatePolicyStatements} back into the
6146
- * exact string the DDL/policies files have always carried: each statement on
6147
- * its own line, terminated by a newline. Keeping the string form derived from
6148
- * the statement array means the two can never drift — the boot-time applier and
6149
- * the generated `policies.sql` emit the same SQL, from the same source.
6150
- */
6151
- var statementsToDdl = (statements) => statements.map((s) => `${s}\n`).join("");
6152
- var generatePolicyDdl = (collection, rule, resolveCollection) => statementsToDdl(generatePolicyStatements(collection, rule, resolveCollection));
6153
- /**
6154
- * The individual SQL statements a single security rule compiles to: a
6155
- * `DROP POLICY IF EXISTS` / `CREATE POLICY` pair per operation, each a complete
6156
- * statement (terminated by `;`, no trailing newline).
6157
- *
6158
- * This is the primitive the boot-time RLS applier runs one statement at a time
6159
- * (the runtime's DB handle speaks the extended query protocol, which forbids
6160
- * multiple commands in one execute), while `db push` writes the joined string.
6161
- */
6162
- var generatePolicyStatements = (collection, rule, resolveCollection) => {
6163
- const tableName = getTableName(collection);
6164
- const ops = rule.operations && rule.operations.length > 0 ? rule.operations : [rule.operation ?? "all"];
6165
- const policyNames = getPolicyNamesForRule(rule, tableName);
6166
- return ops.flatMap((op, opIdx) => {
6167
- return generateSinglePolicyStatements(collection, rule, op, policyNames[opIdx], resolveCollection);
6168
- });
6169
- };
6170
- var generateSinglePolicyStatements = (collection, rule, operation, policyName, resolveCollection) => {
6171
- const schema = isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : "public";
6172
- const tableName = getTableName(collection);
6173
- const mode = (rule.mode ?? "permissive").toUpperCase();
6174
- const operationUpper = operation.toUpperCase();
6175
- const pgRoles = rule.pgRoles ? [...rule.pgRoles].sort() : ["public"];
6176
- const needsUsing = operation !== "insert";
6177
- const needsWithCheck = operation !== "select" && operation !== "delete";
6178
- const { usingExpr, withCheckExpr } = securityRuleToConditions(rule);
6179
- let usingClause = needsUsing && usingExpr ? policyToPostgres(usingExpr, collection, { resolveCollection }) : null;
6180
- let withCheckClause = needsWithCheck && withCheckExpr ? policyToPostgres(withCheckExpr, collection, { resolveCollection }) : null;
6181
- if (!usingClause && needsUsing) usingClause = "false";
6182
- if (!withCheckClause && needsWithCheck) withCheckClause = "false";
6183
- const drop = `DROP POLICY IF EXISTS "${policyName}" ON "${schema}"."${tableName}";`;
6184
- let create = `CREATE POLICY "${policyName}" ON "${schema}"."${tableName}" AS ${mode} FOR ${operationUpper} TO ${pgRoles.map((r) => `"${r}"`).join(", ")}`;
6185
- if (usingClause) create += ` USING (${usingClause})`;
6186
- if (withCheckClause) create += ` WITH CHECK (${withCheckClause})`;
6187
- create += ";";
6188
- return [drop, create];
6189
- };
6190
- /**
6191
- * Single-quote escaping for a SQL string literal (PostgreSQL doubles the
6192
- * quote). Enum labels come straight from user-authored collection config, so a
6193
- * label like `it's` closes the literal early and the whole generated file stops
6194
- * parsing at the `CREATE TYPE`. Lives here rather than next to its other caller
6195
- * because ensure-collection-tables already imports from this module — the
6196
- * reverse would be a cycle.
6197
- */
6198
- var quoteSqlLiteral = (value) => `'${value.replace(/'/g, "''")}'`;
6199
- var getSqlColumnType = (propName, prop, collection, collections) => {
6200
- switch (prop.type) {
6201
- case "string": {
6202
- const stringProp = prop;
6203
- if (stringProp.enum) {
6204
- const tableName = getTableName(collection);
6205
- const colName = resolveColumnName(propName, prop);
6206
- return `"${isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : "public"}"."${tableName}_${colName}"`;
6207
- }
6208
- if (stringProp.isId === "uuid" || stringProp.columnType === "uuid") return "UUID";
6209
- if (stringProp.columnType === "char") return `CHAR(${resolveStringColumnLength(stringProp)})`;
6210
- if (stringProp.columnType === "varchar") return `VARCHAR(${resolveStringColumnLength(stringProp)})`;
6211
- return "TEXT";
6212
- }
6213
- case "number": {
6214
- const numProp = prop;
6215
- const isId = isIdProperty(propName, prop, collection);
6216
- if ("isId" in numProp && numProp.isId === "increment") return "INTEGER GENERATED BY DEFAULT AS IDENTITY";
6217
- if (numProp.columnType) {
6218
- if (numProp.columnType === "double precision") return "DOUBLE PRECISION";
6219
- return numProp.columnType.toUpperCase();
6220
- }
6221
- return numProp.validation?.integer || isId ? "INTEGER" : "NUMERIC";
6222
- }
6223
- case "boolean": return "BOOLEAN";
6224
- case "date": {
6225
- const dateProp = prop;
6226
- if (dateProp.columnType === "date") return "DATE";
6227
- if (dateProp.columnType === "time") return "TIME";
6228
- return "TIMESTAMP WITH TIME ZONE";
6229
- }
6230
- case "map": return prop.columnType === "json" ? "JSON" : "JSONB";
6231
- case "geopoint": return "JSONB";
6232
- case "array": {
6233
- const arrayProp = prop;
6234
- let colType = arrayProp.columnType;
6235
- if (!colType && arrayProp.of && !Array.isArray(arrayProp.of)) {
6236
- const ofProp = arrayProp.of;
6237
- if (ofProp.type === "string") colType = "text[]";
6238
- else if (ofProp.type === "number") colType = ofProp.validation?.integer ? "integer[]" : "numeric[]";
6239
- else if (ofProp.type === "boolean") colType = "boolean[]";
6240
- }
6241
- if (colType === "json") return "JSON";
6242
- if (colType === "text[]") return "TEXT[]";
6243
- if (colType === "integer[]") return "INTEGER[]";
6244
- if (colType === "boolean[]") return "BOOLEAN[]";
6245
- if (colType === "numeric[]") return "NUMERIC[]";
6246
- return "JSONB";
6247
- }
6248
- case "vector": return `VECTOR(${prop.dimensions})`;
6249
- case "binary": return "BYTEA";
6250
- case "relation": {
6251
- const refProp = prop;
6252
- const relation = findRelation(resolveCollectionRelations(collection), refProp.relation?.relationName ?? propName);
6253
- if (relation?.kind !== "belongsTo") throw new Error(`Relation ${propName} does not put a column on this table (only \`belongsTo\` does)`);
6254
- let targetCollection;
6255
- try {
6256
- targetCollection = relation.target();
6257
- } catch {
6258
- return "TEXT";
6259
- }
6260
- const pkProp = getPrimaryKeyProp(targetCollection);
6261
- return pkProp.type === "number" ? "INTEGER" : pkProp.isUuid ? "UUID" : "TEXT";
6262
- }
6263
- case "reference": {
6264
- const refProp = prop;
6265
- const targetCollection = collections.find((c) => c.slug === refProp.path || getTableName(c) === refProp.path);
6266
- if (!targetCollection) return "TEXT";
6267
- const pkProp = getPrimaryKeyProp(targetCollection);
6268
- return pkProp.type === "number" ? "INTEGER" : pkProp.isUuid ? "UUID" : "TEXT";
6269
- }
6270
- default: throw new Error(`No Postgres column type for property '${propName}' of type '${prop.type}' in collection '${collection.slug}'. Add a case to \`getSqlColumnType\` (and to \`getDrizzleColumn\`, which must agree).`);
6271
- }
6272
- };
6273
- var generatePostgresSearchDdl = (allCollections) => {
6274
- const collections = relationalCollections(allCollections);
6275
- const specs = collections.map((c) => buildSearchColumnSpec(c)).filter((s) => s !== void 0);
6276
- if (specs.length === 0) return "";
6277
- const extensions = Array.from(new Set(specs.flatMap(searchExtensionStatements)));
6278
- const helpers = Array.from(new Set(specs.flatMap(searchHelperFunctions)));
6279
- let ddl = "-- This file is auto-generated by the Rebase DDL generator. Do not edit manually.\n";
6280
- ddl += "--\n";
6281
- ddl += "-- Full-text search for the collections declaring a `search` block.\n";
6282
- ddl += "-- Applied by Rebase, not by Atlas — see generatePostgresSearchDdl.\n\n";
6283
- extensions.forEach((s) => {
6284
- ddl += `${s}\n`;
6285
- });
6286
- if (extensions.length > 0) ddl += "\n";
6287
- helpers.forEach((s) => {
6288
- ddl += `${s}\n\n`;
6289
- });
6290
- for (const collection of collections) {
6291
- const spec = buildSearchColumnSpec(collection);
6292
- if (!spec) continue;
6293
- const table = `"${isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : "public"}"."${getTableName(collection)}"`;
6294
- searchStampGuards(spec).forEach((s) => {
6295
- ddl += `${s}\n`;
6296
- });
6297
- ddl += `ALTER TABLE ${table} ADD COLUMN IF NOT EXISTS ${searchColumnDefinition(spec)};\n`;
6298
- const fuzzyDef = fuzzyColumnDefinition(spec);
6299
- if (fuzzyDef) ddl += `ALTER TABLE ${table} ADD COLUMN IF NOT EXISTS ${fuzzyDef};\n`;
6300
- searchColumnStamps(spec).forEach((s) => {
6301
- ddl += `${s.sql}\n`;
6302
- });
6303
- searchIndexStatements(spec).forEach((s) => {
6304
- ddl += `${s}\n`;
6305
- });
6306
- ddl += "\n";
6307
- }
6308
- return ddl;
6309
- };
6310
- var generatePostgresDdl = async (allCollections, options = {
6311
- includePolicies: true,
6312
- includeSearch: true
6313
- }) => {
6314
- const collections = relationalCollections(allCollections);
6315
- let ddl = "-- This file is auto-generated by the Rebase DDL generator. Do not edit manually.\n\n";
6316
- const uniqueSchemas = Array.from(/* @__PURE__ */ new Set([REBASE_SCHEMA, ...collections.map((c) => isPostgresCollectionConfig(c) ? c.schema : void 0).filter(Boolean)]));
6317
- uniqueSchemas.forEach((schema) => {
6318
- if (schema) ddl += `CREATE SCHEMA IF NOT EXISTS "${schema}";\n`;
6319
- });
6320
- if (uniqueSchemas.length > 0) ddl += "\n";
6321
- const searchSpecs = collections.map((c) => buildSearchColumnSpec(c)).filter((s) => s !== void 0);
6322
- if (searchSpecs.length > 0) if (options.includeSearch === false) ddl += "-- Full-text search support lives in `search.sql`, applied separately.\n\n";
6323
- else {
6324
- const extensions = Array.from(new Set(searchSpecs.flatMap(searchExtensionStatements)));
6325
- const helpers = Array.from(new Set(searchSpecs.flatMap(searchHelperFunctions)));
6326
- ddl += "-- Full-text search support (collections declaring a `search` block)\n";
6327
- extensions.forEach((s) => {
6328
- ddl += `${s}\n`;
6329
- });
6330
- if (extensions.length > 0) ddl += "\n";
6331
- helpers.forEach((s) => {
6332
- ddl += `${s}\n\n`;
6333
- });
6334
- }
6335
- const emittedEnums = /* @__PURE__ */ new Set();
6336
- collections.forEach((collection) => {
6337
- const collectionTable = getTableName(collection);
6338
- const schema = isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : "public";
6339
- Object.entries(collection.properties ?? {}).forEach(([propName, prop]) => {
6340
- if ("enum" in prop && (prop.type === "string" || prop.type === "number") && prop.enum) {
6341
- const enumDbName = `${collectionTable}_${resolveColumnName(propName, prop)}`;
6342
- const values = Array.isArray(prop.enum) ? prop.enum.map((v) => String(typeof v === "object" && v !== null && "id" in v ? v.id : v)) : Object.keys(prop.enum);
6343
- if (values.length > 0 && !emittedEnums.has(`${schema}.${enumDbName}`)) {
6344
- emittedEnums.add(`${schema}.${enumDbName}`);
6345
- ddl += `CREATE TYPE "${schema}"."${enumDbName}" AS ENUM (${values.map(quoteSqlLiteral).join(", ")});\n`;
6346
- }
6347
- }
6348
- });
6349
- });
6350
- if (ddl.endsWith(";\n")) ddl += "\n";
6351
- const junctionSpecs = resolveJunctionSpecs(collections);
6352
- const allTablesToGenerate = /* @__PURE__ */ new Map();
6353
- for (const collection of collections) {
6354
- const tableName = getTableName(collection);
6355
- if (tableName) allTablesToGenerate.set(tableName, { collection });
6356
- const resolvedRelations = resolveCollectionRelations(collection);
6357
- for (const relation of Object.values(resolvedRelations)) if (isManyToMany(relation)) {
6358
- const junctionTableName = relation.through.table;
6359
- if (!allTablesToGenerate.has(junctionTableName)) allTablesToGenerate.set(junctionTableName, {
6360
- collection: {
6361
- table: junctionTableName,
6362
- properties: {}
6363
- },
6364
- isJunction: true,
6365
- relation,
6366
- sourceCollection: collection
6367
- });
6368
- }
6369
- }
6370
- const fkStatements = [];
6371
- const indexStatements = [];
6372
- const policyStatements = [];
6373
- for (const [tableName, { collection, isJunction, relation, sourceCollection }] of allTablesToGenerate.entries()) {
6374
- const schema = isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : "public";
6375
- const baseTableName = tableName.includes(".") ? tableName.split(".").pop() : tableName;
6376
- if (isJunction && relation && sourceCollection && isManyToMany(relation)) {
6377
- const targetCollection = relation.target();
6378
- const sourceTable = getTableName(sourceCollection);
6379
- const targetTable = getTableName(targetCollection);
6380
- const sourceSchema = isPostgresCollectionConfig(sourceCollection) && sourceCollection.schema ? sourceCollection.schema : "public";
6381
- const targetSchema = isPostgresCollectionConfig(targetCollection) && targetCollection.schema ? targetCollection.schema : "public";
6382
- const { sourceColumn, targetColumn } = relation.through;
6383
- const sourceColType = isNumericId(sourceCollection) ? "INTEGER" : getPrimaryKeyProp(sourceCollection).isUuid ? "UUID" : "TEXT";
6384
- const targetColType = isNumericId(targetCollection) ? "INTEGER" : getPrimaryKeyProp(targetCollection).isUuid ? "UUID" : "TEXT";
6385
- const sourceId = getPrimaryKeyName(sourceCollection);
6386
- const targetId = getPrimaryKeyName(targetCollection);
6387
- const onDelete = relation.onDelete ?? "CASCADE";
6388
- ddl += `CREATE TABLE "${schema}"."${baseTableName}" (\n`;
6389
- ddl += ` "${sourceColumn}" ${sourceColType} NOT NULL,\n`;
6390
- ddl += ` "${targetColumn}" ${targetColType} NOT NULL,\n`;
6391
- ddl += ` PRIMARY KEY ("${sourceColumn}", "${targetColumn}")\n`;
6392
- ddl += `);\n\n`;
6393
- fkStatements.push(`ALTER TABLE "${schema}"."${baseTableName}" ADD CONSTRAINT "${toPostgresIdentifier(`${baseTableName}_${sourceColumn}_fkey`)}" FOREIGN KEY ("${sourceColumn}") REFERENCES "${sourceSchema}"."${sourceTable}" ("${sourceId}") ON DELETE ${onDelete.toUpperCase()};`);
6394
- fkStatements.push(`ALTER TABLE "${schema}"."${baseTableName}" ADD CONSTRAINT "${toPostgresIdentifier(`${baseTableName}_${targetColumn}_fkey`)}" FOREIGN KEY ("${targetColumn}") REFERENCES "${targetSchema}"."${targetTable}" ("${targetId}") ON DELETE ${onDelete.toUpperCase()};`);
6395
- if (options.includePolicies) {
6396
- ddl += `ALTER TABLE "${schema}"."${baseTableName}" ENABLE ROW LEVEL SECURITY;\n`;
6397
- ddl += `\n`;
6398
- const spec = junctionSpecs.get(baseTableName);
6399
- if (spec) {
6400
- const junctionCollection = getJunctionCollectionConfig(spec);
6401
- const resolveCollection = (slug) => collections.find((c) => c.slug === slug || getTableName(c) === slug);
6402
- getJunctionSecurityRules(spec).forEach((rule) => {
6403
- policyStatements.push(generatePolicyDdl(junctionCollection, rule, resolveCollection));
6404
- });
6405
- }
6406
- }
6407
- } else if (!isJunction) {
6408
- ddl += `CREATE TABLE "${schema}"."${baseTableName}" (\n`;
6409
- const columns = [];
6410
- Object.entries(collection.properties ?? {}).forEach(([propName, prop]) => {
6411
- if (prop.type === "relation") {
6412
- const refProp = prop;
6413
- const relInfo = findRelation(resolveCollectionRelations(collection), refProp.relation?.relationName ?? propName);
6414
- if (relInfo?.kind !== "belongsTo") return;
6415
- if (collection.properties[relInfo.localKey] && propName !== relInfo.localKey) return;
6416
- let targetCollection;
6417
- try {
6418
- targetCollection = relInfo.target();
6419
- } catch {
6420
- return;
6421
- }
6422
- const targetTable = getTableName(targetCollection);
6423
- const targetSchema = isPostgresCollectionConfig(targetCollection) && targetCollection.schema ? targetCollection.schema : "public";
6424
- const targetId = getPrimaryKeyName(targetCollection);
6425
- const fkColType = getSqlColumnType(propName, prop, collection, collections);
6426
- const onUpdate = relInfo.onUpdate ? ` ON UPDATE ${relInfo.onUpdate.toUpperCase()}` : "";
6427
- const required = prop.validation?.required;
6428
- const onDeleteVal = relInfo.onDelete ?? (required ? "CASCADE" : "SET NULL");
6429
- let colDef = ` "${relInfo.localKey}" ${fkColType}`;
6430
- if (required) colDef += " NOT NULL";
6431
- columns.push(colDef);
6432
- fkStatements.push(`ALTER TABLE "${schema}"."${baseTableName}" ADD CONSTRAINT "${toPostgresIdentifier(`${baseTableName}_${relInfo.localKey}_fkey`)}" FOREIGN KEY ("${relInfo.localKey}") REFERENCES "${targetSchema}"."${targetTable}" ("${targetId}") ON DELETE ${onDeleteVal.toUpperCase()}${onUpdate};`);
6433
- } else if (prop.type === "reference") {
6434
- const refProp = prop;
6435
- const targetCollection = collections.find((c) => c.slug === refProp.path || getTableName(c) === refProp.path);
6436
- const colName = resolveColumnName(propName, prop);
6437
- const colType = getSqlColumnType(propName, prop, collection, collections);
6438
- const required = prop.validation?.required;
6439
- if (!targetCollection) {
6440
- let colDef = ` "${colName}" ${colType}`;
6441
- if (required) colDef += " NOT NULL";
6442
- columns.push(colDef);
6443
- } else {
6444
- const targetTable = getTableName(targetCollection);
6445
- const targetSchema = isPostgresCollectionConfig(targetCollection) && targetCollection.schema ? targetCollection.schema : "public";
6446
- const targetId = getPrimaryKeyName(targetCollection);
6447
- const onDelete = required ? "CASCADE" : "SET NULL";
6448
- let colDef = ` "${colName}" ${colType}`;
6449
- if (required) colDef += " NOT NULL";
6450
- columns.push(colDef);
6451
- fkStatements.push(`ALTER TABLE "${schema}"."${baseTableName}" ADD CONSTRAINT "${toPostgresIdentifier(`${baseTableName}_${colName}_fkey`)}" FOREIGN KEY ("${colName}") REFERENCES "${targetSchema}"."${targetTable}" ("${targetId}") ON DELETE ${onDelete.toUpperCase()};`);
6452
- }
6453
- } else {
6454
- const colName = resolveColumnName(propName, prop);
6455
- const authDefinition = isAuthCollection(collection) ? authUsersColumnDefinition(colName) : void 0;
6456
- if (authDefinition && !isIdProperty(propName, prop, collection)) {
6457
- columns.push(` "${colName}" ${authDefinition}`);
6458
- return;
6459
- }
6460
- let colDef = ` "${colName}" ${getSqlColumnType(propName, prop, collection, collections)}`;
6461
- if (isIdProperty(propName, prop, collection)) colDef += " PRIMARY KEY";
6462
- if ("isId" in prop && prop.isId !== "manual" && prop.isId !== true && prop.isId !== "increment") {
6463
- if (prop.isId === "uuid") colDef += " DEFAULT gen_random_uuid()";
6464
- else if (prop.isId === "cuid") colDef += " DEFAULT cuid()";
6465
- else if (typeof prop.isId === "string") colDef += ` DEFAULT ${prop.isId}`;
6466
- }
6467
- if (!isIdProperty(propName, prop, collection) && prop.validation?.unique) colDef += " UNIQUE";
6468
- if (prop.type === "date") {
6469
- const dateProp = prop;
6470
- if (dateProp.autoValue === "on_create" || dateProp.autoValue === "on_update") colDef += " DEFAULT now()";
6471
- }
6472
- if (prop.validation?.required && !colDef.includes("PRIMARY KEY")) colDef += " NOT NULL";
6473
- columns.push(colDef);
6474
- }
6475
- });
6476
- if (isAuthCollection(collection)) {
6477
- const declared = new Set(Object.entries(collection.properties ?? {}).map(([name, prop]) => resolveColumnName(name, prop)));
6478
- for (const spec of AUTH_USERS_COLUMNS) {
6479
- if (declared.has(spec.column)) continue;
6480
- columns.push(` "${spec.column}" ${authUsersColumnSql(spec)}`);
6481
- }
6482
- }
6483
- const searchSpec = options.includeSearch === false ? void 0 : buildSearchColumnSpec(collection);
6484
- if (searchSpec) {
6485
- columns.push(` ${searchColumnDefinition(searchSpec)}`);
6486
- const fuzzyDef = fuzzyColumnDefinition(searchSpec);
6487
- if (fuzzyDef) columns.push(` ${fuzzyDef}`);
6488
- indexStatements.push(...searchIndexStatements(searchSpec));
6489
- }
6490
- const vectorPlan = buildVectorIndexPlan(collection, resolveColumnName);
6491
- indexStatements.push(...vectorIndexStatements(vectorPlan));
6492
- for (const skip of vectorPlan.skipped) indexStatements.push(`-- No ANN index on "${skip.schema}"."${skip.table}"."${skip.column}": ${skip.reason}`);
6493
- if (!columns.some((c) => c.includes("PRIMARY KEY"))) columns.unshift(" \"id\" TEXT PRIMARY KEY");
6494
- ddl += columns.join(",\n");
6495
- ddl += `\n);\n\n`;
6496
- if (options.includePolicies) {
6497
- ddl += `ALTER TABLE "${schema}"."${baseTableName}" ENABLE ROW LEVEL SECURITY;\n`;
6498
- ddl += `\n`;
6499
- const securityRules = getEffectiveSecurityRules(collection);
6500
- if (securityRules.length > 0) {
6501
- const resolveCollection = (slug) => collections.find((c) => c.slug === slug || getTableName(c) === slug);
6502
- securityRules.forEach((rule) => {
6503
- policyStatements.push(generatePolicyDdl(collection, rule, resolveCollection));
6504
- });
6505
- }
6506
- }
6507
- }
6508
- }
6509
- if (fkStatements.length > 0) {
6510
- ddl += "-- Foreign Key Constraints\n";
6511
- ddl += fkStatements.join("\n") + "\n\n";
6512
- }
6513
- if (indexStatements.length > 0) {
6514
- ddl += "-- Indexes\n";
6515
- ddl += indexStatements.join("\n") + "\n\n";
6516
- }
6517
- if (policyStatements.length > 0) {
6518
- ddl += "-- Row Level Security Policies\n";
6519
- ddl += policyStatements.join("");
6520
- ddl += "\n";
6521
- }
6522
- return ddl;
6523
- };
6524
- var schemaOfCollection = (collection) => isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : "public";
6525
- var bareTableName = (name) => name.includes(".") ? name.split(".").pop() : name;
6526
- /**
6527
- * Truncate a derived identifier the way Postgres does: to 63 bytes, silently.
6528
- *
6529
- * This is not cosmetic, and not really a naming choice at all — it is agreeing
6530
- * with the name the database ALREADY stored. `ADD CONSTRAINT` on a longer name
6531
- * succeeds and records the truncated form, so the untruncated name this used to
6532
- * derive matched nothing in the catalogue. Boot-ensure compares its planned
6533
- * constraints against `readExistingSchema`, which reads catalogue names, so the
6534
- * comparison could never hit: every boot re-issued `ADD CONSTRAINT` for the same
6535
- * constraint, forever, and got "already exists" every time. Non-fatal (foreign
6536
- * keys are the one action allowed to fail) and therefore permanent — an error in
6537
- * the log on every restart of a project whose table and column names happened to
6538
- * be long.
6539
- *
6540
- * Byte length, not string length: NAMEDATALEN is 64 bytes, and a multi-byte
6541
- * character straddling the boundary would be cut mid-sequence by `slice(0, 63)`.
6542
- */
6543
- var foreignKeyPlan = (args) => {
6544
- const constraintName = toPostgresIdentifier(`${args.table}_${args.column}_fkey`);
6545
- const onUpdate = args.onUpdate ? ` ON UPDATE ${args.onUpdate.toUpperCase()}` : "";
6546
- return {
6547
- constraintName,
6548
- schema: args.schema,
6549
- table: args.table,
6550
- column: args.column,
6551
- targetSchema: args.targetSchema,
6552
- targetTable: args.targetTable,
6553
- targetColumn: args.targetColumn,
6554
- sql: `ALTER TABLE "${args.schema}"."${args.table}" ADD CONSTRAINT "${constraintName}" FOREIGN KEY ("${args.column}") REFERENCES "${args.targetSchema}"."${args.targetTable}" ("${args.targetColumn}") ON DELETE ${args.onDelete.toUpperCase()}${onUpdate};`
6555
- };
6556
- };
6557
- /**
6558
- * The FK columns the declared collections own — one entry per `relation`
6559
- * (`belongsTo` side) or `reference` property.
6560
- *
6561
- * Split out of {@link generatePostgresDdl} so the boot-time schema ensure can
6562
- * create the same columns with the same names, types and constraints. Before
6563
- * this it skipped them outright, which was survivable only because `db push`
6564
- * always followed; on a managed tenant nothing follows, so a table arrived
6565
- * without the column its own collection reads and wrote 400 on every insert.
6566
- *
6567
- * A relation whose target is not in the bundle yields no column at all (the
6568
- * generator returns early on an unresolvable target); a `reference` whose target
6569
- * is unknown yields the column without a constraint. Both mirror the generator
6570
- * exactly — a divergence here is a schema fork between boot and `db push`.
6571
- */
6572
- var planRelationalColumns = (allCollections) => {
6573
- const collections = relationalCollections(allCollections);
6574
- const plans = [];
6575
- for (const collection of collections) {
6576
- const tableName = getTableName(collection);
6577
- if (!tableName) continue;
6578
- const schema = schemaOfCollection(collection);
6579
- const table = bareTableName(tableName);
6580
- for (const [propName, rawProp] of Object.entries(collection.properties ?? {})) {
6581
- const prop = rawProp;
6582
- if (prop.type === "relation") {
6583
- const refProp = prop;
6584
- const relInfo = findRelation(resolveCollectionRelations(collection), refProp.relation?.relationName ?? propName);
6585
- if (relInfo?.kind !== "belongsTo") continue;
6586
- if (collection.properties[relInfo.localKey] && propName !== relInfo.localKey) continue;
6587
- let targetCollection;
6588
- try {
6589
- targetCollection = relInfo.target();
6590
- } catch {
6591
- continue;
6592
- }
6593
- if (!targetCollection) continue;
6594
- const required = prop.validation?.required;
6595
- const relationName = refProp.relation?.relationName ?? propName;
6596
- const legacyKey = legacyForeignKeyName(relationName);
6597
- const derived = relInfo.localKey === generateForeignKeyName(relationName);
6598
- plans.push({
6599
- schema,
6600
- table,
6601
- column: relInfo.localKey,
6602
- legacyColumn: derived && legacyKey !== relInfo.localKey ? legacyKey : void 0,
6603
- type: getSqlColumnType(propName, prop, collection, collections),
6604
- foreignKey: foreignKeyPlan({
6605
- schema,
6606
- table,
6607
- column: relInfo.localKey,
6608
- targetSchema: schemaOfCollection(targetCollection),
6609
- targetTable: bareTableName(getTableName(targetCollection)),
6610
- targetColumn: getPrimaryKeyName(targetCollection),
6611
- onDelete: relInfo.onDelete ?? (required ? "CASCADE" : "SET NULL"),
6612
- onUpdate: relInfo.onUpdate
6613
- })
6614
- });
6615
- } else if (prop.type === "reference") {
6616
- const refProp = prop;
6617
- const targetCollection = collections.find((c) => c.slug === refProp.path || getTableName(c) === refProp.path);
6618
- const column = resolveColumnName(propName, prop);
6619
- const type = getSqlColumnType(propName, prop, collection, collections);
6620
- const required = prop.validation?.required;
6621
- plans.push({
6622
- schema,
6623
- table,
6624
- column,
6625
- type,
6626
- foreignKey: targetCollection ? foreignKeyPlan({
6627
- schema,
6628
- table,
6629
- column,
6630
- targetSchema: schemaOfCollection(targetCollection),
6631
- targetTable: bareTableName(getTableName(targetCollection)),
6632
- targetColumn: getPrimaryKeyName(targetCollection),
6633
- onDelete: required ? "CASCADE" : "SET NULL"
6634
- }) : void 0
6635
- });
6636
- }
6637
- }
6638
- }
6639
- return plans;
6640
- };
6641
- /**
6642
- * The junction tables a bundle's many-to-many relations imply.
6643
- *
6644
- * Derived from {@link resolveJunctionSpecs}, the same source the junction RLS
6645
- * comes from, so a table created here always has policies planned for it — a
6646
- * junction with row-level security left off is readable and writable by every
6647
- * signed-in user, which is why the two must ship together.
6648
- */
6649
- var planJunctionTables = (allCollections) => {
6650
- const collections = relationalCollections(allCollections);
6651
- const plans = [];
6652
- for (const spec of resolveJunctionSpecs(collections).values()) {
6653
- const [source, target] = spec.endpoints;
6654
- const legacyFor = (endpoint) => {
6655
- const slug = toSnakeCase(endpoint.collection.slug ?? endpoint.collection.name ?? "");
6656
- const legacy = legacyForeignKeyName(slug);
6657
- return endpoint.junctionColumn === generateForeignKeyName(slug) && legacy !== endpoint.junctionColumn ? legacy : void 0;
5599
+ default: return {
5600
+ column,
5601
+ op: predicate.op,
5602
+ value: predicate.value
6658
5603
  };
6659
- const columns = [{
6660
- name: source.junctionColumn,
6661
- type: junctionKeyType(source.collection),
6662
- legacyName: legacyFor(source)
6663
- }, {
6664
- name: target.junctionColumn,
6665
- type: junctionKeyType(target.collection),
6666
- legacyName: legacyFor(target)
6667
- }];
6668
- const onDelete = spec.declaringSides[0]?.relation.onDelete ?? "CASCADE";
6669
- plans.push({
6670
- schema: spec.schema,
6671
- table: spec.table,
6672
- columns,
6673
- createTable: `CREATE TABLE IF NOT EXISTS "${spec.schema}"."${spec.table}" (` + columns.map((c) => `"${c.name}" ${c.type} NOT NULL`).join(", ") + `, PRIMARY KEY (${columns.map((c) => `"${c.name}"`).join(", ")}));`,
6674
- foreignKeys: [source, target].map((endpoint, i) => foreignKeyPlan({
6675
- schema: spec.schema,
6676
- table: spec.table,
6677
- column: columns[i].name,
6678
- targetSchema: schemaOfCollection(endpoint.collection),
6679
- targetTable: bareTableName(getTableName(endpoint.collection)),
6680
- targetColumn: getPrimaryKeyName(endpoint.collection),
6681
- onDelete
6682
- }))
6683
- });
6684
5604
  }
6685
- return plans;
6686
5605
  };
5606
+ /** The primary key columns of a collection, for the "you already have this" refusal. */
5607
+ var primaryKeyColumns = (collection, resolveColumnName) => Object.entries(collection.properties ?? {}).filter(([, prop]) => prop && typeof prop === "object" && "isId" in prop && Boolean(prop.isId)).map(([key, prop]) => resolveColumnName(key, prop));
6687
5608
  /**
6688
- * The per-table RLS plan for the *declared* collections, as executable
6689
- * statements — what the managed runtime applies at boot so a freshly
6690
- * provisioned tenant database serves data instead of 401ing every read.
6691
- *
6692
- * Mirrors {@link generatePostgresPoliciesDdl} exactly (same
6693
- * `generatePolicyStatements`, same enable-RLS, same effective rules, same
6694
- * derived junction rules), so boot and `db push` produce identical policies from
6695
- * identical collections.
5609
+ * Every index one collection declares, resolved and named.
6696
5610
  *
6697
- * Junction tables are included, and have to be: boot creates them now
6698
- * ({@link planJunctionTables}), and a junction with RLS left off is readable and
6699
- * writable by every signed-in user. A junction whose table is still absent is
6700
- * skipped by the applier, not planned away here.
5611
+ * Throws {@link CollectionIndexConfigError} rather than dropping a bad entry:
5612
+ * an index that silently does not exist is the failure mode this whole feature
5613
+ * is here to remove.
6701
5614
  */
6702
- var planCollectionPolicies = (allCollections) => {
6703
- const collections = relationalCollections(allCollections);
6704
- const resolveCollection = (slug) => collections.find((c) => c.slug === slug || getTableName(c) === slug);
6705
- const plans = [];
6706
- const seen = /* @__PURE__ */ new Set();
6707
- for (const collection of collections) {
6708
- const tableName = getTableName(collection);
6709
- if (!tableName) continue;
6710
- const schema = isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : "public";
6711
- const baseTableName = tableName.includes(".") ? tableName.split(".").pop() : tableName;
6712
- const qualified = `${schema}.${baseTableName}`;
6713
- if (seen.has(qualified)) continue;
6714
- seen.add(qualified);
6715
- const policyStatements = [];
6716
- for (const rule of getEffectiveSecurityRules(collection)) policyStatements.push(...generatePolicyStatements(collection, rule, resolveCollection));
6717
- plans.push({
6718
- schema,
6719
- table: baseTableName,
6720
- qualified,
6721
- enableRls: `ALTER TABLE "${schema}"."${baseTableName}" ENABLE ROW LEVEL SECURITY;`,
6722
- policyStatements
6723
- });
6724
- }
6725
- for (const spec of resolveJunctionSpecs(collections).values()) {
6726
- const qualified = `${spec.schema}.${spec.table}`;
6727
- if (seen.has(qualified)) continue;
6728
- seen.add(qualified);
6729
- const junctionCollection = getJunctionCollectionConfig(spec);
6730
- const policyStatements = [];
6731
- for (const rule of getJunctionSecurityRules(spec)) policyStatements.push(...generatePolicyStatements(junctionCollection, rule, resolveCollection));
6732
- plans.push({
6733
- schema: spec.schema,
6734
- table: spec.table,
6735
- qualified,
6736
- enableRls: `ALTER TABLE "${spec.schema}"."${spec.table}" ENABLE ROW LEVEL SECURITY;`,
6737
- policyStatements
6738
- });
6739
- }
6740
- return plans;
6741
- };
6742
- var generatePostgresPoliciesDdl = (allCollections) => {
6743
- const collections = relationalCollections(allCollections);
6744
- let ddl = "-- This file contains RLS policies generated by Rebase. Applied separately from migrations.\n\n";
6745
- const allTablesToGenerate = /* @__PURE__ */ new Map();
6746
- for (const collection of collections) {
6747
- const tableName = getTableName(collection);
6748
- if (tableName) allTablesToGenerate.set(tableName, { collection });
6749
- }
6750
- for (const [tableName, { collection }] of allTablesToGenerate.entries()) {
6751
- const schema = isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : "public";
6752
- const baseTableName = tableName.includes(".") ? tableName.split(".").pop() : tableName;
6753
- ddl += `ALTER TABLE "${schema}"."${baseTableName}" ENABLE ROW LEVEL SECURITY;\n`;
6754
- ddl += `\n`;
6755
- const securityRules = getEffectiveSecurityRules(collection);
6756
- if (securityRules.length > 0) {
6757
- const resolveCollection = (slug) => collections.find((c) => c.slug === slug || getTableName(c) === slug);
6758
- const injectedNames = new Set(getInjectedSecurityRules(collection).map((rule) => rule.name));
6759
- securityRules.forEach((rule) => {
6760
- if (rule.name && injectedNames.has(rule.name)) {
6761
- ddl += `-- Injected by Rebase (not from this collection's securityRules).\n`;
6762
- ddl += `-- Set \`disableDefaultPolicies: true\` on "${collection.slug}" to drop these and own its RLS outright.\n`;
6763
- }
6764
- ddl += generatePolicyDdl(collection, rule, resolveCollection);
6765
- });
6766
- ddl += "\n";
6767
- }
6768
- }
6769
- const junctionSpecs = resolveJunctionSpecs(collections);
6770
- for (const spec of junctionSpecs.values()) {
6771
- ddl += `ALTER TABLE "${spec.schema}"."${spec.table}" ENABLE ROW LEVEL SECURITY;\n`;
6772
- ddl += `\n`;
6773
- const junctionRules = getJunctionSecurityRules(spec);
6774
- if (junctionRules.length === 0) continue;
6775
- const junctionCollection = getJunctionCollectionConfig(spec);
6776
- const resolveCollection = (slug) => collections.find((c) => c.slug === slug || getTableName(c) === slug);
6777
- const declaringSlugs = spec.declaringSides.map((s) => s.collection.slug).join("\", \"");
6778
- ddl += `-- Derived by Rebase for the junction "${spec.table}" (no collection declares it).\n`;
6779
- ddl += `-- Reads require both endpoint rows to be visible; writes follow the update\n`;
6780
- ddl += `-- rules of "${declaringSlugs}". Set \`disableDefaultPolicies: true\` on the\n`;
6781
- ddl += `-- declaring collection(s) to drop these and police the junction yourself.\n`;
6782
- junctionRules.forEach((rule) => {
6783
- ddl += generatePolicyDdl(junctionCollection, rule, resolveCollection);
6784
- });
6785
- ddl += "\n";
6786
- }
6787
- return ddl;
6788
- };
6789
- //#endregion
6790
- //#region src/schema/ensure-collection-tables.ts
6791
- /**
6792
- * Bringing a database up to date with a bundle's collections, additively.
6793
- *
6794
- * ## Why this exists
6795
- *
6796
- * A managed runtime boots someone else's compiled project against a database it
6797
- * has never seen. Auth tables are ensured at boot already, but collection tables
6798
- * were not created by anything: the platform ran the app and every `/api/data/*`
6799
- * request answered 500 on a missing relation. `rebase db push` cannot help — it
6800
- * is an Atlas-driven CLI command, and the runtime image ships no CLI.
6801
- *
6802
- * ## Why additive-only, forever
6803
- *
6804
- * This runs unattended, against a database with customers' data in it, with no
6805
- * human reading a diff. So it may only ever do things that cannot lose data:
6806
- * create a missing table, add a missing column, create a missing enum type.
6807
- *
6808
- * It will **never** drop a table or a column, narrow a type, or alter a
6809
- * constraint. A removed field leaves its column behind; a renamed field looks
6810
- * like an addition and the old column stays. That is the correct trade for an
6811
- * automated path — the alternative is an unattended process that can silently
6812
- * destroy a column, which is precisely the failure `db push` was hardened
6813
- * against. Destructive changes stay a deliberate, human-reviewed migration.
6814
- *
6815
- * Because of that, this is safe to run on every boot, and re-running it is a
6816
- * no-op.
6817
- */
6818
- var ensure_collection_tables_exports = /* @__PURE__ */ __exportAll({
6819
- ensureCollectionTables: () => ensureCollectionTables,
6820
- planCollectionSchemaEnsure: () => planCollectionSchemaEnsure,
6821
- readExistingSchema: () => readExistingSchema,
6822
- readSchemaFactsFor: () => readSchemaFactsFor
6823
- });
6824
- /** Postgres identifiers this module is willing to interpolate. */
6825
- var SAFE_IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_$]*$/;
6826
- function assertSafeIdentifier(value, what) {
6827
- if (!SAFE_IDENTIFIER.test(value)) throw new Error(`Refusing to build SQL with an unsafe ${what}: ${JSON.stringify(value)}`);
6828
- return value;
6829
- }
6830
- function schemaOf(collection) {
6831
- return isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : "public";
6832
- }
6833
- function qualified(collection) {
6834
- return `${schemaOf(collection)}.${getTableName(collection)}`;
6835
- }
6836
- /**
6837
- * Enum types a collection's properties require, as `schema.typename`.
6838
- *
6839
- * Named exactly as the DDL generator names them (`<table>_<column>`), because
6840
- * a column added here has to reference the same type the generator would have
6841
- * created — a second, differently-named type for the same field would be a
6842
- * silent schema fork.
6843
- */
6844
- function requiredEnums(collection) {
5615
+ var buildCollectionIndexSpecs = (collection, resolveColumnName) => {
5616
+ if (!isPostgresCollectionConfig(collection)) return [];
5617
+ const declared = collection.indexes;
5618
+ if (!declared || declared.length === 0) return [];
5619
+ const slug = collection.slug ?? getTableName(collection);
5620
+ const schema = collection.schema ?? "public";
6845
5621
  const table = getTableName(collection);
6846
- const schema = schemaOf(collection);
6847
- const out = [];
6848
- for (const [propName, prop] of Object.entries(collection.properties ?? {})) {
6849
- const p = prop;
6850
- if (!("enum" in p) || !p.enum) continue;
6851
- if (p.type !== "string" && p.type !== "number") continue;
6852
- const values = p.enum.map((entry) => entry && typeof entry === "object" && "id" in entry ? String(entry.id) : String(entry)).filter((v) => v.length > 0);
6853
- if (values.length === 0) continue;
6854
- out.push({
6855
- name: `${schema}.${table}_${resolveColumnName(propName, p)}`,
6856
- values
6857
- });
6858
- }
6859
- return out;
6860
- }
6861
- /**
6862
- * Decide what to add. Pure — the caller supplies what exists and runs the result.
6863
- *
6864
- * Ordering matters and is deliberate: enum types before the tables and columns
6865
- * that reference them, tables before the columns added to other tables (a new
6866
- * table may be the target of a relation), and nothing is emitted twice.
6867
- */
6868
- function planCollectionSchemaEnsure(allCollections, existing, options = {}) {
6869
- const constraintPolicy = options.constraints ?? "additive";
6870
- const withheldConstraints = [];
6871
- assertSearchIsPostgresOnly(allCollections);
6872
- const collections = relationalCollections(allCollections);
6873
- const actions = [];
6874
- const plannedEnums = /* @__PURE__ */ new Set();
6875
- for (const collection of collections) for (const { name, values } of requiredEnums(collection)) {
6876
- if (existing.enums.has(name) || plannedEnums.has(name)) {
6877
- const current = existing.enumValues?.get(name);
6878
- if (!current || plannedEnums.has(name)) continue;
6879
- const [schema, typeName] = name.split(".");
6880
- for (const value of values) {
6881
- if (current.includes(value)) continue;
6882
- actions.push({
6883
- kind: "add-enum-value",
6884
- target: `${name}.${value}`,
6885
- sql: `ALTER TYPE "${schema}"."${typeName}" ADD VALUE IF NOT EXISTS ${quoteSqlLiteral(value)};`
6886
- });
6887
- }
6888
- continue;
5622
+ const pk = primaryKeyColumns(collection, resolveColumnName).sort().join(",");
5623
+ const specs = [];
5624
+ const byName = /* @__PURE__ */ new Map();
5625
+ declared.forEach((index, position) => {
5626
+ const fail = (message) => {
5627
+ throw new CollectionIndexConfigError(slug, position, message);
5628
+ };
5629
+ if (typeof index.reason !== "string" || index.reason.trim() === "") fail("`reason` is required — see the doc comment. An index nobody can justify is one nobody can delete.");
5630
+ if (!Array.isArray(index.on) || index.on.length === 0) fail("`on` must name at least one property.");
5631
+ if (index.on.length > 5) fail(`\`on\` has ${index.on.length} keys; the limit is 5. Payload columns belong in \`include\`.`);
5632
+ const method = index.using ?? "btree";
5633
+ const unique = method === "btree" && Boolean(index.unique);
5634
+ if (!isOrderedMethod(method)) {
5635
+ for (const key of index.on) if (typeof key !== "string" && ("direction" in key || "nulls" in key)) fail(`access method "${method}" does not support ASC/DESC or NULLS options.`);
6889
5636
  }
6890
- plannedEnums.add(name);
6891
- const [schema, typeName] = name.split(".");
6892
- actions.push({
6893
- kind: "create-enum",
6894
- target: name,
6895
- sql: `CREATE TYPE "${schema}"."${typeName}" AS ENUM (${values.map(quoteSqlLiteral).join(", ")});`
6896
- });
6897
- }
6898
- const searchSpecs = collections.map((c) => buildSearchColumnSpec(c)).filter((spec) => spec !== void 0);
6899
- const plannedExtensions = /* @__PURE__ */ new Set();
6900
- for (const spec of searchSpecs) for (const statement of searchExtensionStatements(spec)) {
6901
- if (plannedExtensions.has(statement)) continue;
6902
- plannedExtensions.add(statement);
6903
- actions.push({
6904
- kind: "create-extension",
6905
- target: statement.replace(/^CREATE EXTENSION IF NOT EXISTS |;$/g, ""),
6906
- sql: statement
6907
- });
6908
- }
6909
- const plannedFunctions = /* @__PURE__ */ new Set();
6910
- for (const spec of searchSpecs) for (const statement of searchHelperFunctions(spec)) {
6911
- if (plannedFunctions.has(statement)) continue;
6912
- plannedFunctions.add(statement);
6913
- actions.push({
6914
- kind: "create-function",
6915
- target: statement.includes("unaccent") ? SEARCH_UNACCENT_FN : SEARCH_TEXT_FN,
6916
- sql: statement
6917
- });
6918
- }
6919
- const created = /* @__PURE__ */ new Set();
6920
- for (const collection of collections) {
6921
- const key = qualified(collection);
6922
- if (existing.tables.has(key) || created.has(key)) continue;
6923
- created.add(key);
6924
- const schema = schemaOf(collection);
6925
- const table = getTableName(collection);
6926
- const idEntry = Object.entries(collection.properties ?? {}).find(([n, p]) => isIdProperty(n, p, collection));
6927
- const idName = idEntry ? resolveColumnName(idEntry[0], idEntry[1]) : "id";
6928
- const idProp = idEntry?.[1];
6929
- let idDef = `"${idName}" ${idProp ? getSqlColumnType(idEntry[0], idProp, collection, collections) : "TEXT"} PRIMARY KEY`;
6930
- if (idProp?.type === "string" && idProp.isId === "uuid") idDef += " DEFAULT gen_random_uuid()";
6931
- actions.push({
6932
- kind: "create-table",
6933
- target: key,
6934
- sql: `CREATE TABLE IF NOT EXISTS "${schema}"."${table}" (${idDef});`
6935
- });
6936
- }
6937
- const junctions = planJunctionTables(collections);
6938
- for (const junction of junctions) {
6939
- const key = `${junction.schema}.${junction.table}`;
6940
- if (existing.tables.has(key) || created.has(key)) continue;
6941
- created.add(key);
6942
- actions.push({
6943
- kind: "create-table",
6944
- target: key,
6945
- sql: junction.createTable
6946
- });
6947
- }
6948
- const legacyForeignKeys = [];
6949
- /**
6950
- * Move a relation column that is only missing because it was renamed.
6951
- *
6952
- * Returns true when it handled the column, so the caller skips the ordinary
6953
- * ADD. Adding here would be the wrong move and a quiet one: the data is in
6954
- * the old column, `ADD COLUMN` creates the new one empty beside it, every
6955
- * statement succeeds, and the relation reads the empty one. A rename is
6956
- * metadata-only in Postgres, keeps the values, and carries the column's
6957
- * indexes and constraints with it.
6958
- *
6959
- * Only ever reached when the new name is absent and the old name is
6960
- * present, so there is nothing to overwrite and nothing to choose between.
6961
- */
6962
- const renameLegacyColumn = (key, schema, table, column, legacyName) => {
6963
- const present = existing.tables.get(key);
6964
- if (!legacyName || !present) return false;
6965
- if (present.has(column) || !present.has(legacyName)) return false;
6966
- legacyForeignKeys.push({
6967
- table: key,
6968
- expected: column,
6969
- legacy: legacyName
6970
- });
6971
- actions.push({
6972
- kind: "rename-column",
6973
- target: `${key}.${column}`,
6974
- sql: `ALTER TABLE "${schema}"."${table}" RENAME COLUMN "${legacyName}" TO "${column}";`
6975
- });
6976
- return true;
6977
- };
6978
- const addColumn = (key, schema, table, column, definition) => {
6979
- if (existing.tables.get(key)?.has(column)) return;
6980
- actions.push({
6981
- kind: "add-column",
6982
- target: `${key}.${column}`,
6983
- sql: `ALTER TABLE "${schema}"."${table}" ADD COLUMN IF NOT EXISTS "${column}" ${definition};`
5637
+ const keys = index.on.map((key) => {
5638
+ const column = resolveIndexableColumn(collection, typeof key === "string" ? key : key.prop, resolveColumnName, fail);
5639
+ const direction = (typeof key === "string" ? void 0 : key.direction) ?? "asc";
5640
+ return {
5641
+ column,
5642
+ direction,
5643
+ nulls: (typeof key === "string" ? void 0 : key.nulls) ?? (direction === "desc" ? "first" : "last")
5644
+ };
6984
5645
  });
6985
- };
6986
- for (const collection of collections) {
6987
- const key = qualified(collection);
6988
- const schema = schemaOf(collection);
6989
- const table = getTableName(collection);
6990
- const fresh = created.has(key);
6991
- const auth = isAuthCollection(collection);
6992
- for (const [propName, prop] of Object.entries(collection.properties ?? {})) {
6993
- const p = prop;
6994
- if (isIdProperty(propName, p, collection)) continue;
6995
- if (p.type === "reference" || p.type === "relation") continue;
6996
- const column = resolveColumnName(propName, p);
6997
- const authDefinition = auth ? authUsersColumnDefinition(column) : void 0;
6998
- if (authDefinition) {
6999
- addColumn(key, schema, table, column, authDefinition);
7000
- continue;
7001
- }
7002
- let definition = getSqlColumnType(propName, p, collection, collections);
7003
- if (fresh && p.validation?.unique) definition += " UNIQUE";
7004
- const autoValue = p.autoValue;
7005
- const hasDefault = p.type === "date" && (autoValue === "on_create" || autoValue === "on_update");
7006
- if (hasDefault) definition += " DEFAULT now()";
7007
- const required = p.validation?.required === true;
7008
- const columnKey = `${key}.${column}`;
7009
- const columnExists = existing.tables.get(key)?.has(column) === true;
7010
- const tableIsEmpty = existing.populatedTables !== void 0 && existing.tables.has(key) && !existing.populatedTables.has(key);
7011
- const notNullIsSafe = fresh || tableIsEmpty || hasDefault;
7012
- if (required && !columnExists) if (notNullIsSafe) definition += " NOT NULL";
7013
- else withheldConstraints.push({
7014
- target: columnKey,
7015
- kind: "not-null",
7016
- reason: `"${column}" is required, but "${key}" already holds rows and the column has no default to backfill them with, so NOT NULL would be checked against data that does not have a value yet.`,
7017
- remedy: "Backfill the column, then add the constraint — or give the property a default so every existing row gets one."
7018
- });
7019
- addColumn(key, schema, table, column, definition);
7020
- if (columnExists && constraintPolicy === "converge") {
7021
- const isNotNull = existing.notNullColumns?.has(columnKey) === true;
7022
- if (required && !isNotNull) if (tableIsEmpty) actions.push({
7023
- kind: "set-not-null",
7024
- target: columnKey,
7025
- sql: `ALTER TABLE "${schema}"."${table}" ALTER COLUMN "${column}" SET NOT NULL;`
7026
- });
7027
- else withheldConstraints.push({
7028
- target: columnKey,
7029
- kind: "not-null",
7030
- reason: `"${column}" became required, but "${key}" holds rows and any of them with no value would make SET NOT NULL fail.`,
7031
- remedy: "Backfill the column first — `UPDATE … SET \"" + column + "\" = … WHERE \"" + column + "\" IS NULL` — then apply this again."
7032
- });
7033
- if (!required && isNotNull) actions.push({
7034
- kind: "drop-not-null",
7035
- target: columnKey,
7036
- sql: `ALTER TABLE "${schema}"."${table}" ALTER COLUMN "${column}" DROP NOT NULL;`
7037
- });
7038
- }
5646
+ const duplicateKey = keys.map((k) => k.column).find((c, i, all) => all.indexOf(c) !== i);
5647
+ if (duplicateKey) fail(`"${duplicateKey}" appears twice in \`on\`.`);
5648
+ if (keys.map((k) => k.column).sort().join(",") === pk && pk !== "") fail(`this is the primary key — "${table}_pkey" already indexes exactly these columns.`);
5649
+ const include = (index.include ?? []).map((propKey) => resolveIndexableColumn(collection, propKey, resolveColumnName, fail));
5650
+ const overlap = include.find((c) => keys.some((k) => k.column === c));
5651
+ if (overlap) fail(`"${overlap}" is in both \`on\` and \`include\`; Postgres rejects the overlap.`);
5652
+ if (unique && keys.length === 1) {
5653
+ const propKey = typeof index.on[0] === "string" ? index.on[0] : index.on[0].prop;
5654
+ if ((collection.properties?.[propKey])?.validation?.unique) fail(`"${propKey}" already declares \`validation.unique\`, which compiles to an inline UNIQUE. Two declarations of one guarantee — remove one.`);
7039
5655
  }
7040
- if (auth) {
7041
- const declared = new Set(Object.entries(collection.properties ?? {}).map(([name, prop]) => resolveColumnName(name, prop)));
7042
- for (const spec of AUTH_USERS_COLUMNS) {
7043
- if (declared.has(spec.column)) continue;
7044
- addColumn(key, schema, table, spec.column, authUsersColumnSql(spec));
7045
- }
7046
- }
7047
- }
7048
- const searchDrift = [];
7049
- const searchAdopted = [];
7050
- for (const spec of searchSpecs) {
7051
- const key = `${spec.schema}.${spec.table}`;
7052
- const definitions = { [spec.column]: `tsvector GENERATED ALWAYS AS (${spec.expression}) STORED` };
7053
- if (spec.fuzzy) definitions[spec.fuzzy.column] = `text GENERATED ALWAYS AS (${spec.fuzzy.expression}) STORED`;
7054
- for (const stamp of searchColumnStamps(spec)) {
7055
- const definition = definitions[stamp.column];
7056
- const exists = existing.tables.get(key)?.has(stamp.column) === true;
7057
- const recorded = existing.columnComments?.get(`${key}.${stamp.column}`);
7058
- if (exists && recorded?.startsWith("rebase:search:v1:") && recorded !== stamp.fingerprint) {
7059
- searchDrift.push({
7060
- table: key,
7061
- column: stamp.column,
7062
- found: recorded,
7063
- expected: stamp.fingerprint,
7064
- rebuild: [
7065
- `ALTER TABLE "${spec.schema}"."${spec.table}" DROP COLUMN "${stamp.column}";`,
7066
- `ALTER TABLE "${spec.schema}"."${spec.table}" ADD COLUMN "${stamp.column}" ${definition};`,
7067
- stamp.sql
7068
- ]
7069
- });
7070
- continue;
7071
- }
7072
- addColumn(key, spec.schema, spec.table, stamp.column, definition);
7073
- if (exists && recorded === void 0) searchAdopted.push({
7074
- table: key,
7075
- column: stamp.column
7076
- });
7077
- if (recorded !== stamp.fingerprint) actions.push({
7078
- kind: "comment-column",
7079
- target: `${key}.${stamp.column}`,
7080
- sql: stamp.sql
7081
- });
7082
- }
7083
- }
7084
- for (const junction of junctions) {
7085
- const key = `${junction.schema}.${junction.table}`;
7086
- if (created.has(key)) continue;
7087
- for (const column of junction.columns) {
7088
- if (renameLegacyColumn(key, junction.schema, junction.table, column.name, column.legacyName)) continue;
7089
- addColumn(key, junction.schema, junction.table, column.name, column.type);
7090
- }
7091
- }
7092
- for (const relational of planRelationalColumns(collections)) {
7093
- const relKey = `${relational.schema}.${relational.table}`;
7094
- if (renameLegacyColumn(relKey, relational.schema, relational.table, relational.column, relational.legacyColumn)) continue;
7095
- addColumn(relKey, relational.schema, relational.table, relational.column, relational.type);
7096
- }
7097
- const knownConstraints = existing.constraints ?? /* @__PURE__ */ new Set();
7098
- const plannedConstraints = /* @__PURE__ */ new Set();
7099
- const foreignKeys = [...planRelationalColumns(collections).map((r) => r.foreignKey), ...junctions.flatMap((j) => j.foreignKeys)];
7100
- for (const fk of foreignKeys) {
7101
- if (!fk) continue;
7102
- const name = `${fk.schema}.${fk.table}.${fk.constraintName}`;
7103
- if (knownConstraints.has(name) || plannedConstraints.has(name)) continue;
7104
- plannedConstraints.add(name);
7105
- actions.push({
7106
- kind: "add-constraint",
7107
- target: `${fk.schema}.${fk.table}.${fk.constraintName}`,
7108
- sql: fk.sql
5656
+ const predicate = index.where ? resolvePredicate(collection, index.where, resolveColumnName, fail) : null;
5657
+ const withoutName = {
5658
+ schema,
5659
+ table,
5660
+ method,
5661
+ unique,
5662
+ keys,
5663
+ include,
5664
+ predicate,
5665
+ reason: index.reason
5666
+ };
5667
+ const indexName = deriveIndexName(withoutName);
5668
+ const clash = byName.get(indexName);
5669
+ if (clash !== void 0) fail(`derives the same name as indexes[${clash}] — they are the same index declared twice.`);
5670
+ byName.set(indexName, position);
5671
+ specs.push({
5672
+ ...withoutName,
5673
+ indexName
7109
5674
  });
7110
- }
7111
- for (const spec of searchSpecs) for (const statement of searchIndexStatements(spec)) actions.push({
7112
- kind: "create-index",
7113
- target: `${spec.schema}.${spec.table}`,
7114
- sql: statement.replace("CREATE INDEX IF NOT EXISTS", "CREATE INDEX CONCURRENTLY IF NOT EXISTS")
7115
5675
  });
7116
- const vectorIndexSkipped = [];
7117
- for (const collection of collections) {
7118
- const plan = buildVectorIndexPlan(collection, resolveColumnName);
7119
- for (const spec of plan.specs) actions.push({
7120
- kind: "create-index",
7121
- target: `${spec.schema}.${spec.table}`,
7122
- sql: vectorIndexStatement(spec).replace("CREATE INDEX IF NOT EXISTS", "CREATE INDEX CONCURRENTLY IF NOT EXISTS")
7123
- });
7124
- vectorIndexSkipped.push(...plan.skipped);
7125
- }
7126
- return {
7127
- actions,
7128
- statements: actions.map((a) => a.sql),
7129
- legacyForeignKeys,
7130
- searchDrift,
7131
- searchAdopted,
7132
- vectorIndexSkipped,
7133
- withheldConstraints
7134
- };
7135
- }
7136
- /** Read what the database has, for the schemas the collections live in. */
7137
- async function readExistingSchema(client, schemas) {
7138
- const tables = /* @__PURE__ */ new Map();
7139
- const enums = /* @__PURE__ */ new Set();
7140
- if (schemas.length === 0) return {
7141
- tables,
7142
- enums
7143
- };
7144
- const inList = schemas.map((schema) => `'${assertSafeIdentifier(schema, "schema name")}'`).join(", ");
7145
- const notNullColumns = /* @__PURE__ */ new Set();
7146
- const { rows: columns } = await client.query(`SELECT table_schema, table_name, column_name, is_nullable
7147
- FROM information_schema.columns
7148
- WHERE table_schema IN (${inList})`);
7149
- for (const row of columns) {
7150
- const key = `${row.table_schema}.${row.table_name}`;
7151
- if (!tables.has(key)) tables.set(key, /* @__PURE__ */ new Set());
7152
- tables.get(key).add(row.column_name);
7153
- if (row.is_nullable === "NO") notNullColumns.add(`${key}.${row.column_name}`);
7154
- }
7155
- const populatedTables = /* @__PURE__ */ new Set();
7156
- const { rows: realTables } = await client.query(`SELECT n.nspname AS schema, c.relname AS name
7157
- FROM pg_class c
7158
- JOIN pg_namespace n ON c.relnamespace = n.oid
7159
- WHERE c.relkind IN ('r', 'p') AND n.nspname IN (${inList})`);
7160
- if (realTables.length > 0) {
7161
- const probes = realTables.map((row) => {
7162
- const schema = assertSafeIdentifier(row.schema, "schema name");
7163
- const table = assertSafeIdentifier(row.name, "table name");
7164
- return `SELECT ${quoteSqlLiteral(`${schema}.${table}`)} AS key, EXISTS(SELECT 1 FROM "${schema}"."${table}" LIMIT 1) AS populated`;
7165
- });
7166
- const { rows: populationRows } = await client.query(probes.join(" UNION ALL "));
7167
- for (const row of populationRows) if (row.populated) populatedTables.add(row.key);
7168
- }
7169
- const enumValues = /* @__PURE__ */ new Map();
7170
- const { rows: enumValueRows } = await client.query(`SELECT n.nspname AS schema, t.typname AS name, e.enumlabel AS value
7171
- FROM pg_enum e
7172
- JOIN pg_type t ON e.enumtypid = t.oid
7173
- JOIN pg_namespace n ON t.typnamespace = n.oid
7174
- WHERE n.nspname IN (${inList})
7175
- ORDER BY t.typname, e.enumsortorder`);
7176
- for (const row of enumValueRows) {
7177
- const key = `${row.schema}.${row.name}`;
7178
- if (!enumValues.has(key)) enumValues.set(key, []);
7179
- enumValues.get(key).push(row.value);
7180
- }
7181
- const { rows: enumRows } = await client.query(`SELECT n.nspname AS schema, t.typname AS name
7182
- FROM pg_type t
7183
- JOIN pg_namespace n ON t.typnamespace = n.oid
7184
- WHERE t.typtype = 'e' AND n.nspname IN (${inList})`);
7185
- for (const row of enumRows) enums.add(`${row.schema}.${row.name}`);
7186
- const constraints = /* @__PURE__ */ new Set();
7187
- const { rows: constraintRows } = await client.query(`SELECT n.nspname AS schema, c.relname AS table, con.conname AS name
7188
- FROM pg_constraint con
7189
- JOIN pg_class c ON con.conrelid = c.oid
7190
- JOIN pg_namespace n ON c.relnamespace = n.oid
7191
- WHERE n.nspname IN (${inList})`);
7192
- for (const row of constraintRows) constraints.add(`${row.schema}.${row.table}.${row.name}`);
7193
- const columnComments = /* @__PURE__ */ new Map();
7194
- const { rows: commentRows } = await client.query(`SELECT n.nspname AS schema, c.relname AS table, a.attname AS column, d.description AS comment
7195
- FROM pg_description d
7196
- JOIN pg_class c ON d.objoid = c.oid
7197
- JOIN pg_namespace n ON c.relnamespace = n.oid
7198
- JOIN pg_attribute a ON a.attrelid = c.oid AND a.attnum = d.objsubid
7199
- WHERE d.objsubid > 0 AND n.nspname IN (${inList})`);
7200
- for (const row of commentRows) {
7201
- if (row.comment == null) continue;
7202
- columnComments.set(`${row.schema}.${row.table}.${row.column}`, row.comment);
7203
- }
7204
- return {
7205
- tables,
7206
- enums,
7207
- constraints,
7208
- columnComments,
7209
- enumValues,
7210
- notNullColumns,
7211
- populatedTables
7212
- };
7213
- }
7214
- /**
7215
- * What to tell an operator whose `search` block no longer matches its column.
7216
- *
7217
- * Every line here is doing work: naming the collection is not enough, because
7218
- * the symptom (a search that finds nothing) points at the data, not the schema;
7219
- * and the remediation has to be exact, because it is a table rewrite the
7220
- * operator is being asked to schedule rather than discover.
7221
- */
7222
- function searchDriftMessage(drift) {
7223
- return "The `search` block changed after its generated column was created, and Postgres cannot alter a generated expression in place.\nRebase will not rebuild it for you: dropping and re-adding a STORED generated column rewrites the whole table under an ACCESS EXCLUSIVE lock and rebuilds its GIN index, which is an outage this unattended path may not schedule on your behalf.\nUntil it is rebuilt the column keeps indexing the previous fields, weights and language — searches for anything added since return nothing, which reads from outside as \"no such row\".\nRun these (or revert the block to what the column was built from), then boot again:\n" + drift.map((d) => ` "${d.table}"."${d.column}" was generated from a different \`search\` block (recorded ${d.found}, current ${d.expected}).\n` + d.rebuild.map((s) => ` ${s}`).join("\n")).join("\n") + "\n The GIN index is dropped with the column and recreated concurrently on the next boot.";
7224
- }
7225
- /**
7226
- * The missing-pgvector explanation, appended to the error that reveals it.
7227
- *
7228
- * A `{ type: "vector" }` property compiles to `VECTOR(n)`, and nothing in the
7229
- * OSS pipeline installs pgvector — not this ensure, not `db push`. Installing
7230
- * an extension on someone's database is a decision with a deployment behind it
7231
- * (image, superuser, cloud allow-list), so this path stays a refusal; what it
7232
- * must not stay is a bare `type "vector" does not exist` on a crash-looping
7233
- * pod, which names nothing the reader can act on.
7234
- *
7235
- * The scaffold now ships `pgvector/pgvector:pg18`, so this is reached by a
7236
- * project pointed at a database someone else provisioned — which is exactly
7237
- * the case where naming the extension and the image is worth the words.
7238
- */
7239
- function vectorExtensionHint(message) {
7240
- if (!/type "(vector|halfvec|sparsevec)" does not exist/i.test(message)) return "";
7241
- return "\n pgvector is not installed on this database, and Rebase does not install it: it is a server extension, so it needs an image that ships it (the scaffold's `pgvector/pgvector:pg18` does; a stock `postgres:18` does not) and a role allowed to run `CREATE EXTENSION vector;`. Install it once, then boot again. Rebase then creates an ANN index for the column automatically — see the `index` option on the property.";
7242
- }
7243
- /**
7244
- * Read what the database looks like, for the schemas a set of collections
7245
- * lives in.
7246
- *
7247
- * The same read `ensureCollectionTables` does at boot, exposed on its own for
7248
- * the callers that want to *plan* against a real database without changing it —
7249
- * the live schema editor, which has to tell somebody what a change would do
7250
- * before they agree to it.
7251
- */
7252
- async function readSchemaFactsFor(client, collections) {
7253
- const relational = relationalCollections(collections);
7254
- return readExistingSchema(client, Array.from(/* @__PURE__ */ new Set([...relational.map(schemaOf), ...planJunctionTables(relational).map((junction) => junction.schema)])));
7255
- }
7256
- /**
7257
- * Bring the database up to date. Returns what it did.
7258
- *
7259
- * Each statement runs on its own rather than in one transaction: they are all
7260
- * independently safe and idempotent, and a single failure (an enum label that
7261
- * cannot be added, say) should not roll back the tables that were created fine.
7262
- * The error is surfaced with the statement that caused it.
7263
- */
7264
- async function ensureCollectionTables(client, collections, log) {
7265
- const schemas = Array.from(/* @__PURE__ */ new Set([...collections.map(schemaOf), ...planJunctionTables(collections).map((j) => j.schema)]));
7266
- for (const schema of schemas) {
7267
- assertSafeIdentifier(schema, "schema name");
7268
- if (schema !== "public") await client.query(`CREATE SCHEMA IF NOT EXISTS "${schema}";`);
7269
- }
7270
- const plan = planCollectionSchemaEnsure(collections, await readExistingSchema(client, schemas));
7271
- const failures = [];
7272
- for (const legacy of plan.legacyForeignKeys) {
7273
- const message = `Renaming "${legacy.table}"."${legacy.legacy}" to "${legacy.expected}". The old name is the one Rebase derived for this relation before it singularized properly; the column keeps its data, indexes and constraints. To keep the old name instead, set \`localKey: "${legacy.legacy}"\` on the relation and this will stop.`;
7274
- logger.info(`[schema] ${message}`);
7275
- log?.(message);
7276
- }
7277
- if (plan.searchDrift.length > 0) throw new Error(searchDriftMessage(plan.searchDrift));
7278
- for (const adopted of plan.searchAdopted) {
7279
- const message = `Adopting the existing generated column "${adopted.table}"."${adopted.column}" and recording what the current \`search\` block would generate. Any later change to that block will be detected and refused; a change made *before* this version was deployed cannot be, so if search has been missing content, rebuild the column once: ALTER TABLE "${adopted.table.split(".").join("\".\"")}" DROP COLUMN "${adopted.column}"; and boot again.`;
7280
- logger.info(`[schema] ${message}`);
7281
- log?.(message);
7282
- }
7283
- for (const skip of plan.vectorIndexSkipped) {
7284
- const message = `No ANN index on "${skip.table}"."${skip.column}": ${skip.reason}`;
7285
- logger.warn(`[schema] ${message}`);
7286
- log?.(message);
7287
- }
7288
- for (const withheld of plan.withheldConstraints) {
7289
- const message = `No NOT NULL on "${withheld.target}": ${withheld.reason} ${withheld.remedy}`;
7290
- logger.warn(`[schema] ${message}`);
7291
- log?.(message);
7292
- }
7293
- if (plan.actions.length === 0) {
7294
- log?.("Schema is up to date; nothing to create.");
7295
- return {
7296
- ...plan,
7297
- failures
7298
- };
7299
- }
7300
- for (const action of plan.actions) try {
7301
- if (await applyAction(client, action)) log?.(`${action.kind}: ${action.target}`);
7302
- else log?.(`${action.kind}: ${action.target} (already created by a peer)`);
7303
- } catch (err) {
7304
- const message = err instanceof Error ? err.message : String(err);
7305
- if (action.kind === "add-constraint" || action.kind === "comment-column") {
7306
- failures.push({
7307
- kind: action.kind,
7308
- target: action.target,
7309
- error: message
7310
- });
7311
- continue;
7312
- }
7313
- throw new Error(`Failed to ${action.kind} ${action.target}: ${message}${vectorExtensionHint(message)}\n ${action.sql}`);
7314
- }
7315
- return {
7316
- ...plan,
7317
- failures
7318
- };
7319
- }
7320
- /** Attempts per action, including the first. Matches the server's bootstraps. */
7321
- var DDL_ATTEMPTS = 4;
5676
+ return specs;
5677
+ };
7322
5678
  /**
7323
- * Run one planned statement, surviving a simultaneous boot.
5679
+ * Every declared index across a set of collections, in a stable order.
7324
5680
  *
7325
- * Every statement in a plan is written to be idempotent, and that is not the
7326
- * same as being safe to run concurrently: `CREATE IF NOT EXISTS` reads the
7327
- * catalog and then writes to it as two steps, so peers starting together both
7328
- * see "absent" and the loser gets a duplicate key on a *catalog* index. Measured
7329
- * against Postgres 18: five instances, 8 of 10 calls lost. `CREATE TYPE` is
7330
- * worse, because Postgres has no `IF NOT EXISTS` for it at all.
7331
- *
7332
- * What made that fatal here rather than merely noisy is the loop this sits in.
7333
- * A losing statement threw, and the throw abandoned **every remaining action in
7334
- * the plan** — so a replica that lost one race came up missing tables it never
7335
- * attempted, and the boot log blamed the one statement that failed.
7336
- *
7337
- * @returns `true` if this process applied the statement, `false` if a peer had
7338
- * already created the object. The distinction is only for the log; both mean
7339
- * the object is now there.
7340
- * @throws the original error for anything that is not a race — a syntax error, a
7341
- * permission failure, a unique constraint the customer's own rows violate.
5681
+ * Sorted because the result reaches `schema.sql`, which `doctor` string-
5682
+ * compares against a regenerated copy `generatePostgresDdl` does not sort its
5683
+ * collections, so leaving this in declaration order would make the artifact
5684
+ * depend on the order files happened to load in.
7342
5685
  */
7343
- async function applyAction(client, action) {
7344
- for (let attempt = 1;; attempt++) try {
7345
- await client.query(action.sql);
7346
- return true;
7347
- } catch (err) {
7348
- if (isDuplicateObjectRace(err)) {
7349
- logger.debug(`[schema] ${action.kind} ${action.target}: already created by another instance`);
7350
- return false;
7351
- }
7352
- if (isConcurrentDdlRace(err) && attempt < DDL_ATTEMPTS) {
7353
- logger.debug(`[schema] ${action.kind} ${action.target}: lost a race with another instance (attempt ${attempt}/${DDL_ATTEMPTS}) — retrying`);
7354
- await new Promise((resolve) => setTimeout(resolve, 40 * attempt * (1 + Math.random())));
7355
- continue;
7356
- }
7357
- throw err;
7358
- }
7359
- }
5686
+ var buildCollectionIndexPlan = (collections, resolveColumnName) => collections.flatMap((collection) => buildCollectionIndexSpecs(collection, resolveColumnName)).sort((a, b) => a.schema.localeCompare(b.schema) || a.table.localeCompare(b.table) || a.indexName.localeCompare(b.indexName));
7360
5687
  //#endregion
7361
- export { camelCase as $, fieldKeyForColumn as A, parseIdValues as B, getJunctionCollectionConfig as C, policyToPostgres as D, getEffectiveSecurityRules as E, getTableVarName as F, updateDateAutoValues as G, createRelationRef as H, resolveCollectionRelations as I, legacyForeignKeyName as J, firstFreeKey as K, buildCompositeId as L, getColumnName as M, getEnumVarName as N, securityRuleToConditions as O, getTableName as P, mergeDeep as Q, getDeclaredPrimaryKeys as R, resolveStringColumnLength as S, resolveJunctionSpecs as T, createRelationRefWithData as U, sortCollectionsBySlug as V, normalizeToEntityRelation as W, getPolicyNamesForRule as X, toWireKey as Y, isPrototypePollutingKey as Z, OrderBySpecError as _, generatePostgresDdl as a, ANONYMOUS_USER_ID as at, CollectionRegistry as b, planCollectionPolicies as c, Vector as ct, authUsersColumnSql as d, toSnakeCase as et, SEARCH_UNACCENT_FN as f, buildSdkData as g, visibleColumnProjection as h, readSchemaFactsFor as i, resolveClientListLimit as it, findRelation as j, findAnonymousGrants as k, resolveColumnName as l, hiddenColumnsOption as m, planCollectionSchemaEnsure as n, DEFAULT_ONE_OF_VALUE as nt, generatePostgresPoliciesDdl as o, hasForeignKeyOnTarget as ot, buildSearchColumnSpec as p, generateForeignKeyName as q, readExistingSchema as r, ListLimitError as rt, generatePostgresSearchDdl as s, isManyToMany as st, ensure_collection_tables_exports as t, DEFAULT_ONE_OF_TYPE as tt, AUTH_USERS_COLUMNS as u, normalizeDriverOrderBy as v, getJunctionSecurityRules as w, relationalCollections as x, parseOrderBySpecStrict as y, isAddressableId as z };
5688
+ export { sortCollectionsBySlug as A, getPolicyNamesForRule as B, getTableName as C, getDeclaredPrimaryKeys as D, buildCompositeId as E, firstFreeKey as F, DEFAULT_ONE_OF_TYPE as G, mergeDeep as H, generateForeignKeyName as I, resolveClientListLimit as J, DEFAULT_ONE_OF_VALUE as K, legacyForeignKeyName as L, createRelationRefWithData as M, normalizeToEntityRelation as N, isAddressableId as O, updateDateAutoValues as P, Vector as Q, toPostgresIdentifier as R, getEnumVarName as S, resolveCollectionRelations as T, camelCase as U, isPrototypePollutingKey as V, toSnakeCase as W, hasForeignKeyOnTarget as X, ANONYMOUS_USER_ID as Y, isManyToMany as Z, securityRuleToConditions as _, buildSdkData as a, findRelation as b, parseOrderBySpecStrict as c, getJunctionCollectionConfig as d, getJunctionSecurityRules as f, policyToPostgres as g, getInjectedSecurityRules as h, collectionIndexStatements as i, createRelationRef as j, parseIdValues as k, CollectionRegistry as l, getEffectiveSecurityRules as m, buildCollectionIndexSpecs as n, OrderBySpecError as o, resolveJunctionSpecs as p, ListLimitError as q, collectionIndexStatement as r, normalizeDriverOrderBy as s, buildCollectionIndexPlan as t, relationalCollections as u, findAnonymousGrants as v, getTableVarName as w, getColumnName as x, fieldKeyForColumn as y, toWireKey as z };
7362
5689
 
7363
- //# sourceMappingURL=ensure-collection-tables-DpGX_25A.js.map
5690
+ //# sourceMappingURL=collection-index-DxJBvVTH.js.map