@rebasepro/server-postgres 0.9.1-canary.16c42e9 → 0.9.1-canary.1d2d8b5
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/PostgresBackendDriver.d.ts +2 -25
- package/dist/PostgresBootstrapper.d.ts +0 -10
- package/dist/auth/services.d.ts +0 -16
- package/dist/connection.d.ts +0 -21
- package/dist/data-transformer.d.ts +2 -9
- package/dist/index.es.js +548 -1310
- package/dist/index.es.js.map +1 -1
- package/dist/schema/auth-default-policies.d.ts +10 -0
- package/dist/services/FetchService.d.ts +24 -4
- package/dist/services/PersistService.d.ts +1 -9
- package/dist/services/RelationService.d.ts +1 -34
- package/dist/services/collection-helpers.d.ts +14 -79
- package/dist/services/dataService.d.ts +1 -3
- package/dist/services/index.d.ts +1 -1
- package/dist/services/realtimeService.d.ts +0 -7
- package/package.json +8 -10
- package/src/PostgresBackendDriver.ts +13 -127
- package/src/PostgresBootstrapper.ts +25 -62
- package/src/auth/ensure-tables.ts +11 -73
- package/src/auth/services.ts +19 -49
- package/src/connection.ts +1 -61
- package/src/data-transformer.ts +9 -11
- package/src/databasePoolManager.ts +0 -2
- package/src/schema/auth-default-policies.ts +132 -0
- package/src/schema/generate-drizzle-schema-logic.ts +29 -24
- package/src/schema/generate-postgres-ddl-logic.ts +28 -76
- package/src/schema/introspect-db.ts +2 -19
- package/src/services/BranchService.ts +10 -42
- package/src/services/FetchService.ts +270 -65
- package/src/services/PersistService.ts +9 -62
- package/src/services/RelationService.ts +94 -153
- package/src/services/collection-helpers.ts +47 -164
- package/src/services/dataService.ts +2 -3
- package/src/services/index.ts +0 -1
- package/src/services/realtimeService.ts +19 -40
- package/src/utils/drizzle-conditions.ts +0 -13
- package/src/websocket.ts +1 -4
- package/dist/collections/buildRegistry.d.ts +0 -27
- package/dist/services/row-pipeline.d.ts +0 -63
- package/src/collections/buildRegistry.ts +0 -59
- package/src/services/row-pipeline.ts +0 -215
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { CollectionConfig, SecurityRule } from "@rebasepro/types";
|
|
2
|
+
/**
|
|
3
|
+
* Returns the security rules that should be applied to a collection: the
|
|
4
|
+
* author's explicit `securityRules` plus the framework defaults described in
|
|
5
|
+
* the module doc (baseline server/admin read for all collections; self-read
|
|
6
|
+
* and the admin write gate for auth collections).
|
|
7
|
+
*
|
|
8
|
+
* Collections that opt out via `disableDefaultPolicies` are returned unchanged.
|
|
9
|
+
*/
|
|
10
|
+
export declare function getEffectiveSecurityRules(collection: CollectionConfig): SecurityRule[];
|
|
@@ -40,22 +40,44 @@ export declare class FetchService {
|
|
|
40
40
|
* the target relation so actual row data is returned.
|
|
41
41
|
*/
|
|
42
42
|
private buildWithConfig;
|
|
43
|
+
/**
|
|
44
|
+
* Detect if a many-to-many relation uses a junction table in the Drizzle schema.
|
|
45
|
+
*/
|
|
46
|
+
private isJunctionRelation;
|
|
43
47
|
/**
|
|
44
48
|
* Get the Drizzle relation name on the junction table that points to the actual target row.
|
|
45
49
|
* For example, for posts_tags junction, this returns "tag_id" (the relation pointing to tags).
|
|
46
50
|
*/
|
|
47
51
|
private getJunctionTargetRelationName;
|
|
52
|
+
/**
|
|
53
|
+
* Convert a db.query result row (with nested relation objects) to a flat row.
|
|
54
|
+
* Handles:
|
|
55
|
+
* - Placing `id` at the top level as a string
|
|
56
|
+
* - Type normalization (dates, numbers, NaN) via normalizeDbValues
|
|
57
|
+
* - Converting nested relation objects to { id, path, __type: "relation" } for CMS
|
|
58
|
+
* - Flattening junction-table many-to-many results
|
|
59
|
+
*/
|
|
60
|
+
private drizzleResultToRow;
|
|
48
61
|
/**
|
|
49
62
|
* Post-fetch joinPath relations for a single flat row.
|
|
50
63
|
* joinPath relations cannot be expressed via Drizzle's `with` config,
|
|
51
64
|
* so they must be loaded separately after the primary query.
|
|
52
65
|
*/
|
|
53
66
|
private resolveJoinPathRelations;
|
|
67
|
+
/**
|
|
68
|
+
* Post-fetch joinPath relations for a batch of flat rows.
|
|
69
|
+
* Uses batch fetching to avoid N+1 queries for list views.
|
|
70
|
+
*/
|
|
71
|
+
private resolveJoinPathRelationsBatch;
|
|
54
72
|
/**
|
|
55
73
|
* Resolves joinPath relations for raw REST rows and directly injects them.
|
|
56
74
|
* Uses RelationService to query the database and maps results back to the flattened objects.
|
|
57
75
|
*/
|
|
58
76
|
private resolveJoinPathRelationsBatchRest;
|
|
77
|
+
/**
|
|
78
|
+
* Convert a db.query result row to a flat REST-style object with populated relations.
|
|
79
|
+
*/
|
|
80
|
+
private drizzleResultToRestRow;
|
|
59
81
|
/**
|
|
60
82
|
* Build db.query-compatible options from standard fetch options.
|
|
61
83
|
* Handles filter, search, orderBy, limit, and cursor-based pagination.
|
|
@@ -86,10 +108,8 @@ export declare class FetchService {
|
|
|
86
108
|
}): Promise<Record<string, unknown>[]>;
|
|
87
109
|
/**
|
|
88
110
|
* Fallback path used when db.query is unavailable.
|
|
89
|
-
*
|
|
90
|
-
*
|
|
91
|
-
* relations from what drizzle already nested — no query per row. This one
|
|
92
|
-
* has no nesting to read, so it resolves relations itself, in batches.
|
|
111
|
+
* The primary path uses drizzleResultToRow which handles relation
|
|
112
|
+
* mapping without N+1 queries.
|
|
93
113
|
*
|
|
94
114
|
* Process raw database results into flat rows with relations.
|
|
95
115
|
*/
|
|
@@ -40,16 +40,8 @@ export declare class PersistService {
|
|
|
40
40
|
deleteAll(collectionPath: string, _databaseId?: string): Promise<void>;
|
|
41
41
|
/**
|
|
42
42
|
* Save an row (create or update)
|
|
43
|
-
*
|
|
44
|
-
* With `options.upsert`, the row is written with INSERT ... ON CONFLICT DO
|
|
45
|
-
* UPDATE against the primary key rather than a plain UPDATE. That is one
|
|
46
|
-
* statement, so it cannot lose a race the way a read-then-write can, and it
|
|
47
|
-
* does not care whether the row already exists — which is what a re-runnable
|
|
48
|
-
* import needs.
|
|
49
43
|
*/
|
|
50
|
-
save<M extends Record<string, unknown>>(collectionPath: string, values: Partial<M>, id?: string | number, databaseId?: string,
|
|
51
|
-
upsert?: boolean;
|
|
52
|
-
}): Promise<Record<string, unknown>>;
|
|
44
|
+
save<M extends Record<string, unknown>>(collectionPath: string, values: Partial<M>, id?: string | number, databaseId?: string): Promise<Record<string, unknown>>;
|
|
53
45
|
/**
|
|
54
46
|
* Get the RelationService instance for external use
|
|
55
47
|
*/
|
|
@@ -20,40 +20,6 @@ export declare class RelationService {
|
|
|
20
20
|
private db;
|
|
21
21
|
private registry;
|
|
22
22
|
constructor(db: DrizzleClient, registry: PostgresCollectionRegistry);
|
|
23
|
-
/**
|
|
24
|
-
* One target row, as the {@link RelatedRow} everything here returns.
|
|
25
|
-
*
|
|
26
|
-
* Eight sites built this by hand, which is how the address came to be the
|
|
27
|
-
* target's first key column in all eight — one edit, eight places to miss.
|
|
28
|
-
*
|
|
29
|
-
* `resolveNested` is the one thing they did not agree on, and the
|
|
30
|
-
* disagreement was invisible: the single-parent fetches pass `db` and
|
|
31
|
-
* `registry` to `parseDataFromServer`, so the target's *own* relations get
|
|
32
|
-
* resolved too, while the batch paths deliberately do not — a query per
|
|
33
|
-
* target row is the N+1 the batching exists to avoid. Naming the parameter
|
|
34
|
-
* makes that a decision rather than a difference between two call sites
|
|
35
|
-
* nobody was comparing.
|
|
36
|
-
*/
|
|
37
|
-
private toRelatedRow;
|
|
38
|
-
/**
|
|
39
|
-
* A WHERE matching any of `parentIds`, by the whole key.
|
|
40
|
-
*
|
|
41
|
-
* A single key is an `IN (…)`. A composite one cannot be: matching
|
|
42
|
-
* `tenant_id IN (1, 1)` collects every row of tenant 1, so two parents that
|
|
43
|
-
* share their first column each receive the other's relations. It becomes
|
|
44
|
-
* an OR of ANDs — one exact address per parent — which Postgres indexes the
|
|
45
|
-
* same way it would a multi-column key lookup.
|
|
46
|
-
*/
|
|
47
|
-
private parentKeyCondition;
|
|
48
|
-
/**
|
|
49
|
-
* Reject a relation that cannot express a composite-keyed parent.
|
|
50
|
-
*
|
|
51
|
-
* `localKey` and `foreignKeyOnTarget` are single column names: one column
|
|
52
|
-
* cannot reference a two-column key, so such a relation has no correct
|
|
53
|
-
* reading. Left alone it would silently match on the first key column and
|
|
54
|
-
* hand a tenant's rows to its neighbour — say so instead.
|
|
55
|
-
*/
|
|
56
|
-
private assertSingleKeyAddressable;
|
|
57
23
|
/**
|
|
58
24
|
* Fetch rows related to a parent row through a specific relation
|
|
59
25
|
*/
|
|
@@ -106,6 +72,7 @@ export declare class RelationService {
|
|
|
106
72
|
relationKey: string;
|
|
107
73
|
relation: Relation;
|
|
108
74
|
newValue: unknown;
|
|
75
|
+
currentId?: string | number;
|
|
109
76
|
}>): Promise<void>;
|
|
110
77
|
/**
|
|
111
78
|
* Handle inverse relations with joinPath
|
|
@@ -1,9 +1,6 @@
|
|
|
1
1
|
import { PgTable, AnyPgColumn } from "drizzle-orm/pg-core";
|
|
2
2
|
import { CollectionConfig } from "@rebasepro/types";
|
|
3
3
|
import { PostgresCollectionRegistry } from "../collections/PostgresCollectionRegistry";
|
|
4
|
-
export { buildCompositeId, parseIdValues, COMPOSITE_ID_SEPARATOR } from "@rebasepro/common";
|
|
5
|
-
export type { PrimaryKeyInfo } from "@rebasepro/common";
|
|
6
|
-
import type { PrimaryKeyInfo } from "@rebasepro/common";
|
|
7
4
|
/**
|
|
8
5
|
* Shared helper functions for row operations.
|
|
9
6
|
* These are used by FetchService, PersistService, and RelationService.
|
|
@@ -24,80 +21,18 @@ export interface DrizzleColumnMeta {
|
|
|
24
21
|
export declare function getColumnMeta(col: AnyPgColumn): DrizzleColumnMeta;
|
|
25
22
|
export declare function getCollectionByPath(collectionPath: string, registry: PostgresCollectionRegistry): CollectionConfig;
|
|
26
23
|
export declare function getTableForCollection(collection: CollectionConfig, registry: PostgresCollectionRegistry): PgTable<any>;
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
* drizzle schema, and finally a column literally named `id`. Only the first is
|
|
32
|
-
* visible to the browser, which is why a key known only to drizzle is reported
|
|
33
|
-
* at boot — see {@link warnOnKeysTheAdminCannotResolve}.
|
|
34
|
-
*
|
|
35
|
-
* Returns `[]` when nothing resolves, rather than throwing. It used to open by
|
|
36
|
-
* resolving the table, which throws when there is none — so the `isId` tier,
|
|
37
|
-
* which needs no table at all, was unreachable for exactly the collections
|
|
38
|
-
* most likely to have no table registered. Every caller that wanted "no keys"
|
|
39
|
-
* to mean "no keys" had to spell that out in a try/catch.
|
|
40
|
-
*
|
|
41
|
-
* Callers that cannot proceed without a key must say so themselves, naming the
|
|
42
|
-
* collection: an empty array here means "this collection has no address", which
|
|
43
|
-
* is a different answer in a notification (broadcast a wildcard) than in a save
|
|
44
|
-
* (fail).
|
|
45
|
-
*/
|
|
46
|
-
export declare function getPrimaryKeys(collection: CollectionConfig, registry: PostgresCollectionRegistry): PrimaryKeyInfo[];
|
|
47
|
-
/**
|
|
48
|
-
* The key columns, for callers that cannot do their job without one.
|
|
49
|
-
*
|
|
50
|
-
* {@link getPrimaryKeys} answers "what keys, if any" and returns `[]` for a
|
|
51
|
-
* collection with no address. Most of this driver, though, is building a WHERE
|
|
52
|
-
* clause and has no meaning without a key — for those, an empty array is not an
|
|
53
|
-
* answer, and indexing `[0]` into it produces `Cannot read properties of
|
|
54
|
-
* undefined` three frames from where the real problem is. This says what is
|
|
55
|
-
* wrong and which collection it is wrong about.
|
|
56
|
-
*/
|
|
57
|
-
export declare function requirePrimaryKeys(collection: CollectionConfig, registry: PostgresCollectionRegistry): PrimaryKeyInfo[];
|
|
58
|
-
/**
|
|
59
|
-
* Collections whose key the *browser* cannot resolve, and what it will do
|
|
60
|
-
* instead.
|
|
61
|
-
*
|
|
62
|
-
* The two sides resolve keys from different evidence. This driver reads, in
|
|
63
|
-
* order: properties marked `isId`, the primary keys of the Drizzle schema, then
|
|
64
|
-
* a column literally named `id`. The admin shares the `CollectionConfig` — it
|
|
65
|
-
* compiles the same collection files into its bundle — but never the Drizzle
|
|
66
|
-
* schema, so the middle tier is invisible to it.
|
|
67
|
-
*
|
|
68
|
-
* Nothing can normalize this at runtime: the server does not serve the admin
|
|
69
|
-
* its collections, so a key resolved here cannot be handed over there. The
|
|
70
|
-
* config files are the only thing both sides read, so the fix is an edit to
|
|
71
|
-
* them, and the most this can do is say exactly which edit.
|
|
72
|
-
*
|
|
73
|
-
* Two shapes, and the second is the dangerous one:
|
|
74
|
-
*
|
|
75
|
-
* - No `isId`, no `id` property → the admin resolves no address, warns in the
|
|
76
|
-
* console, and rows cannot be opened or linked.
|
|
77
|
-
* - No `isId`, but an `id` property that is *not* the key → the admin addresses
|
|
78
|
-
* rows by `id` while this driver reads the address as the real key. Nothing
|
|
79
|
-
* errors: the addresses look right and route wrong.
|
|
80
|
-
*/
|
|
81
|
-
export declare function findUnresolvableKeyCollections(collections: CollectionConfig[], registry: PostgresCollectionRegistry): {
|
|
82
|
-
collection: CollectionConfig;
|
|
83
|
-
keys: PrimaryKeyInfo[];
|
|
84
|
-
shadowedByIdProperty: boolean;
|
|
24
|
+
export declare function getPrimaryKeys(collection: CollectionConfig, registry: PostgresCollectionRegistry): {
|
|
25
|
+
fieldName: string;
|
|
26
|
+
type: "string" | "number";
|
|
27
|
+
isUUID?: boolean;
|
|
85
28
|
}[];
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
* row does not carry one — it is exactly its columns.
|
|
97
|
-
*
|
|
98
|
-
* Falls back to a literal `id` column, for a row that reached us from somewhere
|
|
99
|
-
* other than this driver. Returns `""` when there is no key and no `id` —
|
|
100
|
-
* callers decide what that means, since "unaddressable" is a different answer
|
|
101
|
-
* in a notification (broadcast a wildcard) than in a save (fail).
|
|
102
|
-
*/
|
|
103
|
-
export declare function deriveRowAddress(row: Record<string, unknown>, collection: CollectionConfig, registry: PostgresCollectionRegistry): string;
|
|
29
|
+
export declare function parseIdValues(idValue: string | number, primaryKeys: {
|
|
30
|
+
fieldName: string;
|
|
31
|
+
type: "string" | "number";
|
|
32
|
+
isUUID?: boolean;
|
|
33
|
+
}[]): Record<string, string | number>;
|
|
34
|
+
export declare function buildCompositeId(values: Record<string, unknown>, primaryKeys: {
|
|
35
|
+
fieldName: string;
|
|
36
|
+
type: "string" | "number";
|
|
37
|
+
isUUID?: boolean;
|
|
38
|
+
}[]): string;
|
|
@@ -82,9 +82,7 @@ export declare class DataService implements DataRepository {
|
|
|
82
82
|
/**
|
|
83
83
|
* Save an row (create or update)
|
|
84
84
|
*/
|
|
85
|
-
save<M extends Record<string, unknown>>(collectionPath: string, values: Partial<M>, id?: string | number, databaseId?: string,
|
|
86
|
-
upsert?: boolean;
|
|
87
|
-
}): Promise<Record<string, unknown>>;
|
|
85
|
+
save<M extends Record<string, unknown>>(collectionPath: string, values: Partial<M>, id?: string | number, databaseId?: string): Promise<Record<string, unknown>>;
|
|
88
86
|
/**
|
|
89
87
|
* Delete an row by ID
|
|
90
88
|
*/
|
package/dist/services/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
export { FetchService } from "./FetchService";
|
|
2
2
|
export { PersistService } from "./PersistService";
|
|
3
3
|
export { RelationService } from "./RelationService";
|
|
4
|
-
export { getCollectionByPath, getTableForCollection, getPrimaryKeys,
|
|
4
|
+
export { getCollectionByPath, getTableForCollection, getPrimaryKeys, parseIdValues, buildCompositeId } from "./collection-helpers";
|
|
@@ -177,15 +177,8 @@ export declare class RealtimeService extends EventEmitter implements RealtimePro
|
|
|
177
177
|
/**
|
|
178
178
|
* Send a lightweight row-level patch to a collection subscriber.
|
|
179
179
|
* The client can merge this into its cached data for instant feedback.
|
|
180
|
-
*
|
|
181
|
-
* The key columns ride along: the patch names a row by address, and the
|
|
182
|
-
* client has to find that row among the ones it cached — which carry
|
|
183
|
-
* columns and no address. The SDK holds no collection config to derive one
|
|
184
|
-
* from, so this is the only place the mapping can come from.
|
|
185
180
|
*/
|
|
186
181
|
private sendCollectionPatch;
|
|
187
|
-
/** The key columns of the collection at `path`, if they can be resolved. */
|
|
188
|
-
private primaryKeysForPath;
|
|
189
182
|
private sendError;
|
|
190
183
|
private sendMessage;
|
|
191
184
|
/**
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rebasepro/server-postgres",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.9.1-canary.
|
|
4
|
+
"version": "0.9.1-canary.1d2d8b5",
|
|
5
5
|
"description": "PostgreSQL data source backend implementation for Rebase with Drizzle ORM",
|
|
6
6
|
"funding": {
|
|
7
7
|
"url": "https://github.com/sponsors/rebaseco"
|
|
@@ -69,22 +69,21 @@
|
|
|
69
69
|
"dotenv": "^17.4.2",
|
|
70
70
|
"drizzle-orm": "^0.45.2",
|
|
71
71
|
"execa": "^9.6.1",
|
|
72
|
+
"hono": "^4.12.25",
|
|
72
73
|
"pg": "^8.21.0",
|
|
73
74
|
"ws": "^8.21.0",
|
|
74
|
-
"@rebasepro/codegen": "0.9.1-canary.
|
|
75
|
-
"@rebasepro/
|
|
76
|
-
"@rebasepro/
|
|
77
|
-
"@rebasepro/
|
|
78
|
-
"@rebasepro/
|
|
75
|
+
"@rebasepro/codegen": "0.9.1-canary.1d2d8b5",
|
|
76
|
+
"@rebasepro/types": "0.9.1-canary.1d2d8b5",
|
|
77
|
+
"@rebasepro/server": "0.9.1-canary.1d2d8b5",
|
|
78
|
+
"@rebasepro/common": "0.9.1-canary.1d2d8b5",
|
|
79
|
+
"@rebasepro/utils": "0.9.1-canary.1d2d8b5"
|
|
79
80
|
},
|
|
80
81
|
"devDependencies": {
|
|
81
|
-
"@hono/node-server": "^2.0.9",
|
|
82
82
|
"@types/jest": "^30.0.0",
|
|
83
83
|
"@types/node": "^25.9.3",
|
|
84
84
|
"@types/pg": "^8.20.0",
|
|
85
85
|
"@types/ws": "^8.18.1",
|
|
86
86
|
"@vitejs/plugin-react": "^6.0.2",
|
|
87
|
-
"hono": "^4.12.25",
|
|
88
87
|
"jest": "^30.4.2",
|
|
89
88
|
"ts-jest": "^29.4.11",
|
|
90
89
|
"typescript": "^6.0.3",
|
|
@@ -105,7 +104,6 @@
|
|
|
105
104
|
"test:lint": "eslint \"src/**\" --quiet",
|
|
106
105
|
"test": "jest --passWithNoTests",
|
|
107
106
|
"test:e2e": "vitest run --config vitest.e2e.config.ts",
|
|
108
|
-
"clean": "rm -rf dist && find ./src -name '*.js' -type f | xargs rm -f"
|
|
109
|
-
"smoke:baas": "tsx scripts/smoke-baas.ts"
|
|
107
|
+
"clean": "rm -rf dist && find ./src -name '*.js' -type f | xargs rm -f"
|
|
110
108
|
}
|
|
111
109
|
}
|
|
@@ -17,7 +17,6 @@ import {
|
|
|
17
17
|
RebaseData,
|
|
18
18
|
RebaseSdkData,
|
|
19
19
|
RestFetchService,
|
|
20
|
-
SaveManyProps,
|
|
21
20
|
SaveProps,
|
|
22
21
|
TableColumnInfo,
|
|
23
22
|
TableForeignKeyInfo,
|
|
@@ -29,7 +28,6 @@ import {
|
|
|
29
28
|
import { sql as drizzleSql } from "drizzle-orm";
|
|
30
29
|
import { buildPropertyCallbacks, buildSdkData, resolveCollectionRelations, updateDateAutoValues } from "@rebasepro/common";
|
|
31
30
|
import { PostgresCollectionRegistry } from "./collections/PostgresCollectionRegistry";
|
|
32
|
-
import { deriveRowAddress } from "./services/collection-helpers";
|
|
33
31
|
import { HistoryService } from "./history/HistoryService";
|
|
34
32
|
import { mergeDeep } from "@rebasepro/utils";
|
|
35
33
|
import { logger } from "@rebasepro/server";
|
|
@@ -534,8 +532,7 @@ export class PostgresBackendDriver implements DataDriver {
|
|
|
534
532
|
id,
|
|
535
533
|
values,
|
|
536
534
|
collection,
|
|
537
|
-
status
|
|
538
|
-
upsert
|
|
535
|
+
status
|
|
539
536
|
}: SaveProps<M>): Promise<Record<string, unknown>> {
|
|
540
537
|
|
|
541
538
|
const {
|
|
@@ -548,26 +545,13 @@ export class PostgresBackendDriver implements DataDriver {
|
|
|
548
545
|
let updatedValues = values;
|
|
549
546
|
const contextForCallback = this.buildCallContext();
|
|
550
547
|
|
|
551
|
-
// Fetch previous values for callbacks AND history recording
|
|
552
|
-
// as the saved row the callbacks receive (`fetchOneForRest`), so
|
|
553
|
-
// `values` and `previousValues` compare like with like — a Date on one
|
|
554
|
-
// side and its ISO string on the other reads as a change that never
|
|
555
|
-
// happened.
|
|
548
|
+
// Fetch previous values for callbacks AND history recording
|
|
556
549
|
let previousValuesForHistory: Partial<M> | undefined;
|
|
557
550
|
if (status === "existing" && id) {
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
const { id: _existingId, ...existingValues } = existing;
|
|
563
|
-
previousValuesForHistory = existingValues as Partial<M>;
|
|
564
|
-
}
|
|
565
|
-
} catch (err) {
|
|
566
|
-
// Best-effort enrichment: callbacks and history run without
|
|
567
|
-
// previous values rather than the save failing on a read the
|
|
568
|
-
// write itself does not need (e.g. a collection whose key the
|
|
569
|
-
// registry cannot resolve).
|
|
570
|
-
logger.debug(`[save] Could not fetch previous values for "${path}"`, { detail: err instanceof Error ? err.message : String(err) });
|
|
551
|
+
const existing = await this.dataService.fetchOne<M>(path, id, resolvedCollection?.databaseId);
|
|
552
|
+
if (existing) {
|
|
553
|
+
const { id: _existingId, ...existingValues } = existing;
|
|
554
|
+
previousValuesForHistory = existingValues as Partial<M>;
|
|
571
555
|
}
|
|
572
556
|
}
|
|
573
557
|
|
|
@@ -632,8 +616,7 @@ export class PostgresBackendDriver implements DataDriver {
|
|
|
632
616
|
path,
|
|
633
617
|
updatedValues,
|
|
634
618
|
id,
|
|
635
|
-
resolvedCollection?.databaseId
|
|
636
|
-
{ upsert }
|
|
619
|
+
resolvedCollection?.databaseId
|
|
637
620
|
);
|
|
638
621
|
|
|
639
622
|
if (savedRow && (globalCallbacks?.afterRead || callbacks?.afterRead || propertyCallbacks?.afterRead)) {
|
|
@@ -666,19 +649,8 @@ export class PostgresBackendDriver implements DataDriver {
|
|
|
666
649
|
}
|
|
667
650
|
}
|
|
668
651
|
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
// literally named `id`, and is ordinary data for a table that has such
|
|
672
|
-
// a column without it being the key.
|
|
673
|
-
const savedId = deriveRowAddress(
|
|
674
|
-
savedRow,
|
|
675
|
-
(resolvedCollection ?? collection) as CollectionConfig,
|
|
676
|
-
this.registry
|
|
677
|
-
);
|
|
678
|
-
// `values` are the row's columns — all of them. For an `id`-keyed table
|
|
679
|
-
// that includes `id`, which used to be stripped here because it was the
|
|
680
|
-
// synthesized address rather than the column it now is.
|
|
681
|
-
const savedValues = savedRow;
|
|
652
|
+
const savedId = savedRow.id as string | number;
|
|
653
|
+
const { id: _savedId, ...savedValues } = savedRow;
|
|
682
654
|
|
|
683
655
|
if (globalCallbacks?.afterSave || callbacks?.afterSave || propertyCallbacks?.afterSave) {
|
|
684
656
|
// 1. Global callbacks first
|
|
@@ -723,7 +695,7 @@ export class PostgresBackendDriver implements DataDriver {
|
|
|
723
695
|
if (this.historyService && resolvedCollection?.history) {
|
|
724
696
|
this.historyService.recordHistory({
|
|
725
697
|
tableName: path,
|
|
726
|
-
id: savedId,
|
|
698
|
+
id: savedId.toString(),
|
|
727
699
|
action: status === "new" ? "create" : "update",
|
|
728
700
|
values: savedValues as Record<string, unknown>,
|
|
729
701
|
previousValues: previousValuesForHistory as Record<string, unknown> | undefined,
|
|
@@ -735,14 +707,14 @@ export class PostgresBackendDriver implements DataDriver {
|
|
|
735
707
|
if (this._deferNotifications) {
|
|
736
708
|
this._pendingNotifications.push({
|
|
737
709
|
path,
|
|
738
|
-
id: savedId,
|
|
710
|
+
id: savedId.toString(),
|
|
739
711
|
row: savedRow,
|
|
740
712
|
databaseId: resolvedCollection?.databaseId
|
|
741
713
|
});
|
|
742
714
|
} else {
|
|
743
715
|
await this.realtimeService.notifyUpdate(
|
|
744
716
|
path,
|
|
745
|
-
savedId,
|
|
717
|
+
savedId.toString(),
|
|
746
718
|
savedRow,
|
|
747
719
|
resolvedCollection?.databaseId
|
|
748
720
|
);
|
|
@@ -792,86 +764,13 @@ export class PostgresBackendDriver implements DataDriver {
|
|
|
792
764
|
}
|
|
793
765
|
}
|
|
794
766
|
|
|
795
|
-
/**
|
|
796
|
-
* Write many rows through the same pipeline as {@link save}.
|
|
797
|
-
*
|
|
798
|
-
* The batch runs in one transaction of its own, so a failure part-way leaves
|
|
799
|
-
* nothing behind — the point of a batch is that a re-run starts from a known
|
|
800
|
-
* state. When this driver is already inside a transaction (the authenticated
|
|
801
|
-
* path, via `withTransaction`) the nested call becomes a savepoint, which is
|
|
802
|
-
* still atomic and still commits once.
|
|
803
|
-
*
|
|
804
|
-
* Rows are applied in order, so a batch that touches the same key twice ends
|
|
805
|
-
* with the last write winning, exactly as separate calls would.
|
|
806
|
-
*/
|
|
807
|
-
async saveMany<M extends Record<string, unknown>>({
|
|
808
|
-
path,
|
|
809
|
-
rows,
|
|
810
|
-
collection,
|
|
811
|
-
upsert
|
|
812
|
-
}: SaveManyProps<M>): Promise<Record<string, unknown>[]> {
|
|
813
|
-
return this.db.transaction(async (tx) => {
|
|
814
|
-
// Bind the whole batch to the transaction handle. Without this the
|
|
815
|
-
// rows would be written through `this.db` and survive a rollback.
|
|
816
|
-
const txDriver = new PostgresBackendDriver(
|
|
817
|
-
tx, this.realtimeService, this.registry, this.user, this.poolManager, this.historyService
|
|
818
|
-
);
|
|
819
|
-
txDriver.dataService = new DataService(tx, this.registry);
|
|
820
|
-
txDriver.client = this.client;
|
|
821
|
-
// Carry the caller's notification batching through, so a bulk write
|
|
822
|
-
// nested in an outer transaction still holds its events until commit.
|
|
823
|
-
txDriver._deferNotifications = this._deferNotifications;
|
|
824
|
-
txDriver._pendingNotifications = this._pendingNotifications;
|
|
825
|
-
|
|
826
|
-
const saved: Record<string, unknown>[] = [];
|
|
827
|
-
|
|
828
|
-
for (let i = 0; i < rows.length; i++) {
|
|
829
|
-
const values = rows[i];
|
|
830
|
-
const id = (values as Record<string, unknown>)?.id as string | number | undefined;
|
|
831
|
-
try {
|
|
832
|
-
saved.push(await txDriver.save<M>({
|
|
833
|
-
path,
|
|
834
|
-
values,
|
|
835
|
-
// No `id` argument, deliberately: passing one selects the
|
|
836
|
-
// UPDATE path, and an import's rows usually carry a natural
|
|
837
|
-
// key for a row that does not exist yet — which would 404 on
|
|
838
|
-
// every one. Leaving the key inside `values` is what
|
|
839
|
-
// single-row `create(data, id)` does, and it inserts.
|
|
840
|
-
// Callers who want existing rows overwritten pass `upsert`.
|
|
841
|
-
collection,
|
|
842
|
-
status: "new",
|
|
843
|
-
upsert
|
|
844
|
-
}));
|
|
845
|
-
} catch (error) {
|
|
846
|
-
// One bad row in ten thousand is impossible to find from a
|
|
847
|
-
// message that only says the batch failed. Say which row, and
|
|
848
|
-
// keep the original error as the cause so its status survives.
|
|
849
|
-
const label = id !== undefined ? `id ${JSON.stringify(id)}` : "no id";
|
|
850
|
-
throw Object.assign(
|
|
851
|
-
new Error(`Row ${i} of ${rows.length} (${label}) failed: ${(error as Error)?.message ?? error}`, { cause: error }),
|
|
852
|
-
{
|
|
853
|
-
statusCode: (error as { statusCode?: number })?.statusCode,
|
|
854
|
-
code: (error as { code?: string })?.code,
|
|
855
|
-
name: (error as Error)?.name
|
|
856
|
-
}
|
|
857
|
-
);
|
|
858
|
-
}
|
|
859
|
-
}
|
|
860
|
-
|
|
861
|
-
return saved;
|
|
862
|
-
});
|
|
863
|
-
}
|
|
864
|
-
|
|
865
767
|
async delete<M extends Record<string, unknown>>({
|
|
866
768
|
row,
|
|
867
769
|
collection
|
|
868
770
|
}: DeleteProps<M>): Promise<void> {
|
|
869
771
|
|
|
870
772
|
const targetPath = row.path;
|
|
871
|
-
|
|
872
|
-
// travels beside it as `id`, so merging it in here only ever invented an
|
|
873
|
-
// `id` field for tables that have no such column.
|
|
874
|
-
const targetRow: Record<string, unknown> = { ...(row.values ?? {}) };
|
|
773
|
+
const targetRow: Record<string, unknown> = { id: row.id, ...(row.values ?? {}) };
|
|
875
774
|
|
|
876
775
|
// Resolve from backend registry to restore callbacks lost during WebSocket serialization
|
|
877
776
|
const {
|
|
@@ -1463,19 +1362,6 @@ export class AuthenticatedPostgresBackendDriver implements DataDriver {
|
|
|
1463
1362
|
return this.withTransaction((delegate) => delegate.save(props));
|
|
1464
1363
|
}
|
|
1465
1364
|
|
|
1466
|
-
/**
|
|
1467
|
-
* One transaction for the whole batch, rather than one per row.
|
|
1468
|
-
*
|
|
1469
|
-
* This is the point of the method: `save` opens a transaction per call, so
|
|
1470
|
-
* importing 10k rows through it means 10k transactions (and, over HTTP, 10k
|
|
1471
|
-
* round trips). Here the RLS context is established once and every row lands
|
|
1472
|
-
* or none does. Realtime notifications are already deferred to commit by
|
|
1473
|
-
* `withTransaction`, so a batch does not flood subscribers mid-flight.
|
|
1474
|
-
*/
|
|
1475
|
-
async saveMany<M extends Record<string, unknown>>(props: SaveManyProps<M>): Promise<Record<string, unknown>[]> {
|
|
1476
|
-
return this.withTransaction((delegate) => delegate.saveMany(props));
|
|
1477
|
-
}
|
|
1478
|
-
|
|
1479
1365
|
async delete<M extends Record<string, unknown>>(props: DeleteProps<M>): Promise<void> {
|
|
1480
1366
|
return this.withTransaction((delegate) => delegate.delete(props));
|
|
1481
1367
|
}
|