@rebasepro/server-postgres 0.10.1-canary.8d27c46 → 0.10.1-canary.af2af91

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.
@@ -18,6 +18,47 @@ export interface DrizzleDynamicQuery {
18
18
  * const builder: ConditionBuilderStatic<SQL> = DrizzleConditionBuilder;
19
19
  */
20
20
  export declare class DrizzleConditionBuilder {
21
+ /**
22
+ * Express "reachable from this parent through this relation" as a plain
23
+ * `WHERE` condition on the target table.
24
+ *
25
+ * This is the primitive that lets a relation be a *filter* rather than an
26
+ * addressing scheme. A nested listing used to be served by its own query
27
+ * builder — `fetchEntitiesUsingJoins`, which grew joins the root pipeline
28
+ * did not have and lost the options the root pipeline did have (offset,
29
+ * filter, orderBy, include). Reduced to a condition, the same listing runs
30
+ * through the ordinary collection query, so it inherits all of them and
31
+ * there is one read path instead of two.
32
+ *
33
+ * The shapes:
34
+ * - inverse FK → `target.<fk> = :parentId`, a column comparison.
35
+ * - `through` → `EXISTS (SELECT 1 FROM junction …)`, correlated on the
36
+ * target's key, so the junction never multiplies rows the
37
+ * way an `INNER JOIN` would.
38
+ * - `joinPath` → the same `EXISTS`, with the path's steps joined inside
39
+ * it and the final step correlating to the outer row.
40
+ */
41
+ static buildRelationScopeCondition(relation: Relation,
42
+ /**
43
+ * Lazy: only `joinPath` and `localKey` relations need the parent's own
44
+ * table. An inverse foreign key and a junction are both expressible
45
+ * from the parent's *id* alone, and requiring the table for them would
46
+ * make a child listing fail on a parent whose table isn't registered.
47
+ */
48
+ parent: () => {
49
+ table: PgTable<any>;
50
+ idColumn: AnyPgColumn;
51
+ }, parentId: string | number, targetTable: PgTable<any>, targetIdColumn: AnyPgColumn, registry: PostgresCollectionRegistry): SQL;
52
+ /**
53
+ * `EXISTS` for an explicit `joinPath`.
54
+ *
55
+ * The path is declared source → target. The subquery replays every step but
56
+ * the last from inside, and turns the last one into the correlation with the
57
+ * outer target row — so the target table is never named twice and needs no
58
+ * alias. Each intermediate table is aliased positionally, which keeps a path
59
+ * that revisits a table (a self-referencing many-to-many) unambiguous.
60
+ */
61
+ private static buildJoinPathScopeCondition;
21
62
  /**
22
63
  * Build filter conditions from FilterValues
23
64
  */
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@rebasepro/server-postgres",
3
3
  "type": "module",
4
- "version": "0.10.1-canary.8d27c46",
4
+ "version": "0.10.1-canary.af2af91",
5
5
  "description": "PostgreSQL data source backend implementation for Rebase with Drizzle ORM",
6
6
  "funding": {
7
7
  "url": "https://github.com/sponsors/rebaseco"
@@ -47,11 +47,11 @@
47
47
  "execa": "^9.6.1",
48
48
  "pg": "^8.21.0",
49
49
  "ws": "^8.21.0",
50
- "@rebasepro/codegen": "0.10.1-canary.8d27c46",
51
- "@rebasepro/types": "0.10.1-canary.8d27c46",
52
- "@rebasepro/server": "0.10.1-canary.8d27c46",
53
- "@rebasepro/common": "0.10.1-canary.8d27c46",
54
- "@rebasepro/utils": "0.10.1-canary.8d27c46"
50
+ "@rebasepro/codegen": "0.10.1-canary.af2af91",
51
+ "@rebasepro/server": "0.10.1-canary.af2af91",
52
+ "@rebasepro/types": "0.10.1-canary.af2af91",
53
+ "@rebasepro/utils": "0.10.1-canary.af2af91",
54
+ "@rebasepro/common": "0.10.1-canary.af2af91"
55
55
  },
56
56
  "devDependencies": {
57
57
  "@hono/node-server": "^2.0.11",
@@ -37,6 +37,7 @@ import { buildCollectionsFromSchema, introspectSchema, readRlsStatus } from "./s
37
37
  import { buildDrizzleTablesFromSchema, buildDrizzleRelationsFromSchema } from "./schema/dynamic-tables";
38
38
  import { detectConnectionPosture, ensureAppRole, validatePolicyPgRoles, warnOnAnonymousGrants, REBASE_USER_ROLE, type RawSqlRunner } from "./security/rls-enforcement";
39
39
  import { provisionTriggerCdc, type CdcTableRef } from "./services/cdc/trigger-cdc";
40
+ import { collectJunctionLinks } from "./services/cdc/junction-tables";
40
41
  import { createChannelBus, resolveChannelBusSetting } from "./services/channel-bus";
41
42
  import { isChannelBusInstance } from "@rebasepro/types";
42
43
 
@@ -233,8 +234,8 @@ export function createPostgresBootstrapper(pgConfig: PostgresDriverConfig): Back
233
234
  ` The database server is not running or is not accepting\n` +
234
235
  ` connections. Common fixes:\n` +
235
236
  `\n` +
237
+ ` • docker compose up -d db (the service a Rebase scaffold ships)\n` +
236
238
  ` • brew services start postgresql@18\n` +
237
- ` • docker compose up -d postgres\n` +
238
239
  ` • Verify DATABASE_URL in your .env file\n` +
239
240
  `\n` +
240
241
  `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n`;
@@ -417,6 +418,14 @@ export function createPostgresBootstrapper(pgConfig: PostgresDriverConfig): Back
417
418
  table: getCollectionTableName(c)
418
419
  }))
419
420
  .filter((t) => Boolean(t.table) && registry.hasTableForCollection(t.table));
421
+ // Junction tables back no collection, so the list above misses
422
+ // them — and a link or unlink is a write nobody would hear
423
+ // about. Their rows are the contents of a child list, which is
424
+ // as much a change as a write to the rows themselves.
425
+ for (const link of collectJunctionLinks(registry)) {
426
+ cdcTables.push({ schema: link.schema,
427
+ table: link.table });
428
+ }
420
429
  // Provisioning throws only when the connection can't create the
421
430
  // trigger function (insufficient privilege); enableCdc throws when
422
431
  // the LISTEN connection can't be established. Either → fall back.
@@ -19,6 +19,7 @@ import { RelationalQueryBuilder } from "drizzle-orm/pg-core/query-builders/query
19
19
  import { DrizzleClient } from "../interfaces";
20
20
  import { PostgresCollectionRegistry } from "../collections/PostgresCollectionRegistry";
21
21
  import { toCmsRow, toRestRow, isJunctionRelation } from "./row-pipeline";
22
+ import { isNestedPath, resolveNestedPath, type NestedPathHop } from "./nested-path";
22
23
  import { logger } from "@rebasepro/server";
23
24
 
24
25
  /** Type-safe accessor for Drizzle's relational query API via dynamic table name */
@@ -279,7 +280,8 @@ export class FetchService {
279
280
  logical?: LogicalCondition;
280
281
  },
281
282
  collectionPath: string,
282
- withConfig?: Record<string, unknown>
283
+ withConfig?: Record<string, unknown>,
284
+ scopeCondition?: SQL
283
285
  ): Record<string, unknown> {
284
286
  const queryOpts: Record<string, unknown> = {};
285
287
 
@@ -288,6 +290,8 @@ export class FetchService {
288
290
  // Build where conditions
289
291
  const allConditions: SQL[] = [];
290
292
 
293
+ if (scopeCondition) allConditions.push(scopeCondition);
294
+
291
295
  if (options.searchString) {
292
296
  const collection = getCollectionByPath(collectionPath, this.registry);
293
297
  const searchConditions = DrizzleConditionBuilder.buildSearchConditions(
@@ -391,6 +395,59 @@ export class FetchService {
391
395
  return [];
392
396
  }
393
397
 
398
+ /**
399
+ * Compile "rows reachable from this parent" into a `WHERE` condition on the
400
+ * target table, so a nested listing can run as an ordinary collection query.
401
+ */
402
+ private buildRelationScope(hop: NestedPathHop): SQL {
403
+ const parentPks = requirePrimaryKeys(hop.parentCollection, this.registry);
404
+ const parentIdInfo = parentPks[0];
405
+ const parsedParentId = parseIdValues(hop.parentId, parentPks)[parentIdInfo.fieldName];
406
+
407
+ const parent = () => {
408
+ const table = getTableForCollection(hop.parentCollection, this.registry);
409
+ const idColumn = table[parentIdInfo.fieldName as keyof typeof table] as AnyPgColumn;
410
+ if (!idColumn) {
411
+ throw new Error(`ID field '${parentIdInfo.fieldName}' not found in table for collection '${hop.parentCollection.slug}'`);
412
+ }
413
+ return { table,
414
+ idColumn };
415
+ };
416
+
417
+ const targetTable = getTableForCollection(hop.targetCollection, this.registry);
418
+ const targetPks = requirePrimaryKeys(hop.targetCollection, this.registry);
419
+ const targetIdColumn = targetTable[targetPks[0].fieldName as keyof typeof targetTable] as AnyPgColumn;
420
+ if (!targetIdColumn) {
421
+ throw new Error(`ID field '${targetPks[0].fieldName}' not found in table for collection '${hop.targetCollection.slug}'`);
422
+ }
423
+
424
+ return DrizzleConditionBuilder.buildRelationScopeCondition(
425
+ hop.relation,
426
+ parent,
427
+ parsedParentId as string | number,
428
+ targetTable,
429
+ targetIdColumn,
430
+ this.registry
431
+ );
432
+ }
433
+
434
+ /**
435
+ * Whether `id` is actually reachable at `collectionPath`.
436
+ *
437
+ * Trivially true for a root path. For a nested one it is a real question:
438
+ * the path resolves to the target collection, and matching on the primary
439
+ * key alone made the parent segment decorative — `authors/1/posts/43`
440
+ * returned post 43 whoever wrote it, and the REST layer's delete then
441
+ * deleted it. A row that is not under this parent is reported as absent,
442
+ * which is what a caller addressing it through the parent should see.
443
+ */
444
+ private async isAddressableUnder(collectionPath: string, id: string | number): Promise<boolean> {
445
+ if (!isNestedPath(collectionPath)) return true;
446
+ const hop = resolveNestedPath(collectionPath, this.registry);
447
+ if (!hop) return true;
448
+ return this.relationService.isRelated(hop, id);
449
+ }
450
+
394
451
  /**
395
452
  * Fetch a single row by ID
396
453
  */
@@ -399,6 +456,8 @@ export class FetchService {
399
456
  id: string | number,
400
457
  databaseId?: string
401
458
  ): Promise<Record<string, unknown> | undefined> {
459
+ if (!await this.isAddressableUnder(collectionPath, id)) return undefined;
460
+
402
461
  const collection = getCollectionByPath(collectionPath, this.registry);
403
462
  const table = getTableForCollection(collection, this.registry);
404
463
  const idInfoArray = requirePrimaryKeys(collection, this.registry);
@@ -516,8 +575,11 @@ export class FetchService {
516
575
  databaseId?: string;
517
576
  vectorSearch?: VectorSearchParams;
518
577
  logical?: LogicalCondition;
578
+ /** Narrow to the rows reachable from a parent through a relation. */
579
+ relatedTo?: NestedPathHop;
519
580
  } = {}
520
581
  ): Promise<Record<string, unknown>[]> {
582
+ const scopeCondition = options.relatedTo ? this.buildRelationScope(options.relatedTo) : undefined;
521
583
  const collection = getCollectionByPath(collectionPath, this.registry);
522
584
  const table = getTableForCollection(collection, this.registry);
523
585
  const idInfoArray = requirePrimaryKeys(collection, this.registry);
@@ -545,7 +607,7 @@ export class FetchService {
545
607
  if (qb && !options.searchString && !hasRelations && !options.vectorSearch) {
546
608
  try {
547
609
  const queryOpts = this.buildDrizzleQueryOptions<M>(
548
- table, idField, idInfo, options, collectionPath, undefined
610
+ table, idField, idInfo, options, collectionPath, undefined, scopeCondition
549
611
  );
550
612
 
551
613
 
@@ -578,6 +640,8 @@ _distance: vectorMeta.distanceSelect }).from(table).$dynamic()
578
640
  : this.db.select().from(table).$dynamic();
579
641
  const allConditions: SQL[] = [];
580
642
 
643
+ if (scopeCondition) allConditions.push(scopeCondition);
644
+
581
645
  if (options.searchString) {
582
646
  const searchConditions = DrizzleConditionBuilder.buildSearchConditions(
583
647
  options.searchString, collection.properties, table
@@ -771,9 +835,13 @@ _distance: vectorMeta.distanceSelect }).from(table).$dynamic()
771
835
  vectorSearch?: VectorSearchParams;
772
836
  } = {}
773
837
  ): Promise<Record<string, unknown>[]> {
774
- // Handle multi-segment paths by resolving through relations
775
- if (collectionPath.includes("/")) {
776
- return this.fetchCollectionFromPath<M>(collectionPath, options);
838
+ // A nested path is the target collection narrowed by a relation — the
839
+ // same query, one condition heavier. It used to be a separate builder
840
+ // that honoured `limit` and nothing else.
841
+ const hop = isNestedPath(collectionPath) ? resolveNestedPath(collectionPath, this.registry) : undefined;
842
+ if (hop) {
843
+ return this.fetchRowsWithConditions<M>(hop.targetCollection.slug, { ...options,
844
+ relatedTo: hop });
777
845
  }
778
846
 
779
847
  return this.fetchRowsWithConditions<M>(collectionPath, options);
@@ -799,65 +867,6 @@ _distance: vectorMeta.distanceSelect }).from(table).$dynamic()
799
867
  });
800
868
  }
801
869
 
802
- /**
803
- * Fetch collection from multi-segment path
804
- */
805
- private async fetchCollectionFromPath<M extends Record<string, unknown>>(
806
- path: string,
807
- options: {
808
- filter?: FilterValues<Extract<keyof M, string>>;
809
- orderBy?: string;
810
- order?: "desc" | "asc";
811
- limit?: number;
812
- startAfter?: Record<string, unknown>;
813
- searchString?: string;
814
- databaseId?: string;
815
- } = {}
816
- ): Promise<Record<string, unknown>[]> {
817
- const pathSegments = path.split("/").filter(p => p && p !== "undefined");
818
-
819
- if (pathSegments.length < 3 || pathSegments.length % 2 === 0) {
820
- throw new Error(`Invalid relation path: ${path}. Expected format: collection/id/relation`);
821
- }
822
-
823
- const rootCollectionPath = pathSegments[0];
824
- let currentCollection = getCollectionByPath(rootCollectionPath, this.registry);
825
- let currentId: string | number = pathSegments[1];
826
-
827
- for (let i = 2; i < pathSegments.length; i += 2) {
828
- const relationKey = pathSegments[i];
829
- const resolvedRelations = resolveCollectionRelations(currentCollection);
830
- const relation = findRelation(resolvedRelations, relationKey);
831
-
832
- if (!relation) {
833
- throw new Error(`Relation '${relationKey}' not found in collection '${currentCollection.slug}'`);
834
- }
835
-
836
- if (i === pathSegments.length - 1) {
837
- const rows = await this.relationService.fetchRelatedEntities<M>(
838
- currentCollection.slug,
839
- currentId,
840
- relationKey,
841
- options
842
- );
843
- // Flatten RelatedRow[] to rows: the target's columns, and only
844
- // those. Merging `row.id` in last overwrote a real `id` column,
845
- // and the address is derivable without it — a consumer resolves
846
- // this path ("posts/1/comments") to the target collection and
847
- // reads the key columns, which `values` carries.
848
- return rows.map(row => ({ ...row.values as Record<string, unknown> }));
849
- }
850
-
851
- if (i + 1 < pathSegments.length) {
852
- const nextEntityId = pathSegments[i + 1];
853
- currentCollection = relation.target();
854
- currentId = nextEntityId;
855
- }
856
- }
857
-
858
- throw new Error(`Unable to resolve path: ${path}`);
859
- }
860
-
861
870
  /**
862
871
  * Count rows in a collection
863
872
  */
@@ -869,16 +878,20 @@ _distance: vectorMeta.distanceSelect }).from(table).$dynamic()
869
878
  databaseId?: string;
870
879
  } = {}
871
880
  ): Promise<number> {
872
- if (collectionPath.includes("/")) {
873
- return this.countEntitiesFromPath<M>(collectionPath, options);
874
- }
881
+ // Same narrowing as the listing — and, unlike the count it replaces,
882
+ // the same `filter` and `searchString` too, so `total` describes the
883
+ // rows that were actually served.
884
+ const hop = isNestedPath(collectionPath) ? resolveNestedPath(collectionPath, this.registry) : undefined;
885
+ const effectivePath = hop ? hop.targetCollection.slug : collectionPath;
875
886
 
876
- const collection = getCollectionByPath(collectionPath, this.registry);
887
+ const collection = getCollectionByPath(effectivePath, this.registry);
877
888
  const table = getTableForCollection(collection, this.registry);
878
889
 
879
890
  let query = this.db.select({ count: count() }).from(table).$dynamic();
880
891
  const allConditions: SQL[] = [];
881
892
 
893
+ if (hop) allConditions.push(this.buildRelationScope(hop));
894
+
882
895
  if (options.searchString) {
883
896
  const searchConditions = DrizzleConditionBuilder.buildSearchConditions(
884
897
  options.searchString, collection.properties, table
@@ -888,7 +901,7 @@ _distance: vectorMeta.distanceSelect }).from(table).$dynamic()
888
901
  }
889
902
 
890
903
  if (options.filter) {
891
- const filterConditions = this.buildFilterConditions(options.filter, table, collectionPath);
904
+ const filterConditions = this.buildFilterConditions(options.filter, table, effectivePath);
892
905
  if (filterConditions.length > 0) allConditions.push(...filterConditions);
893
906
  }
894
907
 
@@ -901,50 +914,6 @@ _distance: vectorMeta.distanceSelect }).from(table).$dynamic()
901
914
  return Number(result[0]?.count || 0);
902
915
  }
903
916
 
904
- /**
905
- * Count rows from multi-segment path
906
- */
907
- private async countEntitiesFromPath<M extends Record<string, unknown>>(
908
- path: string,
909
- options: { filter?: FilterValues<Extract<keyof M, string>>; databaseId?: string } = {}
910
- ): Promise<number> {
911
- const pathSegments = path.split("/").filter(p => p && p !== "undefined");
912
-
913
- if (pathSegments.length < 3 || pathSegments.length % 2 === 0) {
914
- throw new Error(`Invalid relation path: ${path}`);
915
- }
916
-
917
- const rootCollectionPath = pathSegments[0];
918
- let currentCollection = getCollectionByPath(rootCollectionPath, this.registry);
919
- let currentId: string | number = pathSegments[1];
920
-
921
- for (let i = 2; i < pathSegments.length; i += 2) {
922
- const relationKey = pathSegments[i];
923
- const resolvedRelations = resolveCollectionRelations(currentCollection);
924
- const relation = findRelation(resolvedRelations, relationKey);
925
-
926
- if (!relation) {
927
- throw new Error(`Relation '${relationKey}' not found`);
928
- }
929
-
930
- if (i === pathSegments.length - 1) {
931
- return this.relationService.countRelatedEntities(
932
- currentCollection.slug,
933
- currentId,
934
- relationKey,
935
- options
936
- );
937
- }
938
-
939
- if (i + 1 < pathSegments.length) {
940
- currentCollection = relation.target();
941
- currentId = pathSegments[i + 1];
942
- }
943
- }
944
-
945
- throw new Error(`Unable to count for path: ${path}`);
946
- }
947
-
948
917
  /**
949
918
  * Check if a field value is unique
950
919
  */
@@ -1014,9 +983,25 @@ _distance: vectorMeta.distanceSelect }).from(table).$dynamic()
1014
983
  searchString?: string;
1015
984
  databaseId?: string;
1016
985
  vectorSearch?: VectorSearchParams;
986
+ /** Narrow to the rows reachable from a parent through a relation. */
987
+ relatedTo?: NestedPathHop;
1017
988
  } = {},
1018
989
  include?: string[]
1019
990
  ): Promise<Record<string, unknown>[]> {
991
+ // Resolve a nested path here rather than at the route, so `include`,
992
+ // `offset` and the rest reach a child listing by the same route they
993
+ // reach a root one.
994
+ if (isNestedPath(collectionPath)) {
995
+ const hop = resolveNestedPath(collectionPath, this.registry);
996
+ if (hop) {
997
+ return this.fetchCollectionForRest<M>(
998
+ hop.targetCollection.slug, { ...options,
999
+ relatedTo: hop }, include
1000
+ );
1001
+ }
1002
+ }
1003
+
1004
+ const scopeCondition = options.relatedTo ? this.buildRelationScope(options.relatedTo) : undefined;
1020
1005
  const collection = getCollectionByPath(collectionPath, this.registry);
1021
1006
  const table = getTableForCollection(collection, this.registry);
1022
1007
  const idInfoArray = requirePrimaryKeys(collection, this.registry);
@@ -1039,7 +1024,7 @@ _distance: vectorMeta.distanceSelect }).from(table).$dynamic()
1039
1024
  : undefined;
1040
1025
 
1041
1026
  const queryOpts = this.buildDrizzleQueryOptions<M>(
1042
- table, idField, idInfo, options, collectionPath, withConfig
1027
+ table, idField, idInfo, options, collectionPath, withConfig, scopeCondition
1043
1028
  );
1044
1029
 
1045
1030
 
@@ -1123,6 +1108,8 @@ _distance: vectorMeta.distanceSelect }).from(table).$dynamic()
1123
1108
  include?: string[],
1124
1109
  databaseId?: string
1125
1110
  ): Promise<Record<string, unknown> | null> {
1111
+ if (!await this.isAddressableUnder(collectionPath, id)) return null;
1112
+
1126
1113
  const collection = getCollectionByPath(collectionPath, this.registry);
1127
1114
  const table = getTableForCollection(collection, this.registry);
1128
1115
  const idInfoArray = requirePrimaryKeys(collection, this.registry);
@@ -1229,6 +1216,7 @@ _distance: vectorMeta.distanceSelect }).from(table).$dynamic()
1229
1216
  startAfter?: Record<string, unknown>;
1230
1217
  searchString?: string;
1231
1218
  vectorSearch?: VectorSearchParams;
1219
+ relatedTo?: NestedPathHop;
1232
1220
  } = {}
1233
1221
  ): Promise<Record<string, unknown>[]> {
1234
1222
  const collection = getCollectionByPath(collectionPath, this.registry);
@@ -1248,6 +1236,8 @@ _distance: vectorMeta.distanceSelect }).from(table).$dynamic()
1248
1236
  : this.db.select().from(table).$dynamic();
1249
1237
  const allConditions: SQL[] = [];
1250
1238
 
1239
+ if (options.relatedTo) allConditions.push(this.buildRelationScope(options.relatedTo));
1240
+
1251
1241
  if (options.searchString) {
1252
1242
  const searchConditions = DrizzleConditionBuilder.buildSearchConditions(
1253
1243
  options.searchString, collection.properties, table