@rebasepro/server-postgresql 0.7.0 → 0.8.0
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/build-errors.txt +37 -0
- package/dist/PostgresAdapter.d.ts +6 -0
- package/dist/PostgresBackendDriver.d.ts +118 -0
- package/dist/PostgresBootstrapper.d.ts +46 -0
- package/dist/auth/ensure-tables.d.ts +10 -0
- package/dist/auth/services.d.ts +251 -0
- package/dist/cli-errors.d.ts +29 -0
- package/dist/cli-helpers.d.ts +7 -0
- package/dist/cli.d.ts +1 -0
- package/dist/collections/PostgresCollectionRegistry.d.ts +47 -0
- package/dist/connection.d.ts +65 -0
- package/dist/data-transformer.d.ts +55 -0
- package/dist/databasePoolManager.d.ts +20 -0
- package/dist/history/HistoryService.d.ts +71 -0
- package/dist/history/ensure-history-table.d.ts +7 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.es.js +13560 -0
- package/dist/index.es.js.map +1 -0
- package/dist/interfaces.d.ts +18 -0
- package/dist/schema/auth-default-policies.d.ts +12 -0
- package/dist/schema/auth-schema.d.ts +2376 -0
- package/dist/schema/doctor-cli.d.ts +2 -0
- package/dist/schema/doctor.d.ts +52 -0
- package/dist/schema/generate-drizzle-schema-logic.d.ts +2 -0
- package/dist/schema/generate-drizzle-schema.d.ts +1 -0
- package/dist/schema/generate-postgres-ddl-logic.d.ts +5 -0
- package/dist/schema/generate-postgres-ddl.d.ts +1 -0
- package/dist/schema/introspect-db-inference.d.ts +5 -0
- package/dist/schema/introspect-db-logic.d.ts +118 -0
- package/dist/schema/introspect-db.d.ts +1 -0
- package/dist/schema/test-schema.d.ts +24 -0
- package/dist/services/BranchService.d.ts +47 -0
- package/dist/services/EntityFetchService.d.ts +214 -0
- package/dist/services/EntityPersistService.d.ts +40 -0
- package/dist/services/RelationService.d.ts +98 -0
- package/dist/services/entity-helpers.d.ts +38 -0
- package/dist/services/entityService.d.ts +110 -0
- package/dist/services/index.d.ts +4 -0
- package/dist/services/realtimeService.d.ts +220 -0
- package/dist/types.d.ts +3 -0
- package/dist/utils/drizzle-conditions.d.ts +138 -0
- package/dist/utils/pg-array-null-patch.d.ts +16 -0
- package/dist/utils/pg-error-utils.d.ts +65 -0
- package/dist/utils/table-classification.d.ts +8 -0
- package/dist/websocket.d.ts +11 -0
- package/package.json +17 -17
- package/src/PostgresBackendDriver.ts +135 -24
- package/src/cli.ts +73 -1
- package/src/collections/PostgresCollectionRegistry.ts +6 -6
- package/src/data-transformer.ts +2 -2
- package/src/schema/auth-default-policies.ts +13 -6
- package/src/schema/generate-drizzle-schema-logic.ts +16 -79
- package/src/schema/generate-postgres-ddl-logic.ts +14 -51
- package/src/services/realtimeService.ts +26 -2
- package/test/entity-callbacks-redaction.test.ts +86 -0
- package/test/postgresDataDriver.test.ts +2 -1
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { Entity, FilterValues } from "@rebasepro/types";
|
|
2
|
+
import type { VectorSearchParams } from "@rebasepro/types";
|
|
3
|
+
import { EntityFetchService } from "./EntityFetchService";
|
|
4
|
+
import { EntityPersistService } from "./EntityPersistService";
|
|
5
|
+
import { RelationService } from "./RelationService";
|
|
6
|
+
import { EntityRepository, DrizzleClient } from "../interfaces";
|
|
7
|
+
import { PostgresCollectionRegistry } from "../collections/PostgresCollectionRegistry";
|
|
8
|
+
export { sanitizeAndConvertDates, serializeDataToServer, parseDataFromServer } from "../data-transformer";
|
|
9
|
+
export { EntityFetchService } from "./EntityFetchService";
|
|
10
|
+
export { EntityPersistService } from "./EntityPersistService";
|
|
11
|
+
export { RelationService } from "./RelationService";
|
|
12
|
+
export * from "../interfaces";
|
|
13
|
+
/**
|
|
14
|
+
* EntityService - Facade for entity operations.
|
|
15
|
+
*
|
|
16
|
+
* This class provides a unified API for entity CRUD operations by delegating
|
|
17
|
+
* to specialized services:
|
|
18
|
+
* - EntityFetchService: Read operations (fetch, search, count)
|
|
19
|
+
* - EntityPersistService: Write operations (save, delete)
|
|
20
|
+
* - RelationService: Relation operations (fetch related, update relations)
|
|
21
|
+
*
|
|
22
|
+
* Implements the EntityRepository interface for database abstraction.
|
|
23
|
+
*/
|
|
24
|
+
export declare class EntityService implements EntityRepository {
|
|
25
|
+
private db;
|
|
26
|
+
private registry;
|
|
27
|
+
private fetchService;
|
|
28
|
+
private persistService;
|
|
29
|
+
constructor(db: DrizzleClient, registry: PostgresCollectionRegistry);
|
|
30
|
+
/**
|
|
31
|
+
* Fetch a single entity by ID
|
|
32
|
+
*/
|
|
33
|
+
fetchEntity<M extends Record<string, unknown>>(collectionPath: string, entityId: string | number, databaseId?: string): Promise<Entity<M> | undefined>;
|
|
34
|
+
/**
|
|
35
|
+
* Fetch a collection of entities with optional filtering, ordering, and pagination
|
|
36
|
+
*/
|
|
37
|
+
fetchCollection<M extends Record<string, unknown>>(collectionPath: string, options?: {
|
|
38
|
+
filter?: FilterValues<Extract<keyof M, string>>;
|
|
39
|
+
orderBy?: string;
|
|
40
|
+
order?: "desc" | "asc";
|
|
41
|
+
limit?: number;
|
|
42
|
+
offset?: number;
|
|
43
|
+
startAfter?: Record<string, unknown>;
|
|
44
|
+
searchString?: string;
|
|
45
|
+
databaseId?: string;
|
|
46
|
+
vectorSearch?: VectorSearchParams;
|
|
47
|
+
}): Promise<Entity<M>[]>;
|
|
48
|
+
/**
|
|
49
|
+
* Search entities by text
|
|
50
|
+
*/
|
|
51
|
+
searchEntities<M extends Record<string, unknown>>(collectionPath: string, searchString: string, options?: {
|
|
52
|
+
filter?: FilterValues<Extract<keyof M, string>>;
|
|
53
|
+
orderBy?: string;
|
|
54
|
+
order?: "desc" | "asc";
|
|
55
|
+
limit?: number;
|
|
56
|
+
databaseId?: string;
|
|
57
|
+
}): Promise<Entity<M>[]>;
|
|
58
|
+
/**
|
|
59
|
+
* Count entities in a collection
|
|
60
|
+
*/
|
|
61
|
+
countEntities<M extends Record<string, unknown>>(collectionPath: string, options?: {
|
|
62
|
+
filter?: FilterValues<Extract<keyof M, string>>;
|
|
63
|
+
searchString?: string;
|
|
64
|
+
databaseId?: string;
|
|
65
|
+
}): Promise<number>;
|
|
66
|
+
/**
|
|
67
|
+
* Check if a field value is unique in a collection
|
|
68
|
+
*/
|
|
69
|
+
checkUniqueField(collectionPath: string, fieldName: string, value: unknown, excludeEntityId?: string, databaseId?: string): Promise<boolean>;
|
|
70
|
+
/**
|
|
71
|
+
* Fetch entities related to a parent entity
|
|
72
|
+
*/
|
|
73
|
+
fetchRelatedEntities<M extends Record<string, unknown>>(parentCollectionPath: string, parentEntityId: string | number, relationKey: string, options?: {
|
|
74
|
+
filter?: FilterValues<Extract<keyof M, string>>;
|
|
75
|
+
orderBy?: string;
|
|
76
|
+
order?: "desc" | "asc";
|
|
77
|
+
limit?: number;
|
|
78
|
+
startAfter?: Record<string, unknown>;
|
|
79
|
+
searchString?: string;
|
|
80
|
+
databaseId?: string;
|
|
81
|
+
}): Promise<Entity<M>[]>;
|
|
82
|
+
/**
|
|
83
|
+
* Save an entity (create or update)
|
|
84
|
+
*/
|
|
85
|
+
saveEntity<M extends Record<string, unknown>>(collectionPath: string, values: Partial<M>, entityId?: string | number, databaseId?: string): Promise<Entity<M>>;
|
|
86
|
+
/**
|
|
87
|
+
* Delete an entity by ID
|
|
88
|
+
*/
|
|
89
|
+
deleteEntity(collectionPath: string, entityId: string | number, databaseId?: string): Promise<void>;
|
|
90
|
+
/**
|
|
91
|
+
* Delete all entities from a collection
|
|
92
|
+
*/
|
|
93
|
+
deleteAll(collectionPath: string, databaseId?: string): Promise<void>;
|
|
94
|
+
/**
|
|
95
|
+
* Execute raw SQL
|
|
96
|
+
*/
|
|
97
|
+
executeSql(sqlText: string, params?: unknown[]): Promise<Record<string, unknown>[]>;
|
|
98
|
+
/**
|
|
99
|
+
* Get the underlying EntityFetchService for advanced use
|
|
100
|
+
*/
|
|
101
|
+
getFetchService(): EntityFetchService;
|
|
102
|
+
/**
|
|
103
|
+
* Get the underlying EntityPersistService for advanced use
|
|
104
|
+
*/
|
|
105
|
+
getPersistService(): EntityPersistService;
|
|
106
|
+
/**
|
|
107
|
+
* Get the underlying RelationService for advanced use
|
|
108
|
+
*/
|
|
109
|
+
getRelationService(): RelationService;
|
|
110
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { EntityFetchService } from "./EntityFetchService";
|
|
2
|
+
export { EntityPersistService } from "./EntityPersistService";
|
|
3
|
+
export { RelationService } from "./RelationService";
|
|
4
|
+
export { getCollectionByPath, getTableForCollection, getPrimaryKeys, parseIdValues, buildCompositeId } from "./entity-helpers";
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
import { WebSocket } from "ws";
|
|
2
|
+
import { EventEmitter } from "events";
|
|
3
|
+
import { Entity, DataDriver, WebSocketMessage } from "@rebasepro/types";
|
|
4
|
+
import { NodePgDatabase } from "drizzle-orm/node-postgres";
|
|
5
|
+
import { RealtimeProvider, CollectionSubscriptionConfig, EntitySubscriptionConfig } from "../interfaces";
|
|
6
|
+
import { PostgresCollectionRegistry } from "../collections/PostgresCollectionRegistry";
|
|
7
|
+
/**
|
|
8
|
+
* Auth context stored per-subscription so real-time refetches respect RLS.
|
|
9
|
+
* Mirrors the session variables set by PostgresBackendDriver.withAuth().
|
|
10
|
+
*/
|
|
11
|
+
export interface SubscriptionAuthContext {
|
|
12
|
+
userId: string;
|
|
13
|
+
roles: string[];
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* PostgreSQL-specific realtime service.
|
|
17
|
+
* Handles WebSocket connections and subscriptions for real-time entity updates.
|
|
18
|
+
*
|
|
19
|
+
* Implements the RealtimeProvider interface for database abstraction.
|
|
20
|
+
*/
|
|
21
|
+
export declare class RealtimeService extends EventEmitter implements RealtimeProvider {
|
|
22
|
+
private db;
|
|
23
|
+
private registry;
|
|
24
|
+
private clients;
|
|
25
|
+
private channels;
|
|
26
|
+
private presence;
|
|
27
|
+
private presenceInterval?;
|
|
28
|
+
private static readonly PRESENCE_TIMEOUT_MS;
|
|
29
|
+
private entityService;
|
|
30
|
+
private _subscriptions;
|
|
31
|
+
private subscriptionCallbacks;
|
|
32
|
+
private driver?;
|
|
33
|
+
/** Unique identifier for this process instance, used to skip own notifications. */
|
|
34
|
+
private readonly instanceId;
|
|
35
|
+
/** Dedicated pg.Client for LISTEN (outside the Drizzle pool). */
|
|
36
|
+
private listenClient?;
|
|
37
|
+
/** Connection string used for reconnecting the LISTEN client. */
|
|
38
|
+
private listenConnectionString?;
|
|
39
|
+
/** Whether cross-instance broadcasting is active. */
|
|
40
|
+
private broadcasting;
|
|
41
|
+
/** Reconnection timer handle. */
|
|
42
|
+
private reconnectTimer?;
|
|
43
|
+
/** Debounce timers for collection refetches to prevent refetch storms. */
|
|
44
|
+
private refetchTimers;
|
|
45
|
+
/** Debounce window (ms) for coalescing rapid entity updates into a single correctness refetch. */
|
|
46
|
+
private static readonly REFETCH_DEBOUNCE_MS;
|
|
47
|
+
constructor(db: NodePgDatabase<any>, registry: PostgresCollectionRegistry);
|
|
48
|
+
/** Whether to emit verbose debug logs (disabled in production). */
|
|
49
|
+
private static readonly DEBUG;
|
|
50
|
+
private debugLog;
|
|
51
|
+
setDataDriver(driver: DataDriver): void;
|
|
52
|
+
get subscriptions(): Map<string, {
|
|
53
|
+
clientId: string;
|
|
54
|
+
type: "collection" | "entity";
|
|
55
|
+
path: string;
|
|
56
|
+
entityId?: string | number;
|
|
57
|
+
collectionRequest?: {
|
|
58
|
+
filter?: Record<string, unknown>;
|
|
59
|
+
orderBy?: string;
|
|
60
|
+
order?: "desc" | "asc";
|
|
61
|
+
limit?: number;
|
|
62
|
+
offset?: number;
|
|
63
|
+
startAfter?: Record<string, unknown>;
|
|
64
|
+
databaseId?: string;
|
|
65
|
+
searchString?: string;
|
|
66
|
+
};
|
|
67
|
+
authContext?: SubscriptionAuthContext;
|
|
68
|
+
}>;
|
|
69
|
+
registerDataDriverSubscription(subscriptionId: string, subscription: {
|
|
70
|
+
clientId: string;
|
|
71
|
+
type: "collection" | "entity";
|
|
72
|
+
path: string;
|
|
73
|
+
entityId?: string | number;
|
|
74
|
+
collectionRequest?: {
|
|
75
|
+
filter?: Record<string, unknown>;
|
|
76
|
+
orderBy?: string;
|
|
77
|
+
order?: "desc" | "asc";
|
|
78
|
+
limit?: number;
|
|
79
|
+
offset?: number;
|
|
80
|
+
startAfter?: Record<string, unknown>;
|
|
81
|
+
databaseId?: string;
|
|
82
|
+
searchString?: string;
|
|
83
|
+
};
|
|
84
|
+
authContext?: SubscriptionAuthContext;
|
|
85
|
+
}): void;
|
|
86
|
+
addSubscriptionCallback(subscriptionId: string, callback: (data: Entity[] | Entity | null) => void): void;
|
|
87
|
+
removeSubscriptionCallback(subscriptionId: string): void;
|
|
88
|
+
/**
|
|
89
|
+
* Subscribe to collection changes (RealtimeProvider interface)
|
|
90
|
+
*/
|
|
91
|
+
subscribeToCollection(subscriptionId: string, config: CollectionSubscriptionConfig, callback?: (entities: Entity[]) => void): void;
|
|
92
|
+
/**
|
|
93
|
+
* Subscribe to single entity changes (RealtimeProvider interface)
|
|
94
|
+
*/
|
|
95
|
+
subscribeToEntity(subscriptionId: string, config: EntitySubscriptionConfig, callback?: (entity: Entity | null) => void): void;
|
|
96
|
+
/**
|
|
97
|
+
* Unsubscribe from a subscription (RealtimeProvider interface)
|
|
98
|
+
*/
|
|
99
|
+
unsubscribe(subscriptionId: string): void;
|
|
100
|
+
addClient(clientId: string, ws: WebSocket): void;
|
|
101
|
+
handleClientMessage(clientId: string, message: WebSocketMessage, authContext?: SubscriptionAuthContext): Promise<void>;
|
|
102
|
+
removeClient(clientId: string): Promise<void>;
|
|
103
|
+
private handleMessage;
|
|
104
|
+
private handleCollectionSubscription;
|
|
105
|
+
private handleEntitySubscription;
|
|
106
|
+
private handleUnsubscribe;
|
|
107
|
+
/**
|
|
108
|
+
* Enhanced notification method that handles nested relation updates.
|
|
109
|
+
* @param broadcast When true (default), also sends a pg_notify so other instances
|
|
110
|
+
* pick up the change. Set to false when handling an incoming
|
|
111
|
+
* cross-instance notification to avoid infinite loops.
|
|
112
|
+
*/
|
|
113
|
+
notifyEntityUpdate(path: string, entityId: string, entity: Entity | null, databaseId?: string, broadcast?: boolean): Promise<void>;
|
|
114
|
+
/**
|
|
115
|
+
* Notify subscriptions for a specific path
|
|
116
|
+
*/
|
|
117
|
+
private notifyPathUpdate;
|
|
118
|
+
/**
|
|
119
|
+
* Debounce a collection refetch for a WebSocket subscription.
|
|
120
|
+
* Coalesces rapid entity mutations into a single database query.
|
|
121
|
+
*/
|
|
122
|
+
private debouncedCollectionRefetch;
|
|
123
|
+
/**
|
|
124
|
+
* Debounce a collection refetch for a DataDriver callback subscription.
|
|
125
|
+
*/
|
|
126
|
+
private debouncedDriverRefetch;
|
|
127
|
+
/**
|
|
128
|
+
* Fetch a collection with optional RLS auth context.
|
|
129
|
+
* When authContext is provided, the fetch runs inside a transaction
|
|
130
|
+
* with set_config calls so PostgreSQL RLS policies are enforced.
|
|
131
|
+
*/
|
|
132
|
+
private fetchCollectionWithAuth;
|
|
133
|
+
/**
|
|
134
|
+
* Debounce an entity refetch for a WebSocket subscription.
|
|
135
|
+
*/
|
|
136
|
+
private debouncedEntityRefetch;
|
|
137
|
+
/**
|
|
138
|
+
* Debounce an entity refetch for a Driver callback subscription.
|
|
139
|
+
*/
|
|
140
|
+
private debouncedEntityDriverRefetch;
|
|
141
|
+
/**
|
|
142
|
+
* Fetch a single entity with optional RLS auth context.
|
|
143
|
+
*/
|
|
144
|
+
private fetchEntityWithAuth;
|
|
145
|
+
private sendCollectionUpdate;
|
|
146
|
+
private sendEntityUpdate;
|
|
147
|
+
/**
|
|
148
|
+
* Send a lightweight entity-level patch to a collection subscriber.
|
|
149
|
+
* The client can merge this into its cached data for instant feedback.
|
|
150
|
+
*/
|
|
151
|
+
private sendCollectionEntityPatch;
|
|
152
|
+
private sendError;
|
|
153
|
+
private sendMessage;
|
|
154
|
+
/**
|
|
155
|
+
* Extract parent paths from a nested path like "posts/70/tags"
|
|
156
|
+
* Returns ["posts", "posts/70"] for the example above
|
|
157
|
+
*/
|
|
158
|
+
private getParentPaths;
|
|
159
|
+
/** Join a broadcast channel */
|
|
160
|
+
joinChannel(clientId: string, channel: string): void;
|
|
161
|
+
/** Leave a broadcast channel */
|
|
162
|
+
leaveChannel(clientId: string, channel: string): void;
|
|
163
|
+
/** Broadcast a message to all clients in a channel except sender */
|
|
164
|
+
broadcastToChannel(clientId: string, channel: string, event: string, payload: unknown): void;
|
|
165
|
+
/** Track presence in a channel */
|
|
166
|
+
trackPresence(clientId: string, channel: string, state: Record<string, unknown>): void;
|
|
167
|
+
/** Remove presence from a channel */
|
|
168
|
+
removePresence(clientId: string, channel: string): void;
|
|
169
|
+
/** Send full presence state to a specific client */
|
|
170
|
+
sendPresenceState(clientId: string, channel: string): void;
|
|
171
|
+
/** Broadcast presence diff (joins/leaves) to channel */
|
|
172
|
+
private broadcastPresenceDiff;
|
|
173
|
+
/** Periodic cleanup for stale presences */
|
|
174
|
+
private ensurePresenceCleanup;
|
|
175
|
+
/**
|
|
176
|
+
* Gracefully tear down all realtime resources.
|
|
177
|
+
*
|
|
178
|
+
* This MUST be called during process shutdown, **before** `pool.end()`.
|
|
179
|
+
* It ensures:
|
|
180
|
+
* 1. All debounced refetch timers are cancelled (prevents queries after pool closes).
|
|
181
|
+
* 2. All subscription state and callbacks are cleared.
|
|
182
|
+
* 3. The dedicated LISTEN client (outside the pool) is disconnected.
|
|
183
|
+
* 4. All WebSocket clients are removed (but not forcefully closed — the
|
|
184
|
+
* HTTP server close will handle that).
|
|
185
|
+
*/
|
|
186
|
+
destroy(): Promise<void>;
|
|
187
|
+
/**
|
|
188
|
+
* Enable cross-instance realtime broadcasting via Postgres LISTEN/NOTIFY.
|
|
189
|
+
* Creates a dedicated pg.Client (outside the Drizzle pool) that stays
|
|
190
|
+
* connected and listens for change notifications from other instances.
|
|
191
|
+
*
|
|
192
|
+
* This is an **optional** feature — if never called, the backend operates
|
|
193
|
+
* in single-instance mode (the default, perfectly fine for most setups).
|
|
194
|
+
*
|
|
195
|
+
* @param connectionString Raw Postgres connection string for the LISTEN client.
|
|
196
|
+
*/
|
|
197
|
+
startListening(connectionString: string): Promise<void>;
|
|
198
|
+
/**
|
|
199
|
+
* Stop listening and clean up the dedicated LISTEN connection.
|
|
200
|
+
*/
|
|
201
|
+
stopListening(): Promise<void>;
|
|
202
|
+
/**
|
|
203
|
+
* Broadcast a change notification to other instances via pg_notify.
|
|
204
|
+
* Uses the main Drizzle connection (pooled) — NOT the LISTEN client.
|
|
205
|
+
*/
|
|
206
|
+
private broadcastChange;
|
|
207
|
+
/**
|
|
208
|
+
* Create and connect the dedicated LISTEN client with auto-reconnect.
|
|
209
|
+
*/
|
|
210
|
+
private connectListenClient;
|
|
211
|
+
/**
|
|
212
|
+
* Schedule a reconnection attempt with a fixed 3s delay.
|
|
213
|
+
*/
|
|
214
|
+
private scheduleReconnect;
|
|
215
|
+
}
|
|
216
|
+
/**
|
|
217
|
+
* Alias for RealtimeService for consistent naming with other database implementations.
|
|
218
|
+
* This allows code to use PostgresRealtimeProvider alongside future MongoRealtimeProvider, etc.
|
|
219
|
+
*/
|
|
220
|
+
export declare const PostgresRealtimeProvider: typeof RealtimeService;
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import { SQL } from "drizzle-orm";
|
|
2
|
+
import { AnyPgColumn, PgTable } from "drizzle-orm/pg-core";
|
|
3
|
+
import { FilterValues, WhereFilterOp, Relation, LogicalCondition, FilterCondition } from "@rebasepro/types";
|
|
4
|
+
import { PostgresCollectionRegistry } from "../collections/PostgresCollectionRegistry";
|
|
5
|
+
/** Drizzle dynamic query builder — accepts innerJoin + where chaining */
|
|
6
|
+
export interface DrizzleDynamicQuery {
|
|
7
|
+
innerJoin(table: PgTable<any>, condition: SQL): this;
|
|
8
|
+
where(condition: SQL | undefined): this;
|
|
9
|
+
limit(limit: number): this;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Unified condition builder for Drizzle/PostgreSQL queries.
|
|
13
|
+
*
|
|
14
|
+
* This class uses static methods and satisfies the ConditionBuilderStatic<SQL> type.
|
|
15
|
+
* It translates Rebase filter conditions to Drizzle SQL conditions.
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* const builder: ConditionBuilderStatic<SQL> = DrizzleConditionBuilder;
|
|
19
|
+
*/
|
|
20
|
+
export declare class DrizzleConditionBuilder {
|
|
21
|
+
/**
|
|
22
|
+
* Build filter conditions from FilterValues
|
|
23
|
+
*/
|
|
24
|
+
static buildFilterConditions<M extends Record<string, unknown>>(filter: FilterValues<Extract<keyof M, string>>, table: PgTable<any>, collectionPath: string): SQL[];
|
|
25
|
+
/**
|
|
26
|
+
* Build logical conditions recursively from LogicalCondition or FilterCondition
|
|
27
|
+
*/
|
|
28
|
+
static buildLogicalConditions(cond: LogicalCondition | FilterCondition, table: PgTable<any>, collectionPath: string): SQL | null;
|
|
29
|
+
/**
|
|
30
|
+
* Build a single filter condition for a specific operator and value
|
|
31
|
+
*/
|
|
32
|
+
static buildSingleFilterCondition(column: AnyPgColumn, op: WhereFilterOp, value: unknown): SQL | null;
|
|
33
|
+
/**
|
|
34
|
+
* Build relation-based conditions for different relation types
|
|
35
|
+
*/
|
|
36
|
+
static buildRelationConditions(relation: Relation, parentEntityId: string | number | (string | number)[], targetTable: PgTable<any>, parentTable: PgTable<any>, parentIdColumn: AnyPgColumn, targetIdColumn: AnyPgColumn, registry: PostgresCollectionRegistry): {
|
|
37
|
+
joinConditions: {
|
|
38
|
+
table: PgTable<any>;
|
|
39
|
+
condition: SQL;
|
|
40
|
+
}[];
|
|
41
|
+
whereConditions: SQL[];
|
|
42
|
+
};
|
|
43
|
+
/**
|
|
44
|
+
* Build conditions for join path relations
|
|
45
|
+
*/
|
|
46
|
+
private static buildJoinPathConditions;
|
|
47
|
+
/**
|
|
48
|
+
* Build a single join condition between tables
|
|
49
|
+
*/
|
|
50
|
+
private static buildSingleJoinCondition;
|
|
51
|
+
/**
|
|
52
|
+
* Try to build a junction table join when direct foreign key relationship is not found
|
|
53
|
+
*/
|
|
54
|
+
private static tryBuildJunctionJoin;
|
|
55
|
+
/**
|
|
56
|
+
* Build conditions for junction table (many-to-many) relations
|
|
57
|
+
*/
|
|
58
|
+
private static buildJunctionTableConditions;
|
|
59
|
+
/**
|
|
60
|
+
* Build conditions for inverse junction table (many-to-many) relations
|
|
61
|
+
*/
|
|
62
|
+
private static buildInverseJunctionTableConditions;
|
|
63
|
+
/**
|
|
64
|
+
* Build conditions for simple relations (owning/inverse without join paths)
|
|
65
|
+
*/
|
|
66
|
+
private static buildSimpleRelationCondition;
|
|
67
|
+
/**
|
|
68
|
+
* Combine multiple conditions with AND operator
|
|
69
|
+
*/
|
|
70
|
+
static combineConditionsWithAnd(conditions: SQL[]): SQL | undefined;
|
|
71
|
+
/**
|
|
72
|
+
* Combine multiple conditions with OR operator
|
|
73
|
+
*/
|
|
74
|
+
static combineConditionsWithOr(conditions: SQL[]): SQL | undefined;
|
|
75
|
+
/**
|
|
76
|
+
* Build search conditions for text fields
|
|
77
|
+
*/
|
|
78
|
+
static buildSearchConditions(searchString: string, properties: Record<string, unknown>, table: PgTable<any>): SQL[];
|
|
79
|
+
/**
|
|
80
|
+
* Build a unique field check condition
|
|
81
|
+
*/
|
|
82
|
+
static buildUniqueFieldCondition(fieldColumn: AnyPgColumn, value: unknown, idColumn?: AnyPgColumn, excludeId?: string | number): SQL[];
|
|
83
|
+
/**
|
|
84
|
+
* Build relation-based query with joins and conditions
|
|
85
|
+
*/
|
|
86
|
+
static buildRelationQuery<T extends DrizzleDynamicQuery>(baseQuery: T, relation: Relation, parentEntityId: string | number | (string | number)[], targetTable: PgTable<any>, parentTable: PgTable<any>, parentIdColumn: AnyPgColumn, targetIdColumn: AnyPgColumn, registry: PostgresCollectionRegistry, additionalFilters?: SQL[]): T;
|
|
87
|
+
/**
|
|
88
|
+
* Build count query for relations with proper joins and conditions
|
|
89
|
+
*/
|
|
90
|
+
static buildRelationCountQuery<T extends DrizzleDynamicQuery>(baseCountQuery: T, relation: Relation, parentEntityId: string | number, targetTable: PgTable<any>, parentTable: PgTable<any>, parentIdColumn: AnyPgColumn, targetIdColumn: AnyPgColumn, registry: PostgresCollectionRegistry, additionalFilters?: SQL[]): T;
|
|
91
|
+
/**
|
|
92
|
+
* Build join path conditions for count queries
|
|
93
|
+
*/
|
|
94
|
+
private static buildJoinPathCountQuery;
|
|
95
|
+
/**
|
|
96
|
+
* Build junction table conditions for count queries
|
|
97
|
+
*/
|
|
98
|
+
private static buildJunctionCountQuery;
|
|
99
|
+
/**
|
|
100
|
+
* Build inverse junction table conditions for count queries
|
|
101
|
+
*/
|
|
102
|
+
private static buildInverseJunctionCountQuery;
|
|
103
|
+
/**
|
|
104
|
+
* Helper method to extract table names from columns
|
|
105
|
+
*/
|
|
106
|
+
static getTableNamesFromColumns(columns: string | string[]): string[];
|
|
107
|
+
/**
|
|
108
|
+
* Helper method to extract column names from columns
|
|
109
|
+
*/
|
|
110
|
+
static getColumnNamesFromColumns(columns: string | string[]): string[];
|
|
111
|
+
/**
|
|
112
|
+
* Find the corresponding junction table for an inverse many-to-many relation
|
|
113
|
+
*/
|
|
114
|
+
private static findCorrespondingJunctionTable;
|
|
115
|
+
/**
|
|
116
|
+
* Build vector similarity search expressions for pgvector.
|
|
117
|
+
*
|
|
118
|
+
* Returns:
|
|
119
|
+
* - `orderBy`: SQL expression to ORDER BY distance (ascending = closest first)
|
|
120
|
+
* - `filter`: optional WHERE clause for distance threshold
|
|
121
|
+
* - `distanceSelect`: SQL expression for selecting the distance as `_distance`
|
|
122
|
+
*/
|
|
123
|
+
static buildVectorSearchConditions(table: PgTable<any>, vectorSearch: {
|
|
124
|
+
property: string;
|
|
125
|
+
vector: number[];
|
|
126
|
+
distance?: "cosine" | "l2" | "inner_product";
|
|
127
|
+
threshold?: number;
|
|
128
|
+
}): {
|
|
129
|
+
orderBy: SQL;
|
|
130
|
+
filter?: SQL;
|
|
131
|
+
distanceSelect: SQL;
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Alias for DrizzleConditionBuilder for consistent naming with other database implementations.
|
|
136
|
+
* This allows code to use PostgresConditionBuilder alongside future MongoConditionBuilder, etc.
|
|
137
|
+
*/
|
|
138
|
+
export declare const PostgresConditionBuilder: typeof DrizzleConditionBuilder;
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Patches all PgArray columns on the given tables to handle NULL values safely.
|
|
3
|
+
*
|
|
4
|
+
* Drizzle ORM's `PgArray.mapFromDriverValue` calls `value.map(...)` without
|
|
5
|
+
* guarding against `null`. When a PostgreSQL native array column (`text[]`,
|
|
6
|
+
* `integer[]`, etc.) contains NULL, the pg driver returns `null` in JavaScript,
|
|
7
|
+
* and `null.map(...)` throws `TypeError: value.map is not a function`.
|
|
8
|
+
*
|
|
9
|
+
* This function walks every column of every registered table and, for any
|
|
10
|
+
* `PgArray` column, wraps its `mapFromDriverValue` to return `null` when the
|
|
11
|
+
* database value is nullish.
|
|
12
|
+
*
|
|
13
|
+
* This is a workaround for a known Drizzle ORM issue. Should be removed once
|
|
14
|
+
* Drizzle handles nullable arrays natively.
|
|
15
|
+
*/
|
|
16
|
+
export declare function patchPgArrayNullSafety(tables: Record<string, unknown>): void;
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared PostgreSQL error extraction and user-friendly message formatting.
|
|
3
|
+
*
|
|
4
|
+
* Drizzle wraps native PG errors in a `.cause` chain. These utilities
|
|
5
|
+
* unwrap that chain to get the real PostgreSQL error (identified by a
|
|
6
|
+
* 5-character alphanumeric `code` such as `42P01`) and translate it into
|
|
7
|
+
* a message that is safe and helpful to show to end-users.
|
|
8
|
+
*/
|
|
9
|
+
/** Shape of PostgreSQL errors with diagnostic metadata. */
|
|
10
|
+
export interface PostgresError extends Error {
|
|
11
|
+
code?: string;
|
|
12
|
+
detail?: string;
|
|
13
|
+
hint?: string;
|
|
14
|
+
constraint?: string;
|
|
15
|
+
column?: string;
|
|
16
|
+
table?: string;
|
|
17
|
+
dataType?: string;
|
|
18
|
+
cause?: unknown;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Extract the underlying PostgreSQL error from a Drizzle wrapper.
|
|
22
|
+
* Drizzle wraps PG errors in a `cause` property — this function
|
|
23
|
+
* recursively walks the chain until it finds an object with a PG
|
|
24
|
+
* error code (5-char alphanumeric, e.g. `42P01`).
|
|
25
|
+
*/
|
|
26
|
+
export declare function extractPgError(error: unknown): PostgresError | null;
|
|
27
|
+
/**
|
|
28
|
+
* Walk the error cause chain and return the deepest meaningful message.
|
|
29
|
+
*/
|
|
30
|
+
export declare function extractCauseMessage(error: unknown): string | null;
|
|
31
|
+
/**
|
|
32
|
+
* Detect whether an error is specifically a role-switching permission failure
|
|
33
|
+
* (e.g. "permission denied to set role" or "must be member of role"),
|
|
34
|
+
* as opposed to a table-level permission denial.
|
|
35
|
+
*
|
|
36
|
+
* This is used by the backend driver to auto-disable role switching when the
|
|
37
|
+
* connection user lacks SET ROLE privileges, rather than surfacing a confusing
|
|
38
|
+
* error to the Studio SQL Editor user.
|
|
39
|
+
*/
|
|
40
|
+
export declare function isRoleSwitchingPermissionError(error: unknown): boolean;
|
|
41
|
+
/**
|
|
42
|
+
* Translate a raw PostgreSQL error into a user-friendly message.
|
|
43
|
+
*
|
|
44
|
+
* @param pgError - The extracted PostgreSQL error (from {@link extractPgError})
|
|
45
|
+
* @param context - A human-readable context string (e.g. collection slug or path)
|
|
46
|
+
* @returns An object with a `message` safe for the client and the PG `code`.
|
|
47
|
+
*/
|
|
48
|
+
export declare function pgErrorToFriendlyMessage(pgError: PostgresError, context: string): {
|
|
49
|
+
message: string;
|
|
50
|
+
code: string;
|
|
51
|
+
};
|
|
52
|
+
/**
|
|
53
|
+
* Sanitize any error into a message safe and helpful for the client.
|
|
54
|
+
*
|
|
55
|
+
* Extracts the PG error from the Drizzle cause chain when possible;
|
|
56
|
+
* falls back to a generic message that doesn't leak SQL.
|
|
57
|
+
*
|
|
58
|
+
* @param error - The raw caught error
|
|
59
|
+
* @param context - A human-readable context string (e.g. collection path)
|
|
60
|
+
* @returns An object with `message` (user-friendly) and optional `code` (PG code).
|
|
61
|
+
*/
|
|
62
|
+
export declare function sanitizeErrorForClient(error: unknown, context: string): {
|
|
63
|
+
message: string;
|
|
64
|
+
code?: string;
|
|
65
|
+
};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Table Classification Utility
|
|
3
|
+
*
|
|
4
|
+
* Re-exports shared classification logic from @rebasepro/common.
|
|
5
|
+
* This module exists for backward compatibility — prefer importing directly
|
|
6
|
+
* from @rebasepro/common in new code.
|
|
7
|
+
*/
|
|
8
|
+
export { type TableCategory, REBASE_INTERNAL_SCHEMAS, REBASE_INTERNAL_PREFIXES, classifyTable, isRebaseInternalTable, detectJunctionTables, JUNCTION_TABLES_SQL, } from "@rebasepro/common";
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { RealtimeService } from "./services/realtimeService";
|
|
2
|
+
import { PostgresBackendDriver } from "./PostgresBackendDriver";
|
|
3
|
+
import type { AuthAdapter } from "@rebasepro/types";
|
|
4
|
+
import { Server } from "http";
|
|
5
|
+
/** Minimal subset of RebaseAuthConfig used by the WebSocket layer. */
|
|
6
|
+
interface WsAuthConfig {
|
|
7
|
+
requireAuth?: boolean;
|
|
8
|
+
jwtSecret?: string;
|
|
9
|
+
}
|
|
10
|
+
export declare function createPostgresWebSocket(server: Server, realtimeService: RealtimeService, driver: PostgresBackendDriver, authConfig?: WsAuthConfig, authAdapter?: AuthAdapter): void;
|
|
11
|
+
export {};
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rebasepro/server-postgresql",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.8.0",
|
|
5
5
|
"description": "PostgreSQL data source backend implementation for Rebase with Drizzle ORM",
|
|
6
6
|
"funding": {
|
|
7
7
|
"url": "https://github.com/sponsors/rebaseco"
|
|
@@ -29,14 +29,6 @@
|
|
|
29
29
|
"backend",
|
|
30
30
|
"rebase"
|
|
31
31
|
],
|
|
32
|
-
"scripts": {
|
|
33
|
-
"watch": "vite build --watch",
|
|
34
|
-
"build": "vite build && tsc --emitDeclarationOnly -p tsconfig.prod.json",
|
|
35
|
-
"test:lint": "eslint \"src/**\" --quiet",
|
|
36
|
-
"test": "jest --passWithNoTests",
|
|
37
|
-
"test:e2e": "vitest run --config vitest.e2e.config.ts",
|
|
38
|
-
"clean": "rm -rf dist && find ./src -name '*.js' -type f | xargs rm -f"
|
|
39
|
-
},
|
|
40
32
|
"jest": {
|
|
41
33
|
"transform": {
|
|
42
34
|
"^.+\\.tsx?$": "ts-jest"
|
|
@@ -74,11 +66,7 @@
|
|
|
74
66
|
"./package.json": "./package.json"
|
|
75
67
|
},
|
|
76
68
|
"dependencies": {
|
|
77
|
-
"@
|
|
78
|
-
"@rebasepro/sdk-generator": "workspace:*",
|
|
79
|
-
"@rebasepro/server-core": "workspace:*",
|
|
80
|
-
"@rebasepro/types": "workspace:*",
|
|
81
|
-
"@rebasepro/utils": "workspace:*",
|
|
69
|
+
"@ariga/atlas": "^1.2.2",
|
|
82
70
|
"arg": "^5.0.2",
|
|
83
71
|
"chalk": "^4.1.2",
|
|
84
72
|
"chokidar": "5.0.0",
|
|
@@ -87,10 +75,14 @@
|
|
|
87
75
|
"execa": "^9.6.1",
|
|
88
76
|
"hono": "^4.12.25",
|
|
89
77
|
"pg": "^8.21.0",
|
|
90
|
-
"ws": "^8.21.0"
|
|
78
|
+
"ws": "^8.21.0",
|
|
79
|
+
"@rebasepro/sdk-generator": "0.8.0",
|
|
80
|
+
"@rebasepro/common": "0.8.0",
|
|
81
|
+
"@rebasepro/server-core": "0.8.0",
|
|
82
|
+
"@rebasepro/utils": "0.8.0",
|
|
83
|
+
"@rebasepro/types": "0.8.0"
|
|
91
84
|
},
|
|
92
85
|
"devDependencies": {
|
|
93
|
-
"@ariga/atlas": "^1.2.2",
|
|
94
86
|
"@types/jest": "^30.0.0",
|
|
95
87
|
"@types/node": "^25.9.3",
|
|
96
88
|
"@types/pg": "^8.20.0",
|
|
@@ -105,5 +97,13 @@
|
|
|
105
97
|
"gitHead": "d935eefa5aa8d1009a2398cfac2c1e4ee9aeb6b6",
|
|
106
98
|
"publishConfig": {
|
|
107
99
|
"access": "public"
|
|
100
|
+
},
|
|
101
|
+
"scripts": {
|
|
102
|
+
"watch": "vite build --watch",
|
|
103
|
+
"build": "vite build && tsc --emitDeclarationOnly -p tsconfig.prod.json",
|
|
104
|
+
"test:lint": "eslint \"src/**\" --quiet",
|
|
105
|
+
"test": "jest --passWithNoTests",
|
|
106
|
+
"test:e2e": "vitest run --config vitest.e2e.config.ts",
|
|
107
|
+
"clean": "rm -rf dist && find ./src -name '*.js' -type f | xargs rm -f"
|
|
108
108
|
}
|
|
109
|
-
}
|
|
109
|
+
}
|