@rebasepro/server-postgres 0.13.1-canary.g18cfeb7 → 0.13.1-canary.g1bf9303
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.
- package/dist/PostgresBootstrapper.d.ts +26 -0
- package/dist/auth/services.d.ts +21 -0
- package/dist/{auth-users-columns-Do9mw5Y5.js → auth-users-columns-BxT6FRyu.js} +819 -68
- package/dist/auth-users-columns-BxT6FRyu.js.map +1 -0
- package/dist/{backup-service-Bww-Lg0s.js → backup-service-BH0Dzo_h.js} +2 -3
- package/dist/{backup-service-Bww-Lg0s.js.map → backup-service-BH0Dzo_h.js.map} +1 -1
- package/dist/cli-helpers.d.ts +56 -0
- package/dist/cli-output.d.ts +34 -0
- package/dist/data-transformer.d.ts +7 -2
- package/dist/data_driver-ULAyJEi9.js +193 -0
- package/dist/data_driver-ULAyJEi9.js.map +1 -0
- package/dist/ensure-collection-policies-CP5_YttS.js +124 -0
- package/dist/ensure-collection-policies-CP5_YttS.js.map +1 -0
- package/dist/{ensure-collection-tables-DSIxvLLD.js → ensure-collection-tables-DWVISfcC.js} +119 -13
- package/dist/ensure-collection-tables-DWVISfcC.js.map +1 -0
- package/dist/index.es.js +998 -600
- package/dist/index.es.js.map +1 -1
- package/dist/{rls-bootstrap-sql-Bpv3nUZo.js → rls-bootstrap-sql-69hYT8nr.js} +2 -2
- package/dist/{rls-bootstrap-sql-Bpv3nUZo.js.map → rls-bootstrap-sql-69hYT8nr.js.map} +1 -1
- package/dist/rls-enforcement-Ct9ab42o.js +425 -0
- package/dist/rls-enforcement-Ct9ab42o.js.map +1 -0
- package/dist/schema/auth-schema.d.ts +102 -0
- package/dist/schema/doctor-policy-checks.d.ts +28 -0
- package/dist/schema/doctor.d.ts +41 -25
- package/dist/schema/ensure-collection-policies.d.ts +33 -9
- package/dist/schema/ensure-collection-tables.d.ts +60 -6
- package/dist/schema/generate-drizzle-schema-logic.d.ts +9 -1
- package/dist/schema/generate-postgres-ddl-logic.d.ts +48 -0
- package/dist/schema/search-column.d.ts +248 -0
- package/dist/security/rls-enforcement.d.ts +8 -3
- package/dist/services/FetchService.d.ts +24 -0
- package/dist/services/RelationService.d.ts +30 -0
- package/dist/services/collection-helpers.d.ts +26 -0
- package/dist/services/dataService.d.ts +3 -0
- package/dist/services/realtimeService.d.ts +139 -2
- package/dist/{src-C_wvdMnl.js → src-DCdn3Val.js} +35 -3
- package/dist/src-DCdn3Val.js.map +1 -0
- package/dist/utils/drizzle-conditions.d.ts +124 -2
- package/dist/{websocket-D0TBU3ia.js → websocket-C8ZqVBiV.js} +75 -18
- package/dist/websocket-C8ZqVBiV.js.map +1 -0
- package/package.json +6 -6
- package/src/PostgresBackendDriver.ts +7 -3
- package/src/PostgresBootstrapper.ts +95 -9
- package/src/auth/ensure-tables.ts +27 -5
- package/src/auth/services.ts +82 -5
- package/src/backup/backup-cli.ts +59 -57
- package/src/cli-errors.ts +6 -6
- package/src/cli-helpers.ts +110 -4
- package/src/cli-output.ts +43 -0
- package/src/cli.ts +210 -145
- package/src/collections/buildRegistry.ts +3 -1
- package/src/data-transformer.ts +107 -14
- package/src/history/ensure-history-table.ts +2 -2
- package/src/schema/auth-schema.ts +17 -1
- package/src/schema/doctor-cli.ts +14 -65
- package/src/schema/doctor-policy-checks.ts +105 -0
- package/src/schema/doctor.ts +149 -72
- package/src/schema/ensure-collection-policies.ts +99 -6
- package/src/schema/ensure-collection-tables.ts +286 -13
- package/src/schema/generate-drizzle-schema-logic.ts +126 -42
- package/src/schema/generate-drizzle-schema.ts +11 -10
- package/src/schema/generate-postgres-ddl-logic.ts +204 -10
- package/src/schema/generate-postgres-ddl.ts +38 -14
- package/src/schema/introspect-db-logic.ts +65 -33
- package/src/schema/introspect-db.ts +24 -24
- package/src/schema/search-column.ts +643 -0
- package/src/security/rls-enforcement.ts +9 -4
- package/src/services/FetchService.ts +229 -15
- package/src/services/PersistService.ts +24 -1
- package/src/services/RelationService.ts +119 -69
- package/src/services/cdc/trigger-cdc.ts +5 -1
- package/src/services/channel-history.ts +9 -3
- package/src/services/channel-presence.ts +10 -3
- package/src/services/collection-helpers.ts +54 -1
- package/src/services/dataService.ts +3 -0
- package/src/services/pg-notify-listener.ts +1 -1
- package/src/services/realtimeService.ts +347 -86
- package/src/utils/drizzle-conditions.ts +365 -23
- package/src/utils/pg-error-utils.ts +8 -3
- package/src/websocket.ts +113 -16
- package/dist/auth-users-columns-Do9mw5Y5.js.map +0 -1
- package/dist/ensure-collection-policies-DMUdRQdM.js +0 -57
- package/dist/ensure-collection-policies-DMUdRQdM.js.map +0 -1
- package/dist/ensure-collection-tables-DSIxvLLD.js.map +0 -1
- package/dist/policy-CPkCqVTz.js +0 -105
- package/dist/policy-CPkCqVTz.js.map +0 -1
- package/dist/src-C_wvdMnl.js.map +0 -1
- package/dist/websocket-D0TBU3ia.js.map +0 -1
|
@@ -22,6 +22,7 @@ import { RelationalQueryBuilder } from "drizzle-orm/pg-core/query-builders/query
|
|
|
22
22
|
import { DrizzleClient } from "../interfaces";
|
|
23
23
|
import { PostgresCollectionRegistry } from "../collections/PostgresCollectionRegistry";
|
|
24
24
|
import { toFlatRow, toRestRow, isJunctionRelation } from "./row-pipeline";
|
|
25
|
+
import { visibleColumnProjection, hiddenColumnsOption } from "../schema/search-column";
|
|
25
26
|
import { isNestedPath, resolveNestedPath, type NestedPathHop } from "./nested-path";
|
|
26
27
|
import { ApiError, logger } from "@rebasepro/server";
|
|
27
28
|
import { reachedDatabase } from "../utils/pg-error-utils";
|
|
@@ -119,6 +120,31 @@ export class FetchService {
|
|
|
119
120
|
* and skips rows rather than erroring. The guesses stay, last, for a
|
|
120
121
|
* caller that hands over no collection to resolve against.
|
|
121
122
|
*/
|
|
123
|
+
/**
|
|
124
|
+
* The ORDER BY target, which may be relevance rather than a column.
|
|
125
|
+
*
|
|
126
|
+
* `_score` is only meaningful for a collection that declared a `search`
|
|
127
|
+
* block *and* for a request that carried a search string — ranking rows
|
|
128
|
+
* against no query ranks them all at zero. Outside those two conditions it
|
|
129
|
+
* is an unknown field and gets the same 400 as any other typo, which is the
|
|
130
|
+
* behaviour that matters: a sort that is silently dropped returns 200 with
|
|
131
|
+
* rows in arbitrary order, and paging over that repeats and skips rows.
|
|
132
|
+
*/
|
|
133
|
+
static readonly SCORE_FIELD = "_score";
|
|
134
|
+
|
|
135
|
+
private resolveOrderTarget(
|
|
136
|
+
table: PgTable<any>,
|
|
137
|
+
orderBy: string,
|
|
138
|
+
collection?: CollectionConfig,
|
|
139
|
+
searchString?: string
|
|
140
|
+
): AnyPgColumn | SQL | undefined {
|
|
141
|
+
if (orderBy === FetchService.SCORE_FIELD && collection && searchString) {
|
|
142
|
+
const rank = DrizzleConditionBuilder.buildSearchRankExpression(searchString, table, collection);
|
|
143
|
+
if (rank) return rank;
|
|
144
|
+
}
|
|
145
|
+
return this.resolveOrderByField(table, orderBy, collection);
|
|
146
|
+
}
|
|
147
|
+
|
|
122
148
|
private resolveOrderByField(
|
|
123
149
|
table: PgTable<any>,
|
|
124
150
|
orderBy: string,
|
|
@@ -300,6 +326,14 @@ export class FetchService {
|
|
|
300
326
|
);
|
|
301
327
|
}
|
|
302
328
|
} catch (e) {
|
|
329
|
+
// A relation that failed to load is not a relation that is absent.
|
|
330
|
+
// Without this the request answers 200 with the field quietly
|
|
331
|
+
// missing — and because a Postgres error poisons the surrounding
|
|
332
|
+
// transaction, every later relation in the same request is
|
|
333
|
+
// swallowed too, so one failure becomes a response missing
|
|
334
|
+
// several fields. Same guard the four other catches in this file
|
|
335
|
+
// already use.
|
|
336
|
+
if (reachedDatabase(e)) throw e;
|
|
303
337
|
logger.warn(`Could not resolve joinPath relation '${key}'`, { error: e });
|
|
304
338
|
}
|
|
305
339
|
});
|
|
@@ -378,6 +412,14 @@ export class FetchService {
|
|
|
378
412
|
}
|
|
379
413
|
}
|
|
380
414
|
} catch (e) {
|
|
415
|
+
// A relation that failed to load is not a relation that is absent.
|
|
416
|
+
// Without this the request answers 200 with the field quietly
|
|
417
|
+
// missing — and because a Postgres error poisons the surrounding
|
|
418
|
+
// transaction, every later relation in the same request is
|
|
419
|
+
// swallowed too, so one failure becomes a response missing
|
|
420
|
+
// several fields. Same guard the four other catches in this file
|
|
421
|
+
// already use.
|
|
422
|
+
if (reachedDatabase(e)) throw e;
|
|
381
423
|
logger.warn(`Could not batch resolve joinPath relation '${key}' for REST`, { error: e });
|
|
382
424
|
}
|
|
383
425
|
}
|
|
@@ -407,6 +449,15 @@ export class FetchService {
|
|
|
407
449
|
): Record<string, unknown> {
|
|
408
450
|
const queryOpts: Record<string, unknown> = {};
|
|
409
451
|
|
|
452
|
+
// Same exclusion the `db.select` fallback applies, in the shape the
|
|
453
|
+
// relational query builder takes. Both paths serve the same request, so
|
|
454
|
+
// a row must not carry the search column down one and not the other.
|
|
455
|
+
const hidden = hiddenColumnsOption(
|
|
456
|
+
getTableColumns(table),
|
|
457
|
+
this.registry.getCollectionByPath(collectionPath) ?? undefined
|
|
458
|
+
);
|
|
459
|
+
if (hidden) queryOpts.columns = hidden;
|
|
460
|
+
|
|
410
461
|
if (withConfig) queryOpts.with = withConfig;
|
|
411
462
|
|
|
412
463
|
// Build where conditions
|
|
@@ -417,7 +468,7 @@ export class FetchService {
|
|
|
417
468
|
if (options.searchString) {
|
|
418
469
|
const collection = getCollectionByPath(collectionPath, this.registry);
|
|
419
470
|
const searchConditions = DrizzleConditionBuilder.buildSearchConditions(
|
|
420
|
-
options.searchString, collection.properties, table
|
|
471
|
+
options.searchString, collection.properties, table, collection
|
|
421
472
|
);
|
|
422
473
|
if (searchConditions.length === 0) {
|
|
423
474
|
// Return options that will produce empty results
|
|
@@ -451,7 +502,7 @@ export class FetchService {
|
|
|
451
502
|
const orderExpressions: unknown[] = [];
|
|
452
503
|
if (options.orderBy) {
|
|
453
504
|
const collection = getCollectionByPath(collectionPath, this.registry);
|
|
454
|
-
const orderByField = this.
|
|
505
|
+
const orderByField = this.resolveOrderTarget(table, options.orderBy, collection, options.searchString);
|
|
455
506
|
if (orderByField) {
|
|
456
507
|
orderExpressions.push(options.order === "asc" ? asc(orderByField) : desc(orderByField));
|
|
457
508
|
}
|
|
@@ -485,6 +536,21 @@ export class FetchService {
|
|
|
485
536
|
const cursor = options.startAfter;
|
|
486
537
|
|
|
487
538
|
if (options.orderBy) {
|
|
539
|
+
// Relevance is computed per query, not stored, so there is no value
|
|
540
|
+
// on the cursor row to compare a later page against — and two
|
|
541
|
+
// requests with different search strings would produce scores that
|
|
542
|
+
// are not on the same scale at all. Refusing is the only honest
|
|
543
|
+
// answer: a dropped cursor condition silently repeats and skips
|
|
544
|
+
// rows, which is precisely what paging exists to prevent.
|
|
545
|
+
if (options.orderBy === FetchService.SCORE_FIELD) {
|
|
546
|
+
throw ApiError.badRequest(
|
|
547
|
+
"Cursor pagination (`startAfter`) cannot be combined with `orderBy: \"_score\"`. " +
|
|
548
|
+
"Relevance is computed per query rather than stored, so it cannot key a cursor. " +
|
|
549
|
+
"Use `limit`/`offset` for relevance-ordered pages, or order by a column.",
|
|
550
|
+
"SCORE_CURSOR_UNSUPPORTED",
|
|
551
|
+
{ field: FetchService.SCORE_FIELD }
|
|
552
|
+
);
|
|
553
|
+
}
|
|
488
554
|
const collection = collectionPath ? getCollectionByPath(collectionPath, this.registry) : undefined;
|
|
489
555
|
const orderByField = this.resolveOrderByField(table, options.orderBy, collection);
|
|
490
556
|
if (orderByField) {
|
|
@@ -607,9 +673,12 @@ idColumn };
|
|
|
607
673
|
try {
|
|
608
674
|
const withConfig = this.buildWithConfig(collection);
|
|
609
675
|
|
|
676
|
+
const hidden = hiddenColumnsOption(getTableColumns(table), collection);
|
|
677
|
+
|
|
610
678
|
const row = await qb.findFirst({
|
|
611
679
|
where: eq(idField, parsedId),
|
|
612
|
-
with: withConfig
|
|
680
|
+
with: withConfig,
|
|
681
|
+
...(hidden ? { columns: hidden } : {})
|
|
613
682
|
} as Parameters<NonNullable<typeof qb>["findFirst"]>[0]);
|
|
614
683
|
|
|
615
684
|
if (!row) return undefined;
|
|
@@ -631,8 +700,9 @@ idColumn };
|
|
|
631
700
|
}
|
|
632
701
|
|
|
633
702
|
// Fallback: db.select + N+1 relation loading
|
|
703
|
+
const visibleOne = visibleColumnProjection(getTableColumns(table), collection);
|
|
634
704
|
const result = await this.db
|
|
635
|
-
.select()
|
|
705
|
+
.select(visibleOne as never)
|
|
636
706
|
.from(table)
|
|
637
707
|
.where(eq(idField, parsedId))
|
|
638
708
|
.limit(1);
|
|
@@ -673,6 +743,14 @@ idColumn };
|
|
|
673
743
|
values[key] = createRelationRef(e.id, e.path);
|
|
674
744
|
}
|
|
675
745
|
} catch (e) {
|
|
746
|
+
// A relation that failed to load is not a relation that is absent.
|
|
747
|
+
// Without this the request answers 200 with the field quietly
|
|
748
|
+
// missing — and because a Postgres error poisons the surrounding
|
|
749
|
+
// transaction, every later relation in the same request is
|
|
750
|
+
// swallowed too, so one failure becomes a response missing
|
|
751
|
+
// several fields. Same guard the four other catches in this file
|
|
752
|
+
// already use.
|
|
753
|
+
if (reachedDatabase(e)) throw e;
|
|
676
754
|
logger.warn(`Could not resolve one-to-one relation property: ${key}`, { error: e });
|
|
677
755
|
}
|
|
678
756
|
}
|
|
@@ -700,6 +778,7 @@ idColumn };
|
|
|
700
778
|
offset?: number;
|
|
701
779
|
startAfter?: Record<string, unknown>;
|
|
702
780
|
searchString?: string;
|
|
781
|
+
searchExplain?: boolean;
|
|
703
782
|
databaseId?: string;
|
|
704
783
|
vectorSearch?: VectorSearchParams;
|
|
705
784
|
logical?: LogicalCondition;
|
|
@@ -763,17 +842,41 @@ idColumn };
|
|
|
763
842
|
vectorMeta = DrizzleConditionBuilder.buildVectorSearchConditions(table, options.vectorSearch);
|
|
764
843
|
}
|
|
765
844
|
|
|
845
|
+
// A generated search column is an index in column form; `SELECT *`
|
|
846
|
+
// would ship it to every caller. The projection is undefined — and the
|
|
847
|
+
// SQL therefore unchanged — for any table without one.
|
|
848
|
+
const visible = visibleColumnProjection(getTableColumns(table), collection);
|
|
849
|
+
|
|
850
|
+
// Relevance, alongside the row, exactly as `_distance` rides along with
|
|
851
|
+
// a vector search. Present only when the collection opted in and the
|
|
852
|
+
// request carried a search string, so a caller can order by it, show
|
|
853
|
+
// it, or blend it with a score of their own.
|
|
854
|
+
const rankSelect = options.searchString
|
|
855
|
+
? DrizzleConditionBuilder.buildSearchRankExpression(options.searchString, table, collection)
|
|
856
|
+
: undefined;
|
|
857
|
+
|
|
858
|
+
// Only when asked: a `ts_headline` per declared field per row.
|
|
859
|
+
const matchesSelect = options.searchString && options.searchExplain
|
|
860
|
+
? DrizzleConditionBuilder.buildSearchMatchesExpression(options.searchString, table, collection)
|
|
861
|
+
: undefined;
|
|
862
|
+
|
|
766
863
|
let query = vectorMeta
|
|
767
|
-
? this.db.select({ table_row: table,
|
|
864
|
+
? this.db.select({ table_row: (visible ?? table) as never,
|
|
768
865
|
_distance: vectorMeta.distanceSelect }).from(table).$dynamic()
|
|
769
|
-
:
|
|
866
|
+
: rankSelect
|
|
867
|
+
? this.db.select({
|
|
868
|
+
table_row: (visible ?? table) as never,
|
|
869
|
+
_score: rankSelect,
|
|
870
|
+
...(matchesSelect ? { _matches: matchesSelect } : {})
|
|
871
|
+
}).from(table).$dynamic()
|
|
872
|
+
: (visible ? this.db.select(visible as never).from(table).$dynamic() : this.db.select().from(table).$dynamic());
|
|
770
873
|
const allConditions: SQL[] = [];
|
|
771
874
|
|
|
772
875
|
if (scopeCondition) allConditions.push(scopeCondition);
|
|
773
876
|
|
|
774
877
|
if (options.searchString) {
|
|
775
878
|
const searchConditions = DrizzleConditionBuilder.buildSearchConditions(
|
|
776
|
-
options.searchString, collection.properties, table
|
|
879
|
+
options.searchString, collection.properties, table, collection
|
|
777
880
|
);
|
|
778
881
|
if (searchConditions.length === 0) return [];
|
|
779
882
|
allConditions.push(DrizzleConditionBuilder.combineConditionsWithOr(searchConditions)!);
|
|
@@ -804,7 +907,7 @@ _distance: vectorMeta.distanceSelect }).from(table).$dynamic()
|
|
|
804
907
|
if (vectorMeta) {
|
|
805
908
|
orderExpressions.push(asc(vectorMeta.orderBy));
|
|
806
909
|
} else if (options.orderBy) {
|
|
807
|
-
const orderByField = this.
|
|
910
|
+
const orderByField = this.resolveOrderTarget(table, options.orderBy, collection, options.searchString);
|
|
808
911
|
if (orderByField) {
|
|
809
912
|
orderExpressions.push(options.order === "asc" ? asc(orderByField) : desc(orderByField));
|
|
810
913
|
}
|
|
@@ -838,7 +941,15 @@ _distance: vectorMeta.distanceSelect }).from(table).$dynamic()
|
|
|
838
941
|
...r.table_row,
|
|
839
942
|
_distance: typeof r._distance === "number" ? r._distance : parseFloat(String(r._distance))
|
|
840
943
|
}))
|
|
841
|
-
|
|
944
|
+
// Same nested shape, unwrapped the same way, when a relevance
|
|
945
|
+
// score was selected instead.
|
|
946
|
+
: rankSelect
|
|
947
|
+
? (rawResults as { table_row: Record<string, unknown>; _score: unknown; _matches?: unknown }[]).map(r => ({
|
|
948
|
+
...r.table_row,
|
|
949
|
+
_score: typeof r._score === "number" ? r._score : parseFloat(String(r._score)),
|
|
950
|
+
...(matchesSelect ? { _matches: r._matches ?? [] } : {})
|
|
951
|
+
}))
|
|
952
|
+
: rawResults as Record<string, unknown>[];
|
|
842
953
|
|
|
843
954
|
return this.processRowResults<M>(results, collection, collectionPath, idInfo, options.databaseId, false, idInfoArray);
|
|
844
955
|
}
|
|
@@ -911,6 +1022,14 @@ _distance: vectorMeta.distanceSelect }).from(table).$dynamic()
|
|
|
911
1022
|
}
|
|
912
1023
|
});
|
|
913
1024
|
} catch (e) {
|
|
1025
|
+
// A relation that failed to load is not a relation that is absent.
|
|
1026
|
+
// Without this the request answers 200 with the field quietly
|
|
1027
|
+
// missing — and because a Postgres error poisons the surrounding
|
|
1028
|
+
// transaction, every later relation in the same request is
|
|
1029
|
+
// swallowed too, so one failure becomes a response missing
|
|
1030
|
+
// several fields. Same guard the four other catches in this file
|
|
1031
|
+
// already use.
|
|
1032
|
+
if (reachedDatabase(e)) throw e;
|
|
914
1033
|
logger.warn(`Could not batch load one-to-one relation property: ${key}`, { error: e });
|
|
915
1034
|
}
|
|
916
1035
|
}
|
|
@@ -938,6 +1057,14 @@ _distance: vectorMeta.distanceSelect }).from(table).$dynamic()
|
|
|
938
1057
|
);
|
|
939
1058
|
});
|
|
940
1059
|
} catch (e) {
|
|
1060
|
+
// A relation that failed to load is not a relation that is absent.
|
|
1061
|
+
// Without this the request answers 200 with the field quietly
|
|
1062
|
+
// missing — and because a Postgres error poisons the surrounding
|
|
1063
|
+
// transaction, every later relation in the same request is
|
|
1064
|
+
// swallowed too, so one failure becomes a response missing
|
|
1065
|
+
// several fields. Same guard the four other catches in this file
|
|
1066
|
+
// already use.
|
|
1067
|
+
if (reachedDatabase(e)) throw e;
|
|
941
1068
|
logger.warn(`Could not batch load many relation property: ${key}`, { error: e });
|
|
942
1069
|
}
|
|
943
1070
|
}
|
|
@@ -994,10 +1121,21 @@ relatedTo: hop });
|
|
|
994
1121
|
searchString: string,
|
|
995
1122
|
options: {
|
|
996
1123
|
filter?: FilterValues<Extract<keyof M, string>>;
|
|
1124
|
+
/**
|
|
1125
|
+
* An `or(...)`/`and(...)` group, applied alongside `filter`.
|
|
1126
|
+
*
|
|
1127
|
+
* `fetchRowsWithConditions` has always applied one; it was missing
|
|
1128
|
+
* from this signature, so a realtime search subscription carrying a
|
|
1129
|
+
* group could not pass it on and served every row matching the text
|
|
1130
|
+
* that RLS allowed.
|
|
1131
|
+
*/
|
|
1132
|
+
logical?: LogicalCondition;
|
|
997
1133
|
orderBy?: string;
|
|
998
1134
|
order?: "desc" | "asc";
|
|
999
1135
|
limit?: number;
|
|
1000
1136
|
databaseId?: string;
|
|
1137
|
+
/** Ask each row which declared search field matched. */
|
|
1138
|
+
searchExplain?: boolean;
|
|
1001
1139
|
} = {}
|
|
1002
1140
|
): Promise<Record<string, unknown>[]> {
|
|
1003
1141
|
return this.fetchRowsWithConditions<M>(collectionPath, {
|
|
@@ -1034,7 +1172,7 @@ relatedTo: hop });
|
|
|
1034
1172
|
|
|
1035
1173
|
if (options.searchString) {
|
|
1036
1174
|
const searchConditions = DrizzleConditionBuilder.buildSearchConditions(
|
|
1037
|
-
options.searchString, collection.properties, table
|
|
1175
|
+
options.searchString, collection.properties, table, collection
|
|
1038
1176
|
);
|
|
1039
1177
|
if (searchConditions.length === 0) return 0;
|
|
1040
1178
|
allConditions.push(DrizzleConditionBuilder.combineConditionsWithOr(searchConditions)!);
|
|
@@ -1226,6 +1364,14 @@ relatedTo: hop }, include
|
|
|
1226
1364
|
}
|
|
1227
1365
|
}
|
|
1228
1366
|
} catch (e) {
|
|
1367
|
+
// A relation that failed to load is not a relation that is absent.
|
|
1368
|
+
// Without this the request answers 200 with the field quietly
|
|
1369
|
+
// missing — and because a Postgres error poisons the surrounding
|
|
1370
|
+
// transaction, every later relation in the same request is
|
|
1371
|
+
// swallowed too, so one failure becomes a response missing
|
|
1372
|
+
// several fields. Same guard the four other catches in this file
|
|
1373
|
+
// already use.
|
|
1374
|
+
if (reachedDatabase(e)) throw e;
|
|
1229
1375
|
logger.warn(`[include] Failed to batch load one-to-one '${key}'`, { error: e });
|
|
1230
1376
|
}
|
|
1231
1377
|
}
|
|
@@ -1242,6 +1388,14 @@ relatedTo: hop }, include
|
|
|
1242
1388
|
(row as Record<string, unknown>)[key] = relatedList;
|
|
1243
1389
|
}
|
|
1244
1390
|
} catch (e) {
|
|
1391
|
+
// A relation that failed to load is not a relation that is absent.
|
|
1392
|
+
// Without this the request answers 200 with the field quietly
|
|
1393
|
+
// missing — and because a Postgres error poisons the surrounding
|
|
1394
|
+
// transaction, every later relation in the same request is
|
|
1395
|
+
// swallowed too, so one failure becomes a response missing
|
|
1396
|
+
// several fields. Same guard the four other catches in this file
|
|
1397
|
+
// already use.
|
|
1398
|
+
if (reachedDatabase(e)) throw e;
|
|
1245
1399
|
logger.warn(`[include] Failed to batch load many '${key}'`, { error: e });
|
|
1246
1400
|
}
|
|
1247
1401
|
}
|
|
@@ -1308,8 +1462,9 @@ relatedTo: hop }, include
|
|
|
1308
1462
|
}
|
|
1309
1463
|
|
|
1310
1464
|
// Fallback: db.select + N+1 relation loading
|
|
1465
|
+
const visibleOne = visibleColumnProjection(getTableColumns(table), collection);
|
|
1311
1466
|
const result = await this.db
|
|
1312
|
-
.select()
|
|
1467
|
+
.select(visibleOne as never)
|
|
1313
1468
|
.from(table)
|
|
1314
1469
|
.where(eq(idField, parsedId))
|
|
1315
1470
|
.limit(1);
|
|
@@ -1349,6 +1504,14 @@ relatedTo: hop }, include
|
|
|
1349
1504
|
}));
|
|
1350
1505
|
}
|
|
1351
1506
|
} catch (e) {
|
|
1507
|
+
// A relation that failed to load is not a relation that is absent.
|
|
1508
|
+
// Without this the request answers 200 with the field quietly
|
|
1509
|
+
// missing — and because a Postgres error poisons the surrounding
|
|
1510
|
+
// transaction, every later relation in the same request is
|
|
1511
|
+
// swallowed too, so one failure becomes a response missing
|
|
1512
|
+
// several fields. Same guard the four other catches in this file
|
|
1513
|
+
// already use.
|
|
1514
|
+
if (reachedDatabase(e)) throw e;
|
|
1352
1515
|
logger.warn(`[include] Failed to load relation '${key}'`, { error: e });
|
|
1353
1516
|
}
|
|
1354
1517
|
}
|
|
@@ -1363,12 +1526,26 @@ relatedTo: hop }, include
|
|
|
1363
1526
|
collectionPath: string,
|
|
1364
1527
|
options: {
|
|
1365
1528
|
filter?: FilterValues<Extract<keyof M, string>>;
|
|
1529
|
+
/**
|
|
1530
|
+
* An `or(...)`/`and(...)` group, applied alongside `filter`.
|
|
1531
|
+
*
|
|
1532
|
+
* Declared *and applied*, because this is the path every REST search
|
|
1533
|
+
* and vector read takes: `fetchCollectionForRest` skips `db.query`
|
|
1534
|
+
* whenever a `searchString` or a `vectorSearch` is present. The
|
|
1535
|
+
* group arrived here on `options` from the very beginning and was
|
|
1536
|
+
* simply never read, so `?searchString=x&or=(...)` served every row
|
|
1537
|
+
* matching `x` that RLS allowed — while `count` (which does apply
|
|
1538
|
+
* it) reported the narrowed total, so `meta.total` and `data`
|
|
1539
|
+
* described different sets of rows.
|
|
1540
|
+
*/
|
|
1541
|
+
logical?: LogicalCondition;
|
|
1366
1542
|
orderBy?: string;
|
|
1367
1543
|
order?: "desc" | "asc";
|
|
1368
1544
|
limit?: number;
|
|
1369
1545
|
offset?: number;
|
|
1370
1546
|
startAfter?: Record<string, unknown>;
|
|
1371
1547
|
searchString?: string;
|
|
1548
|
+
searchExplain?: boolean;
|
|
1372
1549
|
vectorSearch?: VectorSearchParams;
|
|
1373
1550
|
relatedTo?: NestedPathHop;
|
|
1374
1551
|
} = {}
|
|
@@ -1384,17 +1561,41 @@ relatedTo: hop }, include
|
|
|
1384
1561
|
vectorMeta = DrizzleConditionBuilder.buildVectorSearchConditions(table, options.vectorSearch);
|
|
1385
1562
|
}
|
|
1386
1563
|
|
|
1564
|
+
// A generated search column is an index in column form; `SELECT *`
|
|
1565
|
+
// would ship it to every caller. The projection is undefined — and the
|
|
1566
|
+
// SQL therefore unchanged — for any table without one.
|
|
1567
|
+
const visible = visibleColumnProjection(getTableColumns(table), collection);
|
|
1568
|
+
|
|
1569
|
+
// Relevance, alongside the row, exactly as `_distance` rides along with
|
|
1570
|
+
// a vector search. Present only when the collection opted in and the
|
|
1571
|
+
// request carried a search string, so a caller can order by it, show
|
|
1572
|
+
// it, or blend it with a score of their own.
|
|
1573
|
+
const rankSelect = options.searchString
|
|
1574
|
+
? DrizzleConditionBuilder.buildSearchRankExpression(options.searchString, table, collection)
|
|
1575
|
+
: undefined;
|
|
1576
|
+
|
|
1577
|
+
// Only when asked: a `ts_headline` per declared field per row.
|
|
1578
|
+
const matchesSelect = options.searchString && options.searchExplain
|
|
1579
|
+
? DrizzleConditionBuilder.buildSearchMatchesExpression(options.searchString, table, collection)
|
|
1580
|
+
: undefined;
|
|
1581
|
+
|
|
1387
1582
|
let query = vectorMeta
|
|
1388
|
-
? this.db.select({ table_row: table,
|
|
1583
|
+
? this.db.select({ table_row: (visible ?? table) as never,
|
|
1389
1584
|
_distance: vectorMeta.distanceSelect }).from(table).$dynamic()
|
|
1390
|
-
:
|
|
1585
|
+
: rankSelect
|
|
1586
|
+
? this.db.select({
|
|
1587
|
+
table_row: (visible ?? table) as never,
|
|
1588
|
+
_score: rankSelect,
|
|
1589
|
+
...(matchesSelect ? { _matches: matchesSelect } : {})
|
|
1590
|
+
}).from(table).$dynamic()
|
|
1591
|
+
: (visible ? this.db.select(visible as never).from(table).$dynamic() : this.db.select().from(table).$dynamic());
|
|
1391
1592
|
const allConditions: SQL[] = [];
|
|
1392
1593
|
|
|
1393
1594
|
if (options.relatedTo) allConditions.push(this.buildRelationScope(options.relatedTo));
|
|
1394
1595
|
|
|
1395
1596
|
if (options.searchString) {
|
|
1396
1597
|
const searchConditions = DrizzleConditionBuilder.buildSearchConditions(
|
|
1397
|
-
options.searchString, collection.properties, table
|
|
1598
|
+
options.searchString, collection.properties, table, collection
|
|
1398
1599
|
);
|
|
1399
1600
|
if (searchConditions.length === 0) return [];
|
|
1400
1601
|
allConditions.push(DrizzleConditionBuilder.combineConditionsWithOr(searchConditions)!);
|
|
@@ -1405,6 +1606,11 @@ _distance: vectorMeta.distanceSelect }).from(table).$dynamic()
|
|
|
1405
1606
|
if (filterConditions.length > 0) allConditions.push(...filterConditions);
|
|
1406
1607
|
}
|
|
1407
1608
|
|
|
1609
|
+
if (options.logical) {
|
|
1610
|
+
const logicalCondition = DrizzleConditionBuilder.buildLogicalConditions(options.logical, table, collectionPath, this.filterContext(collectionPath, table));
|
|
1611
|
+
if (logicalCondition) allConditions.push(logicalCondition);
|
|
1612
|
+
}
|
|
1613
|
+
|
|
1408
1614
|
if (vectorMeta?.filter) {
|
|
1409
1615
|
allConditions.push(vectorMeta.filter);
|
|
1410
1616
|
}
|
|
@@ -1418,7 +1624,7 @@ _distance: vectorMeta.distanceSelect }).from(table).$dynamic()
|
|
|
1418
1624
|
if (vectorMeta) {
|
|
1419
1625
|
orderExpressions.push(asc(vectorMeta.orderBy));
|
|
1420
1626
|
} else if (options.orderBy) {
|
|
1421
|
-
const orderByField = this.
|
|
1627
|
+
const orderByField = this.resolveOrderTarget(table, options.orderBy, collection, options.searchString);
|
|
1422
1628
|
if (orderByField) {
|
|
1423
1629
|
orderExpressions.push(options.order === "asc" ? asc(orderByField) : desc(orderByField));
|
|
1424
1630
|
}
|
|
@@ -1443,6 +1649,14 @@ _distance: vectorMeta.distanceSelect }).from(table).$dynamic()
|
|
|
1443
1649
|
}));
|
|
1444
1650
|
}
|
|
1445
1651
|
|
|
1652
|
+
if (rankSelect) {
|
|
1653
|
+
return (rawResults as { table_row: Record<string, unknown>; _score: unknown; _matches?: unknown }[]).map(r => ({
|
|
1654
|
+
...r.table_row,
|
|
1655
|
+
_score: typeof r._score === "number" ? r._score : parseFloat(String(r._score)),
|
|
1656
|
+
...(matchesSelect ? { _matches: r._matches ?? [] } : {})
|
|
1657
|
+
}));
|
|
1658
|
+
}
|
|
1659
|
+
|
|
1446
1660
|
return rawResults as Record<string, unknown>[];
|
|
1447
1661
|
}
|
|
1448
1662
|
|
|
@@ -1,10 +1,11 @@
|
|
|
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, hasForeignKeyOnTarget } from "@rebasepro/types";
|
|
4
|
+
import { CollectionConfig, Properties, Property, 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 {
|
|
8
|
+
assertWritableColumns,
|
|
8
9
|
getCollectionByPath,
|
|
9
10
|
getTableForCollection,
|
|
10
11
|
getPrimaryKeys,
|
|
@@ -307,6 +308,11 @@ export class PersistService {
|
|
|
307
308
|
|
|
308
309
|
const entityData = sanitizeAndConvertDates(serializedResult.scalarData);
|
|
309
310
|
|
|
311
|
+
// Everything below builds SQL from the table's own column list, so
|
|
312
|
+
// a key that is not a column is silently left out rather than
|
|
313
|
+
// refused. Say so here, while the key is still in hand.
|
|
314
|
+
assertWritableColumns(entityData as Record<string, unknown>, table, effectiveCollectionPath);
|
|
315
|
+
|
|
310
316
|
savedId = await this.db.transaction(async (tx) => {
|
|
311
317
|
let currentId: string | number;
|
|
312
318
|
|
|
@@ -380,6 +386,23 @@ export class PersistService {
|
|
|
380
386
|
// branch; Postgres rejects that against the conflict target.
|
|
381
387
|
for (const info of idInfoArray) delete set[info.fieldName];
|
|
382
388
|
|
|
389
|
+
// A conflict means the row was already there, so its
|
|
390
|
+
// `on_create` stamp is a fact about the past and not
|
|
391
|
+
// this write's to redecide. Bulk rows are saved with
|
|
392
|
+
// `status: "new"` on purpose (an import's rows carry a
|
|
393
|
+
// natural key for rows that may not exist), which
|
|
394
|
+
// computes the creation timestamp for every row — and
|
|
395
|
+
// the conflict-update then wrote it over the original.
|
|
396
|
+
// A nightly re-import reset `createdAt` on everything
|
|
397
|
+
// it touched, and every "new this week" query with it.
|
|
398
|
+
// The INSERT branch keeps the value: it is right there.
|
|
399
|
+
for (const [propName, prop] of Object.entries(collection.properties ?? {})) {
|
|
400
|
+
if ((prop as Property).type === "date"
|
|
401
|
+
&& (prop as { autoValue?: string }).autoValue === "on_create") {
|
|
402
|
+
delete set[propName];
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
|
|
383
406
|
result = Object.keys(set).length > 0
|
|
384
407
|
? await insertQuery.onConflictDoUpdate({ target, set }).returning(returningKeys)
|
|
385
408
|
: await insertQuery.onConflictDoNothing({ target }).returning(returningKeys);
|