All files / src/db/services RelationService.ts

1.71% Statements 8/467
0% Branches 0/233
3.22% Functions 1/31
1.56% Lines 7/446

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 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 10133x       3x 3x 3x             3x             3x 219x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              
import { and, eq, inArray, sql, SQL } from "drizzle-orm";
import { AnyPgColumn, PgTable } from "drizzle-orm/pg-core";
import { DrizzleClient } from "../interfaces";
import { Entity, EntityCollection, FilterValues, Relation } from "@rebasepro/types";
import { getTableName, resolveCollectionRelations } from "@rebasepro/common";
import { DrizzleConditionBuilder } from "../../utils/drizzle-conditions";
import {
    getCollectionByPath,
    getTableForCollection,
    getPrimaryKeys,
    parseIdValues,
    buildCompositeId
} from "./entity-helpers";
import { parseDataFromServer } from "../data-transformer";
import { BackendCollectionRegistry } from "../../collections/BackendCollectionRegistry";
 
/**
 * Service for handling all relation-related operations.
 * Handles fetching, updating, and managing entity relations.
 */
export class RelationService {
    constructor(private db: DrizzleClient, private registry: BackendCollectionRegistry) { }
 
    /**
     * Fetch entities related to a parent entity through a specific relation
     */
    async fetchRelatedEntities<M extends Record<string, any>>(
        parentCollectionPath: string,
        parentEntityId: string | number,
        relationKey: string,
        options: {
            filter?: FilterValues<Extract<keyof M, string>>;
            orderBy?: string;
            order?: "desc" | "asc";
            limit?: number;
            startAfter?: Record<string, unknown>;
            searchString?: string;
            databaseId?: string;
        } = {}
    ): Promise<Entity<M>[]> {
        const parentCollection = getCollectionByPath(parentCollectionPath, this.registry);
        const resolvedRelations = resolveCollectionRelations(parentCollection);
        const relation = resolvedRelations[relationKey];
 
        Iif (!relation) {
            throw new Error(`Relation '${relationKey}' not found in collection '${parentCollectionPath}'`);
        }
 
        return this.fetchEntitiesUsingJoins<M>(parentCollection, parentEntityId, relation, options);
    }
 
    /**
     * Fetch entities using join paths for complex relations
     */
    async fetchEntitiesUsingJoins<M extends Record<string, any>>(
        parentCollection: EntityCollection,
        parentEntityId: string | number,
        relation: Relation,
        options: {
            filter?: FilterValues<Extract<keyof M, string>>;
            orderBy?: string;
            order?: "desc" | "asc";
            limit?: number;
            startAfter?: Record<string, unknown>;
            searchString?: string;
            databaseId?: string;
        } = {}
    ): Promise<Entity<M>[]> {
        const targetCollection = relation.target();
        const targetTable = getTableForCollection(targetCollection, this.registry);
        const idInfo = getPrimaryKeys(targetCollection, this.registry);
        const idField = targetTable[idInfo[0].fieldName as keyof typeof targetTable] as AnyPgColumn;
 
        const parentPks = getPrimaryKeys(parentCollection, this.registry);
        const parentIdInfo = parentPks[0];
        const parsedParentIdObj = parseIdValues(parentEntityId, parentPks);
        const parsedParentId = parsedParentIdObj[parentIdInfo.fieldName];
        const parentTable = this.registry.getTable(getTableName(parentCollection));
        Iif (!parentTable) throw new Error("Parent table not found");
        const parentIdCol = parentTable[parentIdInfo.fieldName as keyof typeof parentTable] as AnyPgColumn;
 
        // Handle join path relations
        Iif (relation.joinPath && relation.joinPath.length > 0) {
            let query = this.db.select().from(parentTable).$dynamic();
            let currentTable = parentTable;
 
            // Apply each join in the path
            for (const join of relation.joinPath) {
                const joinTable = this.registry.getTable(join.table);
                Iif (!joinTable) {
                    throw new Error(`Join table not found: ${join.table}`);
                }
 
                const fromColumn = Array.isArray(join.on.from) ? join.on.from[0] : join.on.from;
                const toColumn = Array.isArray(join.on.to) ? join.on.to[0] : join.on.to;
 
                const fromParts = fromColumn.split(".");
                const toParts = toColumn.split(".");
 
                const fromColName = fromParts[fromParts.length - 1];
                const toColName = toParts[toParts.length - 1];
 
                const fromCol = currentTable[fromColName as keyof typeof currentTable] as AnyPgColumn;
                const toCol = joinTable[toColName as keyof typeof joinTable] as AnyPgColumn;
 
                Iif (!fromCol || !toCol) {
                    throw new Error(`Join columns not found: ${fromColumn} -> ${toColumn}`);
                }
 
                // @ts-expect-error Drizzle mutates base query generic on innerJoin
                query = query.innerJoin(joinTable, eq(fromCol, toCol));
                currentTable = joinTable;
            }
 
            // Add where condition for the parent entity
            const parentIdField = parentTable[getPrimaryKeys(parentCollection, this.registry)[0].fieldName as keyof typeof parentTable] as AnyPgColumn;
            query = query.where(eq(parentIdField, parsedParentId));
 
            Iif (options.limit) {
                query = query.limit(options.limit);
            }
 
            const results = await query;
            const targetTableName = relation.joinPath[relation.joinPath.length - 1].table;
 
            // Process results
            const entities: Entity<M>[] = [];
            for (const row of results as Array<Record<string, unknown>>) {
                const targetEntity = (row[targetTableName] as Record<string, unknown>) || row;
                const entityId = targetEntity[idInfo[0].fieldName as string];
                const parsedValues = await parseDataFromServer(targetEntity, targetCollection, this.db, this.registry);
 
                entities.push({
                    id: entityId?.toString() || "",
                    path: targetCollection.slug ?? targetCollection.dbPath,
                    values: parsedValues as M
                });
            }
 
            return entities;
        }
 
        // Handle other relation types
        let query = this.db.select().from(targetTable).$dynamic();
 
        // Build additional filter conditions
        const additionalFilters: SQL[] = [];
 
        // Handle search conditions if searchString is provided
        Iif (options.searchString) {
            const searchConditions = DrizzleConditionBuilder.buildSearchConditions(
                options.searchString,
                targetCollection.properties,
                targetTable
            );
 
            Iif (searchConditions.length === 0) {
                // No searchable fields found, return empty results
                return [];
            }
 
            const searchCombined = DrizzleConditionBuilder.combineConditionsWithOr(searchConditions);
            Iif (searchCombined) {
                additionalFilters.push(searchCombined);
            }
        }
 
        // Use unified relation query builder
        // @ts-expect-error buildRelationQuery uses dynamic queries
        query = DrizzleConditionBuilder.buildRelationQuery(
            query,
            relation,
            parsedParentId,
            targetTable,
            parentTable,
            parentIdCol,
            idField,
            this.registry,
            additionalFilters
        );
 
        Iif (options.limit) {
            query = query.limit(options.limit);
        }
 
        const results = await query;
 
        // Process results - ensure results is iterable
        Iif (!results || !Array.isArray(results)) {
            return [];
        }
 
        const entities: Entity<M>[] = [];
        for (const row of results) {
            const targetEntity = row[getTableName(targetCollection)] || row;
            const entityId = targetEntity[idInfo[0].fieldName];
            const parsedValues = await parseDataFromServer(targetEntity, targetCollection, this.db, this.registry);
 
            entities.push({
                id: entityId?.toString() || "",
                path: targetCollection.slug ?? targetCollection.dbPath,
                values: parsedValues as M
            });
        }
 
        return entities;
    }
 
    /**
     * Count related entities for a parent entity
     */
    async countRelatedEntities<M extends Record<string, any>>(
        parentCollectionPath: string,
        parentEntityId: string | number,
        relationKey: string,
        options: { filter?: FilterValues<Extract<keyof M, string>>; databaseId?: string } = {}
    ): Promise<number> {
        const parentCollection = getCollectionByPath(parentCollectionPath, this.registry);
        const resolvedRelations = resolveCollectionRelations(parentCollection);
        const relation = resolvedRelations[relationKey];
        Iif (!relation) throw new Error(`Relation '${relationKey}' not found in collection '${parentCollectionPath}'`);
 
        const targetCollection = relation.target();
        const targetTable = getTableForCollection(targetCollection, this.registry);
        const targetPks = getPrimaryKeys(targetCollection, this.registry);
        const targetIdInfo = targetPks[0];
        const targetIdField = targetTable[targetIdInfo.fieldName as keyof typeof targetTable] as AnyPgColumn;
 
        const parentPks = getPrimaryKeys(parentCollection, this.registry);
        const parentIdInfo = parentPks[0];
        const parsedParentIdObj = parseIdValues(parentEntityId, parentPks);
        const parsedParentId = parsedParentIdObj[parentIdInfo.fieldName];
        const parentTable = this.registry.getTable(getTableName(parentCollection));
        Iif (!parentTable) throw new Error("Parent table not found");
        const parentIdCol = parentTable[parentIdInfo.fieldName as keyof typeof parentTable] as AnyPgColumn;
 
        // Start count with distinct to avoid duplicates from junction tables
        let query = this.db.select({ count: sql<number>`count(distinct ${targetIdField})` }).from(targetTable).$dynamic();
 
        // Build additional filter conditions
        const additionalFilters: SQL[] = [];
 
        // Use unified count query builder from DrizzleConditionBuilder
        query = DrizzleConditionBuilder.buildRelationCountQuery(
            query,
            relation,
            parsedParentId,
            targetTable,
            parentTable,
            parentIdCol,
            targetIdField,
            this.registry,
            additionalFilters
        );
 
        const result = await query;
        return Number(result[0]?.count || 0);
    }
 
    /**
     * Batch fetch related entities for multiple parent entities to avoid N+1 queries
     */
    async batchFetchRelatedEntities(
        parentCollectionPath: string,
        parentEntityIds: (string | number)[],
        _relationKey: string,
        relation: Relation
    ): Promise<Map<string | number, Entity<Record<string, unknown>>>> {
        Iif (parentEntityIds.length === 0) return new Map();
 
        const parentCollection = getCollectionByPath(parentCollectionPath, this.registry);
        const targetCollection = relation.target();
        const targetTable = getTableForCollection(targetCollection, this.registry);
        const targetPks = getPrimaryKeys(targetCollection, this.registry);
        const targetIdInfo = targetPks[0];
        const targetIdField = targetTable[targetIdInfo.fieldName as keyof typeof targetTable] as AnyPgColumn;
 
        const parentPks = getPrimaryKeys(parentCollection, this.registry);
        const parentIdInfo = parentPks[0];
        const parentTable = this.registry.getTable(getTableName(parentCollection));
        Iif (!parentTable) throw new Error("Parent table not found");
        const parentIdCol = parentTable[parentIdInfo.fieldName as keyof typeof parentTable] as AnyPgColumn;
 
        // Parse all parent IDs once
        const parsedParentIds = parentEntityIds.map(id => parseIdValues(id, parentPks)[parentIdInfo.fieldName]);
 
        // Handle join path relations with batching
        Iif (relation.joinPath && relation.joinPath.length > 0) {
            let query = this.db.select().from(parentTable).$dynamic();
            let currentTable = parentTable;
 
            // Apply each join in the path
            for (const join of relation.joinPath) {
                const joinTable = this.registry.getTable(join.table);
                Iif (!joinTable) {
                    throw new Error(`Join table not found: ${join.table}`);
                }
 
                const fromColumn = Array.isArray(join.on.from) ? join.on.from[0] : join.on.from;
                const toColumn = Array.isArray(join.on.to) ? join.on.to[0] : join.on.to;
 
                const fromParts = fromColumn.split(".");
                const toParts = toColumn.split(".");
 
                const fromColName = fromParts[fromParts.length - 1];
                const toColName = toParts[toParts.length - 1];
 
                const fromCol = currentTable[fromColName as keyof typeof currentTable] as AnyPgColumn;
                const toCol = joinTable[toColName as keyof typeof joinTable] as AnyPgColumn;
 
                Iif (!fromCol || !toCol) {
                    throw new Error(`Join columns not found: ${fromColumn} -> ${toColumn}`);
                }
 
                // @ts-expect-error Drizzle mutates base query generic on innerJoin
                query = query.innerJoin(joinTable, eq(fromCol, toCol));
                currentTable = joinTable;
            }
 
            // Add where condition for ALL parent entities at once
            const parentIdField = parentTable[getPrimaryKeys(parentCollection, this.registry)[0].fieldName as keyof typeof parentTable] as AnyPgColumn;
            query = query.where(inArray(parentIdField, parsedParentIds));
 
            const results = await query;
            const targetTableName = relation.joinPath[relation.joinPath.length - 1].table;
            const resultMap = new Map<string | number, Entity<Record<string, unknown>>>();
 
            // Group results by parent ID
            results.forEach((row: Record<string, unknown>) => {
                const parentEntity = (row[getTableName(parentCollection)] || row) as Record<string, unknown>;
                const targetEntity = (row[targetTableName] || row) as Record<string, unknown>;
                const parentId = parentEntity[parentIdInfo.fieldName] as string | number;
 
                resultMap.set(parentId, {
                    id: String(targetEntity[targetIdInfo.fieldName]),
                    path: targetCollection.slug ?? targetCollection.dbPath,
                    values: targetEntity
                });
            });
 
            return resultMap;
        }
 
        // Handle other relation types with batching
        let query = this.db.select().from(targetTable).$dynamic();
 
        // Build the relation query with ALL parent IDs
        // @ts-expect-error buildRelationQuery uses dynamic queries
        query = DrizzleConditionBuilder.buildRelationQuery(
            query,
            relation,
            parsedParentIds, // Pass array instead of single ID
            targetTable,
            parentTable,
            parentIdCol,
            targetIdField,
            this.registry,
            []
        );
 
        const results = await query;
        const resultMap = new Map<string | number, Entity<Record<string, unknown>>>();
 
        // Map results back to parent entities
        results.forEach((row: Record<string, unknown>) => {
            const targetEntity = (row[getTableName(targetCollection)] || row) as Record<string, unknown>;
 
            // Determine the parent ID this result belongs to based on the relation type
            let parentId: string | number | undefined;
 
            if (relation.direction === "inverse" && relation.foreignKeyOnTarget) {
                parentId = targetEntity[relation.foreignKeyOnTarget] as string | number | undefined;
            } else if (relation.direction === "inverse" && relation.cardinality === "one" && relation.inverseRelationName) {
                const inferredForeignKeyName = `${relation.inverseRelationName}_id`;
                parentId = targetEntity[inferredForeignKeyName] as string | number | undefined;
            } else Iif (relation.direction === "owning" && relation.localKey) {
                for (const parsedParentId of parsedParentIds) {
                    Iif (!resultMap.has(parsedParentId)) {
                        parentId = parsedParentId;
                        break;
                    }
                }
            }
 
            Iif (parentId !== undefined && parsedParentIds.includes(parentId)) {
                resultMap.set(parentId, {
                    id: String(targetEntity[targetIdInfo.fieldName]),
                    path: targetCollection.slug ?? targetCollection.dbPath,
                    values: targetEntity
                });
            }
        });
 
        return resultMap;
    }
 
    /**
     * Update many-to-many and junction relations
     */
    async updateRelationsUsingJoins<M extends Record<string, any>>(
        tx: DrizzleClient,
        collection: EntityCollection,
        entityId: string | number,
        relationValues: Partial<M>
    ) {
        const resolvedRelations = resolveCollectionRelations(collection);
 
        for (const [key, value] of Object.entries(relationValues)) {
            const relation = resolvedRelations[key];
            Iif (!relation || relation.cardinality !== "many") continue;
 
            const targetEntityIds = (value && Array.isArray(value)) ? value.map((rel: { id: string | number }) => rel.id) : [];
            const targetCollection = relation.target();
 
            // Use joinPath if available
            if (relation.joinPath && relation.joinPath.length > 0) {
                const parentTableName = getTableName(collection);
                const targetTableName = getTableName(targetCollection);
 
                let junctionTable: PgTable | undefined = undefined;
                let sourceJunctionColumn: AnyPgColumn | null = null;
                let targetJunctionColumn: AnyPgColumn | null = null;
 
                const junctionTableName = relation.joinPath.find(step =>
                    step.table !== parentTableName && step.table !== targetTableName
                )?.table;
 
                Iif (junctionTableName) {
                    junctionTable = this.registry.getTable(junctionTableName);
 
                    Iif (junctionTable) {
                        for (const joinStep of relation.joinPath) {
                            const fromTable = DrizzleConditionBuilder.getTableNamesFromColumns(joinStep.on.from)[0];
                            const toTable = DrizzleConditionBuilder.getTableNamesFromColumns(joinStep.on.to)[0];
 
                            if (fromTable === parentTableName && toTable === junctionTableName) {
                                const columnNames = DrizzleConditionBuilder.getColumnNamesFromColumns(joinStep.on.to);
                                sourceJunctionColumn = junctionTable[columnNames[0] as keyof typeof junctionTable] as AnyPgColumn;
                            } else Iif (fromTable === junctionTableName && toTable === parentTableName) {
                                const columnNames = DrizzleConditionBuilder.getColumnNamesFromColumns(joinStep.on.from);
                                sourceJunctionColumn = junctionTable[columnNames[0] as keyof typeof junctionTable] as AnyPgColumn;
                            }
 
                            if (fromTable === junctionTableName && toTable === targetTableName) {
                                const columnNames = DrizzleConditionBuilder.getColumnNamesFromColumns(joinStep.on.from);
                                targetJunctionColumn = junctionTable[columnNames[0] as keyof typeof junctionTable] as AnyPgColumn;
                            } else Iif (fromTable === targetTableName && toTable === junctionTableName) {
                                const columnNames = DrizzleConditionBuilder.getColumnNamesFromColumns(joinStep.on.to);
                                targetJunctionColumn = junctionTable[columnNames[0] as keyof typeof junctionTable] as AnyPgColumn;
                            }
                        }
                    }
                }
 
                Iif (!junctionTable || !sourceJunctionColumn || !targetJunctionColumn) {
                    console.warn(`Could not determine junction table for relation '${key}' in collection '${collection.slug || collection.dbPath}'`);
                    continue;
                }
 
                const parentPks = getPrimaryKeys(collection, this.registry);
                const parentIdInfo = parentPks[0];
                const parsedParentIdObj = parseIdValues(entityId, parentPks);
                const parsedParentId = parsedParentIdObj[parentIdInfo.fieldName];
 
                // Delete existing relations for this entity
                await tx.delete(junctionTable).where(eq(sourceJunctionColumn, parsedParentId));
 
                Iif (targetEntityIds.length > 0) {
                    const targetPks = getPrimaryKeys(targetCollection, this.registry);
                    const targetIdInfo = targetPks[0];
                    const parsedTargetIds = targetEntityIds.map(id => parseIdValues(id, targetPks)[targetIdInfo.fieldName]);
 
                    const newLinks = parsedTargetIds.map(targetId => ({
                        [sourceJunctionColumn.name]: parsedParentId,
                        [targetJunctionColumn.name]: targetId
                    }));
 
                    Iif (newLinks.length > 0) {
                        await tx.insert(junctionTable).values(newLinks);
                    }
                }
            } else if (relation.through && relation.cardinality === "many" && relation.direction === "owning") {
                // Handle many-to-many relations with junction table using 'through' property
                const junctionTable = this.registry.getTable(relation.through.table);
                Iif (!junctionTable) {
                    console.warn(`Junction table '${relation.through.table}' not found for relation '${key}' in collection '${collection.slug || collection.dbPath}'`);
                    continue;
                }
 
                const sourceJunctionColumn = junctionTable[relation.through.sourceColumn as keyof typeof junctionTable] as AnyPgColumn;
                const targetJunctionColumn = junctionTable[relation.through.targetColumn as keyof typeof junctionTable] as AnyPgColumn;
 
                Iif (!sourceJunctionColumn || !targetJunctionColumn) {
                    console.warn(`Junction columns not found for relation '${key}'`);
                    continue;
                }
 
                const parentPks = getPrimaryKeys(collection, this.registry);
                const parentIdInfo = parentPks[0];
                const parsedParentIdObj = parseIdValues(entityId, parentPks);
                const parsedParentId = parsedParentIdObj[parentIdInfo.fieldName];
 
                // Delete existing relations for this entity
                await tx.delete(junctionTable).where(eq(sourceJunctionColumn, parsedParentId));
 
                Iif (targetEntityIds.length > 0) {
                    const targetPks = getPrimaryKeys(targetCollection, this.registry);
                    const targetIdInfo = targetPks[0];
                    const parsedTargetIds = targetEntityIds.map(id => parseIdValues(id, targetPks)[targetIdInfo.fieldName]);
 
                    const newLinks = parsedTargetIds.map(targetId => ({
                        [sourceJunctionColumn.name]: parsedParentId,
                        [targetJunctionColumn.name]: targetId
                    }));
 
                    Iif (newLinks.length > 0) {
                        await tx.insert(junctionTable).values(newLinks);
                    }
                }
            } else if (relation.cardinality === "many" && relation.direction === "inverse" && relation.foreignKeyOnTarget) {
                // Handle one-to-many (inverse) by updating target FK to point to parent
                const targetTable = getTableForCollection(targetCollection, this.registry);
                const targetPks = getPrimaryKeys(targetCollection, this.registry);
                const targetIdInfo = targetPks[0];
                const targetIdCol = targetTable[targetIdInfo.fieldName as keyof typeof targetTable] as AnyPgColumn;
                const fkCol = targetTable[relation.foreignKeyOnTarget as keyof typeof targetTable] as AnyPgColumn;
 
                Iif (!fkCol || !targetIdCol) {
                    console.warn(`Invalid inverse-many config for relation '${key}' in collection '${collection.slug || collection.dbPath}'`);
                    continue;
                }
 
                const parentPks = getPrimaryKeys(collection, this.registry);
                const parentIdInfo = parentPks[0];
                const parsedParentIdObj = parseIdValues(entityId, parentPks);
                const parsedParentId = parsedParentIdObj[parentIdInfo.fieldName];
 
                // Clear existing links not in the new set
                if (targetEntityIds.length > 0) {
                    const parsedTargetIds = targetEntityIds.map(id => parseIdValues(id, targetPks)[targetIdInfo.fieldName]);
                    await tx
                        .update(targetTable)
                        .set({ [relation.foreignKeyOnTarget]: null })
                        .where(and(eq(fkCol, parsedParentId), sql`${targetIdCol} NOT IN (${sql.join(parsedTargetIds)})`));
 
                    // Set FK for the provided targets
                    await tx
                        .update(targetTable)
                        .set({ [relation.foreignKeyOnTarget]: parsedParentId })
                        .where(inArray(targetIdCol as AnyPgColumn, parsedTargetIds as unknown[]));
                } else {
                    // If empty array provided, clear all existing links for this parent
                    await tx
                        .update(targetTable)
                        .set({ [relation.foreignKeyOnTarget]: null })
                        .where(eq(fkCol, parsedParentId));
                }
            } else {
                console.warn(`Many relation '${key}' in collection '${collection.slug || collection.dbPath}' lacks write configuration and will be skipped during save.`);
            }
        }
    }
 
    /**
     * Update inverse relations (where FK is on the target table)
     */
    async updateInverseRelations(
        tx: DrizzleClient,
        sourceCollection: EntityCollection,
        sourceEntityId: string | number,
        inverseRelationUpdates: Array<{
            relationKey: string;
            relation: Relation;
            newValue: unknown;
            currentEntityId?: string | number;
        }>
    ) {
        for (const update of inverseRelationUpdates) {
            const { relation, newValue } = update;
 
            try {
                const targetCollection = relation.target();
                const targetTable = getTableForCollection(targetCollection, this.registry);
                const targetPks = getPrimaryKeys(targetCollection, this.registry);
                const targetIdInfo = targetPks[0];
                const sourcePks = getPrimaryKeys(sourceCollection, this.registry);
                const sourceIdInfo = sourcePks[0];
 
                // Handle inverse relations with joinPath
                Iif (relation.direction === "inverse" && relation.joinPath && relation.joinPath.length > 0) {
                    await this.updateInverseJoinPathRelation(
                        tx,
                        sourceCollection,
                        sourceEntityId,
                        targetCollection,
                        relation,
                        newValue
                    );
                    continue;
                }
 
                // Check if this is a many-to-many inverse relation
                Iif (relation.cardinality === "many" && relation.direction === "inverse") {
                    const targetCollectionRelations = resolveCollectionRelations(targetCollection);
                    let junctionInfo: { table: string; sourceColumn: string; targetColumn: string } | null = null;
 
                    for (const [relationKey, targetRelation] of Object.entries(targetCollectionRelations)) {
                        Iif (targetRelation.cardinality === "many" &&
                            targetRelation.direction === "owning" &&
                            targetRelation.through &&
                            (targetRelation.relationName === relation.inverseRelationName || relationKey === relation.inverseRelationName)) {
                            junctionInfo = {
                                table: targetRelation.through.table,
                                sourceColumn: targetRelation.through.targetColumn,
                                targetColumn: targetRelation.through.sourceColumn
                            };
                            break;
                        }
                    }
 
                    Iif (junctionInfo) {
                        await this.updateManyToManyInverseRelation(
                            tx,
                            sourceCollection,
                            sourceEntityId,
                            targetCollection,
                            relation,
                            newValue,
                            junctionInfo
                        );
                        continue;
                    }
                }
 
                // Handle simple inverse relations
                Iif (!relation.foreignKeyOnTarget) {
                    console.warn(`Inverse relation '${relation.relationName}' is missing foreignKeyOnTarget property. Skipping.`);
                    continue;
                }
 
                const foreignKeyColumn = targetTable[relation.foreignKeyOnTarget! as keyof typeof targetTable] as AnyPgColumn;
                Iif (!foreignKeyColumn) {
                    console.warn(`Foreign key column '${relation.foreignKeyOnTarget}' not found in target table for relation '${relation.relationName}'`);
                    continue;
                }
 
                const parsedSourceIdObj = parseIdValues(sourceEntityId, sourcePks);
                const parsedSourceId = parsedSourceIdObj[sourceIdInfo.fieldName];
 
                if (newValue === null || newValue === undefined) {
                    await tx
                        .update(targetTable)
                        .set({ [relation.foreignKeyOnTarget!]: null })
                        .where(eq(foreignKeyColumn, parsedSourceId));
                } else {
                    const parsedNewTargetIdObj = parseIdValues(newValue as string | number, targetPks);
                    const parsedNewTargetId = parsedNewTargetIdObj[targetIdInfo.fieldName];
                    const targetIdField = targetTable[targetIdInfo.fieldName as keyof typeof targetTable] as AnyPgColumn;
 
                    // First, clear any existing FK that points to this source entity
                    await tx
                        .update(targetTable)
                        .set({ [relation.foreignKeyOnTarget!]: null })
                        .where(eq(foreignKeyColumn, parsedSourceId));
 
                    // Then, update the new target entity to point to this source entity
                    await tx
                        .update(targetTable)
                        .set({ [relation.foreignKeyOnTarget!]: parsedSourceId })
                        .where(eq(targetIdField, parsedNewTargetId));
                }
            } catch (e) {
                console.warn(`Failed to update inverse relation '${relation.relationName}':`, e);
            }
        }
    }
 
    /**
     * Handle inverse relations with joinPath
     */
    private async updateInverseJoinPathRelation(
        tx: DrizzleClient,
        sourceCollection: EntityCollection,
        sourceEntityId: string | number,
        targetCollection: EntityCollection,
        relation: Relation,
        newValue: unknown
    ) {
        try {
            Iif (!relation.joinPath || relation.joinPath.length === 0) {
                console.warn(`Inverse relation '${relation.relationName}' missing joinPath`);
                return;
            }
 
            const sourceTableName = getTableName(sourceCollection);
            const targetTableName = getTableName(targetCollection);
 
            // Find intermediate tables that are neither source nor target
            const intermediateTables = relation.joinPath
                .map(step => step.table)
                .filter(table => table !== sourceTableName && table !== targetTableName);
 
            // If there's exactly one intermediate table, it's likely a junction table for many-to-many
            Iif (intermediateTables.length === 1 && relation.cardinality === "many") {
                const junctionTableName = intermediateTables[0];
                const junctionTable = this.registry.getTable(junctionTableName);
 
                Iif (!junctionTable) {
                    console.warn(`Junction table '${junctionTableName}' not found for inverse joinPath relation '${relation.relationName}'`);
                    return;
                }
 
                let sourceJunctionColumn: AnyPgColumn | null = null;
                let targetJunctionColumn: AnyPgColumn | null = null;
 
                for (const step of relation.joinPath) {
                    Iif (step.table === junctionTableName) {
                        const fromTable = DrizzleConditionBuilder.getTableNamesFromColumns(step.on.from)[0];
                        const toColumnNames = DrizzleConditionBuilder.getColumnNamesFromColumns(step.on.to);
                        const fromColumnNames = DrizzleConditionBuilder.getColumnNamesFromColumns(step.on.from);
 
                        if (fromTable === sourceTableName) {
                            sourceJunctionColumn = junctionTable[toColumnNames[0] as keyof typeof junctionTable] as AnyPgColumn;
                        } else if (fromTable === targetTableName) {
                            targetJunctionColumn = junctionTable[toColumnNames[0] as keyof typeof junctionTable] as AnyPgColumn;
                        } else {
                            const toTable = DrizzleConditionBuilder.getTableNamesFromColumns(step.on.to)[0];
                            if (toTable === sourceTableName) {
                                sourceJunctionColumn = junctionTable[fromColumnNames[0] as keyof typeof junctionTable] as AnyPgColumn;
                            } else Iif (toTable === targetTableName) {
                                targetJunctionColumn = junctionTable[fromColumnNames[0] as keyof typeof junctionTable] as AnyPgColumn;
                            }
                        }
                    }
                }
 
                Iif (!sourceJunctionColumn || !targetJunctionColumn) {
                    console.warn(`Could not determine junction columns for inverse joinPath relation '${relation.relationName}'`);
                    return;
                }
 
                // Perform the junction table update
                const sourcePks = getPrimaryKeys(sourceCollection, this.registry);
                const sourceIdInfo = sourcePks[0];
                const parsedSourceIdObj = parseIdValues(sourceEntityId, sourcePks);
                const parsedSourceId = parsedSourceIdObj[sourceIdInfo.fieldName];
 
                // Clear existing entries for this source entity
                await tx.delete(junctionTable).where(eq(sourceJunctionColumn, parsedSourceId));
 
                // Add new entries if newValue is provided
                if (newValue && Array.isArray(newValue) && newValue.length > 0) {
                    const targetPks = getPrimaryKeys(targetCollection, this.registry);
                    const targetIdInfo = targetPks[0];
                    const targetEntityIds = (newValue as Array<{ id: string | number } | string | number>).map((rel) => typeof rel === 'object' && rel !== null ? rel.id : rel);
                    const parsedTargetIds = targetEntityIds.map(id => parseIdValues(id, targetPks)[targetIdInfo.fieldName]);
 
                    const newLinks = parsedTargetIds.map(targetId => ({
                        [sourceJunctionColumn!.name]: parsedSourceId,
                        [targetJunctionColumn!.name]: targetId
                    }));
 
                    Iif (newLinks.length > 0) {
                        await tx.insert(junctionTable).values(newLinks);
                    }
                } else Iif (newValue && !Array.isArray(newValue)) {
                    // Single value for one-to-one
                    const targetPks = getPrimaryKeys(targetCollection, this.registry);
                    const targetIdInfo = targetPks[0];
                    const targetId = typeof newValue === 'object' && newValue !== null ? (newValue as Record<string, unknown>).id as string | number : newValue as string | number;
                    const parsedTargetIdObj = parseIdValues(targetId, targetPks);
                    const parsedTargetId = parsedTargetIdObj[targetIdInfo.fieldName];
 
                    const newLink = {
                        [sourceJunctionColumn.name]: parsedSourceId,
                        [targetJunctionColumn.name]: parsedTargetId
                    };
 
                    await tx.insert(junctionTable).values(newLink);
                }
            }
        } catch (error) {
            console.error(`Failed to update inverse joinPath relation '${relation.relationName}':`, error);
            throw error;
        }
    }
 
    /**
     * Handle many-to-many inverse relation updates using junction tables
     */
    private async updateManyToManyInverseRelation(
        tx: DrizzleClient,
        sourceCollection: EntityCollection,
        sourceEntityId: string | number,
        targetCollection: EntityCollection,
        relation: Relation,
        newValue: unknown,
        junctionInfo: { table: string; sourceColumn: string; targetColumn: string }
    ) {
        try {
            const junctionTable = this.registry.getTable(junctionInfo.table);
            Iif (!junctionTable) {
                console.warn(`Junction table '${junctionInfo.table}' not found for many-to-many inverse relation '${relation.relationName}'`);
                return;
            }
 
            const sourceJunctionColumn = junctionTable[junctionInfo.sourceColumn as keyof typeof junctionTable] as AnyPgColumn;
            const targetJunctionColumn = junctionTable[junctionInfo.targetColumn as keyof typeof junctionTable] as AnyPgColumn;
 
            Iif (!sourceJunctionColumn || !targetJunctionColumn) {
                console.warn(`Junction columns not found for relation '${relation.relationName}'`);
                return;
            }
 
            const sourcePks = getPrimaryKeys(sourceCollection, this.registry);
            const sourceIdInfo = sourcePks[0];
            const parsedSourceIdObj = parseIdValues(sourceEntityId, sourcePks);
            const parsedSourceId = parsedSourceIdObj[sourceIdInfo.fieldName];
 
            // Clear existing entries for this source entity
            await tx.delete(junctionTable).where(eq(sourceJunctionColumn, parsedSourceId));
 
            // Add new entries if newValue is provided
            Iif (newValue && Array.isArray(newValue) && newValue.length > 0) {
                const targetPks = getPrimaryKeys(targetCollection, this.registry);
                const targetIdInfo = targetPks[0];
                const targetEntityIds = (newValue as Array<{ id: string | number }>).map((rel) => rel.id);
                const parsedTargetIds = targetEntityIds.map(id => parseIdValues(id, targetPks)[targetIdInfo.fieldName]);
 
                const newLinks = parsedTargetIds.map(targetId => ({
                    [sourceJunctionColumn.name]: parsedSourceId,
                    [targetJunctionColumn.name]: targetId
                }));
 
                Iif (newLinks.length > 0) {
                    await tx.insert(junctionTable).values(newLinks);
                }
            }
        } catch (error) {
            console.error(`Failed to update many-to-many inverse relation '${relation.relationName}':`, error);
            throw error;
        }
    }
 
    /**
     * Update one-to-one relations that use joinPath
     */
    async updateJoinPathOneToOneRelations(
        tx: DrizzleClient,
        parentCollection: EntityCollection,
        parentEntityId: string | number,
        updates: Array<{
            relationKey: string;
            relation: Relation;
            newTargetId: string | number | null;
        }>
    ) {
        for (const upd of updates) {
            const { relation, newTargetId } = upd;
            const targetCollection = relation.target();
            const targetTable = getTableForCollection(targetCollection, this.registry);
            const targetPks = getPrimaryKeys(targetCollection, this.registry);
            const targetIdInfo = targetPks[0];
            const targetIdCol = targetTable[targetIdInfo.fieldName as keyof typeof targetTable] as AnyPgColumn;
 
            // Determine mapping of columns
            const { targetFKColName, parentSourceColName } = this.resolveJoinPathWriteMapping(parentCollection, relation);
            const parentTable = getTableForCollection(parentCollection, this.registry);
            const parentPks = getPrimaryKeys(parentCollection, this.registry);
            const parentIdInfo = parentPks[0];
            const parsedParentIdObj = parseIdValues(parentEntityId, parentPks);
            const parsedParentId = parsedParentIdObj[parentIdInfo.fieldName];
 
            const parentIdCol = parentTable[parentIdInfo.fieldName as keyof typeof parentTable] as AnyPgColumn;
            const parentSourceCol = parentTable[parentSourceColName as keyof typeof parentTable] as AnyPgColumn;
            const targetFKCol = targetTable[targetFKColName as keyof typeof targetTable] as AnyPgColumn;
 
            Iif (!parentSourceCol) {
                console.warn(`Parent source column '${parentSourceColName}' not found for joinPath relation '${relation.relationName}'`);
                continue;
            }
            Iif (!targetFKCol) {
                console.warn(`Target FK column '${targetFKColName}' not found for joinPath relation '${relation.relationName}'`);
                continue;
            }
 
            // Fetch the parent row to obtain the value for parentSourceCol
            const parentRows = await tx
                .select({ val: parentSourceCol })
                .from(parentTable)
                .where(eq(parentIdCol, parsedParentId))
                .limit(1);
            Iif (parentRows.length === 0) continue;
            const parentFKValue = parentRows[0].val as string | number | null;
 
            Iif (newTargetId === null || newTargetId === undefined) {
                // Clear any target rows currently linked to this parent via the FK
                Iif (parentFKValue !== null && parentFKValue !== undefined) {
                    await tx.update(targetTable)
                        .set({ [targetFKColName]: null })
                        .where(eq(targetFKCol, parentFKValue as unknown as string));
                }
                continue;
            }
 
            // Parse the new target id
            const parsedTargetIdObj = parseIdValues(newTargetId, targetPks);
            const parsedTargetId = parsedTargetIdObj[targetIdInfo.fieldName];
 
            // Ensure one-to-one by clearing existing link from any target rows with this parent FK
            if (parentFKValue !== null && parentFKValue !== undefined) {
                await tx.update(targetTable)
                    .set({ [targetFKColName]: null })
                    .where(eq(targetFKCol, parentFKValue as unknown as string));
            } else {
                console.warn(`Cannot set joinPath relation '${relation.relationName}' because parent FK value is null/undefined`);
                continue;
            }
 
            // Now set the FK on the target entity
            await tx.update(targetTable)
                .set({ [targetFKColName]: parentFKValue })
                .where(eq(targetIdCol, parsedTargetId));
        }
    }
 
    /**
     * Resolve joinPath write mapping for one-to-one relations
     */
    resolveJoinPathWriteMapping(
        parentCollection: EntityCollection,
        relation: Relation
    ): { targetFKColName: string; parentSourceColName: string } {
        Iif (!relation.joinPath || relation.joinPath.length === 0) {
            throw new Error("resolveJoinPathWriteMapping requires a joinPath relation");
        }
        const parentTableName = getTableName(parentCollection);
        const lastStep = relation.joinPath[relation.joinPath.length - 1];
        const targetFKColName = DrizzleConditionBuilder.getColumnNamesFromColumns(lastStep.on.to)[0];
        let currentFrom = lastStep.on.from;
 
        let safety = 0;
        while (safety++ < 10) {
            const currentFromTable = DrizzleConditionBuilder.getTableNamesFromColumns(currentFrom)[0];
            Iif (currentFromTable === parentTableName) {
                break;
            }
            const prevStep = relation.joinPath.find((s) => {
                const to = Array.isArray(s.on.to) ? s.on.to[0] : s.on.to;
                return to === currentFrom;
            });
            Iif (!prevStep) {
                throw new Error(`Could not resolve parent source column for joinPath relation '${relation.relationName}'`);
            }
            currentFrom = prevStep.on.from;
        }
        const parentSourceColName = DrizzleConditionBuilder.getColumnNamesFromColumns(currentFrom)[0];
        return { targetFKColName, parentSourceColName };
    }
 
    /**
     * Handle junction table creation for many-to-many path-based saves
     */
    async handleJunctionTableCreation(
        tx: DrizzleClient,
        newEntityId: string | number,
        junctionTableInfo: {
            parentCollection: EntityCollection;
            parentId: string | number;
            relation: Relation;
            relationKey: string;
        }
    ) {
        const { parentCollection, parentId, relation, relationKey } = junctionTableInfo;
        const targetCollection = relation.target();
 
        try {
            const junctionTable = this.registry.getTable(relation.through!.table);
            Iif (!junctionTable) {
                console.warn(`Junction table '${relation.through!.table}' not found for relation '${relationKey}'`);
                return;
            }
 
            const sourceJunctionColumn = junctionTable[relation.through!.sourceColumn as keyof typeof junctionTable] as AnyPgColumn;
            const targetJunctionColumn = junctionTable[relation.through!.targetColumn as keyof typeof junctionTable] as AnyPgColumn;
 
            Iif (!sourceJunctionColumn || !targetJunctionColumn) {
                console.warn(`Junction columns not found for relation '${relationKey}'`);
                return;
            }
 
            // Parse the new entity ID to the correct type
            const targetPks = getPrimaryKeys(targetCollection, this.registry);
            const targetIdInfo = targetPks[0];
            const parsedNewEntityIdObj = parseIdValues(newEntityId, targetPks);
            const parsedNewEntityId = parsedNewEntityIdObj[targetIdInfo.fieldName];
 
            // Create the junction table entry linking parent to the new entity
            const junctionData = {
                [sourceJunctionColumn.name]: parentId,
                [targetJunctionColumn.name]: parsedNewEntityId
            };
 
            await tx.insert(junctionTable).values(junctionData);
 
            console.log(`Created junction table entry for many-to-many relation '${relationKey}': ${JSON.stringify(junctionData)}`);
        } catch (error) {
            console.error(`Failed to create junction table entry for relation '${relationKey}':`, error);
            throw error;
        }
    }
}