@rebasepro/server-postgresql 0.6.1 → 0.7.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.
Files changed (75) hide show
  1. package/package.json +24 -18
  2. package/src/PostgresBackendDriver.ts +65 -44
  3. package/src/PostgresBootstrapper.ts +34 -2
  4. package/src/auth/ensure-tables.ts +56 -1
  5. package/src/auth/services.ts +94 -1
  6. package/src/cli-errors.ts +162 -0
  7. package/src/cli-helpers.ts +183 -0
  8. package/src/cli.ts +198 -251
  9. package/src/schema/auth-default-policies.ts +90 -0
  10. package/src/schema/auth-schema.ts +25 -2
  11. package/src/schema/doctor.ts +2 -4
  12. package/src/schema/generate-drizzle-schema-logic.ts +4 -3
  13. package/src/schema/generate-drizzle-schema.ts +3 -5
  14. package/src/schema/generate-postgres-ddl-logic.ts +524 -0
  15. package/src/schema/generate-postgres-ddl.ts +116 -0
  16. package/src/services/EntityPersistService.ts +10 -8
  17. package/src/services/entityService.ts +28 -3
  18. package/src/utils/pg-error-utils.ts +16 -0
  19. package/src/utils/table-classification.ts +16 -0
  20. package/src/websocket.ts +9 -0
  21. package/test/auth-default-policies.test.ts +89 -0
  22. package/test/cli-helpers-extended.test.ts +324 -0
  23. package/test/cli-helpers.test.ts +59 -0
  24. package/test/connection.test.ts +292 -0
  25. package/test/databasePoolManager.test.ts +289 -0
  26. package/test/doctor-extended.test.ts +443 -0
  27. package/test/e2e/db-e2e.test.ts +293 -0
  28. package/test/e2e/pg-setup.ts +79 -0
  29. package/test/entity-persist-composite-keys.test.ts +451 -0
  30. package/test/generate-postgres-ddl-edge-cases.test.ts +716 -0
  31. package/test/generate-postgres-ddl.test.ts +300 -0
  32. package/test/mfa-service.test.ts +544 -0
  33. package/test/pg-error-utils.test.ts +50 -1
  34. package/test/realtimeService-channels.test.ts +696 -0
  35. package/test/unmapped-tables-safety.test.ts +55 -342
  36. package/vitest.e2e.config.ts +10 -0
  37. package/build-errors.txt +0 -37
  38. package/dist/PostgresAdapter.d.ts +0 -6
  39. package/dist/PostgresBackendDriver.d.ts +0 -110
  40. package/dist/PostgresBootstrapper.d.ts +0 -46
  41. package/dist/auth/ensure-tables.d.ts +0 -10
  42. package/dist/auth/services.d.ts +0 -231
  43. package/dist/cli.d.ts +0 -1
  44. package/dist/collections/PostgresCollectionRegistry.d.ts +0 -47
  45. package/dist/connection.d.ts +0 -65
  46. package/dist/data-transformer.d.ts +0 -55
  47. package/dist/databasePoolManager.d.ts +0 -20
  48. package/dist/history/HistoryService.d.ts +0 -71
  49. package/dist/history/ensure-history-table.d.ts +0 -7
  50. package/dist/index.d.ts +0 -14
  51. package/dist/index.es.js +0 -10803
  52. package/dist/index.es.js.map +0 -1
  53. package/dist/interfaces.d.ts +0 -18
  54. package/dist/schema/auth-schema.d.ts +0 -2149
  55. package/dist/schema/doctor-cli.d.ts +0 -2
  56. package/dist/schema/doctor.d.ts +0 -52
  57. package/dist/schema/generate-drizzle-schema-logic.d.ts +0 -2
  58. package/dist/schema/generate-drizzle-schema.d.ts +0 -1
  59. package/dist/schema/introspect-db-inference.d.ts +0 -5
  60. package/dist/schema/introspect-db-logic.d.ts +0 -118
  61. package/dist/schema/introspect-db.d.ts +0 -1
  62. package/dist/schema/test-schema.d.ts +0 -24
  63. package/dist/services/BranchService.d.ts +0 -47
  64. package/dist/services/EntityFetchService.d.ts +0 -214
  65. package/dist/services/EntityPersistService.d.ts +0 -40
  66. package/dist/services/RelationService.d.ts +0 -98
  67. package/dist/services/entity-helpers.d.ts +0 -38
  68. package/dist/services/entityService.d.ts +0 -110
  69. package/dist/services/index.d.ts +0 -4
  70. package/dist/services/realtimeService.d.ts +0 -220
  71. package/dist/types.d.ts +0 -3
  72. package/dist/utils/drizzle-conditions.d.ts +0 -138
  73. package/dist/utils/pg-array-null-patch.d.ts +0 -16
  74. package/dist/utils/pg-error-utils.d.ts +0 -55
  75. package/dist/websocket.d.ts +0 -11
@@ -1,110 +0,0 @@
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): 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
- }
@@ -1,4 +0,0 @@
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";
@@ -1,220 +0,0 @@
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 DELETED
@@ -1,3 +0,0 @@
1
- import type { PgTable, AnyPgColumn } from "drizzle-orm/pg-core";
2
- /** Drizzle PgTable with column access by name. Runtime Drizzle tables satisfy this shape. */
3
- export type RebasePgTable = PgTable & Record<string, AnyPgColumn>;
@@ -1,138 +0,0 @@
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;
@@ -1,16 +0,0 @@
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;
@@ -1,55 +0,0 @@
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
- * Translate a raw PostgreSQL error into a user-friendly message.
33
- *
34
- * @param pgError - The extracted PostgreSQL error (from {@link extractPgError})
35
- * @param context - A human-readable context string (e.g. collection slug or path)
36
- * @returns An object with a `message` safe for the client and the PG `code`.
37
- */
38
- export declare function pgErrorToFriendlyMessage(pgError: PostgresError, context: string): {
39
- message: string;
40
- code: string;
41
- };
42
- /**
43
- * Sanitize any error into a message safe and helpful for the client.
44
- *
45
- * Extracts the PG error from the Drizzle cause chain when possible;
46
- * falls back to a generic message that doesn't leak SQL.
47
- *
48
- * @param error - The raw caught error
49
- * @param context - A human-readable context string (e.g. collection path)
50
- * @returns An object with `message` (user-friendly) and optional `code` (PG code).
51
- */
52
- export declare function sanitizeErrorForClient(error: unknown, context: string): {
53
- message: string;
54
- code?: string;
55
- };
@@ -1,11 +0,0 @@
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 {};