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 | 4x 4x 4x 20x 20x 20x 20x 4x 4x 3x 3x 16x 3x 3x 3x 3x 13x 7x 7x 4x 4x 6x 6x 6x 6x 4x 4x 4x 4x 2x 2x 2x 14x 14x 4x 4x 4x 5x 5x 5x 5x 5x 5x 5x 1x 4x 4x 4x 4x 1x 3x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 4x 4x 4x 4x 4x 1x 1x 1x 1x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 11x 11x 1x 10x 10x 10x 1x 9x 1x 8x 8x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 10x 10x 10x 10x 6x 6x 6x 1x 1x 5x 5x 5x 5x 5x 5x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x | import { and, eq, or, sql, SQL, ilike, inArray } from "drizzle-orm";
import { AnyPgColumn, PgTable } from "drizzle-orm/pg-core";
import { FilterValues, WhereFilterOp, Relation, JoinStep } from "@rebasepro/types";
import { getColumnName, resolveCollectionRelations } from "@rebasepro/common";
import { BackendCollectionRegistry } from "../collections/BackendCollectionRegistry";
import { ConditionBuilderStatic } from "../db/interfaces";
/** Drizzle dynamic query builder — accepts innerJoin + where chaining */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export interface DrizzleDynamicQuery {
innerJoin(table: PgTable<any>, condition: SQL): this;
where(condition: SQL | undefined): this;
limit(limit: number): this;
}
/**
* Unified condition builder for Drizzle/PostgreSQL queries.
*
* This class uses static methods and satisfies the ConditionBuilderStatic<SQL> type.
* It translates Rebase filter conditions to Drizzle SQL conditions.
*
* @example
* const builder: ConditionBuilderStatic<SQL> = DrizzleConditionBuilder;
*/
export class DrizzleConditionBuilder {
/**
* Build filter conditions from FilterValues
*/
static buildFilterConditions<M extends Record<string, any>>(
filter: FilterValues<Extract<keyof M, string>>,
table: PgTable<any>,
collectionPath: string
): SQL[] {
const conditions: SQL[] = [];
for (const [field, filterParam] of Object.entries(filter)) {
Iif (!filterParam) continue;
const [op, value] = filterParam as [WhereFilterOp, any];
const fieldColumn = table[field as keyof typeof table] as AnyPgColumn;
Iif (!fieldColumn) {
console.warn(`Filtering by field '${field}', but it does not exist in table for collection '${collectionPath}'`);
continue;
}
const condition = this.buildSingleFilterCondition(fieldColumn, op, value);
Iif (condition) {
conditions.push(condition);
}
}
return conditions;
}
/**
* Build a single filter condition for a specific operator and value
*/
static buildSingleFilterCondition(
column: AnyPgColumn,
op: WhereFilterOp,
value: unknown
): SQL | null {
switch (op) {
case "==":
return eq(column, value);
case "!=":
return sql`${column} != ${value}`;
case ">":
return sql`${column} > ${value}`;
case ">=":
return sql`${column} >= ${value}`;
case "<":
return sql`${column} < ${value}`;
case "<=":
return sql`${column} <= ${value}`;
case "in":
Iif (Array.isArray(value) && value.length > 0) {
return inArray(column, value);
}
return null;
case "array-contains":
// For JSONB arrays
return sql`${column} @> ${JSON.stringify([value])}`;
default:
console.warn(`Unsupported filter operation: ${op}`);
return null;
}
}
/**
* Build relation-based conditions for different relation types
*/
static buildRelationConditions(
relation: Relation,
parentEntityId: string | number | (string | number)[],
targetTable: PgTable<any>,
parentTable: PgTable<any>,
parentIdColumn: AnyPgColumn,
targetIdColumn: AnyPgColumn,
registry: BackendCollectionRegistry
): {
joinConditions: { table: PgTable<any>; condition: SQL }[];
whereConditions: SQL[];
} {
console.debug(`🔍 [buildRelationConditions] Building conditions for relation:`, {
relationName: relation.relationName,
cardinality: relation.cardinality,
direction: relation.direction,
hasThrough: !!relation.through,
hasForeignKeyOnTarget: !!relation.foreignKeyOnTarget,
inverseRelationName: relation.inverseRelationName,
parentEntityId: parentEntityId
});
const joinConditions: { table: PgTable<any>; condition: SQL }[] = [];
const whereConditions: SQL[] = [];
if (relation.joinPath && relation.joinPath.length > 0) {
console.debug(`🔍 [buildRelationConditions] Using joinPath logic`);
// Handle join path relations
const {
joins,
finalCondition
} = this.buildJoinPathConditions(
relation.joinPath,
targetTable,
parentTable,
parentIdColumn,
parentEntityId,
registry
);
joinConditions.push(...joins);
whereConditions.push(finalCondition);
} else if (relation.through && relation.cardinality === "many" && relation.direction === "owning") {
console.debug(`🔍 [buildRelationConditions] Using owning many-to-many with explicit through`);
// Handle many-to-many relations with junction table
const junctionResult = this.buildJunctionTableConditions(
relation.through,
targetIdColumn,
parentEntityId,
registry
);
joinConditions.push(junctionResult.join);
whereConditions.push(junctionResult.condition);
} else if (relation.through && relation.cardinality === "many" && relation.direction === "inverse") {
console.debug(`🔍 [buildRelationConditions] Using inverse many-to-many with explicit through`);
// Handle inverse many-to-many relations with junction table
const junctionResult = this.buildInverseJunctionTableConditions(
relation.through,
targetIdColumn,
parentEntityId,
registry
);
joinConditions.push(junctionResult.join);
whereConditions.push(junctionResult.condition);
} else if (relation.cardinality === "many" && relation.direction === "inverse" && !relation.through) {
console.debug(`🔍 [buildRelationConditions] Handling inverse many relationship without explicit through`);
// First, try to find a junction table (for many-to-many relationships)
const junctionInfo = this.findCorrespondingJunctionTable(relation, registry);
if (junctionInfo) {
console.debug(`🔍 [buildRelationConditions] Found junction info for inverse many-to-many, building junction conditions`);
const junctionResult = this.buildInverseJunctionTableConditions(
junctionInfo,
targetIdColumn,
parentEntityId,
registry
);
joinConditions.push(junctionResult.join);
whereConditions.push(junctionResult.condition);
} else Iif (relation.foreignKeyOnTarget) {
console.debug(`🔍 [buildRelationConditions] No junction table found, treating as inverse one-to-many with foreign key on target`);
// This is a true inverse one-to-many relationship
const simpleCondition = this.buildSimpleRelationCondition(
relation,
targetTable,
parentTable,
parentEntityId
);
whereConditions.push(simpleCondition);
} else {
console.error(`🔍 [buildRelationConditions] Failed to find junction table info and no foreign key specified`);
throw new Error(`Cannot resolve inverse many relation '${relation.relationName}'. Either specify 'through' property, ensure corresponding owning relation exists with junction table configuration, or specify 'foreignKeyOnTarget' for one-to-many relationships.`);
}
} else E{
console.debug(`🔍 [buildRelationConditions] Using simple relation logic - THIS IS WHERE THE ERROR MIGHT OCCUR`);
// Handle simple relations
const simpleCondition = this.buildSimpleRelationCondition(
relation,
targetTable,
parentTable,
parentEntityId
);
whereConditions.push(simpleCondition);
}
console.debug(`🔍 [buildRelationConditions] Final result:`, {
joinConditionsCount: joinConditions.length,
whereConditionsCount: whereConditions.length
});
return {
joinConditions,
whereConditions
};
}
/**
* Build conditions for join path relations
*/
private static buildJoinPathConditions(
joinPath: JoinStep[],
targetTable: PgTable<any>,
parentTable: PgTable<any>,
parentIdColumn: AnyPgColumn,
parentEntityId: string | number | (string | number)[],
registry: BackendCollectionRegistry
): {
joins: { table: PgTable<any>; condition: SQL }[];
finalCondition: SQL;
} {
const joins: { table: PgTable<any>; condition: SQL }[] = [];
let currentTable = targetTable;
// Process join steps in reverse order to build path back to parent
for (const joinStep of [...joinPath].reverse()) {
const fromTableName = this.getTableNamesFromColumns(joinStep.on.from)[0];
const toTableName = this.getTableNamesFromColumns(joinStep.on.to)[0];
const fromColName = this.getColumnNamesFromColumns(joinStep.on.from)[0];
const toColName = this.getColumnNamesFromColumns(joinStep.on.to)[0];
const fromTable = registry.getTable(fromTableName);
const toTable = registry.getTable(toTableName);
if (!fromTable || !toTable) {
throw new Error(`Join tables not found for step: from ${fromTableName} to ${toTableName}`);
}
const {
joinTable,
condition,
additionalJoins
} = this.buildSingleJoinCondition(
currentTable,
fromTable,
toTable,
fromColName,
toColName,
fromTableName,
toTableName,
registry
);
joins.push({
table: joinTable,
condition
});
currentTable = joinTable;
// Add any additional joins needed for many-to-many relationships
if (additionalJoins && additionalJoins.length > 0) {
joins.push(...additionalJoins);
}
}
// Ensure we've connected back to the parent table
// For junction tables, we might end up at the junction table instead of the parent table
if (currentTable !== parentTable) {
// Try to get table names from the Drizzle table objects
let currentTableName = "unknown";
let parentTableName = "unknown";
// Try multiple ways to extract table names from Drizzle objects
if (currentTable && typeof currentTable === "object") {
// Check common Drizzle table name properties
currentTableName = (currentTable as unknown as Record<string | symbol, unknown>)[Symbol.for("drizzle:Name")] as string ||
((currentTable as unknown as Record<string, unknown>)._ as Record<string, unknown>)?.name as string ||
(currentTable as unknown as Record<string, unknown>).tableName as string ||
(currentTable as unknown as Record<string, unknown>).name as string ||
"unknown";
}
if (parentTable && typeof parentTable === "object") {
parentTableName = (parentTable as unknown as Record<string | symbol, unknown>)[Symbol.for("drizzle:Name")] as string ||
((parentTable as unknown as Record<string, unknown>)._ as Record<string, unknown>)?.name as string ||
(parentTable as unknown as Record<string, unknown>).tableName as string ||
(parentTable as unknown as Record<string, unknown>).name as string ||
"unknown";
}
// For junction table scenarios, be more lenient with validation
// If we can't determine table names reliably, or if this looks like a junction table scenario,
// we'll allow it and let the SQL execution validate the correctness
const couldBeJunctionScenario = currentTableName.includes("_") ||
currentTableName === "unknown" ||
parentTableName === "unknown";
Iif (!couldBeJunctionScenario) {
throw new Error(`Join path did not result in connecting to parent table. Current: ${currentTableName}, Parent: ${parentTableName}`);
}
}
// Handle both single ID and array of IDs
const finalCondition = Array.isArray(parentEntityId)
? inArray(parentIdColumn, parentEntityId)
: eq(parentIdColumn, parentEntityId);
return {
joins,
finalCondition
};
}
/**
* Build a single join condition between tables
*/
private static buildSingleJoinCondition(
currentTable: PgTable<any>,
fromTable: PgTable<any>,
toTable: PgTable<any>,
fromColName: string,
toColName: string,
fromTableName: string,
toTableName: string,
registry?: BackendCollectionRegistry
): { joinTable: PgTable<any>; condition: SQL; additionalJoins?: { table: PgTable<any>; condition: SQL }[] } {
let joinTable: PgTable<any>;
let condition: SQL;
const additionalJoins: { table: PgTable<any>; condition: SQL }[] = [];
if (currentTable === toTable) {
// current -> toTable, so join the fromTable
const left = fromTable[fromColName as keyof typeof fromTable] as AnyPgColumn;
const right = (currentTable as unknown as Record<string, unknown>)[toColName] as AnyPgColumn;
if (!left || !right) {
// Check if this might be a many-to-many relationship requiring a junction table
if (registry) {
const junctionResult = this.tryBuildJunctionJoin(
currentTable,
fromTable,
fromColName,
toColName,
fromTableName,
toTableName,
registry
);
if (junctionResult) {
return junctionResult;
}
}
throw new Error(`Join columns not found: ${fromTableName}.${fromColName} = ${toTableName}.${toColName}`);
}
joinTable = fromTable;
condition = eq(left, right);
} else Eif (currentTable === fromTable) {
// current -> fromTable, so join the toTable
const left = toTable[toColName as keyof typeof toTable] as AnyPgColumn;
const right = (currentTable as unknown as Record<string, unknown>)[fromColName] as AnyPgColumn;
Iif (!left || !right) {
// Check if this might be a many-to-many relationship requiring a junction table
Iif (registry) {
const junctionResult = this.tryBuildJunctionJoin(
currentTable,
toTable,
fromColName,
toColName,
fromTableName,
toTableName,
registry
);
Iif (junctionResult) {
return junctionResult;
}
}
throw new Error(`Join columns not found: ${toTableName}.${toColName} = ${fromTableName}.${fromColName}`);
}
joinTable = toTable;
condition = eq(left, right);
} else {
throw new Error(`Join step does not match current table. Current table does not match from: ${fromTableName} or to: ${toTableName}`);
}
return {
joinTable,
condition,
additionalJoins
};
}
/**
* Try to build a junction table join when direct foreign key relationship is not found
*/
private static tryBuildJunctionJoin(
currentTable: PgTable<any>,
targetTable: PgTable<any>,
fromColName: string,
toColName: string,
fromTableName: string,
toTableName: string,
registry: BackendCollectionRegistry
): { joinTable: PgTable<any>; condition: SQL; additionalJoins: { table: PgTable<any>; condition: SQL }[] } | null {
// Try to find a junction table that connects these two tables
// Common naming patterns: table1_table2, table1Table2, etc.
const possibleJunctionNames = [
`${fromTableName}_${toTableName}`,
`${toTableName}_${fromTableName}`,
`${fromTableName}${toTableName.charAt(0).toUpperCase() + toTableName.slice(1)}`,
`${toTableName}${fromTableName.charAt(0).toUpperCase() + fromTableName.slice(1)}`
];
for (const junctionName of possibleJunctionNames) {
const junctionTable = registry.getTable(junctionName);
if (junctionTable) {
// Try to find the appropriate columns in the junction table
const sourceColName = `${fromTableName.slice(0, -1)}_id`; // Remove 's' and add '_id'
const targetColName = `${toTableName.slice(0, -1)}_id`;
const junctionSourceCol = junctionTable[sourceColName as keyof typeof junctionTable] as AnyPgColumn;
const junctionTargetCol = junctionTable[targetColName as keyof typeof junctionTable] as AnyPgColumn;
if (junctionSourceCol && junctionTargetCol) {
// Found a valid junction table setup
const currentTableIdCol = Object.values(currentTable).find((col: Record<string, unknown>) => col.primary) as AnyPgColumn;
const targetTableIdCol = Object.values(targetTable).find((col: Record<string, unknown>) => col.primary) as AnyPgColumn;
Iif (!currentTableIdCol || !targetTableIdCol) {
continue; // Skip if we can't find primary keys
}
// Determine which direction to join
Iif (currentTable === targetTable) {
// We're joining through junction to reach the other table
return {
joinTable: targetTable,
condition: eq(targetTableIdCol, junctionTargetCol),
additionalJoins: [
{
table: junctionTable,
condition: eq(currentTableIdCol, junctionSourceCol)
}
]
};
} else {
// Standard junction join
return {
joinTable: junctionTable,
condition: eq(currentTableIdCol, junctionSourceCol),
additionalJoins: [
{
table: targetTable,
condition: eq(targetTableIdCol, junctionTargetCol)
}
]
};
}
}
}
}
return null; // No junction table found
}
/**
* Build conditions for junction table (many-to-many) relations
*/
private static buildJunctionTableConditions(
through: { table: string; sourceColumn: string; targetColumn: string },
targetIdColumn: AnyPgColumn,
parentEntityId: string | number | (string | number)[],
registry: BackendCollectionRegistry
): { join: { table: PgTable<any>; condition: SQL }; condition: SQL } {
const junctionTable = registry.getTable(through.table);
Iif (!junctionTable) {
throw new Error(`Junction table not found: ${through.table}`);
}
const junctionSourceCol = junctionTable[through.sourceColumn as keyof typeof junctionTable] as AnyPgColumn;
const junctionTargetCol = junctionTable[through.targetColumn as keyof typeof junctionTable] as AnyPgColumn;
Iif (!junctionSourceCol) {
throw new Error(`Source column '${through.sourceColumn}' not found in junction table '${through.table}'`);
}
Iif (!junctionTargetCol) {
throw new Error(`Target column '${through.targetColumn}' not found in junction table '${through.table}'`);
}
// Handle both single ID and array of IDs
const condition = Array.isArray(parentEntityId)
? inArray(junctionSourceCol, parentEntityId)
: eq(junctionSourceCol, parentEntityId);
return {
join: {
table: junctionTable,
condition: eq(targetIdColumn, junctionTargetCol)
},
condition
};
}
/**
* Build conditions for inverse junction table (many-to-many) relations
*/
private static buildInverseJunctionTableConditions(
through: { table: string; sourceColumn: string; targetColumn: string },
targetIdColumn: AnyPgColumn,
parentEntityId: string | number | (string | number)[],
registry: BackendCollectionRegistry
): { join: { table: PgTable<any>; condition: SQL }; condition: SQL } {
const junctionTable = registry.getTable(through.table);
if (!junctionTable) {
throw new Error(`Junction table not found: ${through.table}`);
}
const junctionSourceCol = junctionTable[through.sourceColumn as keyof typeof junctionTable] as AnyPgColumn;
const junctionTargetCol = junctionTable[through.targetColumn as keyof typeof junctionTable] as AnyPgColumn;
if (!junctionSourceCol) {
throw new Error(`Source column '${through.sourceColumn}' not found in junction table '${through.table}'`);
}
if (!junctionTargetCol) {
throw new Error(`Target column '${through.targetColumn}' not found in junction table '${through.table}'`);
}
// For inverse relations, the parentEntityId (tag ID) should match the sourceColumn (tag_id)
// and we want to find target entities (posts) through the targetColumn (post_id)
const condition = Array.isArray(parentEntityId)
? inArray(junctionSourceCol, parentEntityId)
: eq(junctionSourceCol, parentEntityId);
return {
join: {
table: junctionTable,
condition: eq(targetIdColumn, junctionTargetCol)
},
condition
};
}
/**
* Build conditions for simple relations (owning/inverse without join paths)
*/
private static buildSimpleRelationCondition(
relation: Relation,
targetTable: PgTable<any>,
parentTable: PgTable<any>,
parentEntityId: string | number | (string | number)[]
): SQL {
if (relation.direction === "owning" && relation.localKey) {
// For owning relations, the parentEntityId is actually the foreign key value
// that should match the target table's primary key
const targetIdCol = Object.values(targetTable).find((col: Record<string, unknown>) => col.primary) as AnyPgColumn;
Iif (!targetIdCol) {
// Fallback to looking for an "id" column by name
const idCol = Object.values(targetTable).find((col: Record<string, unknown>) => col.name === "id") as AnyPgColumn;
Iif (!idCol) {
throw new Error("No primary key or \"id\" column found in target table");
}
return Array.isArray(parentEntityId)
? inArray(idCol, parentEntityId)
: eq(idCol, parentEntityId);
}
return Array.isArray(parentEntityId)
? inArray(targetIdCol, parentEntityId)
: eq(targetIdCol, parentEntityId);
} else if (relation.direction === "inverse" && relation.foreignKeyOnTarget) {
// Inverse relation: use foreign key on target table
const foreignKeyCol = targetTable[relation.foreignKeyOnTarget as keyof typeof targetTable] as AnyPgColumn;
Iif (!foreignKeyCol) {
// This could be a many-to-many relationship where foreignKeyOnTarget was set by sanitizeRelation
// but the column doesn't actually exist. In this case, we should suggest using junction tables.
throw new Error(`Foreign key column '${relation.foreignKeyOnTarget}' not found in target table. This might be a many-to-many relationship that requires a junction table. Consider using 'through' property or ensure the corresponding owning relation exists with junction table configuration.`);
}
return Array.isArray(parentEntityId)
? inArray(foreignKeyCol, parentEntityId)
: eq(foreignKeyCol, parentEntityId);
} else if (relation.direction === "inverse" && relation.cardinality === "many" && relation.inverseRelationName) {
// For inverse many-to-many relations, this should not be called directly
// The buildRelationConditions method should handle finding the junction table
// If we reach here, it means the junction table lookup failed
throw new Error(`Inverse many-to-many relation '${relation.relationName}' requires a junction table. Either specify 'through' property or ensure the corresponding owning relation exists with junction table configuration.`);
} else if (relation.direction === "inverse" && relation.cardinality === "one" && relation.inverseRelationName) {
// Auto-infer foreign key column for inverse one-to-one relations
// Pattern: {inverseRelationName}_id (e.g., "author" -> "author_id")
const inferredForeignKeyName = `${relation.inverseRelationName}_id`;
const foreignKeyCol = targetTable[inferredForeignKeyName as keyof typeof targetTable] as AnyPgColumn;
Iif (!foreignKeyCol) {
throw new Error(`Auto-inferred foreign key column '${inferredForeignKeyName}' not found in target table for inverse relation '${relation.relationName}'. Please specify 'foreignKeyOnTarget' explicitly.`);
}
console.debug(`🔍 [DrizzleConditionBuilder] Auto-inferred foreign key '${inferredForeignKeyName}' for inverse relation '${relation.relationName}'`);
return Array.isArray(parentEntityId)
? inArray(foreignKeyCol, parentEntityId)
: eq(foreignKeyCol, parentEntityId);
} else {
throw new Error(`Relation '${relation.relationName}' lacks proper configuration. For many-to-many relations, use 'through' property. For simple relations, use 'localKey' or 'foreignKeyOnTarget'.`);
}
}
/**
* Combine multiple conditions with AND operator
*/
static combineConditionsWithAnd(conditions: SQL[]): SQL | undefined {
Iif (conditions.length === 0) return undefined;
Iif (conditions.length === 1) return conditions[0];
return and(...conditions);
}
/**
* Combine multiple conditions with OR operator
*/
static combineConditionsWithOr(conditions: SQL[]): SQL | undefined {
Iif (conditions.length === 0) return undefined;
Iif (conditions.length === 1) return conditions[0];
return or(...conditions);
}
/**
* Build search conditions for text fields
*/
static buildSearchConditions(
searchString: string,
properties: Record<string, any>,
table: PgTable<any>
): SQL[] {
const searchConditions: SQL[] = [];
for (const [key, prop] of Object.entries(properties)) {
// Only include string properties that don't have enum defined
// PostgreSQL enum and uuid columns don't support ILIKE, so we skip them
Iif (prop.type === "string" && !prop.enum && prop.isId !== "uuid") {
const fieldColumn = table[key as keyof typeof table] as AnyPgColumn;
Iif (fieldColumn) {
searchConditions.push(ilike(fieldColumn, `%${searchString}%`));
}
}
}
return searchConditions;
}
/**
* Build a unique field check condition
*/
static buildUniqueFieldCondition(
fieldColumn: AnyPgColumn,
value: unknown,
idColumn?: AnyPgColumn,
excludeId?: string | number
): SQL[] {
const conditions: SQL[] = [eq(fieldColumn, value)];
Iif (excludeId && idColumn) {
conditions.push(sql`${idColumn} != ${excludeId}`);
}
return conditions;
}
/**
* Build relation-based query with joins and conditions
*/
static buildRelationQuery<T extends DrizzleDynamicQuery>(
baseQuery: T,
relation: Relation,
parentEntityId: string | number | (string | number)[],
targetTable: PgTable<any>,
parentTable: PgTable<any>,
parentIdColumn: AnyPgColumn,
targetIdColumn: AnyPgColumn,
registry: BackendCollectionRegistry,
additionalFilters?: SQL[]
): T {
const { joinConditions, whereConditions } = this.buildRelationConditions(
relation,
parentEntityId,
targetTable,
parentTable,
parentIdColumn,
targetIdColumn,
registry
);
let query = baseQuery;
// Apply joins
for (const { table, condition } of joinConditions) {
query = query.innerJoin(table, condition);
}
// Combine all conditions
const allConditions = [...whereConditions];
if (additionalFilters) {
allConditions.push(...additionalFilters);
}
// Apply where conditions
if (allConditions.length > 0) {
query = query.where(and(...allConditions));
}
return query;
}
/**
* Build count query for relations with proper joins and conditions
*/
static buildRelationCountQuery<T extends DrizzleDynamicQuery>(
baseCountQuery: T,
relation: Relation,
parentEntityId: string | number,
targetTable: PgTable<any>,
parentTable: PgTable<any>,
parentIdColumn: AnyPgColumn,
targetIdColumn: AnyPgColumn,
registry: BackendCollectionRegistry,
additionalFilters?: SQL[]
): T {
// For count queries, we need to handle joins differently to avoid duplicates
Iif (relation.joinPath && relation.joinPath.length > 0) {
return this.buildJoinPathCountQuery(
baseCountQuery,
relation.joinPath,
targetTable,
parentTable,
parentIdColumn,
parentEntityId,
registry,
additionalFilters
);
} else if (relation.through && relation.cardinality === "many" && relation.direction === "owning") {
return this.buildJunctionCountQuery(
baseCountQuery,
relation.through,
targetIdColumn,
parentEntityId,
registry,
additionalFilters
);
} else if (relation.through && relation.cardinality === "many" && relation.direction === "inverse") {
return this.buildInverseJunctionCountQuery(
baseCountQuery,
relation.through,
targetIdColumn,
parentEntityId,
registry,
additionalFilters
);
} else E{
// Simple relations
const simpleCondition = this.buildSimpleRelationCondition(
relation,
targetTable,
parentTable,
parentEntityId
);
const allConditions = [simpleCondition];
Iif (additionalFilters) {
allConditions.push(...additionalFilters);
}
return baseCountQuery.where(and(...allConditions));
}
}
/**
* Build join path conditions for count queries
*/
private static buildJoinPathCountQuery<T extends DrizzleDynamicQuery>(
baseCountQuery: T,
joinPath: JoinStep[],
targetTable: PgTable<any>,
parentTable: PgTable<any>,
parentIdColumn: AnyPgColumn,
parentEntityId: string | number,
registry: BackendCollectionRegistry,
additionalFilters?: SQL[]
): T {
let query = baseCountQuery;
let currentTable = targetTable;
// Process join steps in reverse order
for (const joinStep of [...joinPath].reverse()) {
const fromTableName = this.getTableNamesFromColumns(joinStep.on.from)[0];
const toTableName = this.getTableNamesFromColumns(joinStep.on.to)[0];
const fromColName = this.getColumnNamesFromColumns(joinStep.on.from)[0];
const toColName = this.getColumnNamesFromColumns(joinStep.on.to)[0];
const fromTable = registry.getTable(fromTableName);
const toTable = registry.getTable(toTableName);
Iif (!fromTable || !toTable) {
throw new Error(`Join tables not found for step: from ${fromTableName} to ${toTableName}`);
}
const { joinTable, condition } = this.buildSingleJoinCondition(
currentTable,
fromTable,
toTable,
fromColName,
toColName,
fromTableName,
toTableName
);
query = query.innerJoin(joinTable, condition);
currentTable = joinTable;
}
Iif (currentTable !== parentTable) {
throw new Error("Join path did not result in connecting to parent table");
}
const allConditions = [eq(parentIdColumn, parentEntityId)];
Iif (additionalFilters) {
allConditions.push(...additionalFilters);
}
return query.where(and(...allConditions));
}
/**
* Build junction table conditions for count queries
*/
private static buildJunctionCountQuery<T extends DrizzleDynamicQuery>(
baseCountQuery: T,
through: { table: string; sourceColumn: string; targetColumn: string },
targetIdColumn: AnyPgColumn,
parentEntityId: string | number,
registry: BackendCollectionRegistry,
additionalFilters?: SQL[]
): T {
const junctionTable = registry.getTable(through.table);
Iif (!junctionTable) {
throw new Error(`Junction table not found: ${through.table}`);
}
const junctionSourceCol = junctionTable[through.sourceColumn as keyof typeof junctionTable] as AnyPgColumn;
const junctionTargetCol = junctionTable[through.targetColumn as keyof typeof junctionTable] as AnyPgColumn;
Iif (!junctionSourceCol) {
throw new Error(`Source column '${through.sourceColumn}' not found in junction table '${through.table}'`);
}
Iif (!junctionTargetCol) {
throw new Error(`Target column '${through.targetColumn}' not found in junction table '${through.table}'`);
}
const baseConditions = [eq(junctionSourceCol, parentEntityId)];
Iif (additionalFilters && additionalFilters.length > 0) {
baseConditions.push(...additionalFilters);
}
return baseCountQuery
.innerJoin(junctionTable, eq(targetIdColumn, junctionTargetCol))
.where(and(...baseConditions));
}
/**
* Build inverse junction table conditions for count queries
*/
private static buildInverseJunctionCountQuery<T extends DrizzleDynamicQuery>(
baseCountQuery: T,
through: { table: string; sourceColumn: string; targetColumn: string },
targetIdColumn: AnyPgColumn,
parentEntityId: string | number,
registry: BackendCollectionRegistry,
additionalFilters?: SQL[]
): T {
const junctionTable = registry.getTable(through.table);
Iif (!junctionTable) {
throw new Error(`Junction table not found: ${through.table}`);
}
const junctionSourceCol = junctionTable[through.sourceColumn as keyof typeof junctionTable] as AnyPgColumn;
const junctionTargetCol = junctionTable[through.targetColumn as keyof typeof junctionTable] as AnyPgColumn;
Iif (!junctionSourceCol) {
throw new Error(`Source column '${through.sourceColumn}' not found in junction table '${through.table}'`);
}
Iif (!junctionTargetCol) {
throw new Error(`Target column '${through.targetColumn}' not found in junction table '${through.table}'`);
}
const baseConditions = [eq(junctionSourceCol, parentEntityId)];
Iif (additionalFilters && additionalFilters.length > 0) {
baseConditions.push(...additionalFilters);
}
return baseCountQuery
.innerJoin(junctionTable, eq(targetIdColumn, junctionTargetCol))
.where(and(...baseConditions));
}
/**
* Helper method to extract table names from columns
*/
static getTableNamesFromColumns(columns: string | string[]): string[] {
Iif (Array.isArray(columns)) {
return columns.map(col => col.includes(".") ? col.split(".")[0] : "");
}
return [columns.includes(".") ? columns.split(".")[0] : ""];
}
/**
* Helper method to extract column names from columns
*/
static getColumnNamesFromColumns(columns: string | string[]): string[] {
Iif (Array.isArray(columns)) {
return columns.map(col => getColumnName(col));
}
return [getColumnName(columns)];
}
/**
* Find the corresponding junction table for an inverse many-to-many relation
*/
private static findCorrespondingJunctionTable(
relation: Relation,
registry: BackendCollectionRegistry
): { table: string; sourceColumn: string; targetColumn: string } | null {
try {
console.debug(`🔍 [findCorrespondingJunctionTable] Looking for junction table for inverse relation '${relation.relationName}' with inverseRelationName '${relation.inverseRelationName}'`);
if (!relation.inverseRelationName) {
console.debug(`🔍 [findCorrespondingJunctionTable] No inverseRelationName specified`);
return null;
}
// Get the target collection of the inverse relation
const targetCollection = relation.target();
console.debug(`🔍 [findCorrespondingJunctionTable] Target collection: ${targetCollection.slug || targetCollection.dbPath}`);
// Find the corresponding owning relation on the target collection
const targetCollectionRelations = resolveCollectionRelations(targetCollection);
console.debug(`🔍 [findCorrespondingJunctionTable] Target collection relations:`, Object.keys(targetCollectionRelations));
// Look for the owning many-to-many relation that matches our inverseRelationName
const correspondingRelation = targetCollectionRelations[relation.inverseRelationName];
if (!correspondingRelation) {
console.debug(`🔍 [findCorrespondingJunctionTable] No relation found with key '${relation.inverseRelationName}' on target collection`);
return null;
}
console.debug(`🔍 [findCorrespondingJunctionTable] Found relation:`, {
relationName: correspondingRelation.relationName,
cardinality: correspondingRelation.cardinality,
direction: correspondingRelation.direction,
hasThrough: !!correspondingRelation.through
});
// Verify it's an owning many-to-many relation with junction table
Iif (correspondingRelation.cardinality !== "many" ||
correspondingRelation.direction !== "owning" ||
!correspondingRelation.through) {
console.debug(`🔍 [findCorrespondingJunctionTable] Relation is not an owning many-to-many with junction table`);
return null;
}
console.debug(`🔍 [findCorrespondingJunctionTable] Found matching owning relation with junction table!`);
// For inverse relation, we need to swap source and target columns
const through = correspondingRelation.through;
const result = {
table: through.table,
sourceColumn: through.targetColumn, // Swapped for inverse relation
targetColumn: through.sourceColumn // Swapped for inverse relation
};
console.debug(`🔍 [findCorrespondingJunctionTable] Returning junction info:`, result);
return result;
} catch (error) {
console.error(`🔍 [findCorrespondingJunctionTable] Error finding corresponding junction table for relation '${relation.relationName}':`, error);
return null;
}
}
}
/**
* Alias for DrizzleConditionBuilder for consistent naming with other database implementations.
* This allows code to use PostgresConditionBuilder alongside future MongoConditionBuilder, etc.
*/
export const PostgresConditionBuilder = DrizzleConditionBuilder;
|