@rebasepro/server-postgres 0.12.1-canary.gcfa333c → 0.12.1-canary.gddbd489

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 (81) hide show
  1. package/dist/PostgresBackendDriver.d.ts +1 -1
  2. package/dist/PostgresBootstrapper.d.ts +25 -1
  3. package/dist/auth/services.d.ts +6 -1
  4. package/dist/backup/backup-service.d.ts +10 -1
  5. package/dist/backup/pg-tools.d.ts +47 -0
  6. package/dist/{backup-service-DH9kPg-E.js → backup-service-CD8o_1Sl.js} +144 -11
  7. package/dist/backup-service-CD8o_1Sl.js.map +1 -0
  8. package/dist/cli-helpers.d.ts +39 -0
  9. package/dist/{connection-B5Wndbr1.js → connection-BuZ97wsr.js} +57 -3
  10. package/dist/connection-BuZ97wsr.js.map +1 -0
  11. package/dist/connection.d.ts +42 -0
  12. package/dist/{ensure-collection-policies-Vl3Cv1Q9.js → ensure-collection-policies-ViG8XiPn.js} +2 -2
  13. package/dist/{ensure-collection-policies-Vl3Cv1Q9.js.map → ensure-collection-policies-ViG8XiPn.js.map} +1 -1
  14. package/dist/{ensure-collection-tables-DsDsNl6o.js → ensure-collection-tables-CBQdOETu.js} +72 -12
  15. package/dist/ensure-collection-tables-CBQdOETu.js.map +1 -0
  16. package/dist/index.es.js +990 -677
  17. package/dist/index.es.js.map +1 -1
  18. package/dist/policy-CeA1JcxP.js +105 -0
  19. package/dist/policy-CeA1JcxP.js.map +1 -0
  20. package/dist/schema/ensure-collection-tables.d.ts +21 -1
  21. package/dist/schema/generate-postgres-ddl-logic.d.ts +19 -0
  22. package/dist/schema/introspect-db-constraints.d.ts +57 -0
  23. package/dist/schema/introspect-db-logic.d.ts +94 -5
  24. package/dist/schema/introspect-db-queries.d.ts +119 -0
  25. package/dist/schema/introspect-db-structure.d.ts +263 -0
  26. package/dist/schema/introspect-db-types.d.ts +11 -0
  27. package/dist/services/FetchService.d.ts +4 -1
  28. package/dist/services/RelationService.d.ts +24 -1
  29. package/dist/services/channel-bus/index.d.ts +1 -7
  30. package/dist/services/collection-helpers.d.ts +36 -2
  31. package/dist/services/dataService.d.ts +3 -1
  32. package/dist/services/row-pipeline.d.ts +1 -1
  33. package/dist/{src-DihrDFuP.js → src-DlPBctw_.js} +217 -101
  34. package/dist/src-DlPBctw_.js.map +1 -0
  35. package/dist/utils/connection-string.d.ts +29 -0
  36. package/dist/utils/drizzle-conditions.d.ts +5 -4
  37. package/dist/utils/pg-error-utils.d.ts +16 -0
  38. package/dist/{websocket-BKcGvILX.js → websocket-B2LsrINK.js} +8 -6
  39. package/dist/websocket-B2LsrINK.js.map +1 -0
  40. package/package.json +6 -6
  41. package/src/PostgresAdapter.ts +7 -2
  42. package/src/PostgresBackendDriver.ts +4 -0
  43. package/src/PostgresBootstrapper.ts +83 -22
  44. package/src/auth/services.ts +6 -3
  45. package/src/backup/backup-cli.ts +41 -2
  46. package/src/backup/backup-service.ts +38 -5
  47. package/src/backup/pg-tools.ts +96 -3
  48. package/src/cli-helpers.ts +70 -0
  49. package/src/cli.ts +44 -26
  50. package/src/collections/validate-relations.ts +15 -0
  51. package/src/connection.ts +73 -0
  52. package/src/data-transformer.ts +9 -3
  53. package/src/databasePoolManager.ts +5 -2
  54. package/src/schema/ensure-collection-tables.ts +81 -10
  55. package/src/schema/generate-drizzle-schema-logic.ts +35 -3
  56. package/src/schema/generate-postgres-ddl-logic.ts +50 -6
  57. package/src/schema/introspect-db-constraints.ts +385 -0
  58. package/src/schema/introspect-db-inference.ts +18 -8
  59. package/src/schema/introspect-db-logic.ts +385 -71
  60. package/src/schema/introspect-db-queries.ts +326 -0
  61. package/src/schema/introspect-db-structure.ts +670 -0
  62. package/src/schema/introspect-db-types.ts +56 -0
  63. package/src/schema/introspect-db.ts +37 -80
  64. package/src/security/policy-drift.test.ts +11 -3
  65. package/src/services/FetchService.ts +90 -14
  66. package/src/services/PersistService.ts +20 -6
  67. package/src/services/RelationService.ts +211 -45
  68. package/src/services/channel-bus/index.ts +0 -9
  69. package/src/services/collection-helpers.ts +69 -3
  70. package/src/services/dataService.ts +3 -1
  71. package/src/services/realtimeService.ts +3 -3
  72. package/src/services/row-pipeline.ts +1 -1
  73. package/src/utils/connection-string.ts +58 -0
  74. package/src/utils/drizzle-conditions.ts +31 -6
  75. package/src/utils/pg-error-utils.ts +19 -0
  76. package/src/websocket.ts +18 -9
  77. package/dist/backup-service-DH9kPg-E.js.map +0 -1
  78. package/dist/connection-B5Wndbr1.js.map +0 -1
  79. package/dist/ensure-collection-tables-DsDsNl6o.js.map +0 -1
  80. package/dist/src-DihrDFuP.js.map +0 -1
  81. package/dist/websocket-BKcGvILX.js.map +0 -1
@@ -0,0 +1,56 @@
1
+ /**
2
+ * The PostgreSQL type → Rebase property type mapping.
3
+ *
4
+ * Split out of `introspect-db-logic` so that the structural analysis can use it
5
+ * without importing the generator, which imports the analysis. Re-exported from
6
+ * `introspect-db-logic` so existing callers keep their import path.
7
+ */
8
+
9
+ /**
10
+ * Map a PostgreSQL data type to a Rebase property type.
11
+ */
12
+ export function mapPgType(dataType: string): string {
13
+ const dt = dataType.toLowerCase();
14
+
15
+ // Interval MUST be checked before numeric ("interval" contains "int")
16
+ if (dt === "interval") return "string";
17
+
18
+ // Array types MUST be checked before numeric ("_int4" contains "int")
19
+ if (dt === "array" || dt.startsWith("_")) return "array";
20
+
21
+ // Numeric types
22
+ if (
23
+ dt.includes("int") || // integer, smallint, bigint
24
+ dt.includes("numeric") ||
25
+ dt.includes("decimal") ||
26
+ dt.includes("serial") || // serial, bigserial
27
+ dt === "real" ||
28
+ dt === "float4" ||
29
+ dt === "float8" ||
30
+ dt === "double precision" ||
31
+ dt === "money"
32
+ ) {
33
+ return "number";
34
+ }
35
+
36
+ // Boolean
37
+ if (dt.includes("bool")) return "boolean";
38
+
39
+ // Date / Time
40
+ if (dt.includes("time") || dt.includes("date")) return "date";
41
+
42
+ // JSON
43
+ if (dt === "json" || dt === "jsonb") return "map";
44
+
45
+ // Binary
46
+ if (dt === "bytea") return "binary";
47
+
48
+ // Network types
49
+ if (dt === "inet" || dt === "cidr" || dt === "macaddr" || dt === "macaddr8") return "string";
50
+
51
+ // UUID
52
+ if (dt === "uuid") return "string";
53
+
54
+ // Text/varchar/char — default to string
55
+ return "string";
56
+ }
@@ -7,19 +7,16 @@ import * as dotenv from "dotenv";
7
7
  import readline from "readline";
8
8
 
9
9
  import {
10
- TableRow,
11
- TableColumn,
12
- EnumValue,
13
- PrimaryKeyRow,
14
- ForeignKeyRow,
15
10
  buildTablesMap,
16
11
  buildEnumMap,
17
- identifyJoinTables,
18
12
  generateCollectionFile,
19
13
  generateIndexContent,
20
14
  mergeIndexContent,
21
15
  safeHostFromUrl
22
16
  } from "./introspect-db-logic";
17
+ import { countRowsUpTo, readSchemaMetadata } from "./introspect-db-queries";
18
+ import { classifyTables, lookupCandidates, LOOKUP_MAX_ROWS } from "./introspect-db-structure";
19
+ import { parseCheckConstraints } from "./introspect-db-constraints";
23
20
  import { logger } from "@rebasepro/server";
24
21
 
25
22
  async function main() {
@@ -89,82 +86,41 @@ async function main() {
89
86
  logger.info(chalk.gray(`Introspecting schema '${pgSchema}'...`));
90
87
 
91
88
  try {
92
- // 1. Get Tables
93
- const { rows: tables } = await client.query<TableRow>(`
94
- SELECT table_name
95
- FROM information_schema.tables
96
- WHERE table_schema = $1 AND table_type = 'BASE TABLE'
97
- AND table_name NOT LIKE 'drizzle_%'
98
- AND table_name NOT LIKE 'rebase_%'
99
- ORDER BY table_name
100
- `, [pgSchema]);
101
-
102
- // 2. Get Columns
103
- const { rows: columns } = await client.query<TableColumn>(`
104
- SELECT
105
- c.table_name,
106
- c.column_name,
107
- c.data_type,
108
- c.udt_name,
109
- c.is_nullable,
110
- c.column_default,
111
- (SELECT a.atttypmod FROM pg_attribute a
112
- JOIN pg_class pc ON a.attrelid = pc.oid
113
- WHERE pc.relname = c.table_name
114
- AND a.attname = c.column_name
115
- AND pc.relnamespace = (SELECT oid FROM pg_namespace WHERE nspname = c.table_schema)) as atttypmod
116
- FROM information_schema.columns c
117
- WHERE c.table_schema = $1
118
- `, [pgSchema]);
119
-
120
- // 2b. Get Enum Types and their values
121
- const { rows: enumValues } = await client.query<EnumValue>(`
122
- SELECT t.typname AS enum_name,
123
- e.enumlabel AS enum_value,
124
- e.enumsortorder AS sort_order
125
- FROM pg_type t
126
- JOIN pg_enum e ON t.oid = e.enumtypid
127
- JOIN pg_namespace n ON t.typnamespace = n.oid
128
- WHERE n.nspname = $1
129
- ORDER BY t.typname, e.enumsortorder
130
- `, [pgSchema]);
131
-
132
- // Build a map: enum_name -> ordered list of values
133
- const enumMap = buildEnumMap(enumValues);
134
-
135
- // 3. Get Primary Keys
136
- const { rows: pks } = await client.query<PrimaryKeyRow>(`
137
- SELECT t.relname as table_name, a.attname as column_name
138
- FROM pg_index i
139
- JOIN pg_attribute a ON a.attrelid = i.indrelid
140
- AND a.attnum = ANY(i.indkey)
141
- JOIN pg_class t ON t.oid = i.indrelid
142
- JOIN pg_namespace n ON n.oid = t.relnamespace
143
- WHERE i.indisprimary AND n.nspname = $1
144
- `, [pgSchema]);
89
+ const metadata = await readSchemaMetadata(client, pgSchema);
90
+ const enumMap = buildEnumMap(metadata.enumValues);
91
+ const tablesMap = buildTablesMap(metadata.tables, metadata.columns, metadata.pks, metadata.fks);
92
+ const fks = metadata.fks;
93
+
94
+ // Only tables that could structurally be a code list are counted, and
95
+ // each count stops at the threshold — see `countRowsUpTo`. Introspection
96
+ // runs against a database it does not own, so "cheap on a table of any
97
+ // size" is a requirement, not an optimization.
98
+ for (const table of lookupCandidates(metadata, tablesMap)) {
99
+ try {
100
+ metadata.rowCounts[table] = await countRowsUpTo(client, pgSchema, table, LOOKUP_MAX_ROWS);
101
+ } catch (err) {
102
+ // A table this run cannot read is simply not classified as a code
103
+ // list; everything else about it still generates.
104
+ logger.info(chalk.gray(` (skipped row count for ${table}: ${err instanceof Error ? err.message : String(err)})`));
105
+ }
106
+ }
145
107
 
146
- // 4. Get Foreign Keys
147
- const { rows: fks } = await client.query<ForeignKeyRow>(`
148
- SELECT
149
- tc.table_name,
150
- kcu.column_name,
151
- ccu.table_name AS foreign_table_name,
152
- ccu.column_name AS foreign_column_name
153
- FROM
154
- information_schema.table_constraints AS tc
155
- JOIN information_schema.key_column_usage AS kcu
156
- ON tc.constraint_name = kcu.constraint_name
157
- AND tc.table_schema = kcu.table_schema
158
- JOIN information_schema.constraint_column_usage AS ccu
159
- ON ccu.constraint_name = tc.constraint_name
160
- AND ccu.table_schema = tc.table_schema
161
- WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_schema = $1
162
- `, [pgSchema]);
108
+ const classifications = classifyTables(metadata, tablesMap);
109
+ const checkFacts = parseCheckConstraints(metadata.checks);
110
+ const joinTables = new Set(
111
+ Array.from(classifications.values())
112
+ .filter((c) => c.role === "junction")
113
+ .map((c) => c.table)
114
+ );
163
115
 
164
- const tablesMap = buildTablesMap(tables, columns, pks, fks);
165
- const joinTables = identifyJoinTables(tablesMap);
116
+ const roleCount = (role: string) =>
117
+ Array.from(classifications.values()).filter((c) => c.role === role).length;
166
118
 
167
- logger.info(chalk.blue(`Found ${tablesMap.size} tables (including ${joinTables.size} detected join tables).`));
119
+ logger.info(chalk.blue(`Found ${tablesMap.size} tables.`));
120
+ logger.info(chalk.gray(
121
+ ` ${roleCount("entity")} entities, ${joinTables.size} join tables (folded into relations), ` +
122
+ `${roleCount("lookup")} code lists, ${roleCount("owned-child")} owned by another table (hidden from navigation).`
123
+ ));
168
124
 
169
125
  let runDataInference = false;
170
126
  if (args["--no-data-inference"]) {
@@ -224,7 +180,8 @@ async function main() {
224
180
  joinTables,
225
181
  tablesMap,
226
182
  enumMap,
227
- sampleData
183
+ sampleData,
184
+ { metadata, classifications, checkFacts }
228
185
  );
229
186
 
230
187
  fs.writeFileSync(filePath, fileContent, "utf-8");
@@ -158,15 +158,23 @@ describe("checkPolicyDrift", () => {
158
158
  it("also flags the tautology in a WITH CHECK clause", async () => {
159
159
  const cols = [collection("posts")];
160
160
  const expected = parseExpectedPolicies(generatePostgresPoliciesDdl(cols));
161
+ const withCheck = expected.filter((p) => p.hasWithCheck);
162
+ // Asserted rather than assumed: if the generator ever stopped emitting a
163
+ // WITH CHECK for these rules the fixture would carry no tautology at
164
+ // all, and every assertion below would be vacuously satisfied.
165
+ expect(withCheck.length).toBeGreaterThan(0);
166
+
161
167
  const live = expected.map((p) => liveRow(p, {
162
168
  with_check: p.hasWithCheck ? "(auth.uid() IS NOT NULL)" : null
163
169
  }));
164
170
 
165
171
  const drift = await checkPolicyDrift(dbWith(live), cols);
166
172
 
167
- const flagged = drift.insecure.some((i) => /WITH CHECK/.test(i.reason));
168
- // Only assert when the fixture actually had a WITH CHECK policy to carry it.
169
- if (expected.some((p) => p.hasWithCheck)) expect(flagged).toBe(true);
173
+ // Every WITH CHECK policy carries the tautology and no USING clause
174
+ // does, so anything flagged here came from the WITH CHECK scan — the
175
+ // half that a check reading only `qual` would miss entirely.
176
+ expect(drift.insecure.map((i) => i.policy.name)).toEqual(withCheck.map((p) => p.name));
177
+ expect(drift.insecure.every((i) => /WITH CHECK/.test(i.reason))).toBe(true);
170
178
  });
171
179
 
172
180
  it("parses roles when the driver returns the raw {a,b} text form", async () => {
@@ -1,10 +1,10 @@
1
- import { and, asc, count, desc, eq, getTableName, gt, lt, or, SQL, TableRelationalConfig, TablesRelationalConfig } from "drizzle-orm";
1
+ import { and, asc, count, desc, eq, getTableColumns, getTableName, gt, lt, or, SQL, TableRelationalConfig, TablesRelationalConfig } from "drizzle-orm";
2
2
  import { AnyPgColumn, PgTable } from "drizzle-orm/pg-core";
3
3
  import { CollectionConfig, FilterValues, ResolvedRelation, LogicalCondition, isManyToMany } from "@rebasepro/types";
4
4
  import type { VectorSearchParams } from "@rebasepro/types";
5
5
  import { resolveCollectionRelations, findRelation, createRelationRef, createRelationRefWithData } from "@rebasepro/common";
6
6
  import { generateForeignKeyName } from "@rebasepro/utils";
7
- import { DrizzleConditionBuilder, type FilterCompilationOptions } from "../utils/drizzle-conditions";
7
+ import { DrizzleConditionBuilder, getUnknownFilterFieldsMode, type FilterCompilationOptions } from "../utils/drizzle-conditions";
8
8
  import {
9
9
  getCollectionByPath,
10
10
  getTableForCollection,
@@ -12,6 +12,7 @@ import {
12
12
  requirePrimaryKeys,
13
13
  deriveRowAddress,
14
14
  parseIdValues,
15
+ idCanAddressTable,
15
16
  buildCompositeId,
16
17
  COMPOSITE_ID_SEPARATOR
17
18
  } from "./collection-helpers";
@@ -20,9 +21,10 @@ import { RelationService } from "./RelationService";
20
21
  import { RelationalQueryBuilder } from "drizzle-orm/pg-core/query-builders/query";
21
22
  import { DrizzleClient } from "../interfaces";
22
23
  import { PostgresCollectionRegistry } from "../collections/PostgresCollectionRegistry";
23
- import { toCmsRow, toRestRow, isJunctionRelation } from "./row-pipeline";
24
+ import { toFlatRow, toRestRow, isJunctionRelation } from "./row-pipeline";
24
25
  import { isNestedPath, resolveNestedPath, type NestedPathHop } from "./nested-path";
25
- import { logger } from "@rebasepro/server";
26
+ import { ApiError, logger } from "@rebasepro/server";
27
+ import { reachedDatabase } from "../utils/pg-error-utils";
26
28
 
27
29
  /** Type-safe accessor for Drizzle's relational query API via dynamic table name */
28
30
  type DbQueryAccessor = Record<string, RelationalQueryBuilder<any, any>> | undefined;
@@ -129,12 +131,10 @@ export class FetchService {
129
131
  if (direct) return direct;
130
132
 
131
133
  // Owning relation, resolved: the relation names its own local key.
132
- if (collection) {
133
- const relation = resolveCollectionRelations(collection)[orderBy];
134
- if (relation?.kind === "belongsTo") {
135
- const foreignKey = columnAt(relation.localKey);
136
- if (foreignKey) return foreignKey;
137
- }
134
+ const declaredRelation = collection ? resolveCollectionRelations(collection)[orderBy] : undefined;
135
+ if (declaredRelation?.kind === "belongsTo") {
136
+ const foreignKey = columnAt(declaredRelation.localKey);
137
+ if (foreignKey) return foreignKey;
138
138
  }
139
139
 
140
140
  // No collection in hand — the two shapes an owning relation's key takes
@@ -145,7 +145,61 @@ export class FetchService {
145
145
  if (foreignKey) return foreignKey;
146
146
  }
147
147
 
148
- return undefined;
148
+ // Nothing resolved. Returning `undefined` is exactly what the docblock
149
+ // above describes: the caller drops the ORDER BY and hands back rows in
150
+ // whatever order Postgres pleases, while the requester believes they
151
+ // are sorted. `?orderBy=titel` answered 200 with unsorted data and no
152
+ // hint that the sort had been ignored.
153
+ //
154
+ // A *filter* naming a field that does not exist is already refused for
155
+ // precisely this reason — it "used to widen results silently". An
156
+ // unresolvable sort field is the same drift between a query and the
157
+ // schema, so it answers the same way and honours the same switch: one
158
+ // knob, because a deployment that wants the lenient behaviour wants it
159
+ // for both.
160
+ const collectionName = collection?.slug ?? collection?.name;
161
+ const onCollection = collectionName ? ` on collection '${collectionName}'` : "";
162
+
163
+ // A declared to-many relation is a different mistake from a typo, and
164
+ // saying "unknown field" about a field the collection plainly declares
165
+ // sends the reader looking for a spelling error that is not there.
166
+ // There is simply no single value per row to order by — `posts.tags` is
167
+ // a set — so no ORDER BY exists to write, with or without a typo.
168
+ if (declaredRelation && declaredRelation.kind !== "belongsTo") {
169
+ throw ApiError.badRequest(
170
+ `Cannot sort by '${orderBy}'${onCollection}: it is a to-many relation ` +
171
+ `(${declaredRelation.kind}), which has no single value per row to order by.`,
172
+ "ORDER_BY_FIELD_NOT_SORTABLE",
173
+ { field: orderBy, kind: declaredRelation.kind, ...(collectionName && { collection: collectionName }) }
174
+ );
175
+ }
176
+
177
+ if (getUnknownFilterFieldsMode() === "warn") {
178
+ logger.warn(
179
+ `Sorting by field '${orderBy}'${onCollection}, but it does not exist in the table — ` +
180
+ "the ORDER BY was dropped and these rows are unsorted."
181
+ );
182
+ return undefined;
183
+ }
184
+
185
+ let validFields: string[] = [];
186
+ try {
187
+ validFields = Object.keys(getTableColumns(table)).sort();
188
+ } catch {
189
+ // A table stand-in without Drizzle's column symbols — the message
190
+ // is worth less without the list, but not worth failing over.
191
+ }
192
+
193
+ throw ApiError.badRequest(
194
+ `Unknown orderBy field '${orderBy}'${onCollection}` +
195
+ (validFields.length > 0 ? `. Valid fields: ${validFields.join(", ")}` : ""),
196
+ "UNKNOWN_ORDER_BY_FIELD",
197
+ {
198
+ field: orderBy,
199
+ ...(collectionName && { collection: collectionName }),
200
+ ...(validFields.length > 0 && { validFields })
201
+ }
202
+ );
149
203
  }
150
204
 
151
205
  /**
@@ -536,6 +590,11 @@ idColumn };
536
590
  throw new Error(`ID field '${idInfo.fieldName}' not found in table for collection '${collectionPath}'`);
537
591
  }
538
592
 
593
+ // An address the key columns cannot hold names no row — the same answer
594
+ // as a well-formed id nobody has. Asking Postgres instead raises 22P02
595
+ // and aborts the transaction around this read.
596
+ if (!idCanAddressTable(id, table, idInfoArray)) return undefined;
597
+
539
598
  const parsedIdObj = parseIdValues(id, idInfoArray);
540
599
  const parsedId = parsedIdObj[idInfo.fieldName];
541
600
 
@@ -555,7 +614,7 @@ idColumn };
555
614
 
556
615
  if (!row) return undefined;
557
616
 
558
- const flatRow = toCmsRow(row, collection, this.registry);
617
+ const flatRow = toFlatRow(row, collection, this.registry);
559
618
 
560
619
  // Post-fetch joinPath relations that Drizzle's `with` can't express
561
620
  await this.resolveJoinPathRelations<M>(flatRow, collection, collectionPath, parsedId, databaseId);
@@ -566,6 +625,7 @@ idColumn };
566
625
  logger.error(`[FetchService] ResolvedRelation inference error for collection '${collectionPath}': ${e.message}`);
567
626
  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.");
568
627
  }
628
+ if (reachedDatabase(e)) throw e;
569
629
  logger.warn(`[FetchService] db.query.findFirst failed for ${collectionPath}, falling back to db.select`, { error: e });
570
630
  }
571
631
  }
@@ -682,7 +742,7 @@ idColumn };
682
742
  const results = await qb.findMany(queryOpts as Parameters<NonNullable<typeof qb>["findMany"]>[0]);
683
743
 
684
744
  const rows = (results as Record<string, unknown>[]).map(row =>
685
- toCmsRow(row, collection, this.registry)
745
+ toFlatRow(row, collection, this.registry)
686
746
  );
687
747
 
688
748
  return rows;
@@ -691,6 +751,7 @@ idColumn };
691
751
  logger.error(`[FetchService] ResolvedRelation inference error for collection '${collectionPath}': ${e.message}`);
692
752
  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.");
693
753
  }
754
+ if (reachedDatabase(e)) throw e;
694
755
  logger.warn(`[FetchService] db.query.findMany failed for ${collectionPath}, falling back to db.select`, { error: e });
695
756
  }
696
757
  }
@@ -785,7 +846,7 @@ _distance: vectorMeta.distanceSelect }).from(table).$dynamic()
785
846
  /**
786
847
  * Fallback path used when db.query is unavailable.
787
848
  *
788
- * The primary path runs the results through `toCmsRow`, which maps
849
+ * The primary path runs the results through `toFlatRow`, which maps
789
850
  * relations from what drizzle already nested — no query per row. This one
790
851
  * has no nesting to read, so it resolves relations itself, in batches.
791
852
  *
@@ -942,6 +1003,7 @@ relatedTo: hop });
942
1003
  collectionPath: string,
943
1004
  options: {
944
1005
  filter?: FilterValues<Extract<keyof M, string>>;
1006
+ logical?: LogicalCondition;
945
1007
  searchString?: string;
946
1008
  databaseId?: string;
947
1009
  } = {}
@@ -973,6 +1035,13 @@ relatedTo: hop });
973
1035
  if (filterConditions.length > 0) allConditions.push(...filterConditions);
974
1036
  }
975
1037
 
1038
+ if (options.logical) {
1039
+ const logicalCondition = DrizzleConditionBuilder.buildLogicalConditions(
1040
+ options.logical, table, effectivePath, this.filterContext(effectivePath, table)
1041
+ );
1042
+ if (logicalCondition) allConditions.push(logicalCondition);
1043
+ }
1044
+
976
1045
  if (allConditions.length > 0) {
977
1046
  const finalCondition = DrizzleConditionBuilder.combineConditionsWithAnd(allConditions);
978
1047
  if (finalCondition) query = query.where(finalCondition);
@@ -1043,6 +1112,8 @@ relatedTo: hop });
1043
1112
  collectionPath: string,
1044
1113
  options: {
1045
1114
  filter?: FilterValues<Extract<keyof M, string>>;
1115
+ /** An `or(...)`/`and(...)` group, applied alongside `filter`. */
1116
+ logical?: LogicalCondition;
1046
1117
  orderBy?: string;
1047
1118
  order?: "desc" | "asc";
1048
1119
  limit?: number;
@@ -1111,6 +1182,7 @@ relatedTo: hop }, include
1111
1182
  logger.error(`[FetchService] ResolvedRelation inference error for collection '${collectionPath}': ${e.message}`);
1112
1183
  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.");
1113
1184
  }
1185
+ if (reachedDatabase(e)) throw e;
1114
1186
  logger.warn(`[fetchCollectionForRest] db.query.findMany failed for ${collectionPath}, falling back`, { error: e });
1115
1187
  }
1116
1188
  }
@@ -1184,6 +1256,9 @@ relatedTo: hop }, include
1184
1256
  const idInfo = idInfoArray[0];
1185
1257
  const idField = table[idInfo.fieldName as keyof typeof table] as AnyPgColumn;
1186
1258
 
1259
+ // See `fetchOne`: an unaddressable id is a 404, not a database error.
1260
+ if (!idCanAddressTable(id, table, idInfoArray)) return null;
1261
+
1187
1262
  const parsedIdObj = parseIdValues(id, idInfoArray);
1188
1263
  const parsedId = parsedIdObj[idInfo.fieldName];
1189
1264
 
@@ -1217,6 +1292,7 @@ relatedTo: hop }, include
1217
1292
  logger.error(`[FetchService] ResolvedRelation inference error for collection '${collectionPath}': ${e.message}`);
1218
1293
  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.");
1219
1294
  }
1295
+ if (reachedDatabase(e)) throw e;
1220
1296
  logger.warn(`[fetchOneForRest] db.query.findFirst failed for ${collectionPath}, falling back`, { error: e });
1221
1297
  }
1222
1298
  }
@@ -1,7 +1,7 @@
1
1
  import { eq, and, sql, SQL } from "drizzle-orm";
2
2
  import { AnyPgColumn, PgTable } from "drizzle-orm/pg-core";
3
3
  // import { NodePgDatabase } from "drizzle-orm/node-postgres";
4
- import { CollectionConfig, Properties, ResolvedRelation, type ResolvedManyToMany, isManyToMany } from "@rebasepro/types";
4
+ import { CollectionConfig, Properties, ResolvedRelation, type ResolvedManyToMany, isManyToMany, hasForeignKeyOnTarget } from "@rebasepro/types";
5
5
  import { getTableName, resolveCollectionRelations } from "@rebasepro/common";
6
6
  import { DrizzleConditionBuilder } from "../utils/drizzle-conditions";
7
7
  import {
@@ -240,16 +240,30 @@ export class PersistService {
240
240
  throw ApiError.notFound(`No row "${id}" in "${collectionPath}" to update.`);
241
241
  }
242
242
  } else {
243
- // One-to-many create: stamp the parent's id onto the child's FK.
243
+ // One-to-many create: stamp the parent's key onto the child's FK.
244
244
  const targetColumnName = this.resolveParentForeignKeyColumn(hop);
245
245
 
246
246
  if (targetColumnName) {
247
- const parsedParentId = parentIdForWrite();
247
+ // Not necessarily the id in the path: a link with a
248
+ // `sourceKey` is pointed at a column on the parent row, and
249
+ // stamping the id would create a child that belongs to
250
+ // nobody — a row the read path would never return again.
251
+ const parentKeyValue = hasForeignKeyOnTarget(hop.relation)
252
+ ? await this.relationService.parentKeyValue(hop.parentCollection, hop.relation, hop.parentId)
253
+ : parentIdForWrite();
254
+
255
+ if (parentKeyValue === undefined) {
256
+ throw ApiError.badRequest(
257
+ `Cannot create under "${collectionPath}": the parent row has no value in ` +
258
+ `\`sourceKey\`, so the new row has nothing to point at.`
259
+ );
260
+ }
261
+
248
262
  const existingValue = (effectiveValues as Record<string, unknown>)[targetColumnName];
249
- if (existingValue !== undefined && existingValue !== null && existingValue !== parsedParentId) {
250
- logger.warn(`Overriding provided value '${existingValue}' for FK '${targetColumnName}' with path parent id '${parsedParentId}'.`);
263
+ if (existingValue !== undefined && existingValue !== null && existingValue !== parentKeyValue) {
264
+ logger.warn(`Overriding provided value '${existingValue}' for FK '${targetColumnName}' with path parent key '${parentKeyValue}'.`);
251
265
  }
252
- (effectiveValues as Record<string, unknown>)[targetColumnName] = parsedParentId;
266
+ (effectiveValues as Record<string, unknown>)[targetColumnName] = parentKeyValue;
253
267
  }
254
268
  }
255
269
  }