@rebasepro/server-postgres 0.12.1-canary.g7fff3b4 → 0.12.1-canary.g802486a

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 (71) hide show
  1. package/dist/PostgresBackendDriver.d.ts +1 -1
  2. package/dist/auth/services.d.ts +6 -1
  3. package/dist/backup/backup-service.d.ts +10 -1
  4. package/dist/backup/pg-tools.d.ts +47 -0
  5. package/dist/{backup-service-vAKWJkYL.js → backup-service-CD8o_1Sl.js} +142 -10
  6. package/dist/backup-service-CD8o_1Sl.js.map +1 -0
  7. package/dist/cli-helpers.d.ts +15 -0
  8. package/dist/{ensure-collection-policies-BjSwj0FM.js → ensure-collection-policies-ViG8XiPn.js} +2 -2
  9. package/dist/{ensure-collection-policies-BjSwj0FM.js.map → ensure-collection-policies-ViG8XiPn.js.map} +1 -1
  10. package/dist/{ensure-collection-tables-D6-XhqnQ.js → ensure-collection-tables-CBQdOETu.js} +72 -12
  11. package/dist/ensure-collection-tables-CBQdOETu.js.map +1 -0
  12. package/dist/index.es.js +969 -685
  13. package/dist/index.es.js.map +1 -1
  14. package/dist/schema/ensure-collection-tables.d.ts +21 -1
  15. package/dist/schema/generate-postgres-ddl-logic.d.ts +19 -0
  16. package/dist/schema/introspect-db-constraints.d.ts +57 -0
  17. package/dist/schema/introspect-db-logic.d.ts +94 -5
  18. package/dist/schema/introspect-db-queries.d.ts +119 -0
  19. package/dist/schema/introspect-db-structure.d.ts +263 -0
  20. package/dist/schema/introspect-db-types.d.ts +11 -0
  21. package/dist/services/FetchService.d.ts +4 -1
  22. package/dist/services/RelationService.d.ts +24 -1
  23. package/dist/services/channel-bus/index.d.ts +1 -7
  24. package/dist/services/collection-helpers.d.ts +36 -2
  25. package/dist/services/dataService.d.ts +3 -1
  26. package/dist/services/row-pipeline.d.ts +1 -1
  27. package/dist/{src-C_NHNVW2.js → src-DlPBctw_.js} +207 -22
  28. package/dist/src-DlPBctw_.js.map +1 -0
  29. package/dist/utils/connection-string.d.ts +29 -0
  30. package/dist/utils/drizzle-conditions.d.ts +5 -4
  31. package/dist/utils/pg-error-utils.d.ts +16 -0
  32. package/dist/{websocket-DB7TbFPT.js → websocket-B2LsrINK.js} +4 -3
  33. package/dist/websocket-B2LsrINK.js.map +1 -0
  34. package/package.json +6 -6
  35. package/src/PostgresAdapter.ts +7 -2
  36. package/src/PostgresBackendDriver.ts +4 -0
  37. package/src/auth/services.ts +6 -3
  38. package/src/backup/backup-cli.ts +41 -2
  39. package/src/backup/backup-service.ts +38 -5
  40. package/src/backup/pg-tools.ts +96 -3
  41. package/src/cli-helpers.ts +26 -0
  42. package/src/cli.ts +13 -23
  43. package/src/collections/validate-relations.ts +15 -0
  44. package/src/data-transformer.ts +9 -3
  45. package/src/schema/ensure-collection-tables.ts +81 -10
  46. package/src/schema/generate-drizzle-schema-logic.ts +26 -1
  47. package/src/schema/generate-postgres-ddl-logic.ts +50 -6
  48. package/src/schema/introspect-db-constraints.ts +385 -0
  49. package/src/schema/introspect-db-inference.ts +18 -8
  50. package/src/schema/introspect-db-logic.ts +385 -71
  51. package/src/schema/introspect-db-queries.ts +326 -0
  52. package/src/schema/introspect-db-structure.ts +670 -0
  53. package/src/schema/introspect-db-types.ts +56 -0
  54. package/src/schema/introspect-db.ts +37 -80
  55. package/src/security/policy-drift.test.ts +11 -3
  56. package/src/services/BranchService.ts +66 -28
  57. package/src/services/FetchService.ts +90 -14
  58. package/src/services/PersistService.ts +20 -6
  59. package/src/services/RelationService.ts +211 -45
  60. package/src/services/channel-bus/index.ts +0 -9
  61. package/src/services/collection-helpers.ts +69 -3
  62. package/src/services/dataService.ts +3 -1
  63. package/src/services/row-pipeline.ts +1 -1
  64. package/src/utils/connection-string.ts +58 -0
  65. package/src/utils/drizzle-conditions.ts +31 -6
  66. package/src/utils/pg-error-utils.ts +19 -0
  67. package/src/websocket.ts +15 -6
  68. package/dist/backup-service-vAKWJkYL.js.map +0 -1
  69. package/dist/ensure-collection-tables-D6-XhqnQ.js.map +0 -1
  70. package/dist/src-C_NHNVW2.js.map +0 -1
  71. package/dist/websocket-DB7TbFPT.js.map +0 -1
package/dist/index.es.js CHANGED
@@ -2,11 +2,11 @@ import { createRequire as __createRequire } from "module";
2
2
  import process from "process";
3
3
  __createRequire(import.meta.url);
4
4
  import { a as guardPoolAgainstDirtyRelease, i as createReadReplicaConnection, n as createDirectDatabaseConnection, o as pinSearchPath, r as createPostgresDatabaseConnection } from "./connection-BuZ97wsr.js";
5
- import { C as updateDateAutoValues, D as camelCase, E as mergeDeep, M as isManyToMany, N as Vector, O as toSnakeCase, S as normalizeToEntityRelation, T as getPolicyNamesForRule, _ as buildCompositeId, a as getJunctionSecurityRules, b as createRelationRef, c as policyToPostgres, d as findRelation, f as getColumnName, g as resolveCollectionRelations, h as getTableVarName, i as getJunctionCollectionConfig, j as hasForeignKeyOnTarget, l as securityRuleToConditions, m as getTableName$1, n as CollectionRegistry, o as resolveJunctionSpecs, p as getEnumVarName, r as resolveStringColumnLength, s as getEffectiveSecurityRules, t as buildSdkData, u as findAnonymousGrants, v as getDeclaredPrimaryKeys, w as generateForeignKeyName, x as createRelationRefWithData, y as parseIdValues } from "./src-C_NHNVW2.js";
5
+ import { A as toSnakeCase, C as normalizeToEntityRelation, D as getPolicyNamesForRule, F as Vector, N as hasForeignKeyOnTarget, O as mergeDeep, P as isManyToMany, S as createRelationRefWithData, T as generateForeignKeyName, _ as buildCompositeId, a as getJunctionSecurityRules, b as parseIdValues, c as policyToPostgres, d as findRelation, f as getColumnName, g as resolveCollectionRelations, h as getTableVarName, i as getJunctionCollectionConfig, k as camelCase, l as securityRuleToConditions, m as getTableName$1, n as CollectionRegistry, o as resolveJunctionSpecs, p as getEnumVarName, r as resolveStringColumnLength, s as getEffectiveSecurityRules, t as buildSdkData, u as findAnonymousGrants, v as getDeclaredPrimaryKeys, w as updateDateAutoValues, x as createRelationRef, y as isAddressableId } from "./src-DlPBctw_.js";
6
6
  import { n as isPostgresCollectionConfig, r as isRelationalCollectionConfig } from "./src-DoU9yPqq.js";
7
7
  import { t as ANONYMOUS_USER_ID } from "./policy-CeA1JcxP.js";
8
- import { t as createPostgresWebSocket } from "./websocket-DB7TbFPT.js";
9
- import { A as serverVersionNumToMajor, C as globalsFileForDump, D as parseDbNameFromUrl, E as parseBackupTimestamp, M as withDatabaseName, O as parsePgToolMajor, S as checkToolServerCompatibility, T as parseBackupDestination, _ as buildBackupFilename, a as detectToolMajor, b as buildPgRestoreArgs, c as listBackups, d as resolvePgBinary, f as restoreDump, g as selectBackupsToPrune, h as require_source, i as createDump, j as splitGlobalsStatements, k as resolveConnectionString, l as preflight, m as validateDump, n as applyGlobals, o as ensureDatabaseExists, p as uploadBackup, s as getServerVersionMajor, t as BackupToolError, u as pruneBackups, v as buildPgDumpArgs, w as joinStorageKey, x as buildPgRestoreListArgs, y as buildPgDumpallGlobalsArgs } from "./backup-service-vAKWJkYL.js";
8
+ import { t as createPostgresWebSocket } from "./websocket-B2LsrINK.js";
9
+ import { A as parsePgToolMajor, C as checkToolServerCompatibility, D as parseBackupDestination, E as joinStorageKey, M as serverVersionNumToMajor, N as splitGlobalsStatements, O as parseBackupTimestamp, P as withDatabaseName, S as buildRowSecurityPgOptions, T as globalsFileForDump, _ as buildBackupFilename, a as detectToolMajor, b as buildPgRestoreArgs, c as listBackups, d as resolvePgBinary, f as restoreDump, g as selectBackupsToPrune, h as require_source, i as createDump, j as resolveConnectionString, k as parseDbNameFromUrl, l as preflight, m as validateDump, n as applyGlobals, o as ensureDatabaseExists, p as uploadBackup, s as getServerVersionMajor, t as BackupToolError, u as pruneBackups, v as buildPgDumpArgs, w as diagnoseRowSecurityDumpFailure, x as buildPgRestoreListArgs, y as buildPgDumpallGlobalsArgs } from "./backup-service-CD8o_1Sl.js";
10
10
  import { Client, Pool } from "pg";
11
11
  import { drizzle } from "drizzle-orm/node-postgres";
12
12
  import { ApiError, createEmailService, loadCollectionsFromDirectory, logger } from "@rebasepro/server";
@@ -50,6 +50,39 @@ function resolveClientListLimit(rawLimit, opts = {}) {
50
50
  return opts.vectorSearch ? opts.vectorDefaultLimit ?? 10 : opts.defaultLimit ?? 50;
51
51
  }
52
52
  //#endregion
53
+ //#region ../common/src/util/email.ts
54
+ /**
55
+ * Email normalization — one implementation, because the database enforces it.
56
+ *
57
+ * `ensureAuthTablesExist` puts a `UNIQUE INDEX ON users (lower(email))` on the
58
+ * auth table. That index decides what "the same address" means, and it does not
59
+ * trim: to Postgres, `' foo@bar.com'` and `'foo@bar.com'` are two addresses and
60
+ * both may exist. So every write that reaches the column has to agree with
61
+ * every read, exactly, or the two disagree in the one direction that matters —
62
+ * a row that exists and cannot be found.
63
+ *
64
+ * That is not hypothetical. The lookup path trimmed and the admin create paths
65
+ * did not, so a user created through `POST /api/data/users` or
66
+ * `POST /api/auth/admin/users` with a stray space was stored untrimmed,
67
+ * survived the unique index alongside the real address, and was unreachable by
68
+ * login forever after. The HTTP auth routes were unaffected only because Zod's
69
+ * `.email()` happens to reject surrounding whitespace — a guard on a different
70
+ * layer, for a different reason, that the admin paths do not sit behind.
71
+ *
72
+ * It lives in `common` because `server`, `server-postgres` and `server-mongo`
73
+ * all write this column and must agree exactly, and `common` is the only
74
+ * package all three already depend on.
75
+ */
76
+ /**
77
+ * Canonical form of an email address: trimmed, lower-cased.
78
+ *
79
+ * Non-strings pass through untouched, so this is safe to apply to a value out
80
+ * of a partial update payload whose type is not known yet.
81
+ */
82
+ function normalizeEmail(email) {
83
+ return typeof email === "string" ? email.trim().toLowerCase() : email;
84
+ }
85
+ //#endregion
53
86
  //#region ../common/src/util/callbacks.ts
54
87
  /**
55
88
  * Helper function to recursively check if there are any callbacks in the properties.
@@ -195,6 +228,27 @@ function getColumnMeta(col) {
195
228
  primary: typeof raw.primary === "boolean" ? raw.primary : void 0
196
229
  };
197
230
  }
231
+ /**
232
+ * Whether an address could name a row in this table, judged by the columns.
233
+ *
234
+ * {@link getPrimaryKeys} lets a config's `isId: "uuid"` win over the schema, so
235
+ * its `isUUID` is a claim rather than a fact — right for deriving addresses,
236
+ * wrong for refusing a query. Here the Drizzle column type decides, because it
237
+ * is what Postgres will enforce: a `uuid` column meets `/c/products/new` with
238
+ * `22P02`, which aborts the surrounding transaction and turns every later
239
+ * statement into an unrelated-looking `25P02`.
240
+ */
241
+ function idCanAddressTable(id, table, idInfoArray) {
242
+ return isAddressableId(id, idInfoArray.map((info) => {
243
+ const col = table[info.fieldName];
244
+ const meta = col ? getColumnMeta(col) : void 0;
245
+ if (!meta?.columnType) return info;
246
+ return {
247
+ ...info,
248
+ isUUID: meta.columnType === "PgUUID"
249
+ };
250
+ }));
251
+ }
198
252
  function getCollectionByPath(collectionPath, registry) {
199
253
  const collection = registry.getCollectionByPath(collectionPath);
200
254
  if (!collection) {
@@ -282,6 +336,35 @@ function requirePrimaryKeys(collection, registry) {
282
336
  return keys;
283
337
  }
284
338
  /**
339
+ * The column on the *source* table that a `hasOne`/`hasMany` link points at.
340
+ *
341
+ * `sourceKey` is authored when the two sides join on a natural key — an
342
+ * external identity id, a SKU — and left off when they join on the row id,
343
+ * which is the overwhelming majority. That makes `undefined` the only optional
344
+ * field on a resolved relation, so it gets exactly one reader: this function.
345
+ * Every consumer that needs the column asks here, and none of them re-derives
346
+ * "or else the primary key" for itself. That is the whole point — the fallback
347
+ * chains this codebase removed from relation resolution were dangerous because
348
+ * they were *duplicated* and could disagree, not because they existed.
349
+ */
350
+ function sourceKeyField(relation, sourceCollection, registry) {
351
+ if (relation.sourceKey) return relation.sourceKey;
352
+ return requirePrimaryKeys(sourceCollection, registry)[0].fieldName;
353
+ }
354
+ /**
355
+ * Whether this link joins on something other than the source's primary key.
356
+ *
357
+ * Callers that hold a parent *id* — which is most of them, since an id is what
358
+ * a URL carries — must translate it to the source key's value before it can be
359
+ * compared with the target's foreign key. Those that hold the parent *row*, or
360
+ * that build a correlated subquery over the source table, can read the column
361
+ * directly and skip the lookup.
362
+ */
363
+ function joinsOnNaturalKey(relation, sourceCollection, registry) {
364
+ if (!relation.sourceKey) return false;
365
+ return relation.sourceKey !== requirePrimaryKeys(sourceCollection, registry)[0].fieldName;
366
+ }
367
+ /**
285
368
  * Collections whose key the *browser* cannot resolve, and what it will do
286
369
  * instead.
287
370
  *
@@ -452,7 +535,9 @@ var DrizzleConditionBuilder = class {
452
535
  case "hasMany": {
453
536
  const fkColumn = targetTable[relation.foreignKeyOnTarget];
454
537
  if (!fkColumn) throw new Error(`Foreign key column '${relation.foreignKeyOnTarget}' not found in the target table of relation '${relation.relationName}'.`);
455
- return eq(fkColumn, parentId);
538
+ if (!relation.sourceKey) return eq(fkColumn, parentId);
539
+ const { table, idColumn } = parent();
540
+ return sql`${fkColumn} = (SELECT ${sql.identifier(relation.sourceKey)} FROM ${table} WHERE ${idColumn} = ${parentId})`;
456
541
  }
457
542
  case "belongsTo": {
458
543
  const { table, idColumn } = parent();
@@ -542,12 +627,16 @@ var DrizzleConditionBuilder = class {
542
627
  column: foreignKey
543
628
  };
544
629
  }
545
- if (relation && (hasForeignKeyOnTarget(relation) || isManyToMany(relation)) && registry && sourceIdColumn) return {
546
- kind: "relation",
547
- relation,
548
- registry,
549
- sourceIdColumn
550
- };
630
+ if (relation && (hasForeignKeyOnTarget(relation) || isManyToMany(relation)) && registry && sourceIdColumn) {
631
+ const correlationColumn = hasForeignKeyOnTarget(relation) && relation.sourceKey ? columnAt(relation.sourceKey) : sourceIdColumn;
632
+ if (!correlationColumn) throw new Error(`\`sourceKey: "${relation.sourceKey}"\` on relation '${relation.relationName}' is not a column on '${collectionPath}', so a filter on that relation has nothing to correlate against.`);
633
+ return {
634
+ kind: "relation",
635
+ relation,
636
+ registry,
637
+ sourceIdColumn: correlationColumn
638
+ };
639
+ }
551
640
  }
552
641
  for (const guess of [`${field}_id`, generateForeignKeyName(field)]) {
553
642
  const foreignKey = columnAt(guess);
@@ -1346,8 +1435,9 @@ async function parseDataFromServer(data, collection, db, registry) {
1346
1435
  } else if (hasForeignKeyOnTarget(relation) && db && registry) try {
1347
1436
  const targetCollection = relation.target();
1348
1437
  const targetTable = registry.getTable(getTableName$1(targetCollection));
1349
- const currentId = buildCompositeId(data, getPrimaryKeys(collection, registry));
1350
- if (targetTable && currentId) {
1438
+ const pks = getPrimaryKeys(collection, registry);
1439
+ const currentId = relation.sourceKey ? data[relation.sourceKey] : buildCompositeId(data, pks);
1440
+ if (targetTable && currentId !== void 0 && currentId !== null && currentId !== "") {
1351
1441
  const foreignKeyColumn = targetTable[relation.foreignKeyOnTarget];
1352
1442
  if (foreignKeyColumn) {
1353
1443
  const relatedRows = await db.select().from(targetTable).where(eq(foreignKeyColumn, currentId)).limit(relation.cardinality === "one" ? 1 : 100);
@@ -1719,8 +1809,67 @@ var RelationService = class {
1719
1809
  * reading. Left alone it would silently match on the first key column and
1720
1810
  * hand a tenant's rows to its neighbour — say so instead.
1721
1811
  */
1722
- assertSingleKeyAddressable(parentCollection, parentPks, via) {
1723
- if (parentPks.length > 1) throw new Error(`Relation on '${parentCollection.slug}' uses '${via}', a single foreign-key column, but '${parentCollection.slug}' is keyed on ${parentPks.map((k) => `'${k.fieldName}'`).join(" + ")}. One column cannot reference a composite key — express this relation with \`joinPath\`, whose \`on.from\`/\`on.to\` take every key column.`);
1812
+ assertSingleKeyAddressable(parentCollection, parentPks, via, relation) {
1813
+ if (relation && hasForeignKeyOnTarget(relation) && relation.sourceKey) return;
1814
+ if (parentPks.length > 1) throw new Error(`Relation on '${parentCollection.slug}' uses '${via}', a single foreign-key column, but '${parentCollection.slug}' is keyed on ${parentPks.map((k) => `'${k.fieldName}'`).join(" + ")}. One column cannot reference a composite key — give the relation a \`sourceKey\` naming a single unique column to point at, or express it with \`joinPath\`, whose \`on.from\`/\`on.to\` take every key column.`);
1815
+ }
1816
+ /**
1817
+ * What the target's foreign key holds, for each of these parent rows.
1818
+ *
1819
+ * Ordinarily the parent's id, and then this is free. When the relation
1820
+ * declares a `sourceKey` the two are different values, and the mapping
1821
+ * between them lives in the source table — so it costs one SELECT, issued
1822
+ * once for the whole batch rather than per parent.
1823
+ *
1824
+ * Both directions come back because both are needed and deriving one from
1825
+ * the other by hand is how a batch loader ends up attributing a child to the
1826
+ * wrong parent: reads translate id → key to build the WHERE, and then
1827
+ * translate key → id to attribute each row that comes back.
1828
+ */
1829
+ /**
1830
+ * The value a related row's foreign key must hold to belong to this parent.
1831
+ *
1832
+ * `undefined` when the parent's source key is null — which is not an error
1833
+ * here, only in the callers that were about to write it. Exposed for
1834
+ * {@link PersistService}, which stamps this onto a child created under a
1835
+ * nested path and would otherwise write the id and lose the row.
1836
+ */
1837
+ async parentKeyValue(parentCollection, relation, parentId, db = this.db) {
1838
+ const { keyByParentId } = await this.resolveSourceKeys(parentCollection, relation, [parentId], db);
1839
+ return keyByParentId.get(String(parentId));
1840
+ }
1841
+ async resolveSourceKeys(parentCollection, relation, parentIds, db = this.db) {
1842
+ const keyByParentId = /* @__PURE__ */ new Map();
1843
+ const parentIdByKey = /* @__PURE__ */ new Map();
1844
+ const parentPks = requirePrimaryKeys(parentCollection, this.registry);
1845
+ if (!joinsOnNaturalKey(relation, parentCollection, this.registry)) {
1846
+ for (const id of parentIds) {
1847
+ const value = parseIdValues(id, parentPks)[parentPks[0].fieldName];
1848
+ keyByParentId.set(String(id), value);
1849
+ parentIdByKey.set(String(value), id);
1850
+ }
1851
+ return {
1852
+ keyByParentId,
1853
+ parentIdByKey
1854
+ };
1855
+ }
1856
+ const field = sourceKeyField(relation, parentCollection, this.registry);
1857
+ const parentTable = getTableForCollection(parentCollection, this.registry);
1858
+ if (!parentTable[field]) throw new Error(`\`sourceKey: "${field}"\` on relation '${relation.relationName}' is not a column on '${parentCollection.slug}'. It names a column on the source table, not on the target.`);
1859
+ const rows = await db.select().from(parentTable).where(this.parentKeyCondition(parentTable, parentPks, parentIds));
1860
+ for (const row of rows) {
1861
+ const keyValue = row[field];
1862
+ if (keyValue === null || keyValue === void 0) continue;
1863
+ const parentId = buildCompositeId(row, parentPks);
1864
+ keyByParentId.set(String(parentId), keyValue);
1865
+ const existing = parentIdByKey.get(String(keyValue));
1866
+ if (existing !== void 0 && String(existing) !== String(parentId)) throw new Error(`\`sourceKey: "${field}"\` on relation '${relation.relationName}' is not unique on '${parentCollection.slug}': rows '${existing}' and '${parentId}' both hold '${keyValue}'. Add a unique constraint — a link that addresses more than one source row cannot say which one a related row belongs to.`);
1867
+ parentIdByKey.set(String(keyValue), parentId);
1868
+ }
1869
+ return {
1870
+ keyByParentId,
1871
+ parentIdByKey
1872
+ };
1724
1873
  }
1725
1874
  /**
1726
1875
  * Fetch rows related to a parent row through a specific relation
@@ -1779,6 +1928,8 @@ var RelationService = class {
1779
1928
  }
1780
1929
  return rows;
1781
1930
  }
1931
+ const matchValue = hasForeignKeyOnTarget(relation) ? (await this.resolveSourceKeys(parentCollection, relation, [parentId])).keyByParentId.get(String(parentId)) : parsedParentId;
1932
+ if (matchValue === void 0) return [];
1782
1933
  let query = this.db.select().from(targetTable).$dynamic();
1783
1934
  const additionalFilters = [];
1784
1935
  if (options.searchString) {
@@ -1787,7 +1938,7 @@ var RelationService = class {
1787
1938
  const searchCombined = DrizzleConditionBuilder.combineConditionsWithOr(searchConditions);
1788
1939
  if (searchCombined) additionalFilters.push(searchCombined);
1789
1940
  }
1790
- query = applyDynamicRelationQuery(query, query, relation, parsedParentId, targetTable, parentTable, parentIdCol, idField, this.registry, additionalFilters);
1941
+ query = applyDynamicRelationQuery(query, query, relation, matchValue, targetTable, parentTable, parentIdCol, idField, this.registry, additionalFilters);
1791
1942
  if (options.limit) query = query.limit(options.limit);
1792
1943
  const results = await query;
1793
1944
  if (!results || !Array.isArray(results)) return [];
@@ -1830,8 +1981,10 @@ var RelationService = class {
1830
1981
  const parentTable = this.registry.getTable(getTableName$1(parentCollection));
1831
1982
  if (!parentTable) throw new Error("Parent table not found");
1832
1983
  const parentIdCol = parentTable[parentIdInfo.fieldName];
1984
+ const matchValue = hasForeignKeyOnTarget(relation) ? (await this.resolveSourceKeys(parentCollection, relation, [parentId])).keyByParentId.get(String(parentId)) : parsedParentId;
1985
+ if (matchValue === void 0) return 0;
1833
1986
  let query = this.db.select({ count: sql`count(distinct ${targetIdField})` }).from(targetTable).$dynamic();
1834
- query = DrizzleConditionBuilder.buildRelationCountQuery(query, relation, parsedParentId, targetTable, parentTable, parentIdCol, targetIdField, this.registry, additionalFilters);
1987
+ query = DrizzleConditionBuilder.buildRelationCountQuery(query, relation, matchValue, targetTable, parentTable, parentIdCol, targetIdField, this.registry, additionalFilters);
1835
1988
  const result = await query;
1836
1989
  return Number(result[0]?.count || 0);
1837
1990
  }
@@ -1958,17 +2111,24 @@ var RelationService = class {
1958
2111
  }
1959
2112
  return resultMap;
1960
2113
  }
1961
- this.assertSingleKeyAddressable(parentCollection, parentPks, hasForeignKeyOnTarget(relation) ? relation.foreignKeyOnTarget : relation.relationName);
2114
+ this.assertSingleKeyAddressable(parentCollection, parentPks, hasForeignKeyOnTarget(relation) ? relation.foreignKeyOnTarget : relation.relationName, relation);
2115
+ const { keyByParentId, parentIdByKey } = hasForeignKeyOnTarget(relation) ? await this.resolveSourceKeys(parentCollection, relation, parentIds) : {
2116
+ keyByParentId: /* @__PURE__ */ new Map(),
2117
+ parentIdByKey: /* @__PURE__ */ new Map()
2118
+ };
2119
+ const matchValues = hasForeignKeyOnTarget(relation) ? [...keyByParentId.values()] : parsedParentIds;
2120
+ if (matchValues.length === 0) return /* @__PURE__ */ new Map();
1962
2121
  let query = this.db.select().from(targetTable).$dynamic();
1963
- query = applyDynamicRelationQuery(query, query, relation, parsedParentIds, targetTable, parentTable, parentIdCol, targetIdField, this.registry, []);
2122
+ query = applyDynamicRelationQuery(query, query, relation, matchValues, targetTable, parentTable, parentIdCol, targetIdField, this.registry, []);
1964
2123
  const results = await query;
1965
2124
  const resultMap = /* @__PURE__ */ new Map();
1966
- const parentIdSet = new Set(parsedParentIds.map(String));
1967
2125
  for (const row of results) {
1968
2126
  const targetRow = row[getTableName$1(targetCollection)] || row;
1969
- let parentId;
1970
- if (hasForeignKeyOnTarget(relation)) parentId = targetRow[relation.foreignKeyOnTarget];
1971
- if (parentId !== void 0 && parentIdSet.has(String(parentId))) resultMap.set(String(parentId), await this.toRelatedRow(targetRow, targetCollection, targetPks));
2127
+ if (!hasForeignKeyOnTarget(relation)) continue;
2128
+ const foreignKeyValue = targetRow[relation.foreignKeyOnTarget];
2129
+ if (foreignKeyValue === void 0 || foreignKeyValue === null) continue;
2130
+ const parentId = parentIdByKey.get(String(foreignKeyValue));
2131
+ if (parentId !== void 0) resultMap.set(String(parentId), await this.toRelatedRow(targetRow, targetCollection, targetPks));
1972
2132
  }
1973
2133
  return resultMap;
1974
2134
  }
@@ -2046,17 +2206,24 @@ var RelationService = class {
2046
2206
  }
2047
2207
  return resultMap;
2048
2208
  }
2049
- this.assertSingleKeyAddressable(parentCollection, parentPks, hasForeignKeyOnTarget(relation) ? relation.foreignKeyOnTarget : relation.relationName);
2209
+ this.assertSingleKeyAddressable(parentCollection, parentPks, hasForeignKeyOnTarget(relation) ? relation.foreignKeyOnTarget : relation.relationName, relation);
2210
+ const { keyByParentId, parentIdByKey } = hasForeignKeyOnTarget(relation) ? await this.resolveSourceKeys(parentCollection, relation, parentIds) : {
2211
+ keyByParentId: /* @__PURE__ */ new Map(),
2212
+ parentIdByKey: /* @__PURE__ */ new Map()
2213
+ };
2214
+ const matchValues = hasForeignKeyOnTarget(relation) ? [...keyByParentId.values()] : parsedParentIds;
2215
+ if (matchValues.length === 0) return /* @__PURE__ */ new Map();
2050
2216
  let query = this.db.select().from(targetTable).$dynamic();
2051
- query = applyDynamicRelationQuery(query, query, relation, parsedParentIds, targetTable, parentTable, parentIdCol, targetIdField, this.registry, []);
2217
+ query = applyDynamicRelationQuery(query, query, relation, matchValues, targetTable, parentTable, parentIdCol, targetIdField, this.registry, []);
2052
2218
  const results = await query;
2053
2219
  const resultMap = /* @__PURE__ */ new Map();
2054
- const parentIdSet = new Set(parsedParentIds.map(String));
2055
2220
  for (const row of results) {
2056
2221
  const targetRow = row[getTableName$1(targetCollection)] || row;
2057
- let parentId;
2058
- if (hasForeignKeyOnTarget(relation)) parentId = targetRow[relation.foreignKeyOnTarget];
2059
- if (parentId !== void 0 && parentIdSet.has(String(parentId))) {
2222
+ if (!hasForeignKeyOnTarget(relation)) continue;
2223
+ const foreignKeyValue = targetRow[relation.foreignKeyOnTarget];
2224
+ if (foreignKeyValue === void 0 || foreignKeyValue === null) continue;
2225
+ const parentId = parentIdByKey.get(String(foreignKeyValue));
2226
+ if (parentId !== void 0) {
2060
2227
  const key = String(parentId);
2061
2228
  const arr = resultMap.get(key) || [];
2062
2229
  arr.push(await this.toRelatedRow(targetRow, targetCollection, targetPks));
@@ -2155,14 +2322,13 @@ var RelationService = class {
2155
2322
  logger.warn(`Invalid inverse-many config for relation '${key}' in collection '${collection.slug}'`);
2156
2323
  continue;
2157
2324
  }
2158
- const parentPks = requirePrimaryKeys(collection, this.registry);
2159
- const parentIdInfo = parentPks[0];
2160
- const parsedParentId = parseIdValues(id, parentPks)[parentIdInfo.fieldName];
2325
+ const parentKeyValue = (await this.resolveSourceKeys(collection, relation, [id], tx)).keyByParentId.get(String(id));
2326
+ if (parentKeyValue === void 0) throw new Error(`Cannot write relation '${key}' on '${collection.slug}': row '${id}' has no value in \`sourceKey: "${sourceKeyField(relation, collection, this.registry)}"\`, so there is nothing for the related rows to point at.`);
2161
2327
  if (targetEntityIds.length > 0) {
2162
2328
  const parsedTargetIds = targetEntityIds.map((id) => parseIdValues(id, targetPks)[targetIdInfo.fieldName]);
2163
- await tx.update(targetTable).set({ [relation.foreignKeyOnTarget]: null }).where(and(eq(fkCol, parsedParentId), sql`${targetIdCol} NOT IN (${sql.join(parsedTargetIds)})`));
2164
- await tx.update(targetTable).set({ [relation.foreignKeyOnTarget]: parsedParentId }).where(inArray(targetIdCol, parsedTargetIds));
2165
- } else await tx.update(targetTable).set({ [relation.foreignKeyOnTarget]: null }).where(eq(fkCol, parsedParentId));
2329
+ await tx.update(targetTable).set({ [relation.foreignKeyOnTarget]: null }).where(and(eq(fkCol, parentKeyValue), sql`${targetIdCol} NOT IN (${sql.join(parsedTargetIds)})`));
2330
+ await tx.update(targetTable).set({ [relation.foreignKeyOnTarget]: parentKeyValue }).where(inArray(targetIdCol, parsedTargetIds));
2331
+ } else await tx.update(targetTable).set({ [relation.foreignKeyOnTarget]: null }).where(eq(fkCol, parentKeyValue));
2166
2332
  } else logger.warn(`Many relation '${key}' in collection '${collection.slug}' lacks write configuration and will be skipped during save.`);
2167
2333
  }
2168
2334
  }
@@ -2177,8 +2343,7 @@ var RelationService = class {
2177
2343
  const targetTable = getTableForCollection(targetCollection, this.registry);
2178
2344
  const targetPks = requirePrimaryKeys(targetCollection, this.registry);
2179
2345
  const targetIdInfo = targetPks[0];
2180
- const sourcePks = requirePrimaryKeys(sourceCollection, this.registry);
2181
- const sourceIdInfo = sourcePks[0];
2346
+ requirePrimaryKeys(sourceCollection, this.registry)[0];
2182
2347
  if (relation.kind === "via") {
2183
2348
  await this.updateInverseJoinPathRelation(tx, sourceCollection, sourceEntityId, targetCollection, relation, newValue);
2184
2349
  continue;
@@ -2200,13 +2365,14 @@ var RelationService = class {
2200
2365
  logger.warn(`Foreign key column '${relation.foreignKeyOnTarget}' not found in target table for relation '${relation.relationName}'`);
2201
2366
  continue;
2202
2367
  }
2203
- const parsedSourceId = parseIdValues(sourceEntityId, sourcePks)[sourceIdInfo.fieldName];
2204
- if (newValue === null || newValue === void 0) await tx.update(targetTable).set({ [relation.foreignKeyOnTarget]: null }).where(eq(foreignKeyColumn, parsedSourceId));
2368
+ const sourceKeyValue = (await this.resolveSourceKeys(sourceCollection, relation, [sourceEntityId], tx)).keyByParentId.get(String(sourceEntityId));
2369
+ if (sourceKeyValue === void 0) throw new Error(`Cannot write relation '${relation.relationName}' on '${sourceCollection.slug}': row '${sourceEntityId}' has no value in \`sourceKey: "${sourceKeyField(relation, sourceCollection, this.registry)}"\`, so there is nothing for the related row to point at.`);
2370
+ if (newValue === null || newValue === void 0) await tx.update(targetTable).set({ [relation.foreignKeyOnTarget]: null }).where(eq(foreignKeyColumn, sourceKeyValue));
2205
2371
  else {
2206
2372
  const parsedNewTargetId = parseIdValues(newValue, targetPks)[targetIdInfo.fieldName];
2207
2373
  const targetIdField = targetTable[targetIdInfo.fieldName];
2208
- await tx.update(targetTable).set({ [relation.foreignKeyOnTarget]: null }).where(eq(foreignKeyColumn, parsedSourceId));
2209
- await tx.update(targetTable).set({ [relation.foreignKeyOnTarget]: parsedSourceId }).where(eq(targetIdField, parsedNewTargetId));
2374
+ await tx.update(targetTable).set({ [relation.foreignKeyOnTarget]: null }).where(eq(foreignKeyColumn, sourceKeyValue));
2375
+ await tx.update(targetTable).set({ [relation.foreignKeyOnTarget]: sourceKeyValue }).where(eq(targetIdField, parsedNewTargetId));
2210
2376
  }
2211
2377
  } catch (e) {
2212
2378
  logger.warn(`Failed to update inverse relation '${relation.relationName}'`, { error: e });
@@ -2512,7 +2678,7 @@ function relationTargetAddress(targetRow, targetCollection, registry) {
2512
2678
  * expects real types. The row's own address is *not* among the columns — it is
2513
2679
  * derived by the consumer from the collection's primary keys.
2514
2680
  */
2515
- function toCmsRow(row, collection, registry) {
2681
+ function toFlatRow(row, collection, registry) {
2516
2682
  const resolvedRelations = resolveCollectionRelations(collection);
2517
2683
  const normalized = normalizeDbValues(row, collection);
2518
2684
  for (const [key, relation] of Object.entries(resolvedRelations)) {
@@ -2627,238 +2793,497 @@ function assertWritableThrough(hop, path) {
2627
2793
  throw ApiError.badRequest(`"${path}" ends in the to-one relation '${hop.relationKey}', which cannot be written through: the foreign key for a to-one relation lives on '${hop.parentCollection.slug}', not on '${hop.targetCollection.slug}'. Write the target row at "${hop.targetCollection.slug}" and set '${hop.relationKey}' on the parent instead.`, "RELATION_NOT_WRITABLE");
2628
2794
  }
2629
2795
  //#endregion
2630
- //#region src/services/FetchService.ts
2796
+ //#region src/utils/pg-error-utils.ts
2631
2797
  /**
2632
- * Service for handling all row read operations.
2633
- * Handles fetching, searching, counting, and filtering rows.
2798
+ * Shared PostgreSQL error extraction and user-friendly message formatting.
2799
+ *
2800
+ * Drizzle wraps native PG errors in a `.cause` chain. These utilities
2801
+ * unwrap that chain to get the real PostgreSQL error (identified by a
2802
+ * 5-character alphanumeric `code` such as `42P01`) and translate it into
2803
+ * a message that is safe and helpful to show to end-users.
2634
2804
  */
2635
- var FetchService = class {
2636
- db;
2637
- registry;
2638
- relationService;
2639
- constructor(db, registry) {
2640
- this.db = db;
2641
- this.registry = registry;
2642
- this.relationService = new RelationService(db, registry);
2643
- }
2644
- /**
2645
- * Get the relational query builder for a given table name.
2646
- * Safely narrows the DrizzleClient union type to access db.query[tableName].
2647
- */
2648
- getQueryBuilder(tableName) {
2649
- return this.db.query?.[tableName];
2650
- }
2651
- /**
2652
- * The context the condition builder needs to compile a filter key that is
2653
- * not a column name outright.
2654
- *
2655
- * Two such keys. An owning relation's key resolves through the collection's
2656
- * relations to its foreign-key column; a relation whose link lives on the
2657
- * target table or in a junction resolves to a correlated `EXISTS`, which
2658
- * needs the registry to reach that other table and this table's key column
2659
- * to correlate back.
2660
- *
2661
- * Looked up rather than passed: every read path already has the path, only
2662
- * some have the collection, and a path that names no registered collection
2663
- * (a nested/derived one) is not an error here — the builder simply falls
2664
- * back to guessing the default key shapes, and a relation filter it cannot
2665
- * compile stays unresolvable and so fails closed.
2666
- */
2667
- filterContext(collectionPath, table) {
2668
- const collection = this.registry.getCollectionByPath(collectionPath) ?? void 0;
2669
- return {
2670
- collection,
2671
- registry: this.registry,
2672
- sourceIdColumn: collection ? this.resolveIdColumn(collection, table) : void 0
2673
- };
2674
- }
2675
- /**
2676
- * The table column this collection's rows are keyed by, or `undefined`.
2677
- *
2678
- * `getPrimaryKeys` rather than `requirePrimaryKeys`: a collection with no
2679
- * resolvable key is not an error on the filter path — it only means the
2680
- * relation filters that would correlate on it cannot be compiled, which
2681
- * the builder already handles by failing that field closed.
2682
- */
2683
- resolveIdColumn(collection, table) {
2684
- const [idInfo] = getPrimaryKeys(collection, this.registry);
2685
- if (!idInfo) return void 0;
2686
- return table[idInfo.fieldName];
2687
- }
2688
- /**
2689
- * Build filter conditions from FilterValues
2690
- * Delegates to DrizzleConditionBuilder.buildFilterConditions
2691
- */
2692
- buildFilterConditions(filter, table, collectionPath) {
2693
- return DrizzleConditionBuilder.buildFilterConditions(filter, table, collectionPath, this.filterContext(collectionPath, table));
2694
- }
2695
- /**
2696
- * Resolves the correct Drizzle column for sorting.
2697
- * Automatically maps owning relation property keys to their underlying foreign key column.
2698
- *
2699
- * The relation's own `localKey` is the authority for that foreign key, not
2700
- * `<field>_id`. The default local key comes from `generateForeignKeyName`,
2701
- * which snake-cases *and singularises* — `userProfile` → `user_profile_id`,
2702
- * `users` → `user_id` — and an author can override it outright. A wrong
2703
- * guess resolves to nothing, the caller drops the `ORDER BY`, and the rows
2704
- * come back in whatever order Postgres pleases: paging over that repeats
2705
- * and skips rows rather than erroring. The guesses stay, last, for a
2706
- * caller that hands over no collection to resolve against.
2707
- */
2708
- resolveOrderByField(table, orderBy, collection) {
2709
- const columnAt = (key) => (key in table ? table[key] : void 0) || void 0;
2710
- const direct = columnAt(orderBy);
2711
- if (direct) return direct;
2712
- if (collection) {
2713
- const relation = resolveCollectionRelations(collection)[orderBy];
2714
- if (relation?.kind === "belongsTo") {
2715
- const foreignKey = columnAt(relation.localKey);
2716
- if (foreignKey) return foreignKey;
2717
- }
2718
- }
2719
- for (const guess of [`${orderBy}_id`, generateForeignKeyName(orderBy)]) {
2720
- const foreignKey = columnAt(guess);
2721
- if (foreignKey) return foreignKey;
2722
- }
2723
- }
2724
- /**
2725
- * Build the `with` config for Drizzle's relational query API.
2726
- * Converts collection relations to a Drizzle-compatible `with` object.
2727
- *
2728
- * When `include` is provided, only those relations are loaded.
2729
- * When `include` is absent, ALL relations are loaded (the admin path).
2730
- *
2731
- * Automatically detects many-to-many junction tables and nests
2732
- * the target relation so actual row data is returned.
2733
- */
2734
- buildWithConfig(collection, include) {
2735
- const resolvedRelations = resolveCollectionRelations(collection);
2736
- const withConfig = {};
2737
- const shouldInclude = (key) => !include || include.length === 0 || include[0] === "*" || include.includes(key);
2738
- for (const [key, relation] of Object.entries(resolvedRelations)) {
2739
- if (!shouldInclude(key)) continue;
2740
- const drizzleRelName = relation.relationName || key;
2741
- if (relation.kind === "via") continue;
2742
- if (relation.cardinality === "many" && isJunctionRelation(relation)) {
2743
- const targetFkName = this.getJunctionTargetRelationName(relation, collection);
2744
- if (targetFkName) withConfig[drizzleRelName] = { with: { [targetFkName]: true } };
2745
- else withConfig[drizzleRelName] = true;
2746
- } else withConfig[drizzleRelName] = true;
2747
- }
2748
- return withConfig;
2749
- }
2750
- /**
2751
- * Get the Drizzle relation name on the junction table that points to the actual target row.
2752
- * For example, for posts_tags junction, this returns "tag_id" (the relation pointing to tags).
2753
- */
2754
- getJunctionTargetRelationName(relation, _collection) {
2755
- if (isManyToMany(relation)) return relation.through.targetColumn.replace(/_id$/, "_id");
2805
+ /**
2806
+ * Return the error when it is a deliberate 4xx, otherwise null.
2807
+ *
2808
+ * A thrown `ApiError` is a decision the server made about the request, not a
2809
+ * database failure: its message and code are already written for the client.
2810
+ */
2811
+ function asClientFacingError(error) {
2812
+ if (!(error instanceof Error)) return null;
2813
+ const e = error;
2814
+ if (typeof e.statusCode !== "number" || e.statusCode < 400 || e.statusCode >= 500) return null;
2815
+ return e;
2816
+ }
2817
+ /**
2818
+ * Extract the underlying PostgreSQL error from a Drizzle wrapper.
2819
+ * Drizzle wraps PG errors in a `cause` property — this function
2820
+ * recursively walks the chain until it finds an object with a PG
2821
+ * error code (5-char alphanumeric, e.g. `42P01`).
2822
+ */
2823
+ function extractPgError(error) {
2824
+ if (!error || typeof error !== "object") return null;
2825
+ if (!(error instanceof Error)) {
2826
+ if ("cause" in error && error.cause && typeof error.cause === "object") return extractPgError(error.cause);
2756
2827
  return null;
2757
2828
  }
2758
- /**
2759
- * Post-fetch joinPath relations for a single flat row.
2760
- * joinPath relations cannot be expressed via Drizzle's `with` config,
2761
- * so they must be loaded separately after the primary query.
2762
- */
2763
- async resolveJoinPathRelations(row, collection, collectionPath, parsedId, _databaseId) {
2764
- const resolvedRelations = resolveCollectionRelations(collection);
2765
- const promises = Object.entries(resolvedRelations).filter(([key, relation]) => relation.kind === "via").map(async ([key, relation]) => {
2766
- try {
2767
- const relatedRows = await this.relationService.fetchRelatedEntities(collectionPath, parsedId, key, { limit: relation.cardinality === "one" ? 1 : void 0 });
2768
- if (relation.cardinality === "one" && relatedRows.length > 0) {
2769
- const e = relatedRows[0];
2770
- row[key] = createRelationRefWithData(e.id, e.path, e);
2771
- } else if (relation.cardinality === "many") row[key] = relatedRows.map((e) => createRelationRefWithData(e.id, e.path, e));
2772
- } catch (e) {
2773
- logger.warn(`Could not resolve joinPath relation '${key}'`, { error: e });
2774
- }
2775
- });
2776
- await Promise.all(promises);
2829
+ if ("code" in error && typeof error.code === "string" && /^[0-9A-Z]{5}$/.test(error.code)) return error;
2830
+ if (error.cause && typeof error.cause === "object") return extractPgError(error.cause);
2831
+ return null;
2832
+ }
2833
+ /**
2834
+ * Whether the failure came back from Postgres rather than from building the
2835
+ * query — which decides whether a fallback query is worth issuing.
2836
+ *
2837
+ * Reads here run inside a transaction (that is where `SET LOCAL ROLE` binds
2838
+ * RLS). Once a statement raises, that transaction is aborted, and every later
2839
+ * statement on it returns `25P02` — "current transaction is aborted, commands
2840
+ * ignored until end of transaction block". So a retry after a database error
2841
+ * cannot succeed, and it replaces a precise diagnosis ("invalid input syntax
2842
+ * for type uuid") with a generic one. Rethrow instead.
2843
+ *
2844
+ * A query the driver could not even build — a missing reciprocal relation, say
2845
+ * — never reached Postgres, leaves the transaction usable, and is exactly what
2846
+ * the fallback paths exist for.
2847
+ */
2848
+ function reachedDatabase(error) {
2849
+ return extractPgError(error) !== null;
2850
+ }
2851
+ /**
2852
+ * Walk the error cause chain and return the deepest meaningful message.
2853
+ */
2854
+ function extractCauseMessage(error) {
2855
+ if (!error || typeof error !== "object") return null;
2856
+ if (!(error instanceof Error)) return null;
2857
+ if (error.cause && typeof error.cause === "object") {
2858
+ const deeper = extractCauseMessage(error.cause);
2859
+ if (deeper) return deeper;
2860
+ if (error.cause instanceof Error && error.cause.message) return error.cause.message;
2777
2861
  }
2778
- /**
2779
- * Resolves joinPath relations for raw REST rows and directly injects them.
2780
- * Uses RelationService to query the database and maps results back to the flattened objects.
2781
- */
2782
- async resolveJoinPathRelationsBatchRest(rows, collection, collectionPath, idInfoArray, include) {
2783
- if (rows.length === 0) return;
2784
- const resolvedRelations = resolveCollectionRelations(collection);
2785
- const propertyKeys = new Set(Object.keys(collection.properties || {}));
2786
- const shouldInclude = (key) => !include || include.length === 0 || include[0] === "*" || include.includes(key);
2787
- const joinPathRelations = Object.entries(resolvedRelations).filter(([key, relation]) => relation.kind === "via" && propertyKeys.has(key) && shouldInclude(key));
2788
- if (joinPathRelations.length === 0) return;
2789
- const parentIdOf = (row) => {
2790
- const address = buildCompositeId(row, idInfoArray);
2791
- return address && address.split(":::").some((part) => part !== "") ? address : void 0;
2862
+ return null;
2863
+ }
2864
+ /**
2865
+ * Codes that mean "this connection will never work as configured".
2866
+ *
2867
+ * A wrong password or a database that does not exist is a settled fact about
2868
+ * the connection string, not a transient fault — retrying produces the same
2869
+ * answer forever.
2870
+ */
2871
+ var UNRECOVERABLE_CONNECT_CODES = /* @__PURE__ */ new Set([
2872
+ "28P01",
2873
+ "28000",
2874
+ "3D000",
2875
+ "42501"
2876
+ ]);
2877
+ /**
2878
+ * Describe a failed connection attempt in terms a developer can act on.
2879
+ *
2880
+ * The error a caller catches is Drizzle's wrapper: its message is
2881
+ * `Failed query: SELECT 1` and its stack runs through drizzle internals, while
2882
+ * the sentence that says what is actually wrong — "password authentication
2883
+ * failed for user …", "database … does not exist" — sits in `.cause`. Logging
2884
+ * the wrapper, as the bootstrapper used to, tells a developer with a typo in
2885
+ * their `DATABASE_URL` nothing at all.
2886
+ */
2887
+ function classifyConnectFailure(error) {
2888
+ const pgError = extractPgError(error);
2889
+ const reason = pgError?.message ?? extractCauseMessage(error) ?? (error instanceof Error ? error.message : String(error));
2890
+ return {
2891
+ fatal: Boolean(pgError?.code && UNRECOVERABLE_CONNECT_CODES.has(pgError.code)),
2892
+ reason,
2893
+ code: pgError?.code
2894
+ };
2895
+ }
2896
+ /**
2897
+ * Detect whether an error is specifically a role-switching permission failure
2898
+ * (e.g. "permission denied to set role" or "must be member of role"),
2899
+ * as opposed to a table-level permission denial.
2900
+ *
2901
+ * This is used by the backend driver to auto-disable role switching when the
2902
+ * connection user lacks SET ROLE privileges, rather than surfacing a confusing
2903
+ * error to the Studio SQL Editor user.
2904
+ */
2905
+ function isRoleSwitchingPermissionError(error) {
2906
+ const pgError = extractPgError(error);
2907
+ if (!pgError || pgError.code !== "42501") return false;
2908
+ const msg = pgError.message.toLowerCase();
2909
+ return msg.includes("set role") || msg.includes("member of role");
2910
+ }
2911
+ /**
2912
+ * Translate a raw PostgreSQL error into a user-friendly message.
2913
+ *
2914
+ * @param pgError - The extracted PostgreSQL error (from {@link extractPgError})
2915
+ * @param context - A human-readable context string (e.g. collection slug or path)
2916
+ * @returns An object with a `message` safe for the client and the PG `code`.
2917
+ */
2918
+ function pgErrorToFriendlyMessage(pgError, context) {
2919
+ const detail = pgError.detail;
2920
+ const hint = pgError.hint;
2921
+ const constraint = pgError.constraint;
2922
+ const column = pgError.column;
2923
+ const table = pgError.table;
2924
+ const dataType = pgError.dataType;
2925
+ const pgMessage = pgError.message || "Unknown database error";
2926
+ const code = pgError.code || "UNKNOWN";
2927
+ const suffix = hint ? ` Hint: ${hint}` : "";
2928
+ const tableRef = table ?? context;
2929
+ switch (pgError.code) {
2930
+ case "23503": return {
2931
+ message: detail ? `Foreign key constraint violated: ${detail}${suffix}` : `Cannot complete operation: a foreign key constraint${constraint ? ` (${constraint})` : ""} was violated in "${context}".${suffix}`,
2932
+ code
2792
2933
  };
2793
- for (const [key, relation] of joinPathRelations) try {
2794
- const addressable = rows.filter((r) => parentIdOf(r) !== void 0 && parentIdOf(r) !== null);
2795
- if (addressable.length === 0) continue;
2796
- const rowIds = addressable.map((r) => parentIdOf(r));
2797
- if (relation.cardinality === "one") {
2798
- const resultMap = await this.relationService.batchFetchRelatedEntities(collectionPath, rowIds, key, relation);
2799
- for (const row of addressable) {
2800
- const relatedRow = resultMap.get(String(parentIdOf(row)));
2801
- row[key] = relatedRow ? { ...relatedRow.values } : null;
2802
- }
2803
- } else if (relation.cardinality === "many") {
2804
- const resultMap = await this.relationService.batchFetchRelatedEntitiesMany(collectionPath, rowIds, key, relation);
2805
- for (const row of addressable) row[key] = (resultMap.get(String(parentIdOf(row))) || []).map((e) => ({ ...e.values }));
2806
- }
2807
- } catch (e) {
2808
- logger.warn(`Could not batch resolve joinPath relation '${key}' for REST`, { error: e });
2934
+ case "23505": return {
2935
+ message: detail ? `Duplicate value: ${detail}${suffix}` : `Cannot complete operation: a unique constraint${constraint ? ` (${constraint})` : ""} was violated in "${context}".${suffix}`,
2936
+ code
2937
+ };
2938
+ case "23502": return {
2939
+ message: `Missing required field: "${column ?? "unknown"}" in "${tableRef}" cannot be empty.${suffix}`,
2940
+ code
2941
+ };
2942
+ case "23514": return {
2943
+ message: `Validation failed: a check constraint${constraint ? ` (${constraint})` : ""} was violated in "${context}".${suffix}`,
2944
+ code
2945
+ };
2946
+ case "22P02": return {
2947
+ message: `Invalid data format in "${context}": ${pgMessage}${suffix}`,
2948
+ code
2949
+ };
2950
+ case "22001": return {
2951
+ message: `Value too long for column "${column ?? "unknown"}" in "${tableRef}": ${pgMessage}${suffix}`,
2952
+ code
2953
+ };
2954
+ case "22003": return {
2955
+ message: `Numeric value out of range for column "${column ?? "unknown"}" in "${tableRef}": ${pgMessage}${suffix}`,
2956
+ code
2957
+ };
2958
+ case "42703": return {
2959
+ message: `Unknown column in "${tableRef}": ${pgMessage}. Check if your schema is up to date (run migrations).${suffix}`,
2960
+ code
2961
+ };
2962
+ case "42P01": return {
2963
+ message: `Table not found for "${context}": ${pgMessage}. Check if your schema is up to date (run migrations).${suffix}`,
2964
+ code
2965
+ };
2966
+ case "42501": return {
2967
+ message: `Permission denied on "${tableRef}". Check your database credentials and RLS policies.${suffix}`,
2968
+ code
2969
+ };
2970
+ case "28000": return {
2971
+ message: `Authorization failed for "${context}". Check your database credentials.${suffix}`,
2972
+ code
2973
+ };
2974
+ default: {
2975
+ const parts = [`Database error in "${context}" [${code}]: ${pgMessage}`];
2976
+ if (detail) parts.push(`Detail: ${detail}`);
2977
+ if (column) parts.push(`Column: ${column}`);
2978
+ if (dataType) parts.push(`Data type: ${dataType}`);
2979
+ if (constraint) parts.push(`Constraint: ${constraint}`);
2980
+ if (hint) parts.push(`Hint: ${hint}`);
2981
+ return {
2982
+ message: parts.join(". "),
2983
+ code
2984
+ };
2809
2985
  }
2810
2986
  }
2987
+ }
2988
+ /**
2989
+ * Sanitize any error into a message safe and helpful for the client.
2990
+ *
2991
+ * A deliberate 4xx (`ApiError`) passes through untouched — the server already
2992
+ * decided what the client should read. Otherwise the PG error is extracted
2993
+ * from the Drizzle cause chain, falling back to a generic message that
2994
+ * doesn't leak SQL.
2995
+ *
2996
+ * @param error - The raw caught error
2997
+ * @param context - A human-readable context string (e.g. collection path)
2998
+ * @returns An object with `message` (user-friendly) and optional `code`
2999
+ * (the `ApiError` code, or the PG SQLSTATE).
3000
+ */
3001
+ function sanitizeErrorForClient(error, context) {
3002
+ const clientError = asClientFacingError(error);
3003
+ if (clientError) {
3004
+ const line = `[API ${clientError.statusCode} ${clientError.code ?? "BAD_REQUEST"}] in "${context}": ${clientError.message}`;
3005
+ if (clientError.expected) logger.debug(line);
3006
+ else logger.warn(`⚠️ ${line}`);
3007
+ return {
3008
+ message: clientError.message,
3009
+ ...clientError.code && { code: clientError.code }
3010
+ };
3011
+ }
3012
+ const pgError = extractPgError(error);
3013
+ if (pgError) {
3014
+ logger.error(`[PG ${pgError.code}] Error in "${context}"`, {
3015
+ code: pgError.code,
3016
+ message: pgError.message,
3017
+ detail: pgError.detail,
3018
+ hint: pgError.hint,
3019
+ column: pgError.column,
3020
+ table: pgError.table,
3021
+ constraint: pgError.constraint,
3022
+ dataType: pgError.dataType,
3023
+ drizzleMessage: error instanceof Error ? error.message : String(error)
3024
+ });
3025
+ return pgErrorToFriendlyMessage(pgError, context);
3026
+ }
3027
+ logger.error(`Database error in "${context}" (no PG error extracted)`, {
3028
+ error: error instanceof Error ? error.message : String(error),
3029
+ stack: error instanceof Error ? error.stack : void 0,
3030
+ cause: error instanceof Error && error.cause ? error.cause instanceof Error ? error.cause.message : String(error.cause) : void 0
3031
+ });
3032
+ const causeMessage = extractCauseMessage(error);
3033
+ if (causeMessage) return { message: `Database error in "${context}": ${causeMessage}` };
3034
+ return { message: `Could not load data for "${context}". Check server logs for details.` };
3035
+ }
3036
+ //#endregion
3037
+ //#region src/services/FetchService.ts
3038
+ /**
3039
+ * Service for handling all row read operations.
3040
+ * Handles fetching, searching, counting, and filtering rows.
3041
+ */
3042
+ var FetchService = class {
3043
+ db;
3044
+ registry;
3045
+ relationService;
3046
+ constructor(db, registry) {
3047
+ this.db = db;
3048
+ this.registry = registry;
3049
+ this.relationService = new RelationService(db, registry);
3050
+ }
2811
3051
  /**
2812
- * Build db.query-compatible options from standard fetch options.
2813
- * Handles filter, search, orderBy, limit, and cursor-based pagination.
3052
+ * Get the relational query builder for a given table name.
3053
+ * Safely narrows the DrizzleClient union type to access db.query[tableName].
2814
3054
  */
2815
- buildDrizzleQueryOptions(table, idField, idInfo, options, collectionPath, withConfig, scopeCondition) {
2816
- const queryOpts = {};
2817
- if (withConfig) queryOpts.with = withConfig;
2818
- const allConditions = [];
2819
- if (scopeCondition) allConditions.push(scopeCondition);
2820
- if (options.searchString) {
2821
- const collection = getCollectionByPath(collectionPath, this.registry);
2822
- const searchConditions = DrizzleConditionBuilder.buildSearchConditions(options.searchString, collection.properties, table);
2823
- if (searchConditions.length === 0) {
2824
- queryOpts.where = and(eq(idField, -99999999));
2825
- return queryOpts;
2826
- }
2827
- allConditions.push(DrizzleConditionBuilder.combineConditionsWithOr(searchConditions));
2828
- }
2829
- if (options.filter) {
2830
- const filterConditions = this.buildFilterConditions(options.filter, table, collectionPath);
2831
- if (filterConditions.length > 0) allConditions.push(...filterConditions);
2832
- }
2833
- if (options.logical) {
2834
- const logicalCondition = DrizzleConditionBuilder.buildLogicalConditions(options.logical, table, collectionPath, this.filterContext(collectionPath, table));
2835
- if (logicalCondition) allConditions.push(logicalCondition);
2836
- }
2837
- if (options.startAfter) {
2838
- const cursorConditions = this.buildCursorConditions(table, idField, idInfo, options, collectionPath);
2839
- if (cursorConditions.length > 0) allConditions.push(...cursorConditions);
2840
- }
2841
- if (allConditions.length > 0) queryOpts.where = and(...allConditions);
2842
- const orderExpressions = [];
2843
- if (options.orderBy) {
2844
- const collection = getCollectionByPath(collectionPath, this.registry);
2845
- const orderByField = this.resolveOrderByField(table, options.orderBy, collection);
2846
- if (orderByField) orderExpressions.push(options.order === "asc" ? asc(orderByField) : desc(orderByField));
2847
- }
2848
- orderExpressions.push(desc(idField));
2849
- if (orderExpressions.length > 0) queryOpts.orderBy = orderExpressions;
2850
- const limitValue = options.searchString ? options.limit || 50 : options.limit;
2851
- if (limitValue) queryOpts.limit = limitValue;
2852
- if (options.offset && options.offset > 0) queryOpts.offset = options.offset;
2853
- return queryOpts;
3055
+ getQueryBuilder(tableName) {
3056
+ return this.db.query?.[tableName];
2854
3057
  }
2855
3058
  /**
2856
- * Extract cursor pagination conditions from startAfter options.
2857
- */
2858
- buildCursorConditions(table, idField, idInfo, options, collectionPath) {
2859
- if (!options.startAfter) return [];
2860
- const cursor = options.startAfter;
2861
- if (options.orderBy) {
3059
+ * The context the condition builder needs to compile a filter key that is
3060
+ * not a column name outright.
3061
+ *
3062
+ * Two such keys. An owning relation's key resolves through the collection's
3063
+ * relations to its foreign-key column; a relation whose link lives on the
3064
+ * target table or in a junction resolves to a correlated `EXISTS`, which
3065
+ * needs the registry to reach that other table and this table's key column
3066
+ * to correlate back.
3067
+ *
3068
+ * Looked up rather than passed: every read path already has the path, only
3069
+ * some have the collection, and a path that names no registered collection
3070
+ * (a nested/derived one) is not an error here — the builder simply falls
3071
+ * back to guessing the default key shapes, and a relation filter it cannot
3072
+ * compile stays unresolvable and so fails closed.
3073
+ */
3074
+ filterContext(collectionPath, table) {
3075
+ const collection = this.registry.getCollectionByPath(collectionPath) ?? void 0;
3076
+ return {
3077
+ collection,
3078
+ registry: this.registry,
3079
+ sourceIdColumn: collection ? this.resolveIdColumn(collection, table) : void 0
3080
+ };
3081
+ }
3082
+ /**
3083
+ * The table column this collection's rows are keyed by, or `undefined`.
3084
+ *
3085
+ * `getPrimaryKeys` rather than `requirePrimaryKeys`: a collection with no
3086
+ * resolvable key is not an error on the filter path — it only means the
3087
+ * relation filters that would correlate on it cannot be compiled, which
3088
+ * the builder already handles by failing that field closed.
3089
+ */
3090
+ resolveIdColumn(collection, table) {
3091
+ const [idInfo] = getPrimaryKeys(collection, this.registry);
3092
+ if (!idInfo) return void 0;
3093
+ return table[idInfo.fieldName];
3094
+ }
3095
+ /**
3096
+ * Build filter conditions from FilterValues
3097
+ * Delegates to DrizzleConditionBuilder.buildFilterConditions
3098
+ */
3099
+ buildFilterConditions(filter, table, collectionPath) {
3100
+ return DrizzleConditionBuilder.buildFilterConditions(filter, table, collectionPath, this.filterContext(collectionPath, table));
3101
+ }
3102
+ /**
3103
+ * Resolves the correct Drizzle column for sorting.
3104
+ * Automatically maps owning relation property keys to their underlying foreign key column.
3105
+ *
3106
+ * The relation's own `localKey` is the authority for that foreign key, not
3107
+ * `<field>_id`. The default local key comes from `generateForeignKeyName`,
3108
+ * which snake-cases *and singularises* — `userProfile` → `user_profile_id`,
3109
+ * `users` → `user_id` — and an author can override it outright. A wrong
3110
+ * guess resolves to nothing, the caller drops the `ORDER BY`, and the rows
3111
+ * come back in whatever order Postgres pleases: paging over that repeats
3112
+ * and skips rows rather than erroring. The guesses stay, last, for a
3113
+ * caller that hands over no collection to resolve against.
3114
+ */
3115
+ resolveOrderByField(table, orderBy, collection) {
3116
+ const columnAt = (key) => (key in table ? table[key] : void 0) || void 0;
3117
+ const direct = columnAt(orderBy);
3118
+ if (direct) return direct;
3119
+ const declaredRelation = collection ? resolveCollectionRelations(collection)[orderBy] : void 0;
3120
+ if (declaredRelation?.kind === "belongsTo") {
3121
+ const foreignKey = columnAt(declaredRelation.localKey);
3122
+ if (foreignKey) return foreignKey;
3123
+ }
3124
+ for (const guess of [`${orderBy}_id`, generateForeignKeyName(orderBy)]) {
3125
+ const foreignKey = columnAt(guess);
3126
+ if (foreignKey) return foreignKey;
3127
+ }
3128
+ const collectionName = collection?.slug ?? collection?.name;
3129
+ const onCollection = collectionName ? ` on collection '${collectionName}'` : "";
3130
+ if (declaredRelation && declaredRelation.kind !== "belongsTo") throw ApiError.badRequest(`Cannot sort by '${orderBy}'${onCollection}: it is a to-many relation (${declaredRelation.kind}), which has no single value per row to order by.`, "ORDER_BY_FIELD_NOT_SORTABLE", {
3131
+ field: orderBy,
3132
+ kind: declaredRelation.kind,
3133
+ ...collectionName && { collection: collectionName }
3134
+ });
3135
+ if (getUnknownFilterFieldsMode() === "warn") {
3136
+ logger.warn(`Sorting by field '${orderBy}'${onCollection}, but it does not exist in the table — the ORDER BY was dropped and these rows are unsorted.`);
3137
+ return;
3138
+ }
3139
+ let validFields = [];
3140
+ try {
3141
+ validFields = Object.keys(getTableColumns(table)).sort();
3142
+ } catch {}
3143
+ throw ApiError.badRequest(`Unknown orderBy field '${orderBy}'${onCollection}` + (validFields.length > 0 ? `. Valid fields: ${validFields.join(", ")}` : ""), "UNKNOWN_ORDER_BY_FIELD", {
3144
+ field: orderBy,
3145
+ ...collectionName && { collection: collectionName },
3146
+ ...validFields.length > 0 && { validFields }
3147
+ });
3148
+ }
3149
+ /**
3150
+ * Build the `with` config for Drizzle's relational query API.
3151
+ * Converts collection relations to a Drizzle-compatible `with` object.
3152
+ *
3153
+ * When `include` is provided, only those relations are loaded.
3154
+ * When `include` is absent, ALL relations are loaded (the admin path).
3155
+ *
3156
+ * Automatically detects many-to-many junction tables and nests
3157
+ * the target relation so actual row data is returned.
3158
+ */
3159
+ buildWithConfig(collection, include) {
3160
+ const resolvedRelations = resolveCollectionRelations(collection);
3161
+ const withConfig = {};
3162
+ const shouldInclude = (key) => !include || include.length === 0 || include[0] === "*" || include.includes(key);
3163
+ for (const [key, relation] of Object.entries(resolvedRelations)) {
3164
+ if (!shouldInclude(key)) continue;
3165
+ const drizzleRelName = relation.relationName || key;
3166
+ if (relation.kind === "via") continue;
3167
+ if (relation.cardinality === "many" && isJunctionRelation(relation)) {
3168
+ const targetFkName = this.getJunctionTargetRelationName(relation, collection);
3169
+ if (targetFkName) withConfig[drizzleRelName] = { with: { [targetFkName]: true } };
3170
+ else withConfig[drizzleRelName] = true;
3171
+ } else withConfig[drizzleRelName] = true;
3172
+ }
3173
+ return withConfig;
3174
+ }
3175
+ /**
3176
+ * Get the Drizzle relation name on the junction table that points to the actual target row.
3177
+ * For example, for posts_tags junction, this returns "tag_id" (the relation pointing to tags).
3178
+ */
3179
+ getJunctionTargetRelationName(relation, _collection) {
3180
+ if (isManyToMany(relation)) return relation.through.targetColumn.replace(/_id$/, "_id");
3181
+ return null;
3182
+ }
3183
+ /**
3184
+ * Post-fetch joinPath relations for a single flat row.
3185
+ * joinPath relations cannot be expressed via Drizzle's `with` config,
3186
+ * so they must be loaded separately after the primary query.
3187
+ */
3188
+ async resolveJoinPathRelations(row, collection, collectionPath, parsedId, _databaseId) {
3189
+ const resolvedRelations = resolveCollectionRelations(collection);
3190
+ const promises = Object.entries(resolvedRelations).filter(([key, relation]) => relation.kind === "via").map(async ([key, relation]) => {
3191
+ try {
3192
+ const relatedRows = await this.relationService.fetchRelatedEntities(collectionPath, parsedId, key, { limit: relation.cardinality === "one" ? 1 : void 0 });
3193
+ if (relation.cardinality === "one" && relatedRows.length > 0) {
3194
+ const e = relatedRows[0];
3195
+ row[key] = createRelationRefWithData(e.id, e.path, e);
3196
+ } else if (relation.cardinality === "many") row[key] = relatedRows.map((e) => createRelationRefWithData(e.id, e.path, e));
3197
+ } catch (e) {
3198
+ logger.warn(`Could not resolve joinPath relation '${key}'`, { error: e });
3199
+ }
3200
+ });
3201
+ await Promise.all(promises);
3202
+ }
3203
+ /**
3204
+ * Resolves joinPath relations for raw REST rows and directly injects them.
3205
+ * Uses RelationService to query the database and maps results back to the flattened objects.
3206
+ */
3207
+ async resolveJoinPathRelationsBatchRest(rows, collection, collectionPath, idInfoArray, include) {
3208
+ if (rows.length === 0) return;
3209
+ const resolvedRelations = resolveCollectionRelations(collection);
3210
+ const propertyKeys = new Set(Object.keys(collection.properties || {}));
3211
+ const shouldInclude = (key) => !include || include.length === 0 || include[0] === "*" || include.includes(key);
3212
+ const joinPathRelations = Object.entries(resolvedRelations).filter(([key, relation]) => relation.kind === "via" && propertyKeys.has(key) && shouldInclude(key));
3213
+ if (joinPathRelations.length === 0) return;
3214
+ const parentIdOf = (row) => {
3215
+ const address = buildCompositeId(row, idInfoArray);
3216
+ return address && address.split(":::").some((part) => part !== "") ? address : void 0;
3217
+ };
3218
+ for (const [key, relation] of joinPathRelations) try {
3219
+ const addressable = rows.filter((r) => parentIdOf(r) !== void 0 && parentIdOf(r) !== null);
3220
+ if (addressable.length === 0) continue;
3221
+ const rowIds = addressable.map((r) => parentIdOf(r));
3222
+ if (relation.cardinality === "one") {
3223
+ const resultMap = await this.relationService.batchFetchRelatedEntities(collectionPath, rowIds, key, relation);
3224
+ for (const row of addressable) {
3225
+ const relatedRow = resultMap.get(String(parentIdOf(row)));
3226
+ row[key] = relatedRow ? { ...relatedRow.values } : null;
3227
+ }
3228
+ } else if (relation.cardinality === "many") {
3229
+ const resultMap = await this.relationService.batchFetchRelatedEntitiesMany(collectionPath, rowIds, key, relation);
3230
+ for (const row of addressable) row[key] = (resultMap.get(String(parentIdOf(row))) || []).map((e) => ({ ...e.values }));
3231
+ }
3232
+ } catch (e) {
3233
+ logger.warn(`Could not batch resolve joinPath relation '${key}' for REST`, { error: e });
3234
+ }
3235
+ }
3236
+ /**
3237
+ * Build db.query-compatible options from standard fetch options.
3238
+ * Handles filter, search, orderBy, limit, and cursor-based pagination.
3239
+ */
3240
+ buildDrizzleQueryOptions(table, idField, idInfo, options, collectionPath, withConfig, scopeCondition) {
3241
+ const queryOpts = {};
3242
+ if (withConfig) queryOpts.with = withConfig;
3243
+ const allConditions = [];
3244
+ if (scopeCondition) allConditions.push(scopeCondition);
3245
+ if (options.searchString) {
3246
+ const collection = getCollectionByPath(collectionPath, this.registry);
3247
+ const searchConditions = DrizzleConditionBuilder.buildSearchConditions(options.searchString, collection.properties, table);
3248
+ if (searchConditions.length === 0) {
3249
+ queryOpts.where = and(eq(idField, -99999999));
3250
+ return queryOpts;
3251
+ }
3252
+ allConditions.push(DrizzleConditionBuilder.combineConditionsWithOr(searchConditions));
3253
+ }
3254
+ if (options.filter) {
3255
+ const filterConditions = this.buildFilterConditions(options.filter, table, collectionPath);
3256
+ if (filterConditions.length > 0) allConditions.push(...filterConditions);
3257
+ }
3258
+ if (options.logical) {
3259
+ const logicalCondition = DrizzleConditionBuilder.buildLogicalConditions(options.logical, table, collectionPath, this.filterContext(collectionPath, table));
3260
+ if (logicalCondition) allConditions.push(logicalCondition);
3261
+ }
3262
+ if (options.startAfter) {
3263
+ const cursorConditions = this.buildCursorConditions(table, idField, idInfo, options, collectionPath);
3264
+ if (cursorConditions.length > 0) allConditions.push(...cursorConditions);
3265
+ }
3266
+ if (allConditions.length > 0) queryOpts.where = and(...allConditions);
3267
+ const orderExpressions = [];
3268
+ if (options.orderBy) {
3269
+ const collection = getCollectionByPath(collectionPath, this.registry);
3270
+ const orderByField = this.resolveOrderByField(table, options.orderBy, collection);
3271
+ if (orderByField) orderExpressions.push(options.order === "asc" ? asc(orderByField) : desc(orderByField));
3272
+ }
3273
+ orderExpressions.push(desc(idField));
3274
+ if (orderExpressions.length > 0) queryOpts.orderBy = orderExpressions;
3275
+ const limitValue = options.searchString ? options.limit || 50 : options.limit;
3276
+ if (limitValue) queryOpts.limit = limitValue;
3277
+ if (options.offset && options.offset > 0) queryOpts.offset = options.offset;
3278
+ return queryOpts;
3279
+ }
3280
+ /**
3281
+ * Extract cursor pagination conditions from startAfter options.
3282
+ */
3283
+ buildCursorConditions(table, idField, idInfo, options, collectionPath) {
3284
+ if (!options.startAfter) return [];
3285
+ const cursor = options.startAfter;
3286
+ if (options.orderBy) {
2862
3287
  const collection = collectionPath ? getCollectionByPath(collectionPath, this.registry) : void 0;
2863
3288
  const orderByField = this.resolveOrderByField(table, options.orderBy, collection);
2864
3289
  if (orderByField) {
@@ -2923,6 +3348,7 @@ var FetchService = class {
2923
3348
  const idInfo = idInfoArray[0];
2924
3349
  const idField = table[idInfo.fieldName];
2925
3350
  if (!idField) throw new Error(`ID field '${idInfo.fieldName}' not found in table for collection '${collectionPath}'`);
3351
+ if (!idCanAddressTable(id, table, idInfoArray)) return void 0;
2926
3352
  const parsedId = parseIdValues(id, idInfoArray)[idInfo.fieldName];
2927
3353
  const tableName = getTableName(table);
2928
3354
  const qb = this.getQueryBuilder(tableName);
@@ -2933,7 +3359,7 @@ var FetchService = class {
2933
3359
  with: withConfig
2934
3360
  });
2935
3361
  if (!row) return void 0;
2936
- const flatRow = toCmsRow(row, collection, this.registry);
3362
+ const flatRow = toFlatRow(row, collection, this.registry);
2937
3363
  await this.resolveJoinPathRelations(flatRow, collection, collectionPath, parsedId, databaseId);
2938
3364
  return flatRow;
2939
3365
  } catch (e) {
@@ -2941,6 +3367,7 @@ var FetchService = class {
2941
3367
  logger.error(`[FetchService] ResolvedRelation inference error for collection '${collectionPath}': ${e.message}`);
2942
3368
  logger.error("Hint: This usually means a relation in your drizzle schema is missing a reciprocal 'one()' or 'many()' definition. Run 'rebase schema generate' to fix this.");
2943
3369
  }
3370
+ if (reachedDatabase(e)) throw e;
2944
3371
  logger.warn(`[FetchService] db.query.findFirst failed for ${collectionPath}, falling back to db.select`, { error: e });
2945
3372
  }
2946
3373
  const result = await this.db.select().from(table).where(eq(idField, parsedId)).limit(1);
@@ -2988,12 +3415,13 @@ var FetchService = class {
2988
3415
  const hasRelations = withConfig && Object.keys(withConfig).length > 0;
2989
3416
  if (qb && !options.searchString && !hasRelations && !options.vectorSearch) try {
2990
3417
  const queryOpts = this.buildDrizzleQueryOptions(table, idField, idInfo, options, collectionPath, void 0, scopeCondition);
2991
- return (await qb.findMany(queryOpts)).map((row) => toCmsRow(row, collection, this.registry));
3418
+ return (await qb.findMany(queryOpts)).map((row) => toFlatRow(row, collection, this.registry));
2992
3419
  } catch (e) {
2993
3420
  if (e instanceof Error && e.message.includes("not enough information to infer relation")) {
2994
3421
  logger.error(`[FetchService] ResolvedRelation inference error for collection '${collectionPath}': ${e.message}`);
2995
3422
  logger.error("Hint: This usually means a relation in your drizzle schema is missing a reciprocal 'one()' or 'many()' definition. Run 'rebase schema generate' to fix this.");
2996
3423
  }
3424
+ if (reachedDatabase(e)) throw e;
2997
3425
  logger.warn(`[FetchService] db.query.findMany failed for ${collectionPath}, falling back to db.select`, { error: e });
2998
3426
  }
2999
3427
  let vectorMeta;
@@ -3051,7 +3479,7 @@ var FetchService = class {
3051
3479
  /**
3052
3480
  * Fallback path used when db.query is unavailable.
3053
3481
  *
3054
- * The primary path runs the results through `toCmsRow`, which maps
3482
+ * The primary path runs the results through `toFlatRow`, which maps
3055
3483
  * relations from what drizzle already nested — no query per row. This one
3056
3484
  * has no nesting to read, so it resolves relations itself, in batches.
3057
3485
  *
@@ -3144,6 +3572,10 @@ var FetchService = class {
3144
3572
  const filterConditions = this.buildFilterConditions(options.filter, table, effectivePath);
3145
3573
  if (filterConditions.length > 0) allConditions.push(...filterConditions);
3146
3574
  }
3575
+ if (options.logical) {
3576
+ const logicalCondition = DrizzleConditionBuilder.buildLogicalConditions(options.logical, table, effectivePath, this.filterContext(effectivePath, table));
3577
+ if (logicalCondition) allConditions.push(logicalCondition);
3578
+ }
3147
3579
  if (allConditions.length > 0) {
3148
3580
  const finalCondition = DrizzleConditionBuilder.combineConditionsWithAnd(allConditions);
3149
3581
  if (finalCondition) query = query.where(finalCondition);
@@ -3209,6 +3641,7 @@ var FetchService = class {
3209
3641
  logger.error(`[FetchService] ResolvedRelation inference error for collection '${collectionPath}': ${e.message}`);
3210
3642
  logger.error("Hint: This usually means a relation in your drizzle schema is missing a reciprocal 'one()' or 'many()' definition. Run 'rebase schema generate' to fix this.");
3211
3643
  }
3644
+ if (reachedDatabase(e)) throw e;
3212
3645
  logger.warn(`[fetchCollectionForRest] db.query.findMany failed for ${collectionPath}, falling back`, { error: e });
3213
3646
  }
3214
3647
  const rows = await this.fetchRowsWithConditionsRaw(collectionPath, options);
@@ -3254,6 +3687,7 @@ var FetchService = class {
3254
3687
  const idInfoArray = requirePrimaryKeys(collection, this.registry);
3255
3688
  const idInfo = idInfoArray[0];
3256
3689
  const idField = table[idInfo.fieldName];
3690
+ if (!idCanAddressTable(id, table, idInfoArray)) return null;
3257
3691
  const parsedId = parseIdValues(id, idInfoArray)[idInfo.fieldName];
3258
3692
  const tableName = getTableName(table);
3259
3693
  const qb = this.getQueryBuilder(tableName);
@@ -3272,6 +3706,7 @@ var FetchService = class {
3272
3706
  logger.error(`[FetchService] ResolvedRelation inference error for collection '${collectionPath}': ${e.message}`);
3273
3707
  logger.error("Hint: This usually means a relation in your drizzle schema is missing a reciprocal 'one()' or 'many()' definition. Run 'rebase schema generate' to fix this.");
3274
3708
  }
3709
+ if (reachedDatabase(e)) throw e;
3275
3710
  logger.warn(`[fetchOneForRest] db.query.findFirst failed for ${collectionPath}, falling back`, { error: e });
3276
3711
  }
3277
3712
  const result = await this.db.select().from(table).where(eq(idField, parsedId)).limit(1);
@@ -3302,356 +3737,133 @@ var FetchService = class {
3302
3737
  }
3303
3738
  }
3304
3739
  return flatEntity;
3305
- }
3306
- /**
3307
- * Fetch raw rows without any relation processing (for REST fast path)
3308
- */
3309
- async fetchRowsWithConditionsRaw(collectionPath, options = {}) {
3310
- const collection = getCollectionByPath(collectionPath, this.registry);
3311
- const table = getTableForCollection(collection, this.registry);
3312
- const idField = table[requirePrimaryKeys(collection, this.registry)[0].fieldName];
3313
- let vectorMeta;
3314
- if (options.vectorSearch) vectorMeta = DrizzleConditionBuilder.buildVectorSearchConditions(table, options.vectorSearch);
3315
- let query = vectorMeta ? this.db.select({
3316
- table_row: table,
3317
- _distance: vectorMeta.distanceSelect
3318
- }).from(table).$dynamic() : this.db.select().from(table).$dynamic();
3319
- const allConditions = [];
3320
- if (options.relatedTo) allConditions.push(this.buildRelationScope(options.relatedTo));
3321
- if (options.searchString) {
3322
- const searchConditions = DrizzleConditionBuilder.buildSearchConditions(options.searchString, collection.properties, table);
3323
- if (searchConditions.length === 0) return [];
3324
- allConditions.push(DrizzleConditionBuilder.combineConditionsWithOr(searchConditions));
3325
- }
3326
- if (options.filter) {
3327
- const filterConditions = this.buildFilterConditions(options.filter, table, collectionPath);
3328
- if (filterConditions.length > 0) allConditions.push(...filterConditions);
3329
- }
3330
- if (vectorMeta?.filter) allConditions.push(vectorMeta.filter);
3331
- if (allConditions.length > 0) {
3332
- const finalCondition = DrizzleConditionBuilder.combineConditionsWithAnd(allConditions);
3333
- if (finalCondition) query = query.where(finalCondition);
3334
- }
3335
- const orderExpressions = [];
3336
- if (vectorMeta) orderExpressions.push(asc(vectorMeta.orderBy));
3337
- else if (options.orderBy) {
3338
- const orderByField = this.resolveOrderByField(table, options.orderBy, collection);
3339
- if (orderByField) orderExpressions.push(options.order === "asc" ? asc(orderByField) : desc(orderByField));
3340
- }
3341
- orderExpressions.push(desc(idField));
3342
- if (orderExpressions.length > 0) query = query.orderBy(...orderExpressions);
3343
- const limitValue = options.vectorSearch ? options.limit || 10 : options.searchString ? options.limit || 50 : options.limit;
3344
- if (limitValue) query = query.limit(limitValue);
3345
- if (options.offset && options.offset > 0) query = query.offset(options.offset);
3346
- const rawResults = await query;
3347
- if (vectorMeta) return rawResults.map((r) => ({
3348
- ...r.table_row,
3349
- _distance: typeof r._distance === "number" ? r._distance : parseFloat(String(r._distance))
3350
- }));
3351
- return rawResults;
3352
- }
3353
- /**
3354
- * Check if the Drizzle instance has the relational query API available
3355
- * for a given collection path.
3356
- * Note: Primary path now uses inline `getQueryBuilder()` checks.
3357
- */
3358
- hasDrizzleQueryAPI(collectionPath) {
3359
- if (!this.getQueryBuilder("__probe__")) return false;
3360
- const tableName = getTableName(getTableForCollection(getCollectionByPath(collectionPath, this.registry), this.registry));
3361
- return !!this.getQueryBuilder(tableName);
3362
- }
3363
- /**
3364
- * Attempt to use Drizzle's relational query API (db.query.<table>.findMany)
3365
- * for efficient JOIN-based relation loading.
3366
- * Returns null if the API is not available or the query fails.
3367
- * Note: Primary path now uses `buildWithConfig` + `buildDrizzleQueryOptions`.
3368
- */
3369
- async fetchWithDrizzleQuery(collectionPath, collection, options, include, idInfo, idInfoArray) {
3370
- try {
3371
- const table = getTableForCollection(collection, this.registry);
3372
- const tableName = getTableName(table);
3373
- const queryTarget = this.getQueryBuilder(tableName);
3374
- if (!queryTarget?.findMany) return null;
3375
- const resolvedRelations = resolveCollectionRelations(collection);
3376
- const withConfig = {};
3377
- for (const [key, relation] of Object.entries(resolvedRelations)) if (include[0] === "*" || include.includes(key)) {
3378
- const drizzleRelName = relation.relationName || key;
3379
- withConfig[drizzleRelName] = true;
3380
- }
3381
- const queryOpts = { with: withConfig };
3382
- if (options.limit) queryOpts.limit = options.limit;
3383
- if (options.filter) {
3384
- const filterConditions = this.buildFilterConditions(options.filter, table, collectionPath);
3385
- if (filterConditions.length > 0) queryOpts.where = and(...filterConditions);
3386
- }
3387
- if (options.orderBy) {
3388
- const orderByField = this.resolveOrderByField(table, options.orderBy, collection);
3389
- if (orderByField) queryOpts.orderBy = options.order === "asc" ? asc(orderByField) : desc(orderByField);
3390
- }
3391
- return (await queryTarget.findMany(queryOpts)).map((row) => {
3392
- const flat = {};
3393
- for (const [k, v] of Object.entries(row)) if (Array.isArray(v)) flat[k] = v.map((item) => {
3394
- const keys = Object.keys(item);
3395
- const nestedObj = keys.find((nk) => typeof item[nk] === "object" && item[nk] !== null && !Array.isArray(item[nk]));
3396
- if (nestedObj && keys.length <= 3) return { ...item[nestedObj] };
3397
- return { ...item };
3398
- });
3399
- else if (typeof v === "object" && v !== null) flat[k] = { ...v };
3400
- else flat[k] = v;
3401
- return flat;
3402
- });
3403
- } catch (e) {
3404
- logger.warn(`[include] Drizzle relational query failed for '${collectionPath}', falling back`, { error: e });
3405
- return null;
3406
- }
3407
- }
3408
- /**
3409
- * Fallback path used when db.query is unavailable.
3410
- * The primary path uses db.query.findMany with `with` config, which
3411
- * loads all relations in a single query.
3412
- *
3413
- * Batch fetch many-to-many related rows for multiple parent IDs.
3414
- * Groups results by parent ID to avoid N+1.
3415
- */
3416
- async batchFetchManyRelatedRows(parentCollectionPath, parentIds, relationKey) {
3417
- if (parentIds.length === 0) return /* @__PURE__ */ new Map();
3418
- const relation = resolveCollectionRelations(getCollectionByPath(parentCollectionPath, this.registry))[relationKey];
3419
- if (!relation) {
3420
- logger.warn(`[batchFetchManyRelatedRows] ResolvedRelation '${relationKey}' not found, skipping`);
3421
- return /* @__PURE__ */ new Map();
3422
- }
3423
- const entityMap = await this.relationService.batchFetchRelatedEntitiesMany(parentCollectionPath, parentIds, relationKey, relation);
3424
- const flatMap = /* @__PURE__ */ new Map();
3425
- for (const [key, rows] of entityMap) flatMap.set(key, rows.map((e) => ({
3426
- ...e.values,
3427
- id: e.id
3428
- })));
3429
- return flatMap;
3430
- }
3431
- };
3432
- //#endregion
3433
- //#region src/utils/pg-error-utils.ts
3434
- /**
3435
- * Shared PostgreSQL error extraction and user-friendly message formatting.
3436
- *
3437
- * Drizzle wraps native PG errors in a `.cause` chain. These utilities
3438
- * unwrap that chain to get the real PostgreSQL error (identified by a
3439
- * 5-character alphanumeric `code` such as `42P01`) and translate it into
3440
- * a message that is safe and helpful to show to end-users.
3441
- */
3442
- /**
3443
- * Return the error when it is a deliberate 4xx, otherwise null.
3444
- *
3445
- * A thrown `ApiError` is a decision the server made about the request, not a
3446
- * database failure: its message and code are already written for the client.
3447
- */
3448
- function asClientFacingError(error) {
3449
- if (!(error instanceof Error)) return null;
3450
- const e = error;
3451
- if (typeof e.statusCode !== "number" || e.statusCode < 400 || e.statusCode >= 500) return null;
3452
- return e;
3453
- }
3454
- /**
3455
- * Extract the underlying PostgreSQL error from a Drizzle wrapper.
3456
- * Drizzle wraps PG errors in a `cause` property — this function
3457
- * recursively walks the chain until it finds an object with a PG
3458
- * error code (5-char alphanumeric, e.g. `42P01`).
3459
- */
3460
- function extractPgError(error) {
3461
- if (!error || typeof error !== "object") return null;
3462
- if (!(error instanceof Error)) {
3463
- if ("cause" in error && error.cause && typeof error.cause === "object") return extractPgError(error.cause);
3464
- return null;
3465
- }
3466
- if ("code" in error && typeof error.code === "string" && /^[0-9A-Z]{5}$/.test(error.code)) return error;
3467
- if (error.cause && typeof error.cause === "object") return extractPgError(error.cause);
3468
- return null;
3469
- }
3470
- /**
3471
- * Walk the error cause chain and return the deepest meaningful message.
3472
- */
3473
- function extractCauseMessage(error) {
3474
- if (!error || typeof error !== "object") return null;
3475
- if (!(error instanceof Error)) return null;
3476
- if (error.cause && typeof error.cause === "object") {
3477
- const deeper = extractCauseMessage(error.cause);
3478
- if (deeper) return deeper;
3479
- if (error.cause instanceof Error && error.cause.message) return error.cause.message;
3480
- }
3481
- return null;
3482
- }
3483
- /**
3484
- * Codes that mean "this connection will never work as configured".
3485
- *
3486
- * A wrong password or a database that does not exist is a settled fact about
3487
- * the connection string, not a transient fault — retrying produces the same
3488
- * answer forever.
3489
- */
3490
- var UNRECOVERABLE_CONNECT_CODES = /* @__PURE__ */ new Set([
3491
- "28P01",
3492
- "28000",
3493
- "3D000",
3494
- "42501"
3495
- ]);
3496
- /**
3497
- * Describe a failed connection attempt in terms a developer can act on.
3498
- *
3499
- * The error a caller catches is Drizzle's wrapper: its message is
3500
- * `Failed query: SELECT 1` and its stack runs through drizzle internals, while
3501
- * the sentence that says what is actually wrong — "password authentication
3502
- * failed for user …", "database … does not exist" — sits in `.cause`. Logging
3503
- * the wrapper, as the bootstrapper used to, tells a developer with a typo in
3504
- * their `DATABASE_URL` nothing at all.
3505
- */
3506
- function classifyConnectFailure(error) {
3507
- const pgError = extractPgError(error);
3508
- const reason = pgError?.message ?? extractCauseMessage(error) ?? (error instanceof Error ? error.message : String(error));
3509
- return {
3510
- fatal: Boolean(pgError?.code && UNRECOVERABLE_CONNECT_CODES.has(pgError.code)),
3511
- reason,
3512
- code: pgError?.code
3513
- };
3514
- }
3515
- /**
3516
- * Detect whether an error is specifically a role-switching permission failure
3517
- * (e.g. "permission denied to set role" or "must be member of role"),
3518
- * as opposed to a table-level permission denial.
3519
- *
3520
- * This is used by the backend driver to auto-disable role switching when the
3521
- * connection user lacks SET ROLE privileges, rather than surfacing a confusing
3522
- * error to the Studio SQL Editor user.
3523
- */
3524
- function isRoleSwitchingPermissionError(error) {
3525
- const pgError = extractPgError(error);
3526
- if (!pgError || pgError.code !== "42501") return false;
3527
- const msg = pgError.message.toLowerCase();
3528
- return msg.includes("set role") || msg.includes("member of role");
3529
- }
3530
- /**
3531
- * Translate a raw PostgreSQL error into a user-friendly message.
3532
- *
3533
- * @param pgError - The extracted PostgreSQL error (from {@link extractPgError})
3534
- * @param context - A human-readable context string (e.g. collection slug or path)
3535
- * @returns An object with a `message` safe for the client and the PG `code`.
3536
- */
3537
- function pgErrorToFriendlyMessage(pgError, context) {
3538
- const detail = pgError.detail;
3539
- const hint = pgError.hint;
3540
- const constraint = pgError.constraint;
3541
- const column = pgError.column;
3542
- const table = pgError.table;
3543
- const dataType = pgError.dataType;
3544
- const pgMessage = pgError.message || "Unknown database error";
3545
- const code = pgError.code || "UNKNOWN";
3546
- const suffix = hint ? ` Hint: ${hint}` : "";
3547
- const tableRef = table ?? context;
3548
- switch (pgError.code) {
3549
- case "23503": return {
3550
- message: detail ? `Foreign key constraint violated: ${detail}${suffix}` : `Cannot complete operation: a foreign key constraint${constraint ? ` (${constraint})` : ""} was violated in "${context}".${suffix}`,
3551
- code
3552
- };
3553
- case "23505": return {
3554
- message: detail ? `Duplicate value: ${detail}${suffix}` : `Cannot complete operation: a unique constraint${constraint ? ` (${constraint})` : ""} was violated in "${context}".${suffix}`,
3555
- code
3556
- };
3557
- case "23502": return {
3558
- message: `Missing required field: "${column ?? "unknown"}" in "${tableRef}" cannot be empty.${suffix}`,
3559
- code
3560
- };
3561
- case "23514": return {
3562
- message: `Validation failed: a check constraint${constraint ? ` (${constraint})` : ""} was violated in "${context}".${suffix}`,
3563
- code
3564
- };
3565
- case "22P02": return {
3566
- message: `Invalid data format in "${context}": ${pgMessage}${suffix}`,
3567
- code
3568
- };
3569
- case "22001": return {
3570
- message: `Value too long for column "${column ?? "unknown"}" in "${tableRef}": ${pgMessage}${suffix}`,
3571
- code
3572
- };
3573
- case "22003": return {
3574
- message: `Numeric value out of range for column "${column ?? "unknown"}" in "${tableRef}": ${pgMessage}${suffix}`,
3575
- code
3576
- };
3577
- case "42703": return {
3578
- message: `Unknown column in "${tableRef}": ${pgMessage}. Check if your schema is up to date (run migrations).${suffix}`,
3579
- code
3580
- };
3581
- case "42P01": return {
3582
- message: `Table not found for "${context}": ${pgMessage}. Check if your schema is up to date (run migrations).${suffix}`,
3583
- code
3584
- };
3585
- case "42501": return {
3586
- message: `Permission denied on "${tableRef}". Check your database credentials and RLS policies.${suffix}`,
3587
- code
3588
- };
3589
- case "28000": return {
3590
- message: `Authorization failed for "${context}". Check your database credentials.${suffix}`,
3591
- code
3592
- };
3593
- default: {
3594
- const parts = [`Database error in "${context}" [${code}]: ${pgMessage}`];
3595
- if (detail) parts.push(`Detail: ${detail}`);
3596
- if (column) parts.push(`Column: ${column}`);
3597
- if (dataType) parts.push(`Data type: ${dataType}`);
3598
- if (constraint) parts.push(`Constraint: ${constraint}`);
3599
- if (hint) parts.push(`Hint: ${hint}`);
3600
- return {
3601
- message: parts.join(". "),
3602
- code
3603
- };
3740
+ }
3741
+ /**
3742
+ * Fetch raw rows without any relation processing (for REST fast path)
3743
+ */
3744
+ async fetchRowsWithConditionsRaw(collectionPath, options = {}) {
3745
+ const collection = getCollectionByPath(collectionPath, this.registry);
3746
+ const table = getTableForCollection(collection, this.registry);
3747
+ const idField = table[requirePrimaryKeys(collection, this.registry)[0].fieldName];
3748
+ let vectorMeta;
3749
+ if (options.vectorSearch) vectorMeta = DrizzleConditionBuilder.buildVectorSearchConditions(table, options.vectorSearch);
3750
+ let query = vectorMeta ? this.db.select({
3751
+ table_row: table,
3752
+ _distance: vectorMeta.distanceSelect
3753
+ }).from(table).$dynamic() : this.db.select().from(table).$dynamic();
3754
+ const allConditions = [];
3755
+ if (options.relatedTo) allConditions.push(this.buildRelationScope(options.relatedTo));
3756
+ if (options.searchString) {
3757
+ const searchConditions = DrizzleConditionBuilder.buildSearchConditions(options.searchString, collection.properties, table);
3758
+ if (searchConditions.length === 0) return [];
3759
+ allConditions.push(DrizzleConditionBuilder.combineConditionsWithOr(searchConditions));
3760
+ }
3761
+ if (options.filter) {
3762
+ const filterConditions = this.buildFilterConditions(options.filter, table, collectionPath);
3763
+ if (filterConditions.length > 0) allConditions.push(...filterConditions);
3764
+ }
3765
+ if (vectorMeta?.filter) allConditions.push(vectorMeta.filter);
3766
+ if (allConditions.length > 0) {
3767
+ const finalCondition = DrizzleConditionBuilder.combineConditionsWithAnd(allConditions);
3768
+ if (finalCondition) query = query.where(finalCondition);
3769
+ }
3770
+ const orderExpressions = [];
3771
+ if (vectorMeta) orderExpressions.push(asc(vectorMeta.orderBy));
3772
+ else if (options.orderBy) {
3773
+ const orderByField = this.resolveOrderByField(table, options.orderBy, collection);
3774
+ if (orderByField) orderExpressions.push(options.order === "asc" ? asc(orderByField) : desc(orderByField));
3604
3775
  }
3776
+ orderExpressions.push(desc(idField));
3777
+ if (orderExpressions.length > 0) query = query.orderBy(...orderExpressions);
3778
+ const limitValue = options.vectorSearch ? options.limit || 10 : options.searchString ? options.limit || 50 : options.limit;
3779
+ if (limitValue) query = query.limit(limitValue);
3780
+ if (options.offset && options.offset > 0) query = query.offset(options.offset);
3781
+ const rawResults = await query;
3782
+ if (vectorMeta) return rawResults.map((r) => ({
3783
+ ...r.table_row,
3784
+ _distance: typeof r._distance === "number" ? r._distance : parseFloat(String(r._distance))
3785
+ }));
3786
+ return rawResults;
3605
3787
  }
3606
- }
3607
- /**
3608
- * Sanitize any error into a message safe and helpful for the client.
3609
- *
3610
- * A deliberate 4xx (`ApiError`) passes through untouched — the server already
3611
- * decided what the client should read. Otherwise the PG error is extracted
3612
- * from the Drizzle cause chain, falling back to a generic message that
3613
- * doesn't leak SQL.
3614
- *
3615
- * @param error - The raw caught error
3616
- * @param context - A human-readable context string (e.g. collection path)
3617
- * @returns An object with `message` (user-friendly) and optional `code`
3618
- * (the `ApiError` code, or the PG SQLSTATE).
3619
- */
3620
- function sanitizeErrorForClient(error, context) {
3621
- const clientError = asClientFacingError(error);
3622
- if (clientError) {
3623
- const line = `[API ${clientError.statusCode} ${clientError.code ?? "BAD_REQUEST"}] in "${context}": ${clientError.message}`;
3624
- if (clientError.expected) logger.debug(line);
3625
- else logger.warn(`⚠️ ${line}`);
3626
- return {
3627
- message: clientError.message,
3628
- ...clientError.code && { code: clientError.code }
3629
- };
3788
+ /**
3789
+ * Check if the Drizzle instance has the relational query API available
3790
+ * for a given collection path.
3791
+ * Note: Primary path now uses inline `getQueryBuilder()` checks.
3792
+ */
3793
+ hasDrizzleQueryAPI(collectionPath) {
3794
+ if (!this.getQueryBuilder("__probe__")) return false;
3795
+ const tableName = getTableName(getTableForCollection(getCollectionByPath(collectionPath, this.registry), this.registry));
3796
+ return !!this.getQueryBuilder(tableName);
3630
3797
  }
3631
- const pgError = extractPgError(error);
3632
- if (pgError) {
3633
- logger.error(`[PG ${pgError.code}] Error in "${context}"`, {
3634
- code: pgError.code,
3635
- message: pgError.message,
3636
- detail: pgError.detail,
3637
- hint: pgError.hint,
3638
- column: pgError.column,
3639
- table: pgError.table,
3640
- constraint: pgError.constraint,
3641
- dataType: pgError.dataType,
3642
- drizzleMessage: error instanceof Error ? error.message : String(error)
3643
- });
3644
- return pgErrorToFriendlyMessage(pgError, context);
3798
+ /**
3799
+ * Attempt to use Drizzle's relational query API (db.query.<table>.findMany)
3800
+ * for efficient JOIN-based relation loading.
3801
+ * Returns null if the API is not available or the query fails.
3802
+ * Note: Primary path now uses `buildWithConfig` + `buildDrizzleQueryOptions`.
3803
+ */
3804
+ async fetchWithDrizzleQuery(collectionPath, collection, options, include, idInfo, idInfoArray) {
3805
+ try {
3806
+ const table = getTableForCollection(collection, this.registry);
3807
+ const tableName = getTableName(table);
3808
+ const queryTarget = this.getQueryBuilder(tableName);
3809
+ if (!queryTarget?.findMany) return null;
3810
+ const resolvedRelations = resolveCollectionRelations(collection);
3811
+ const withConfig = {};
3812
+ for (const [key, relation] of Object.entries(resolvedRelations)) if (include[0] === "*" || include.includes(key)) {
3813
+ const drizzleRelName = relation.relationName || key;
3814
+ withConfig[drizzleRelName] = true;
3815
+ }
3816
+ const queryOpts = { with: withConfig };
3817
+ if (options.limit) queryOpts.limit = options.limit;
3818
+ if (options.filter) {
3819
+ const filterConditions = this.buildFilterConditions(options.filter, table, collectionPath);
3820
+ if (filterConditions.length > 0) queryOpts.where = and(...filterConditions);
3821
+ }
3822
+ if (options.orderBy) {
3823
+ const orderByField = this.resolveOrderByField(table, options.orderBy, collection);
3824
+ if (orderByField) queryOpts.orderBy = options.order === "asc" ? asc(orderByField) : desc(orderByField);
3825
+ }
3826
+ return (await queryTarget.findMany(queryOpts)).map((row) => {
3827
+ const flat = {};
3828
+ for (const [k, v] of Object.entries(row)) if (Array.isArray(v)) flat[k] = v.map((item) => {
3829
+ const keys = Object.keys(item);
3830
+ const nestedObj = keys.find((nk) => typeof item[nk] === "object" && item[nk] !== null && !Array.isArray(item[nk]));
3831
+ if (nestedObj && keys.length <= 3) return { ...item[nestedObj] };
3832
+ return { ...item };
3833
+ });
3834
+ else if (typeof v === "object" && v !== null) flat[k] = { ...v };
3835
+ else flat[k] = v;
3836
+ return flat;
3837
+ });
3838
+ } catch (e) {
3839
+ logger.warn(`[include] Drizzle relational query failed for '${collectionPath}', falling back`, { error: e });
3840
+ return null;
3841
+ }
3645
3842
  }
3646
- logger.error(`Database error in "${context}" (no PG error extracted)`, {
3647
- error: error instanceof Error ? error.message : String(error),
3648
- stack: error instanceof Error ? error.stack : void 0,
3649
- cause: error instanceof Error && error.cause ? error.cause instanceof Error ? error.cause.message : String(error.cause) : void 0
3650
- });
3651
- const causeMessage = extractCauseMessage(error);
3652
- if (causeMessage) return { message: `Database error in "${context}": ${causeMessage}` };
3653
- return { message: `Could not load data for "${context}". Check server logs for details.` };
3654
- }
3843
+ /**
3844
+ * Fallback path used when db.query is unavailable.
3845
+ * The primary path uses db.query.findMany with `with` config, which
3846
+ * loads all relations in a single query.
3847
+ *
3848
+ * Batch fetch many-to-many related rows for multiple parent IDs.
3849
+ * Groups results by parent ID to avoid N+1.
3850
+ */
3851
+ async batchFetchManyRelatedRows(parentCollectionPath, parentIds, relationKey) {
3852
+ if (parentIds.length === 0) return /* @__PURE__ */ new Map();
3853
+ const relation = resolveCollectionRelations(getCollectionByPath(parentCollectionPath, this.registry))[relationKey];
3854
+ if (!relation) {
3855
+ logger.warn(`[batchFetchManyRelatedRows] ResolvedRelation '${relationKey}' not found, skipping`);
3856
+ return /* @__PURE__ */ new Map();
3857
+ }
3858
+ const entityMap = await this.relationService.batchFetchRelatedEntitiesMany(parentCollectionPath, parentIds, relationKey, relation);
3859
+ const flatMap = /* @__PURE__ */ new Map();
3860
+ for (const [key, rows] of entityMap) flatMap.set(key, rows.map((e) => ({
3861
+ ...e.values,
3862
+ id: e.id
3863
+ })));
3864
+ return flatMap;
3865
+ }
3866
+ };
3655
3867
  //#endregion
3656
3868
  //#region src/services/PersistService.ts
3657
3869
  /**
@@ -3775,10 +3987,11 @@ var PersistService = class {
3775
3987
  } else {
3776
3988
  const targetColumnName = this.resolveParentForeignKeyColumn(hop);
3777
3989
  if (targetColumnName) {
3778
- const parsedParentId = parentIdForWrite();
3990
+ const parentKeyValue = hasForeignKeyOnTarget(hop.relation) ? await this.relationService.parentKeyValue(hop.parentCollection, hop.relation, hop.parentId) : parentIdForWrite();
3991
+ if (parentKeyValue === void 0) throw ApiError.badRequest(`Cannot create under "${collectionPath}": the parent row has no value in \`sourceKey\`, so the new row has nothing to point at.`);
3779
3992
  const existingValue = effectiveValues[targetColumnName];
3780
- if (existingValue !== void 0 && existingValue !== null && existingValue !== parsedParentId) logger.warn(`Overriding provided value '${existingValue}' for FK '${targetColumnName}' with path parent id '${parsedParentId}'.`);
3781
- effectiveValues[targetColumnName] = parsedParentId;
3993
+ if (existingValue !== void 0 && existingValue !== null && existingValue !== parentKeyValue) logger.warn(`Overriding provided value '${existingValue}' for FK '${targetColumnName}' with path parent key '${parentKeyValue}'.`);
3994
+ effectiveValues[targetColumnName] = parentKeyValue;
3782
3995
  }
3783
3996
  }
3784
3997
  }
@@ -4052,19 +4265,34 @@ function validateIdentifier(value, label) {
4052
4265
  if (!/^[a-zA-Z0-9_-]+$/.test(value)) throw new Error(`Invalid ${label}: only letters, digits, underscores, and hyphens are allowed.`);
4053
4266
  }
4054
4267
  /**
4055
- * Sanitize a user-provided branch name to a safe PostgreSQL identifier.
4056
- * Only allows alphanumeric characters and underscores.
4268
+ * Postgres truncates identifiers at NAMEDATALEN-1 = 63 bytes, and does it
4269
+ * silently. The prefix comes out of the same budget.
4270
+ */
4271
+ var MAX_BRANCH_NAME_LENGTH = 60;
4272
+ /**
4273
+ * Check a user-provided branch name, and otherwise leave it exactly as given.
4274
+ *
4275
+ * This used to strip everything outside [a-zA-Z0-9_], so `my-feature` was
4276
+ * quietly created as `myfeature`: the name you typed was not the name `list`
4277
+ * gave back. Nothing ever needed that. Every identifier this service builds is
4278
+ * double-quoted (see `CREATE DATABASE` below), which is what makes a hyphen
4279
+ * safe, and `validateIdentifier` has always accepted hyphens for the `--from`
4280
+ * source database — the two disagreed about the same character class.
4281
+ *
4282
+ * Refusing a name we cannot represent is better than representing a different
4283
+ * one, which is also why the length is checked here rather than left to
4284
+ * Postgres, whose answer to an over-long identifier is a silent rename.
4057
4285
  */
4058
- function sanitizeBranchName(name) {
4059
- return name.replace(/[^a-zA-Z0-9_]/g, "");
4286
+ function assertValidBranchName(name) {
4287
+ validateIdentifier(name, "branch name");
4288
+ if (name.length > MAX_BRANCH_NAME_LENGTH) throw new Error(`Branch name "${name}" is too long: ${name.length} characters, maximum ${MAX_BRANCH_NAME_LENGTH}. Postgres truncates identifiers past 63 bytes, which would give the branch a name you did not choose.`);
4060
4289
  }
4061
4290
  /**
4062
4291
  * Convert a user-facing branch name to the actual PostgreSQL database name.
4063
4292
  */
4064
4293
  function toBranchDbName(name) {
4065
- const sanitized = sanitizeBranchName(name);
4066
- if (!sanitized) throw new Error("Branch name must contain at least one alphanumeric character.");
4067
- return `${BRANCH_DB_PREFIX}${sanitized}`;
4294
+ assertValidBranchName(name);
4295
+ return `${BRANCH_DB_PREFIX}${name}`;
4068
4296
  }
4069
4297
  var BranchService = class {
4070
4298
  db;
@@ -4101,9 +4329,8 @@ var BranchService = class {
4101
4329
  async createBranch(name, options) {
4102
4330
  if (options?.source) validateIdentifier(options.source, "source database name");
4103
4331
  const dbName = toBranchDbName(name);
4104
- const sanitizedName = sanitizeBranchName(name);
4105
4332
  const sourceDb = options?.source || this.poolManager.defaultDatabaseName;
4106
- if ((await this.db.execute(sql`SELECT name FROM rebase.branches WHERE name = ${sanitizedName} OR db_name = ${dbName}`)).rows.length > 0) throw new Error(`Branch "${sanitizedName}" already exists.`);
4333
+ if ((await this.db.execute(sql`SELECT name FROM rebase.branches WHERE name = ${name} OR db_name = ${dbName}`)).rows.length > 0) throw new Error(`Branch "${name}" already exists.`);
4107
4334
  await this.poolManager.disconnectDatabase(sourceDb);
4108
4335
  const safeDbName = dbName.replace(/"/g, "\"\"");
4109
4336
  const safeSourceDb = sourceDb.replace(/"/g, "\"\"");
@@ -4114,10 +4341,10 @@ var BranchService = class {
4114
4341
  throw describeBranchDdlError(err, dbName);
4115
4342
  }
4116
4343
  const now = /* @__PURE__ */ new Date();
4117
- await this.db.execute(sql`INSERT INTO rebase.branches (name, db_name, parent_db, created_at)
4118
- VALUES (${sanitizedName}, ${dbName}, ${sourceDb}, ${now.toISOString()})`);
4344
+ await this.db.execute(sql`INSERT INTO rebase.branches (name, db_name, parent_db, created_at)
4345
+ VALUES (${name}, ${dbName}, ${sourceDb}, ${now.toISOString()})`);
4119
4346
  return {
4120
- name: sanitizedName,
4347
+ name,
4121
4348
  parentDatabase: sourceDb,
4122
4349
  createdAt: now
4123
4350
  };
@@ -4127,19 +4354,21 @@ var BranchService = class {
4127
4354
  * Cannot delete the main/default database.
4128
4355
  */
4129
4356
  async deleteBranch(name) {
4130
- const sanitizedName = sanitizeBranchName(name);
4131
- const dbName = toBranchDbName(name);
4357
+ assertValidBranchName(name);
4358
+ if (toBranchDbName(name) === this.poolManager.defaultDatabaseName) throw new Error("Cannot delete the main database.");
4359
+ const existingRows = (await this.db.execute(sql`SELECT db_name FROM rebase.branches WHERE name = ${name}`)).rows;
4360
+ if (existingRows.length === 0) throw new Error(`Branch "${name}" not found.`);
4361
+ const dbName = existingRows[0].db_name;
4132
4362
  if (dbName === this.poolManager.defaultDatabaseName) throw new Error("Cannot delete the main database.");
4133
- if ((await this.db.execute(sql`SELECT db_name FROM rebase.branches WHERE name = ${sanitizedName}`)).rows.length === 0) throw new Error(`Branch "${sanitizedName}" not found.`);
4134
4363
  await this.poolManager.disconnectDatabase(dbName);
4135
4364
  const safeDbName = dbName.replace(/"/g, "\"\"");
4136
4365
  try {
4137
4366
  await this.db.execute(sql.raw(`DROP DATABASE "${safeDbName}"`));
4138
4367
  } catch (err) {
4139
- if (extractPgError(err)?.code === PG_OBJECT_IN_USE) throw new Error(`Cannot delete branch "${sanitizedName}": the database has active connections. Close other clients and try again.`);
4368
+ if (extractPgError(err)?.code === PG_OBJECT_IN_USE) throw new Error(`Cannot delete branch "${name}": the database has active connections. Close other clients and try again.`);
4140
4369
  throw describeBranchDdlError(err, dbName);
4141
4370
  }
4142
- await this.db.execute(sql`DELETE FROM rebase.branches WHERE name = ${sanitizedName}`);
4371
+ await this.db.execute(sql`DELETE FROM rebase.branches WHERE name = ${name}`);
4143
4372
  }
4144
4373
  /**
4145
4374
  * List all branches recorded in the metadata table.
@@ -4166,20 +4395,21 @@ var BranchService = class {
4166
4395
  * Get info about a specific branch.
4167
4396
  */
4168
4397
  async getBranchInfo(name) {
4169
- const sanitizedName = sanitizeBranchName(name);
4398
+ assertValidBranchName(name);
4170
4399
  const rows = (await this.db.execute(sql`
4171
- SELECT
4400
+ SELECT
4172
4401
  b.name,
4402
+ b.db_name,
4173
4403
  b.parent_db,
4174
4404
  b.created_at
4175
4405
  FROM rebase.branches b
4176
- WHERE b.name = ${sanitizedName}
4406
+ WHERE b.name = ${name}
4177
4407
  `)).rows;
4178
4408
  if (rows.length === 0) return void 0;
4179
4409
  const row = rows[0];
4180
4410
  let sizeBytes;
4181
4411
  try {
4182
- const dbName = toBranchDbName(sanitizedName);
4412
+ const dbName = row.db_name;
4183
4413
  const sizeRows = (await this.db.execute(sql`SELECT pg_database_size(${dbName}) as size_bytes`)).rows;
4184
4414
  if (sizeRows.length > 0 && sizeRows[0].size_bytes != null) sizeBytes = Number(sizeRows[0].size_bytes);
4185
4415
  } catch {}
@@ -5056,9 +5286,10 @@ var PostgresBackendDriver = class PostgresBackendDriver {
5056
5286
  async checkUniqueField(path, name, value, id, collection) {
5057
5287
  return this.dataService.checkUniqueField(path, name, value, id, collection?.databaseId);
5058
5288
  }
5059
- async count({ path, collection, filter, searchString }) {
5289
+ async count({ path, collection, filter, logical, searchString }) {
5060
5290
  return this.dataService.count(path, {
5061
5291
  filter,
5292
+ logical,
5062
5293
  searchString
5063
5294
  });
5064
5295
  }
@@ -5777,6 +6008,7 @@ var getDrizzleColumn = (propName, prop, collection, collections) => {
5777
6008
  const isId = isIdProperty(propName, prop, collection);
5778
6009
  let baseType = numProp.validation?.integer || isId ? `integer("${colName}")` : `numeric("${colName}")`;
5779
6010
  if (numProp.columnType) if (numProp.columnType === "double precision") baseType = `doublePrecision("${colName}")`;
6011
+ else if (numProp.columnType === "bigint" || numProp.columnType === "bigserial") baseType = `${numProp.columnType}("${colName}", { mode: "number" })`;
5780
6012
  else baseType = `${numProp.columnType}("${colName}")`;
5781
6013
  if ("isId" in numProp && numProp.isId === "increment") columnDefinition = `${baseType}.generatedByDefaultAsIdentity()`;
5782
6014
  else if ("isId" in numProp && typeof numProp.isId === "string" && numProp.isId !== "manual") {
@@ -6129,8 +6361,9 @@ var generateSchema = async (collections, stripPolicies = false) => {
6129
6361
  if (!emittedRelationNames.has(deduplicationKey)) {
6130
6362
  const otherTableVar = getTableVarName(getTableName$1(otherCollection));
6131
6363
  const drizzleFieldKey = resolvePropertyKeyForColumn(collection, otherRel.foreignKeyOnTarget);
6364
+ const referencedKey = otherRel.sourceKey ? resolvePropertyKeyForColumn(otherCollection, otherRel.sourceKey) : getPrimaryKeyName(otherCollection);
6132
6365
  const synthKey = `_synth_${otherTableVar}_${drizzleFieldKey}`;
6133
- tableRelations.push(` "${synthKey}": one(${otherTableVar}, {\n fields: [${tableVarName}.${drizzleFieldKey}],\n references: [${otherTableVar}.${getPrimaryKeyName(otherCollection)}],\n relationName: \"${drizzleRelationName}\"\n })`);
6366
+ tableRelations.push(` "${synthKey}": one(${otherTableVar}, {\n fields: [${tableVarName}.${drizzleFieldKey}],\n references: [${otherTableVar}.${referencedKey}],\n relationName: \"${drizzleRelationName}\"\n })`);
6134
6367
  emittedRelationNames.add(deduplicationKey);
6135
6368
  }
6136
6369
  }
@@ -7288,14 +7521,6 @@ function resolveChannelBusSetting(configured) {
7288
7521
  return raw === "memory" ? { type: "memory" } : { type: "postgres" };
7289
7522
  }
7290
7523
  /**
7291
- * @deprecated Use {@link resolveChannelBusSetting}, which also accepts a
7292
- * supplied {@link ChannelBus} instance. Kept as a narrow alias so existing
7293
- * config-only callers keep their exact types.
7294
- */
7295
- function resolveChannelBusConfig(configured) {
7296
- return resolveChannelBusSetting(configured);
7297
- }
7298
- /**
7299
7524
  * Produce the bus a setting asks for.
7300
7525
  *
7301
7526
  * An instance is handed straight back — constructing it was the application's
@@ -8906,7 +9131,7 @@ function createBackupCron(config) {
8906
9131
  enabled: config.enabled ?? true,
8907
9132
  timeoutSeconds: 3600,
8908
9133
  async handler({ log }) {
8909
- const { createDump, pruneBackups, uploadBackup, validateDump } = await import("./backup-service-vAKWJkYL.js").then((n) => n.r);
9134
+ const { createDump, pruneBackups, uploadBackup, validateDump } = await import("./backup-service-CD8o_1Sl.js").then((n) => n.r);
8910
9135
  const { destination } = config;
8911
9136
  if (destination.kind !== "local" && !config.storage) throw new Error(`Backup destination is ${destination.kind} but no storage controller was provided. Pass the backend's configured StorageController to createBackupCron({ storage }).`);
8912
9137
  log(`Starting backup of "${dbName}"…`);
@@ -9037,6 +9262,11 @@ function findRelationDefects(collections, registry) {
9037
9262
  problem: `\`foreignKeyOnTarget: "${relation.foreignKeyOnTarget}"\` is not a column on the target table \`${targetTableName}\``,
9038
9263
  fix: `add the column, or set \`foreignKeyOnTarget\` to one of: ${quote(targetColumns)}`
9039
9264
  });
9265
+ if (relation.sourceKey && !sourceColumns.has(relation.sourceKey)) defects.push({
9266
+ ...at,
9267
+ problem: `\`sourceKey: "${relation.sourceKey}"\` is not a column on \`${sourceTableName}\``,
9268
+ fix: targetColumns.has(relation.sourceKey) ? `it is a column on the *target* table \`${targetTableName}\` — \`sourceKey\` names the column on this collection that the target's foreign key points at, so it must be one of: ${quote(sourceColumns)}` : `add the column, or set \`sourceKey\` to one of: ${quote(sourceColumns)}`
9269
+ });
9040
9270
  break;
9041
9271
  case "manyToMany": {
9042
9272
  const { table, sourceColumn, targetColumn } = relation.through;
@@ -9788,21 +10018,6 @@ async function ensureAuthTablesExist(db, collection) {
9788
10018
  }
9789
10019
  //#endregion
9790
10020
  //#region src/auth/services.ts
9791
- function getColumnKey(table, ...keys) {
9792
- if (!table) return void 0;
9793
- for (const key of keys) {
9794
- if (key in table) return key;
9795
- const snake = toSnakeCase(key);
9796
- if (snake in table) return snake;
9797
- const camel = camelCase(key);
9798
- if (camel in table) return camel;
9799
- }
9800
- }
9801
- function getColumn(table, ...keys) {
9802
- if (!table) return void 0;
9803
- const key = getColumnKey(table, ...keys);
9804
- return key ? table[key] : void 0;
9805
- }
9806
10021
  /**
9807
10022
  * The single definition of what an email address looks like in storage.
9808
10023
  *
@@ -9817,9 +10032,25 @@ function getColumn(table, ...keys) {
9817
10032
  *
9818
10033
  * Whitespace goes too: a trailing space survives the fold and reproduces the
9819
10034
  * problem exactly.
10035
+ *
10036
+ * Re-exported rather than defined here: `@rebasepro/server` and
10037
+ * `@rebasepro/server-mongo` write this column too, and a second copy of this
10038
+ * rule is the defect it exists to prevent.
9820
10039
  */
9821
- function normalizeEmail(email) {
9822
- return typeof email === "string" ? email.trim().toLowerCase() : email;
10040
+ function getColumnKey(table, ...keys) {
10041
+ if (!table) return void 0;
10042
+ for (const key of keys) {
10043
+ if (key in table) return key;
10044
+ const snake = toSnakeCase(key);
10045
+ if (snake in table) return snake;
10046
+ const camel = camelCase(key);
10047
+ if (camel in table) return camel;
10048
+ }
10049
+ }
10050
+ function getColumn(table, ...keys) {
10051
+ if (!table) return void 0;
10052
+ const key = getColumnKey(table, ...keys);
10053
+ return key ? table[key] : void 0;
9823
10054
  }
9824
10055
  /**
9825
10056
  * PostgreSQL implementation of UserRepository.
@@ -11160,6 +11391,31 @@ function humanize(snakeName) {
11160
11391
  return snakeName.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
11161
11392
  }
11162
11393
  //#endregion
11394
+ //#region src/schema/introspect-db-types.ts
11395
+ /**
11396
+ * The PostgreSQL type → Rebase property type mapping.
11397
+ *
11398
+ * Split out of `introspect-db-logic` so that the structural analysis can use it
11399
+ * without importing the generator, which imports the analysis. Re-exported from
11400
+ * `introspect-db-logic` so existing callers keep their import path.
11401
+ */
11402
+ /**
11403
+ * Map a PostgreSQL data type to a Rebase property type.
11404
+ */
11405
+ function mapPgType(dataType) {
11406
+ const dt = dataType.toLowerCase();
11407
+ if (dt === "interval") return "string";
11408
+ if (dt === "array" || dt.startsWith("_")) return "array";
11409
+ if (dt.includes("int") || dt.includes("numeric") || dt.includes("decimal") || dt.includes("serial") || dt === "real" || dt === "float4" || dt === "float8" || dt === "double precision" || dt === "money") return "number";
11410
+ if (dt.includes("bool")) return "boolean";
11411
+ if (dt.includes("time") || dt.includes("date")) return "date";
11412
+ if (dt === "json" || dt === "jsonb") return "map";
11413
+ if (dt === "bytea") return "binary";
11414
+ if (dt === "inet" || dt === "cidr" || dt === "macaddr" || dt === "macaddr8") return "string";
11415
+ if (dt === "uuid") return "string";
11416
+ return "string";
11417
+ }
11418
+ //#endregion
11163
11419
  //#region src/schema/introspect-db-logic.ts
11164
11420
  var IRREGULAR_SINGULARS = {
11165
11421
  people: "person",
@@ -11175,6 +11431,36 @@ var IRREGULAR_SINGULARS = {
11175
11431
  criteria: "criterion",
11176
11432
  phenomena: "phenomenon"
11177
11433
  };
11434
+ /**
11435
+ * Plurals in "-ves" whose singular really ends in f/fe, and which of the two.
11436
+ *
11437
+ * A blanket "-ves" -> "-f" rule gets `knives` -> `knif`, and mangles every
11438
+ * ordinary "-ive" noun that happens to be plural along with it: `archives` ->
11439
+ * `archif`, `objectives` -> `objectif`. The set of English words that genuinely
11440
+ * swap f/fe for ves is small and closed, so it is listed rather than guessed —
11441
+ * anything else ending in "ves" drops the trailing 's' like any other plural.
11442
+ *
11443
+ * Matched on the whole word, not on the suffix: `olives` ends in `lives`.
11444
+ */
11445
+ var VES_SINGULAR_ENDINGS = {
11446
+ calves: "f",
11447
+ dwarves: "f",
11448
+ elves: "f",
11449
+ halves: "f",
11450
+ hooves: "f",
11451
+ leaves: "f",
11452
+ loaves: "f",
11453
+ scarves: "f",
11454
+ selves: "f",
11455
+ sheaves: "f",
11456
+ shelves: "f",
11457
+ thieves: "f",
11458
+ wharves: "f",
11459
+ wolves: "f",
11460
+ knives: "fe",
11461
+ lives: "fe",
11462
+ wives: "fe"
11463
+ };
11178
11464
  /** Words ending in 's' that are already singular. */
11179
11465
  var UNCOUNTABLE = /* @__PURE__ */ new Set([
11180
11466
  "status",
@@ -11213,7 +11499,7 @@ function singularize(word) {
11213
11499
  if (UNCOUNTABLE.has(lower)) return word;
11214
11500
  if (lower.endsWith("ices") && lower.length > 5) return word.slice(0, -4) + "ex";
11215
11501
  if (lower.endsWith("ies") && lower.length > 3) return word.slice(0, -3) + "y";
11216
- if (lower.endsWith("ves")) return word.slice(0, -3) + "f";
11502
+ if (VES_SINGULAR_ENDINGS[lower]) return word.slice(0, -3) + VES_SINGULAR_ENDINGS[lower];
11217
11503
  if (lower.endsWith("ches") || lower.endsWith("shes") || lower.endsWith("sses") || lower.endsWith("xes") || lower.endsWith("zes")) return word.slice(0, -2);
11218
11504
  if (lower.endsWith("ses") && !lower.endsWith("sses")) return word.slice(0, -1);
11219
11505
  if (lower.endsWith("s") && !lower.endsWith("ss") && !lower.endsWith("us") && !lower.endsWith("is")) return word.slice(0, -1);
@@ -11234,22 +11520,6 @@ function getIconForTable(tableName) {
11234
11520
  if (table.includes("comment") || table.includes("review") || table.includes("feedback")) return "MessageCircle";
11235
11521
  return "Database";
11236
11522
  }
11237
- /**
11238
- * Map a PostgreSQL data type to a Rebase property type.
11239
- */
11240
- function mapPgType(dataType) {
11241
- const dt = dataType.toLowerCase();
11242
- if (dt === "interval") return "string";
11243
- if (dt === "array" || dt.startsWith("_")) return "array";
11244
- if (dt.includes("int") || dt.includes("numeric") || dt.includes("decimal") || dt.includes("serial") || dt === "real" || dt === "float4" || dt === "float8" || dt === "double precision" || dt === "money") return "number";
11245
- if (dt.includes("bool")) return "boolean";
11246
- if (dt.includes("time") || dt.includes("date")) return "date";
11247
- if (dt === "json" || dt === "jsonb") return "map";
11248
- if (dt === "bytea") return "binary";
11249
- if (dt === "inet" || dt === "cidr" || dt === "macaddr" || dt === "macaddr8") return "string";
11250
- if (dt === "uuid") return "string";
11251
- return "string";
11252
- }
11253
11523
  function buildEnumMap(enumValues) {
11254
11524
  const enumMap = /* @__PURE__ */ new Map();
11255
11525
  for (const ev of enumValues) {
@@ -11269,6 +11539,20 @@ function buildTablesMap(tables, columns, pks, fks) {
11269
11539
  });
11270
11540
  return tablesMap;
11271
11541
  }
11542
+ /**
11543
+ * Join tables, identified by column name.
11544
+ *
11545
+ * Superseded for the CLI by `classifyTables` in `./introspect-db-structure`,
11546
+ * which asks the database instead: two single-column keys, unique together, no
11547
+ * payload column, nothing referencing the table. This rule folds away
11548
+ * `northwind.order_details` — which has the key shape and carries unit price,
11549
+ * quantity and discount — because it recognises `id`, `created_at` and
11550
+ * `updated_at` by name and calls everything else a foreign key.
11551
+ *
11552
+ * Still used by `./introspect-runtime`, which builds collections in memory from
11553
+ * a narrower set of catalog queries and has no unique-constraint or row-count
11554
+ * data to reason with.
11555
+ */
11272
11556
  function identifyJoinTables(tablesMap) {
11273
11557
  const joinTables = /* @__PURE__ */ new Set();
11274
11558
  for (const [tableName, meta] of tablesMap.entries()) if (meta.fks.length === 2) {
@@ -12004,7 +12288,7 @@ function createPostgresBootstrapper(pgConfig) {
12004
12288
  */
12005
12289
  async ensureCollectionSchema(collections, driverResult, log) {
12006
12290
  const internals = driverResult.internals;
12007
- const { ensureCollectionTables } = await import("./ensure-collection-tables-D6-XhqnQ.js");
12291
+ const { ensureCollectionTables } = await import("./ensure-collection-tables-CBQdOETu.js");
12008
12292
  const plan = await ensureCollectionTables({ async query(text) {
12009
12293
  const result = await internals.db.execute(sql.raw(text));
12010
12294
  return { rows: result.rows ?? (Array.isArray(result) ? result : []) };
@@ -12029,7 +12313,7 @@ function createPostgresBootstrapper(pgConfig) {
12029
12313
  */
12030
12314
  async ensureCollectionPolicies(collections, driverResult, log) {
12031
12315
  const internals = driverResult.internals;
12032
- const { ensureCollectionPolicies } = await import("./ensure-collection-policies-BjSwj0FM.js");
12316
+ const { ensureCollectionPolicies } = await import("./ensure-collection-policies-ViG8XiPn.js");
12033
12317
  const outcome = await ensureCollectionPolicies({ async query(text) {
12034
12318
  const result = await internals.db.execute(sql.raw(text));
12035
12319
  return { rows: result.rows ?? (Array.isArray(result) ? result : []) };
@@ -12043,7 +12327,7 @@ function createPostgresBootstrapper(pgConfig) {
12043
12327
  },
12044
12328
  mountRoutes(app, basePath, driverResult) {},
12045
12329
  async initializeWebsockets(server, realtimeService, driver, config, adapter) {
12046
- const { createPostgresWebSocket } = await import("./websocket-DB7TbFPT.js").then((n) => n.n);
12330
+ const { createPostgresWebSocket } = await import("./websocket-B2LsrINK.js").then((n) => n.n);
12047
12331
  createPostgresWebSocket(server, realtimeService, driver, config, adapter);
12048
12332
  }
12049
12333
  };
@@ -12069,8 +12353,8 @@ function createPostgresAdapter(pgConfig) {
12069
12353
  async initializeHistory(config, driverResult) {
12070
12354
  if (bootstrapper.initializeHistory) return bootstrapper.initializeHistory(config, driverResult);
12071
12355
  },
12072
- initializeWebsockets(server, realtimeService, driver, config) {
12073
- if (bootstrapper.initializeWebsockets) return bootstrapper.initializeWebsockets(server, realtimeService, driver, config);
12356
+ initializeWebsockets(server, realtimeService, driver, config, adapter) {
12357
+ if (bootstrapper.initializeWebsockets) return bootstrapper.initializeWebsockets(server, realtimeService, driver, config, adapter);
12074
12358
  },
12075
12359
  ensureCollectionSchema: bootstrapper.ensureCollectionSchema ? (collections, driverResult, log) => bootstrapper.ensureCollectionSchema(collections, driverResult, log) : void 0,
12076
12360
  ensureCollectionPolicies: bootstrapper.ensureCollectionPolicies ? (collections, driverResult, log) => bootstrapper.ensureCollectionPolicies(collections, driverResult, log) : void 0,
@@ -12083,6 +12367,6 @@ function createPostgresAdapter(pgConfig) {
12083
12367
  };
12084
12368
  }
12085
12369
  //#endregion
12086
- export { AuthenticatedPostgresBackendDriver, BackupToolError, BranchService, CHANNEL_BUS_NOTIFY_CHANNEL, DEFAULT_BATCH_WINDOW_MS, DatabasePoolManager, DrizzleConditionBuilder, MemoryChannelBus, PG_NOTIFY_MAX_PAYLOAD_BYTES, PostgresBackendDriver, PostgresChannelBus, PostgresCollectionRegistry, PostgresConditionBuilder, PostgresRealtimeProvider, RealtimeService, appConfig, applyGlobals, backupCronConfigFromEnv, buildBackupFilename, buildPgDumpArgs, buildPgDumpallGlobalsArgs, buildPgRestoreArgs, buildPgRestoreListArgs, checkToolServerCompatibility, configureUnknownFilterFields, createAuthSchema, createBackupCron, createChannelBus, createDirectDatabaseConnection, createDump, createPostgresAdapter, createPostgresBootstrapper, createPostgresDatabaseConnection, createPostgresWebSocket, createReadReplicaConnection, detectToolMajor, ensureDatabaseExists, frameByteLength, generateSchema, getServerVersionMajor, getUnknownFilterFieldsMode, globalsFileForDump, guardPoolAgainstDirtyRelease, isChannelBusInstance, joinStorageKey, listBackups, magicLinkTokens, magicLinkTokensRelations, mfaChallenges, mfaChallengesRelations, mfaFactors, mfaFactorsRelations, parseBackupDestination, parseBackupTimestamp, parseChannelBusFrame, parseChannelBusPayload, parseDbNameFromUrl, parsePgToolMajor, passwordResetTokens, passwordResetTokensRelations, pinSearchPath, preflight, pruneBackups, recoveryCodes, recoveryCodesRelations, refreshTokens, refreshTokensRelations, resolveChannelBusConfig, resolveChannelBusSetting, resolveConnectionString, resolveDriftCheckName, resolvePgBinary, restoreDump, selectBackupsToPrune, serverVersionNumToMajor, splitGlobalsStatements, uploadBackup, userIdentities, userIdentitiesRelations, users, usersRelations, usersSchema, validateDump, withDatabaseName };
12370
+ export { AuthenticatedPostgresBackendDriver, BackupToolError, BranchService, CHANNEL_BUS_NOTIFY_CHANNEL, DEFAULT_BATCH_WINDOW_MS, DatabasePoolManager, DrizzleConditionBuilder, MemoryChannelBus, PG_NOTIFY_MAX_PAYLOAD_BYTES, PostgresBackendDriver, PostgresChannelBus, PostgresCollectionRegistry, PostgresConditionBuilder, PostgresRealtimeProvider, RealtimeService, appConfig, applyGlobals, backupCronConfigFromEnv, buildBackupFilename, buildPgDumpArgs, buildPgDumpallGlobalsArgs, buildPgRestoreArgs, buildPgRestoreListArgs, buildRowSecurityPgOptions, checkToolServerCompatibility, configureUnknownFilterFields, createAuthSchema, createBackupCron, createChannelBus, createDirectDatabaseConnection, createDump, createPostgresAdapter, createPostgresBootstrapper, createPostgresDatabaseConnection, createPostgresWebSocket, createReadReplicaConnection, detectToolMajor, diagnoseRowSecurityDumpFailure, ensureDatabaseExists, frameByteLength, generateSchema, getServerVersionMajor, getUnknownFilterFieldsMode, globalsFileForDump, guardPoolAgainstDirtyRelease, isChannelBusInstance, joinStorageKey, listBackups, magicLinkTokens, magicLinkTokensRelations, mfaChallenges, mfaChallengesRelations, mfaFactors, mfaFactorsRelations, parseBackupDestination, parseBackupTimestamp, parseChannelBusFrame, parseChannelBusPayload, parseDbNameFromUrl, parsePgToolMajor, passwordResetTokens, passwordResetTokensRelations, pinSearchPath, preflight, pruneBackups, recoveryCodes, recoveryCodesRelations, refreshTokens, refreshTokensRelations, resolveChannelBusSetting, resolveConnectionString, resolveDriftCheckName, resolvePgBinary, restoreDump, selectBackupsToPrune, serverVersionNumToMajor, splitGlobalsStatements, uploadBackup, userIdentities, userIdentitiesRelations, users, usersRelations, usersSchema, validateDump, withDatabaseName };
12087
12371
 
12088
12372
  //# sourceMappingURL=index.es.js.map