All files / src/services postgresDataDriver.ts

26.64% Statements 73/274
10.21% Branches 14/137
40% Functions 26/65
27.2% Lines 68/250

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981  3x         3x 3x                                       3x     3x 52x 52x                       52x           52x     52x   52x   52x     52x 52x 52x 52x 52x                                                                       2x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           31x       3x 31x 31x           31x     31x 31x           19x   19x 21x 21x 4x 4x     21x 21x 17x   21x 10x   21x   21x             21x 21x   21x 21x 21x   21x     18x 6x 6x             1x       18x       11x               4x 4x 4x 4x 2x   4x       3x               1x       7x       1x                   1x       1x                 1x       1x       1x       1x       1x       1x      
// import { NodePgDatabase } from "drizzle-orm/node-postgres";
import { EntityService } from "../db/entityService";
import { RealtimeService } from "./realtimeService";
import { DatabasePoolManager } from "./databasePoolManager";
import { DrizzleClient } from "../db/interfaces";
import { User } from "@rebasepro/types";
import { sql as drizzleSql } from "drizzle-orm";
import { buildPropertyCallbacks, mergeDeep } from "@rebasepro/common";
import { BackendCollectionRegistry } from "../collections/BackendCollectionRegistry";
import {
    DataDriver,
    DeleteEntityProps,
    Entity,
    EntityCollection,
    FetchCollectionProps,
    FetchEntityProps,
    ListenCollectionProps,
    ListenEntityProps,
    RebaseCallContext,
    SaveEntityProps,
    RebaseData,
    TableMetadata,
    TableColumnInfo,
    TableForeignKeyInfo,
    TableJunctionInfo,
    TablePolicyInfo
} from "@rebasepro/types";
import { buildRebaseData } from "@rebasepro/common";
import { HistoryService } from "../history/HistoryService";
 
export class PostgresDataDriver implements DataDriver {
    key = "postgres";
    initialised = true;
 
    public entityService: EntityService;
    public realtimeService: RealtimeService;
    public historyService?: HistoryService;
    public user?: User;
    public data: RebaseData;
 
    /**
     * When true, realtime notifications are deferred until after the
     * wrapping transaction commits.  Set by `withAuth` → `withTransaction`.
     */
    _deferNotifications = false;
    _pendingNotifications: Array<{
        path: string;
        entityId: string;
        entity: Entity | null;
        databaseId?: string;
    }> = [];
 
    constructor(
        public db: DrizzleClient,
        realtimeService: RealtimeService,
        public readonly registry: BackendCollectionRegistry,
        user?: User,
        public poolManager?: DatabasePoolManager,
        historyService?: HistoryService
    ) {
        this.entityService = new EntityService(db, registry);
        this.realtimeService = realtimeService;
        this.historyService = historyService;
        this.user = user;
        this.data = buildRebaseData(this);
    }
 
 
 
    private resolveCollectionCallbacks<M extends Record<string, any>>(collection: EntityCollection<M> | undefined, path: string) {
        Iif (!collection && !path) return { collection: undefined, callbacks: undefined, propertyCallbacks: undefined };
        const registryCollection = this.registry.getCollectionByPath(path);
        const resolvedCollection = registryCollection
            ? { ...collection, ...registryCollection } as EntityCollection<M>
            : collection as EntityCollection<M>;
 
        const callbacks = resolvedCollection?.callbacks;
        const properties = resolvedCollection?.properties;
        let propertyCallbacks;
        Iif (properties) {
            propertyCallbacks = buildPropertyCallbacks(properties);
        }
        return {
            collection: resolvedCollection,
            callbacks,
            propertyCallbacks
        };
    }
 
    async fetchCollection<M extends Record<string, any>>({
        path,
        collection,
        filter,
        limit,
        startAfter,
        orderBy,
        searchString,
        order
    }: FetchCollectionProps<M>): Promise<Entity<M>[]> {
 
        const entities = await this.entityService.fetchCollection<M>(path, {
            filter,
            orderBy,
            order,
            limit,
            startAfter: startAfter as Record<string, unknown> | undefined,
            databaseId: collection?.databaseId,
            searchString
        });
 
        const { collection: resolvedCollection, callbacks, propertyCallbacks } = this.resolveCollectionCallbacks(collection, path);
 
        Iif (callbacks?.afterRead || propertyCallbacks?.afterRead) {
            const contextForCallback = {
                user: this.user,
                driver: this,
                data: this.data
            } as unknown as RebaseCallContext; // Backend context
            return Promise.all(entities.map(async (entity) => {
                let fetched = entity;
                Iif (callbacks?.afterRead) {
                    fetched = await callbacks.afterRead({
                        collection: resolvedCollection as EntityCollection<M>,
                        path,
                        entity: fetched,
                        context: contextForCallback
                    }) ?? fetched;
                }
                Iif (propertyCallbacks?.afterRead) {
                    fetched = await propertyCallbacks.afterRead({
                        collection: resolvedCollection as EntityCollection<M>,
                        path,
                        entity: fetched,
                        context: contextForCallback
                    }) ?? fetched;
                }
                return fetched;
            }));
        }
 
        return entities;
    }
 
    listenCollection<M extends Record<string, any>>({
        path,
        collection,
        filter,
        limit,
        startAfter,
        orderBy,
        searchString,
        order,
        onUpdate,
        onError
    }: ListenCollectionProps<M>): () => void {
 
        const subscriptionId = this.generateSubscriptionId();
 
        // Type-adapter wrapper: RealtimeService expects a union callback signature
        const callbackWrapper = (entities: Entity<M>[]) => {
            onUpdate(entities);
        };
 
        // Store the subscription in RealtimeService properly using the new public method
        this.realtimeService.registerDataDriverSubscription(subscriptionId, {
            clientId: "driver",
            type: "collection" as const,
            path,
            collectionRequest: {
                filter,
                orderBy,
                order,
                limit,
                startAfter: startAfter as Record<string, unknown> | undefined,
                databaseId: collection?.databaseId,
                searchString
            }
        });
 
        // Store the callback for this subscription
        this.realtimeService.addSubscriptionCallback(subscriptionId, callbackWrapper as (data: Entity | Entity[] | null) => void);
 
        // Send initial data immediately
        this.fetchCollection({
            path: path,
            collection,
            filter,
            limit,
            startAfter,
            orderBy,
            searchString,
            order
        }).then(entities => {
            callbackWrapper(entities);
        }).catch(error => {
            Iif (onError) onError(error);
        });
 
        return () => {
            this.realtimeService.removeSubscriptionCallback(subscriptionId);
            this.realtimeService.subscriptions.delete(subscriptionId);
        };
    }
 
    async fetchEntity<M extends Record<string, any>>({
        path,
        entityId,
        databaseId,
        collection
    }: FetchEntityProps<M>): Promise<Entity<M> | undefined> {
        let entity = await this.entityService.fetchEntity<M>(
            path,
            entityId,
            databaseId || collection?.databaseId
        );
 
        const { collection: resolvedCollection, callbacks, propertyCallbacks } = this.resolveCollectionCallbacks(collection, path);
 
        Iif (entity && (callbacks?.afterRead || propertyCallbacks?.afterRead)) {
            const contextForCallback = {
                user: this.user,
                driver: this,
                data: this.data
            } as unknown as RebaseCallContext; // Backend context
            Iif (callbacks?.afterRead) {
                entity = await callbacks.afterRead({
                    collection: resolvedCollection as EntityCollection<M>,
                    path,
                    entity,
                    context: contextForCallback
                }) ?? entity;
            }
            Iif (propertyCallbacks?.afterRead) {
                entity = await propertyCallbacks.afterRead({
                    collection: resolvedCollection as EntityCollection<M>,
                    path,
                    entity,
                    context: contextForCallback
                }) ?? entity;
            }
        }
 
        return entity;
    }
 
    listenEntity<M extends Record<string, any>>({
        path,
        entityId,
        collection,
        onUpdate,
        onError
    }: ListenEntityProps<M>): () => void {
 
        const subscriptionId = this.generateSubscriptionId();
        const callbackWrapper = (entity: Entity<M> | null) => {
            Iif (entity)
                onUpdate(entity);
        };
 
        // Register the subscription with the RealtimeService
        this.realtimeService.registerDataDriverSubscription(subscriptionId, {
            clientId: "driver",
            type: "entity" as const,
            path,
            entityId
        });
 
        // Store the callback for this subscription
        this.realtimeService.addSubscriptionCallback(subscriptionId, callbackWrapper as (data: Entity | Entity[] | null) => void);
 
        // Fetch initial data
        this.fetchEntity({
            path,
            entityId,
            collection
        })
            .then(entity => {
                Iif (entity) onUpdate(entity);
            })
            .catch(error => {
                Iif (onError) onError(error as Error);
            });
 
        // Return the unsubscribe function
        return () => {
            this.realtimeService.removeSubscriptionCallback(subscriptionId);
            this.realtimeService.subscriptions.delete(subscriptionId);
        };
    }
 
    async saveEntity<M extends Record<string, any>>({
        path,
        entityId,
        values,
        collection,
        status
    }: SaveEntityProps<M>): Promise<Entity<M>> {
 
        const { collection: resolvedCollection, callbacks, propertyCallbacks } = this.resolveCollectionCallbacks(collection, path);
 
        let updatedValues = values;
        const contextForCallback = {
            user: this.user,
            driver: this,
            data: this.data
        } as unknown as RebaseCallContext;
 
        // Fetch previous values for callbacks AND history recording
        let previousValuesForHistory: Partial<Entity<M>["values"]> | undefined;
        Iif (status === "existing" && entityId) {
            const existing = await this.entityService.fetchEntity<M>(path, entityId, resolvedCollection?.databaseId);
            Iif (existing) {
                previousValuesForHistory = existing.values as Partial<Entity<M>["values"]>;
            }
        }
 
        Iif (callbacks?.beforeSave || propertyCallbacks?.beforeSave) {
            Iif (callbacks?.beforeSave) {
                const result = await callbacks.beforeSave({
                    collection: resolvedCollection as EntityCollection<M>,
                    path,
                    entityId,
                    values: updatedValues,
                    previousValues: previousValuesForHistory,
                    status,
                    context: contextForCallback
                });
                Iif (result) updatedValues = mergeDeep(updatedValues, result);
            }
 
            Iif (propertyCallbacks?.beforeSave) {
                const result = await propertyCallbacks.beforeSave({
                    collection: resolvedCollection as EntityCollection<M>,
                    path,
                    entityId,
                    values: updatedValues,
                    previousValues: previousValuesForHistory,
                    status,
                    context: contextForCallback
                });
                Iif (result) updatedValues = mergeDeep(updatedValues, result);
            }
 
        }
 
        try {
            let savedEntity = await this.entityService.saveEntity<M>(
                path,
                updatedValues,
                entityId,
                resolvedCollection?.databaseId
            );
 
            Iif (savedEntity && (callbacks?.afterRead || propertyCallbacks?.afterRead)) {
                Iif (callbacks?.afterRead) {
                    savedEntity = await callbacks.afterRead({
                        collection: resolvedCollection as EntityCollection<M>,
                        path,
                        entity: savedEntity,
                        context: contextForCallback
                    }) ?? savedEntity;
                }
                Iif (propertyCallbacks?.afterRead) {
                    savedEntity = await propertyCallbacks.afterRead({
                        collection: resolvedCollection as EntityCollection<M>,
                        path,
                        entity: savedEntity,
                        context: contextForCallback
                    }) ?? savedEntity;
                }
            }
 
            Iif (callbacks?.afterSave || propertyCallbacks?.afterSave) {
                Iif (callbacks?.afterSave) {
                    await callbacks.afterSave({
                        collection: resolvedCollection as EntityCollection<M>,
                        path,
                        entityId: savedEntity.id,
                        values: updatedValues,
                        previousValues: previousValuesForHistory,
                        status,
                        context: contextForCallback
                    });
                }
                Iif (propertyCallbacks?.afterSave) {
                    await propertyCallbacks.afterSave({
                        collection: resolvedCollection as EntityCollection<M>,
                        path,
                        entityId: savedEntity.id,
                        values: updatedValues,
                        previousValues: previousValuesForHistory,
                        status,
                        context: contextForCallback
                    });
                }
            }
 
            // Record entity history (fire-and-forget, never blocks the save)
            Iif (this.historyService && resolvedCollection?.history) {
                this.historyService.recordHistory({
                    tableName: path,
                    entityId: savedEntity.id.toString(),
                    action: status === "new" ? "create" : "update",
                    values: savedEntity.values as Record<string, unknown>,
                    previousValues: previousValuesForHistory as Record<string, unknown> | undefined,
                    updatedBy: this.user?.uid
                });
            }
 
            // Notify real-time subscribers (deferred if inside a transaction)
            if (this._deferNotifications) {
                this._pendingNotifications.push({
                    path,
                    entityId: savedEntity.id.toString(),
                    entity: savedEntity,
                    databaseId: resolvedCollection?.databaseId
                });
            } else {
                await this.realtimeService.notifyEntityUpdate(
                    path,
                    savedEntity.id.toString(),
                    savedEntity,
                    resolvedCollection?.databaseId
                );
            }
 
            return savedEntity;
        } catch (error) {
            Iif (callbacks?.afterSaveError || propertyCallbacks?.afterSaveError) {
                Iif (callbacks?.afterSaveError) {
                    await callbacks.afterSaveError({
                        collection: resolvedCollection as EntityCollection<M>,
                        path,
                        entityId: entityId || "unknown",
                        values: updatedValues,
                        previousValues: undefined,
                        status,
                        context: contextForCallback
                    });
                }
                Iif (propertyCallbacks?.afterSaveError) {
                    await propertyCallbacks.afterSaveError({
                        collection: resolvedCollection as EntityCollection<M>,
                        path,
                        entityId: entityId || "unknown",
                        values: updatedValues,
                        previousValues: undefined,
                        status,
                        context: contextForCallback
                    });
                }
            }
            throw error;
        }
    }
 
    async deleteEntity<M extends Record<string, any>>({
        entity,
        collection
    }: DeleteEntityProps<M>): Promise<void> {
 
        // Resolve from backend registry to restore callbacks lost during WebSocket serialization
        const { collection: resolvedCollection, callbacks, propertyCallbacks } = this.resolveCollectionCallbacks(collection, entity.path);
 
        const contextForCallback = {
            user: this.user,
            driver: this,
            data: this.data
        } as unknown as RebaseCallContext;
 
        Iif (callbacks?.beforeDelete || propertyCallbacks?.beforeDelete) {
            Iif (callbacks?.beforeDelete) {
                await callbacks.beforeDelete({
                    collection: resolvedCollection as EntityCollection<M>,
                    path: entity.path,
                    entityId: entity.id,
                    entity,
                    context: contextForCallback
                });
            }
            Iif (propertyCallbacks?.beforeDelete) {
                await propertyCallbacks.beforeDelete({
                    collection: resolvedCollection as EntityCollection<M>,
                    path: entity.path,
                    entityId: entity.id,
                    entity,
                    context: contextForCallback
                });
            }
        }
 
        await this.entityService.deleteEntity(
            entity.path,
            entity.id,
            entity.databaseId || resolvedCollection?.databaseId
        );
 
        Iif (callbacks?.afterDelete || propertyCallbacks?.afterDelete) {
            Iif (callbacks?.afterDelete) {
                await callbacks.afterDelete({
                    collection: resolvedCollection as EntityCollection<M>,
                    path: entity.path,
                    entityId: entity.id,
                    entity,
                    context: contextForCallback
                });
            }
            Iif (propertyCallbacks?.afterDelete) {
                await propertyCallbacks.afterDelete({
                    collection: resolvedCollection as EntityCollection<M>,
                    path: entity.path,
                    entityId: entity.id,
                    entity,
                    context: contextForCallback
                });
            }
        }
 
        // Record delete history (fire-and-forget)
        Iif (this.historyService && resolvedCollection?.history) {
            this.historyService.recordHistory({
                tableName: entity.path,
                entityId: entity.id.toString(),
                action: "delete",
                values: entity.values as Record<string, unknown>,
                updatedBy: this.user?.uid
            });
        }
 
        // Notify real-time subscribers (deferred if inside a transaction)
        if (this._deferNotifications) {
            this._pendingNotifications.push({
                path: entity.path,
                entityId: entity.id.toString(),
                entity: null,
                databaseId: entity.databaseId || resolvedCollection?.databaseId
            });
        } else {
            await this.realtimeService.notifyEntityUpdate(
                entity.path,
                entity.id.toString(),
                null,
                entity.databaseId || resolvedCollection?.databaseId
            );
        }
 
    }
 
    async checkUniqueField(
        path: string,
        name: string,
        value: unknown,
        entityId?: string,
        collection?: EntityCollection
    ): Promise<boolean> {
        return this.entityService.checkUniqueField(
            path,
            name,
            value,
            entityId,
            collection?.databaseId
        );
    }
 
 
    async countEntities<M extends Record<string, any>>({
        path,
        collection,
        filter
    }: FetchCollectionProps<M>): Promise<number> {
        return this.entityService.countEntities(
            path,
            { filter }
        );
    }
 
    private getTargetDb(databaseName?: string): DrizzleClient {
        Iif (!databaseName || databaseName === this.poolManager?.defaultDatabaseName) {
            return this.db;
        }
        Iif (!this.poolManager) {
            throw new Error(
                "Cross-database execution requires adminConnectionString to be configured in the backend."
            );
        }
        return this.poolManager.getDrizzle(databaseName);
    }
 
    async executeSql(sqlText: string, options?: { database?: string, role?: string }): Promise<Record<string, unknown>[]> {
        Iif (!options?.database && !options?.role) {
            return this.entityService.executeSql(sqlText);
        }
 
        const targetDb = this.getTargetDb(options?.database);
 
        try {
            Iif (options?.role) {
                const safeRole = options.role.replace(/"/g, '""');
                return await targetDb.transaction(async (tx) => {
                    await tx.execute(drizzleSql.raw(`SET LOCAL ROLE "${safeRole}"`));
                    const result = await tx.execute(drizzleSql.raw(sqlText));
                    return result.rows as Record<string, unknown>[];
                });
            }
 
            const result = await targetDb.execute(drizzleSql.raw(sqlText));
            return result.rows as Record<string, unknown>[];
        } catch (error: unknown) {
            const msg = error instanceof Error ? error.message : String(error);
            // Provide a user-friendly message for connection/auth errors
            Iif (msg.includes("pg_hba.conf") || msg.includes("no encryption") || msg.includes("connection refused")) {
                const dbName = options?.database || "unknown";
                throw new Error(`Cannot connect to database "${dbName}": the server rejected the connection. This database may require SSL or is not accessible from this host.`);
            }
            throw error;
        }
    }
 
    async fetchAvailableDatabases(): Promise<string[]> {
        // Exclude template databases, Cloud SQL internal databases, and the default 'postgres' system db
        const result = await this.executeSql(
            `SELECT datname FROM pg_database 
             WHERE datistemplate = false 
             AND datname NOT IN ('postgres', 'cloudsqladmin', '_cloudsqladmin')
             ORDER BY datname;`
        );
        const databases = result.map((r: Record<string, unknown>) => r.datname as string);
        // Ensure the current connected database is always first in the list
        const currentDb = this.poolManager?.defaultDatabaseName;
        if (currentDb && !databases.includes(currentDb)) {
            databases.unshift(currentDb);
        } else Iif (currentDb) {
            // Move it to the front
            const idx = databases.indexOf(currentDb);
            Iif (idx > 0) {
                databases.splice(idx, 1);
                databases.unshift(currentDb);
            }
        }
        return databases;
    }
 
    async fetchAvailableRoles(): Promise<string[]> {
        const result = await this.executeSql(`SELECT rolname FROM pg_roles;`);
        return result.map((r: Record<string, unknown>) => r.rolname as string);
    }
 
    async fetchCurrentDatabase(): Promise<string | undefined> {
        return this.poolManager?.defaultDatabaseName;
    }
 
    /**
     * Fetch public tables that are not yet mapped to a collection.
     * Excludes internal tables (_rebase_*, _auth_*, auth tables, etc.)
     * and junction/connection tables used for many-to-many relations.
     */
    async fetchUnmappedTables(mappedPaths?: string[]): Promise<string[]> {
        const result = await this.executeSql(`
            SELECT table_name
            FROM information_schema.tables
            WHERE table_schema = 'public'
              AND table_type = 'BASE TABLE'
            ORDER BY table_name;
        `);
 
        const internalPrefixes = ["_rebase_", "_auth_"];
        const internalExact = [
            "users", "roles", "user_roles", "refresh_tokens",
            "password_reset_tokens", "email_verification_tokens"
        ];
 
        const allTables = result
            .map((r: Record<string, unknown>) => r.table_name as string)
            .filter((name: string) => {
                Iif (internalPrefixes.some(prefix => name.startsWith(prefix))) return false;
                Iif (internalExact.includes(name)) return false;
                return true;
            });
 
        // Detect junction tables: tables where every column is part of a foreign key.
        // These are typically many-to-many connection tables and shouldn't be suggested.
        let junctionTables = new Set<string>();
        try {
            const junctionResult = await this.executeSql(`
                SELECT t.table_name
                FROM information_schema.tables t
                WHERE t.table_schema = 'public'
                  AND t.table_type = 'BASE TABLE'
                  AND NOT EXISTS (
                    -- Find columns that are NOT part of any foreign key
                    SELECT 1
                    FROM information_schema.columns c
                    WHERE c.table_schema = t.table_schema
                      AND c.table_name = t.table_name
                      AND c.column_name NOT IN (
                        SELECT kcu.column_name
                        FROM information_schema.key_column_usage kcu
                        JOIN information_schema.table_constraints tc
                          ON tc.constraint_name = kcu.constraint_name
                          AND tc.table_schema = kcu.table_schema
                        WHERE tc.constraint_type = 'FOREIGN KEY'
                          AND kcu.table_schema = t.table_schema
                          AND kcu.table_name = t.table_name
                      )
                  );
            `);
            junctionTables = new Set(junctionResult.map((r: Record<string, unknown>) => r.table_name as string));
        } catch (e) {
            console.warn("Could not detect junction tables:", e);
        }
 
        const filteredTables = allTables.filter(name => !junctionTables.has(name));
 
        Iif (!mappedPaths || mappedPaths.length === 0) return filteredTables;
 
        const mappedSet = new Set(mappedPaths.map(p => p.toLowerCase()));
        return filteredTables.filter((name: string) => !mappedSet.has(name.toLowerCase()));
    }
 
    
    /**
     * Fetch metadata for a given table from information_schema (columns, policies, constraints).
     */
    async fetchTableMetadata(tableName: string): Promise<TableMetadata> {
        // Sanitize table name as defense-in-depth (parameterized below)
        const safeName = tableName.replace(/[^a-zA-Z0-9_]/g, "");
 
        // 1. Fetch Columns
        const result = await this.db.execute(drizzleSql`
            SELECT column_name, data_type, udt_name, is_nullable, column_default, character_maximum_length
            FROM information_schema.columns
            WHERE table_schema = 'public'
              AND table_name = ${safeName}
            ORDER BY ordinal_position
        `);
        const columns = result.rows as Record<string, unknown>[];
 
        // Also fetch enum values for any USER-DEFINED columns
        const enumColumns = columns.filter((c) => c.data_type === "USER-DEFINED");
        Iif (enumColumns.length > 0) {
            for (const col of enumColumns) {
                try {
                    const enumResult = await this.db.execute(drizzleSql`
                        SELECT e.enumlabel
                        FROM pg_type t
                        JOIN pg_enum e ON t.oid = e.enumtypid
                        WHERE t.typname = ${col.udt_name as string}
                        ORDER BY e.enumsortorder
                    `);
                    col.enum_values = (enumResult.rows as Record<string, unknown>[]).map(e => e.enumlabel);
                } catch {
                    col.enum_values = [];
                }
            }
        }
        const typedColumns = columns as unknown as TableColumnInfo[];
 
        // 2. Fetch Foreign Keys
        const fkResult = await this.db.execute(drizzleSql`
            SELECT
                kcu.column_name as column_name,
                ccu.table_name AS foreign_table_name,
                ccu.column_name AS foreign_column_name
            FROM 
                information_schema.table_constraints AS tc 
                JOIN information_schema.key_column_usage AS kcu
                  ON tc.constraint_name = kcu.constraint_name
                  AND tc.table_schema = kcu.table_schema
                JOIN information_schema.constraint_column_usage AS ccu
                  ON ccu.constraint_name = tc.constraint_name
                  AND ccu.table_schema = tc.table_schema
            WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_name = ${safeName};
        `);
        const foreignKeys = fkResult.rows as unknown as TableForeignKeyInfo[];
 
        // 3. Fetch Junction Tables (Many-to-Many)
        // A simple junction table is one that has foreign keys to our table and other tables
        const junctionsResult = await this.db.execute(drizzleSql`
            SELECT 
                tc1.table_name as junction_table_name,
                kcu1.column_name as source_column_name,
                ccu2.table_name as target_table_name,
                kcu2.column_name as target_column_name
            FROM information_schema.table_constraints tc1
            JOIN information_schema.key_column_usage kcu1 ON tc1.constraint_name = kcu1.constraint_name
            JOIN information_schema.constraint_column_usage ccu1 ON ccu1.constraint_name = tc1.constraint_name
            JOIN information_schema.table_constraints tc2 ON tc1.table_name = tc2.table_name AND tc2.constraint_type = 'FOREIGN KEY'
            JOIN information_schema.key_column_usage kcu2 ON tc2.constraint_name = kcu2.constraint_name
            JOIN information_schema.constraint_column_usage ccu2 ON ccu2.constraint_name = tc2.constraint_name
            WHERE tc1.constraint_type = 'FOREIGN KEY' 
              AND ccu1.table_name = ${safeName}
              AND ccu2.table_name != ${safeName};
        `);
        const junctions = junctionsResult.rows as unknown as TableJunctionInfo[];
 
        // 4. Fetch RLS Policies
        const policiesResult = await this.db.execute(drizzleSql`
            SELECT 
                polname as policy_name, 
                polcmd as cmd, 
                polroles::regrole[]::text[] as roles, 
                pg_get_expr(polqual, polrelid) as qual, 
                pg_get_expr(polwithcheck, polrelid) as with_check
            FROM pg_policy
            WHERE polrelid = (SELECT oid FROM pg_class WHERE relname = ${safeName} AND relnamespace = 'public'::regnamespace);
        `);
        const policies = policiesResult.rows as unknown as TablePolicyInfo[];
 
        return {
            columns: typedColumns,
            foreignKeys,
            junctions,
            policies
        };
    }
 
    private generateSubscriptionId(): string {
        return `sub_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
    }
 
    /**
     * Create a new delegate instance with authenticated context.
     * Starts a transaction and sets the current_user_id and current_user_roles
     * configuration parameters for PostgreSQL Row Level Security.
     */
    async withAuth(user: User): Promise<DataDriver> {
        return new AuthenticatedPostgresDataDriver(this, user);
    }
}
 
export class AuthenticatedPostgresDataDriver implements DataDriver {
    key = "postgres";
    initialised = true;
 
    public user: User;
    public data: RebaseData;
 
    constructor(
        public delegate: PostgresDataDriver,
        user: User
    ) {
        this.user = user;
        this.data = buildRebaseData(this);
    }
 
    private async withTransaction<T>(
        operation: (delegate: PostgresDataDriver) => Promise<T>
    ): Promise<T> {
        const pendingNotifications: PostgresDataDriver["_pendingNotifications"] = [];
        
        const result = await this.delegate.db.transaction(async (tx) => {
            let userId = this.user?.uid;
            if (!userId) {
                console.warn(`[DataDriver] User ID (uid) is missing for authenticated delegate. Using 'anonymous'. User object:`, this.user);
                userId = 'anonymous';
            }
 
            let userRoles = this.user?.roles ?? [];
            if (!this.user?.roles) {
                console.warn(`[DataDriver] User roles are missing for authenticated delegate. Using empty array. User object:`, this.user);
            }
            const normalizedRoles = userRoles.map((r: unknown) =>
                typeof r === "string" ? r : (r as Record<string, unknown>)?.id ?? String(r)
            );
            const rolesString = normalizedRoles.join(",");
 
            await tx.execute(drizzleSql`
                SELECT 
                    set_config('app.user_id', ${userId}, true),
                    set_config('app.user_roles', ${rolesString}, true),
                    set_config('app.jwt', ${JSON.stringify({ sub: userId, roles: userRoles })}, true)
            `);
 
            const txEntityService = new EntityService(tx, this.delegate.registry);
            const txDelegate = new PostgresDataDriver(tx, this.delegate.realtimeService, this.delegate.registry, this.user, this.delegate.poolManager, this.delegate.historyService);
            
            txDelegate.entityService = txEntityService;
            txDelegate._deferNotifications = true;
            txDelegate._pendingNotifications = pendingNotifications;
 
            return await operation(txDelegate);
        });
 
        for (const notification of pendingNotifications) {
            try {
                await this.delegate.realtimeService.notifyEntityUpdate(
                    notification.path,
                    notification.entityId,
                    notification.entity,
                    notification.databaseId
                );
            } catch (e) {
                console.error("[DataDriver] Error flushing deferred notification:", e);
            }
        }
 
        return result;
    }
 
    async fetchCollection<M extends Record<string, any>>(props: FetchCollectionProps<M>): Promise<Entity<M>[]> {
        return this.withTransaction((delegate) => delegate.fetchCollection(props));
    }
 
    /**
     * Injects the authenticated user's context into the most recently
     * registered realtime subscription so RLS-aware polling can apply.
     */
    private injectAuthContext(unsubscribe: () => void): () => void {
        const authContext = { userId: this.user?.uid || "anonymous", roles: this.user?.roles ?? [] };
        const entries = Array.from(this.delegate.realtimeService.subscriptions.entries());
        const lastEntry = entries[entries.length - 1];
        if (lastEntry && lastEntry[1].clientId === "driver") {
            lastEntry[1].authContext = authContext;
        }
        return unsubscribe;
    }
 
    listenCollection<M extends Record<string, any>>(props: ListenCollectionProps<M>): () => void {
        return this.injectAuthContext(this.delegate.listenCollection(props));
    }
 
    async fetchEntity<M extends Record<string, any>>(props: FetchEntityProps<M>): Promise<Entity<M> | undefined> {
        return this.withTransaction((delegate) => delegate.fetchEntity(props));
    }
 
    listenEntity<M extends Record<string, any>>(props: ListenEntityProps<M>): () => void {
        return this.injectAuthContext(this.delegate.listenEntity(props));
    }
 
    async saveEntity<M extends Record<string, any>>(props: SaveEntityProps<M>): Promise<Entity<M>> {
        return this.withTransaction((delegate) => delegate.saveEntity(props));
    }
 
    async deleteEntity<M extends Record<string, any>>(props: DeleteEntityProps<M>): Promise<void> {
        return this.withTransaction((delegate) => delegate.deleteEntity(props));
    }
 
    async checkUniqueField(
        path: string,
        name: string,
        value: unknown,
        entityId?: string,
        collection?: EntityCollection
    ): Promise<boolean> {
        return this.withTransaction((delegate) => delegate.checkUniqueField(path, name, value, entityId, collection));
    }
 
    async countEntities<M extends Record<string, any>>(props: FetchCollectionProps<M>): Promise<number> {
        return this.withTransaction((delegate) => delegate.countEntities(props));
    }
 
    /**
     * Intentionally delegates to the base delegate WITHOUT RLS wrapping.
     * executeSql is an admin-only feature; access control should be enforced
     * at the API route level, not via database-level RLS.
     */
    async executeSql(sqlText: string, options?: { database?: string, role?: string }): Promise<Record<string, unknown>[]> {
        return this.delegate.executeSql(sqlText, options);
    }
 
    async fetchAvailableDatabases(): Promise<string[]> {
        return this.delegate.fetchAvailableDatabases();
    }
 
    async fetchAvailableRoles(): Promise<string[]> {
        return this.delegate.fetchAvailableRoles();
    }
 
    async fetchCurrentDatabase(): Promise<string | undefined> {
        return this.delegate.fetchCurrentDatabase();
    }
 
    async fetchUnmappedTables(mappedPaths?: string[]): Promise<string[]> {
        return this.delegate.fetchUnmappedTables(mappedPaths);
    }
 
    async fetchTableMetadata(tableName: string) {
        return this.delegate.fetchTableMetadata(tableName);
    }
}