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 | 2x 2x 43x 65x 43x 3x 40x 40x 40x 2x 14x 2x 29x 2x 86x 175x 77x 2x 114x 114x 68x 68x 68x 2x 66x 2x 64x 2x 62x 68x 6x 68x 3x 2x 1x 1x 1x 1x 68x 1x 68x 18x 18x 18x 18x 9x 8x 18x 2x 16x 16x 18x 3x 18x 1x 18x 3x 3x 5x 5x 1x 4x 1x 3x 5x 6x 6x 2x 4x 6x 14x 14x 14x 14x 8x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 100x 2x 100x 2x 8x 8x 2x 5x 4x 4x 2x 4x 4x 2x 35x 7x 28x 12x 16x 12x 4x 2x 9x 1x 8x 2x 27x 27x 31x 31x 2x 31x 31x 31x 31x 31x 31x 31x 8x 4x 4x 6x 4x 8x 8x 31x 31x 31x 31x 31x 31x 32x 31x 31x 31x 2x 56x 68x 56x 68x 114x 56x 68x 111x 56x 56x 56x 56x 56x 56x 56x 56x 56x 56x 56x 56x 68x 68x 114x 56x 56x 68x 68x 68x 68x 68x 14x 4x 4x 4x 56x 72x 72x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 68x 68x 68x 68x 114x 114x 105x 68x 59x 68x 68x 68x 24x 24x 27x 24x 44x 72x 56x 72x 72x 72x 8x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 4x 4x 4x 68x 68x 14x 14x 14x 14x 14x 14x 7x 6x 1x 1x 1x 7x 7x 1x 6x 4x 4x 2x 72x 16x 16x 16x 56x 56x 56x 56x 56x | import { EntityCollection, NumberProperty, Property, Relation, RelationProperty, SecurityOperation, SecurityRule, StringProperty } from "@rebasepro/types";
import { getPrimaryKeys } from "./db/services/entity-helpers";
import {
getEnumVarName,
getTableName,
getTableVarName,
resolveCollectionRelations,
toSnakeCase
} from "@rebasepro/common";
// --- Helper Functions ---
const getPrimaryKeyProp = (collection: EntityCollection): { name: string, type: "string" | "number" } => {
if (collection.properties) {
const idPropEntry = Object.entries(collection.properties).find(([_, prop]) => "isId" in (prop as object) && Boolean((prop as unknown as Record<string, unknown>).isId));
if (idPropEntry) {
return { name: idPropEntry[0], type: (idPropEntry[1] as Property).type === "number" ? "number" : "string" };
}
}
// Fallback
const idProp = collection.properties?.["id"] as Property | undefined;
Iif (idProp?.type === "number") {
return { name: "id", type: "number" };
}
return { name: "id", type: "string" };
};
const isNumericId = (collection: EntityCollection): boolean => {
return getPrimaryKeyProp(collection).type === "number";
};
const getPrimaryKeyName = (collection: EntityCollection): string => {
return getPrimaryKeyProp(collection).name;
};
const isIdProperty = (propName: string, prop: Property, collection: EntityCollection): boolean => {
if ("isId" in prop && Boolean(prop.isId)) return true;
// We only fallback to "id" if NO property is explicitly marked with `isId: true` or a generator string
const hasExplicitId = Object.values(collection.properties ?? {}).some(p => "isId" in (p as object) && Boolean((p as unknown as Record<string, unknown>).isId));
return !hasExplicitId && propName === "id";
};
const getDrizzleColumn = (propName: string, prop: Property, collection: EntityCollection): string | null => {
const colName = toSnakeCase(propName);
let columnDefinition: string;
switch (prop.type) {
case "string": {
const stringProp = prop as StringProperty;
Iif (stringProp.enum) {
const enumName = getEnumVarName(getTableName(collection), propName);
columnDefinition = `${enumName}("${colName}")`;
} else if ("isId" in stringProp && stringProp.isId === "uuid") {
columnDefinition = `uuid("${colName}")`;
} else if (stringProp.columnType === "text") {
columnDefinition = `text("${colName}")`;
} else if (stringProp.columnType === "char") {
columnDefinition = `char("${colName}")`;
} else {
columnDefinition = `varchar("${colName}")`;
}
if (isIdProperty(propName, prop, collection)) {
columnDefinition += `.primaryKey()`;
}
if ("isId" in stringProp && stringProp.isId !== "manual" && stringProp.isId !== true) {
if (stringProp.isId === "uuid") {
columnDefinition += `.defaultRandom()`;
} else Iif (stringProp.isId === "cuid") {
columnDefinition += `.default(sql\`cuid()\`)`;
} else if (typeof stringProp.isId === "string") {
const sqlContent = stringProp.isId.startsWith("sql`") && stringProp.isId.endsWith("`")
? stringProp.isId.substring(4, stringProp.isId.length - 1)
: stringProp.isId;
columnDefinition += `.default(sql\`${sqlContent}\`)`;
}
}
if (stringProp.validation?.unique) {
columnDefinition += `.unique()`;
}
break;
}
case "number": {
const numProp = prop as NumberProperty;
const isId = isIdProperty(propName, prop, collection);
let baseType = (numProp.validation?.integer || isId) ? `integer("${colName}")` : `numeric("${colName}")`;
if (numProp.columnType) {
if (numProp.columnType === "double precision") baseType = `doublePrecision("${colName}")`;
else baseType = `${numProp.columnType}("${colName}")`;
}
if ("isId" in numProp && numProp.isId === "increment") {
columnDefinition = `${baseType}.generatedByDefaultAsIdentity()`;
} else Iif ("isId" in numProp && typeof numProp.isId === "string" && numProp.isId !== "manual") {
columnDefinition = baseType;
const sqlContent = numProp.isId.startsWith("sql`") && numProp.isId.endsWith("`")
? numProp.isId.substring(4, numProp.isId.length - 1)
: numProp.isId;
columnDefinition += `.default(sql\`${sqlContent}\`)`;
} else {
columnDefinition = baseType;
}
if (isId) {
columnDefinition += `.primaryKey()`;
}
if (numProp.validation?.unique) {
columnDefinition += `.unique()`;
}
break;
}
case "boolean":
columnDefinition = `boolean("${colName}")`;
break;
case "date": {
const dateProp = prop as import("@rebasepro/types").DateProperty;
if (dateProp.columnType === "date") {
columnDefinition = `date("${colName}", { mode: 'string' })`;
} else if (dateProp.columnType === "time") {
columnDefinition = `time("${colName}")`;
} else {
columnDefinition = `timestamp("${colName}", { withTimezone: true, mode: 'string' })`;
}
break;
}
case "map":
case "array": {
const arrayOrMapProp = prop as import("@rebasepro/types").ArrayProperty | import("@rebasepro/types").MapProperty;
if (arrayOrMapProp.columnType === "json") {
columnDefinition = `json("${colName}")`;
} else {
columnDefinition = `jsonb("${colName}")`;
}
break;
}
case "relation": {
const refProp = prop as RelationProperty;
const resolvedRelations = resolveCollectionRelations(collection);
const relation = resolvedRelations[refProp.relationName ?? propName];
// Only owning one-to-one/many-to-one relations create a column here.
if (!relation || relation.direction !== "owning" || relation.cardinality !== "one") {
return null;
}
// The localKey property is the source of truth for the FK column name.
Iif (!relation.localKey) {
console.warn(`Could not generate column for owning relation '${relation.relationName}' on '${collection.name}': 'localKey' is not defined.`);
return null;
}
// If the localKey property is defined elsewhere in the properties, it will be handled there.
// This logic is for when the relation property itself defines the FK.
Iif (collection.properties[relation.localKey] && propName !== relation.localKey) {
return null;
}
let targetCollection: EntityCollection;
try {
targetCollection = relation.target();
} catch {
return null; // Cannot resolve target
}
const fkColumnName = toSnakeCase(relation.localKey);
const targetTableVar = getTableVarName(getTableName(targetCollection));
const targetIdField = getPrimaryKeyName(targetCollection);
const baseColumn = isNumericId(targetCollection) ? `integer(\"${fkColumnName}\")` : `varchar(\"${fkColumnName}\")`;
const onUpdate = relation.onUpdate ? `onUpdate: \"${relation.onUpdate}\"` : "";
const required = prop.validation?.required;
const onDeleteVal = relation.onDelete ?? (required ? "cascade" : "set null");
const onDelete = `onDelete: \"${onDeleteVal}\"`;
const refOptionsParts = [onUpdate, onDelete].filter(Boolean);
const refOptions = refOptionsParts.length > 0 ? `{ ${refOptionsParts.join(", ")} }` : "";
let columnDef = `${baseColumn}.references(() => ${targetTableVar}.${targetIdField}${refOptions ? `, ${refOptions}` : ""})`;
Iif (required) {
columnDef += ".notNull()";
}
return ` ${relation.localKey}: ${columnDef}`;
}
default:
return null;
}
if (prop.validation?.required) {
columnDefinition += ".notNull()";
}
return ` ${propName}: ${columnDefinition}`;
};
/**
* Resolves a raw SQL string, replacing `{column_name}` with `${table.column_name}`.
* The result is wrapped in a Drizzle sql`` template literal.
*/
const resolveRawSql = (expression: string): string => {
// Replace {column_name} with ${table.column_name}
const resolved = expression.replace(/\{(\w+)\}/g, (_, col) => `\${table.${col}}`);
return `sql\`${resolved}\``;
};
/**
* Wraps a SQL clause with a role check using AND.
* Generates: `(<clause>) AND (string_to_array(auth.roles(), ',') && ARRAY['<role1>','<role2>'])`
*/
const wrapWithRoleCheck = (clause: string, roles: string[]): string => {
const rolesArrayString = `ARRAY[${roles.map(r => `'${r}'`).join(',')}]`;
const roleCondition = `string_to_array(auth.roles(), ',') @> ${rolesArrayString}`;
return `sql\`(${unwrapSql(clause)}) AND (${roleCondition})\``;
};
/**
* Extracts the inner expression from a `sql\`...\`` wrapper.
*/
const unwrapSql = (sqlExpr: string): string => {
const match = sqlExpr.match(/^sql`(.*)`$/s);
return match ? match[1] : sqlExpr;
};
/**
* Builds the USING clause for a policy based on shortcuts or raw SQL.
*/
const buildUsingClause = (rule: SecurityRule): string | null => {
if (rule.using) {
return resolveRawSql(rule.using);
}
if (rule.access === "public") {
return `sql\`true\``;
}
if (rule.ownerField) {
return `sql\`\${table.${rule.ownerField}} = auth.uid()\``;
}
return null;
};
/**
* Builds the WITH CHECK clause for a policy based on shortcuts or raw SQL.
* Falls back to the USING clause if not explicitly provided.
*/
const buildWithCheckClause = (rule: SecurityRule): string | null => {
if (rule.withCheck) {
return resolveRawSql(rule.withCheck);
}
// For insert/update/all, fall back to using clause if withCheck not specified
return buildUsingClause(rule);
};
/**
* Generates Drizzle pgPolicy() calls from a declarative SecurityRule definition.
*
* Supports the full spectrum:
* - Convenience shortcuts: ownerField, access, roles
* - Raw SQL: using, withCheck
* - Mode: permissive (default) or restrictive
* - operations[] array: generates one policy per operation
* - Combinations: roles + ownerField, roles + raw SQL, etc.
*/
const generatePolicyCode = (tableName: string, rule: SecurityRule, index: number): string => {
// Resolve operations: operations[] takes precedence over operation (singular)
const ops: SecurityOperation[] = rule.operations && rule.operations.length > 0
? rule.operations
: [rule.operation ?? "all"];
// Generate one pgPolicy per operation
return ops.map((op, opIdx) => {
const policyName = rule.name
? (ops.length > 1 ? `${rule.name}_${op}` : rule.name)
: `${tableName}_${op}_policy_${index}${ops.length > 1 ? `_${opIdx}` : ""}`;
return generateSinglePolicyCode(tableName, rule, op, policyName);
}).join("");
};
/**
* Generates a single pgPolicy() call for one specific operation.
*/
const generateSinglePolicyCode = (tableName: string, rule: SecurityRule, operation: SecurityOperation, policyName: string): string => {
const mode = rule.mode ?? "permissive";
const roles = rule.roles;
// Determine which clauses this operation needs:
// SELECT, DELETE → USING only
// INSERT → WITH CHECK only
// UPDATE, ALL → both USING and WITH CHECK
const needsUsing = operation !== "insert";
const needsWithCheck = operation !== "select" && operation !== "delete";
let usingClause = needsUsing ? buildUsingClause(rule) : null;
let withCheckClause = needsWithCheck ? buildWithCheckClause(rule) : null;
// If roles are specified, wrap existing clauses with role check,
// or generate a roles-only clause.
if (roles && roles.length > 0) {
if (usingClause) {
usingClause = wrapWithRoleCheck(usingClause, roles);
} else if (needsUsing) {
// Roles-only rule (e.g. { operation: "select", roles: ["admin"] })
const rolesArrayString = `ARRAY[${roles.map(r => `'${r}'`).join(',')}]`;
usingClause = `sql\`string_to_array(auth.roles(), ',') @> ${rolesArrayString}\``;
}
Iif (withCheckClause) {
withCheckClause = wrapWithRoleCheck(withCheckClause, roles);
} else Iif (needsWithCheck) {
const rolesArrayString = `ARRAY[${roles.map(r => `'${r}'`).join(',')}]`;
withCheckClause = `sql\`string_to_array(auth.roles(), ',') @> ${rolesArrayString}\``;
}
}
// Fallback: if we still have no clauses, deny all (safety net)
Iif (!usingClause && needsUsing) {
usingClause = `sql\`false\``;
}
Iif (!withCheckClause && needsWithCheck) {
withCheckClause = `sql\`false\``;
}
// Build the policy options object
const parts: string[] = [];
parts.push(`as: "${mode}"`);
parts.push(`for: "${operation}"`);
const toRoles = rule.pgRoles ?? ["public"];
parts.push(`to: [${toRoles.map(r => `"${r}"`).join(", ")}]`);
if (usingClause) parts.push(`using: ${usingClause}`);
if (withCheckClause) parts.push(`withCheck: ${withCheckClause}`);
return ` pgPolicy("${policyName}", { ${parts.join(", ")} }),\n`;
};
// --- Main Schema Generation Logic ---
export const generateSchema = async (collections: EntityCollection[]): Promise<string> => {
let schemaContent = "// This file is auto-generated by the Rebase Drizzle generator. Do not edit manually.\n\n";
const hasRLS = collections.some(c => c.securityRules && c.securityRules.length > 0);
const hasUuid = collections.some(c =>
c.properties && Object.values(c.properties).some(
(p: Property) => p.type === "string" && ((p as unknown as Record<string, unknown>).autoValue === "uuid" || (p as unknown as Record<string, unknown>).isId === "uuid")
)
);
const hasJson = collections.some(c =>
c.properties && Object.values(c.properties).some(
(p: Property) => (p.type === "map" || p.type === "array") && (p as unknown as Record<string, unknown>).columnType === "json"
)
);
const pgCoreImports = ["primaryKey", "pgTable", "integer", "varchar", "text", "char", "boolean", "timestamp", "date", "time", "jsonb", "json", "pgEnum", "numeric", "real", "doublePrecision", "bigint", "serial", "bigserial"];
if (hasRLS) pgCoreImports.push("pgPolicy");
if (hasUuid) pgCoreImports.push("uuid");
schemaContent += `import { ${pgCoreImports.join(", ")} } from 'drizzle-orm/pg-core';\n`;
const drizzleOrmImports = ["relations as drizzleRelations"];
if (hasRLS) drizzleOrmImports.push("sql");
schemaContent += `import { ${drizzleOrmImports.join(", ")} } from 'drizzle-orm';\n\n`;
const exportedTableVars: string[] = [];
const exportedEnumVars: string[] = [];
const exportedRelationVars: string[] = [];
const allTablesToGenerate = new Map<string, {
collection: EntityCollection,
isJunction?: boolean,
relation?: Relation,
sourceCollection?: EntityCollection
}>();
// 1. Generate Enums
collections.forEach(collection => {
const collectionPath = getTableName(collection);
Object.entries(collection.properties ?? {}).forEach(([propName, prop]) => {
Iif (("enum" in prop) && (prop.type === "string" || prop.type === "number") && prop.enum) {
const enumVarName = getEnumVarName(collectionPath, propName);
const enumDbName = `${collectionPath}_${toSnakeCase(propName)}`;
const values = Array.isArray(prop.enum)
? prop.enum.map(v => String(v.id ?? v))
: Object.keys(prop.enum);
Iif (values.length > 0) {
schemaContent += `export const ${enumVarName} = pgEnum(\"${enumDbName}\", [${values.map(v => `'${v}'`).join(", ")}]);\n`;
Iif (!exportedEnumVars.includes(enumVarName)) exportedEnumVars.push(enumVarName);
}
}
});
});
schemaContent += "\n";
// 2. Identify all tables (collections and junction tables only)
for (const collection of collections) {
const tableName = getTableName(collection);
if (tableName) {
allTablesToGenerate.set(tableName, { collection });
}
const resolvedRelations = resolveCollectionRelations(collection);
for (const relation of Object.values(resolvedRelations)) {
if (relation.through) { // Standard M2M junction table
const junctionTableName = relation.through.table;
if (!allTablesToGenerate.has(junctionTableName)) {
allTablesToGenerate.set(junctionTableName, {
collection: {
dbPath: junctionTableName,
properties: {}
} as EntityCollection,
isJunction: true,
relation: relation,
sourceCollection: collection
});
}
}
// joinPath relations use existing user-controlled tables - no generation needed
}
}
// 3. Generate pgTable definitions for all unique tables
for (const [tableName, {
collection,
isJunction,
relation,
sourceCollection
}] of allTablesToGenerate.entries()) {
const tableVarName = getTableVarName(tableName);
if (isJunction && relation && sourceCollection && relation.through) {
const targetCollection = relation.target();
const {
sourceColumn,
targetColumn
} = relation.through;
const onDelete = relation.onDelete ?? "cascade";
const refOptions = `{ onDelete: \"${onDelete}\" }`;
const sourceColType = isNumericId(sourceCollection) ? "integer" : "varchar";
const targetColType = isNumericId(targetCollection) ? "integer" : "varchar";
const sourceId = getPrimaryKeyName(sourceCollection);
const targetId = getPrimaryKeyName(targetCollection);
schemaContent += `export const ${tableVarName} = pgTable(\"${tableName}\", {\n`;
schemaContent += ` ${sourceColumn}: ${sourceColType}(\"${toSnakeCase(sourceColumn)}\").notNull().references(() => ${getTableVarName(getTableName(sourceCollection))}.${sourceId}, ${refOptions}),\n`;
schemaContent += ` ${targetColumn}: ${targetColType}(\"${toSnakeCase(targetColumn)}\").notNull().references(() => ${getTableVarName(getTableName(targetCollection))}.${targetId}, ${refOptions}),\n`;
schemaContent += `}, (table) => ({\n`;
schemaContent += ` pk: primaryKey({ columns: [table.${sourceColumn}, table.${targetColumn}] })\n`;
schemaContent += `}));\n\n`;
} else if (!isJunction) {
schemaContent += `export const ${tableVarName} = pgTable(\"${tableName}\", {\n`;
const columns = new Set<string>();
Object.entries(collection.properties ?? {}).forEach(([propName, prop]) => {
const columnString = getDrizzleColumn(propName, prop as Property, collection);
if (columnString) columns.add(columnString);
});
// Backwards compatibility: if no id/primary key column is found in properties, but `id` wasn't explicitly provided
// We should generate a basic id column if one was completely omitted.
const hasIdColumn = Array.from(columns).some(col => col.includes(".primaryKey()"));
if (!hasIdColumn) {
columns.add(` id: varchar(\"id\").primaryKey()`);
}
schemaContent += `${Array.from(columns).join(",\n")}`;
const securityRules = collection.securityRules;
if (securityRules && securityRules.length > 0) {
schemaContent += "\n}, (table) => ([\n";
securityRules.forEach((rule, idx) => {
schemaContent += generatePolicyCode(tableName, rule, idx);
});
schemaContent += "]));\n\n";
} else {
schemaContent += "\n});\n\n";
}
}
if (!exportedTableVars.includes(tableVarName)) exportedTableVars.push(tableVarName);
}
// 4. Generate Drizzle Relations
for (const [tableName, {
collection,
isJunction
}] of allTablesToGenerate.entries()) {
const tableVarName = getTableVarName(tableName);
const tableRelations: string[] = [];
if (isJunction) {
const relationInfo = Array.from(allTablesToGenerate.values()).find(v => v.isJunction && getTableName(v.collection) === tableName);
if (relationInfo && relationInfo.relation && relationInfo.sourceCollection && relationInfo.relation.through) {
const {
relation,
sourceCollection
} = relationInfo;
const targetCollection = relation.target();
const sourceTableVar = getTableVarName(getTableName(sourceCollection));
const targetTableVar = getTableVarName(getTableName(targetCollection));
const sourceId = getPrimaryKeyName(sourceCollection);
const targetId = getPrimaryKeyName(targetCollection);
Iif (!relation?.through)
throw new Error("Internal, the relation should have a through property. Relations passed to this script should sanitized first with sanitizeRelation().");
// The owning relation's name — used on the source side of the junction
const owningRelationName = relation.relationName ?? toSnakeCase(getTableName(targetCollection));
// Find the inverse relation name on the target collection (if any)
// This is needed so the junction's target-side one() can pair with the
// inverse many() on the target table.
let inverseRelationName: string | null = null;
try {
const targetRelations = resolveCollectionRelations(targetCollection);
for (const [, targetRel] of Object.entries(targetRelations)) {
Iif (targetRel.direction === "inverse" &&
targetRel.cardinality === "many" &&
targetRel.inverseRelationName === owningRelationName) {
inverseRelationName = targetRel.relationName ?? null;
break;
}
}
} catch {
// ignore — inverse side may not exist
}
// Source side one(): pairs with owning table's many(junctionTable, { relationName })
tableRelations.push(` ${relation.through.sourceColumn}: one(${sourceTableVar}, {\n fields: [${tableVarName}.${relation.through.sourceColumn}],\n references: [${sourceTableVar}.${sourceId}],\n relationName: \"${owningRelationName}\"\n })`);
// Target side one(): pairs with inverse table's many(junctionTable, { relationName })
const targetRelName = inverseRelationName ?? owningRelationName;
tableRelations.push(` ${relation.through.targetColumn}: one(${targetTableVar}, {\n fields: [${tableVarName}.${relation.through.targetColumn}],\n references: [${targetTableVar}.${targetId}],\n relationName: \"${targetRelName}\"\n })`);
}
} else {
const resolvedRelations = resolveCollectionRelations(collection);
for (const [relationKey, rel] of Object.entries(resolvedRelations)) {
try {
const target = rel.target();
const targetTableVar = getTableVarName(getTableName(target));
const relationName = rel.relationName ?? relationKey;
// Determine the correct relation name for Drizzle
// For inverse relations, we should use the current relation's name, not the inverse name
const drizzleRelationName = relationName;
if (rel.cardinality === "one") {
if (rel.direction === "owning" && rel.localKey) {
tableRelations.push(` ${relationKey}: one(${targetTableVar}, {\n fields: [${tableVarName}.${rel.localKey}],\n references: [${targetTableVar}.${getPrimaryKeyName(target)}],\n relationName: \"${drizzleRelationName}\"\n })`);
} else if (rel.direction === "inverse" && rel.foreignKeyOnTarget) {
const sourceIdField = getPrimaryKeyName(collection);
tableRelations.push(` ${relationKey}: one(${targetTableVar}, {\n fields: [${tableVarName}.${sourceIdField}],\n references: [${targetTableVar}.${rel.foreignKeyOnTarget}],\n relationName: \"${drizzleRelationName}\"\n })`);
} else IEif (rel.direction === "inverse" && !rel.foreignKeyOnTarget) {
// Handle inverse one-to-one relations where the FK is on the target table
// but foreignKeyOnTarget is not explicitly specified
// In this case, we need to find the corresponding owning relation on the target
try {
const targetCollection = rel.target();
const targetResolvedRelations = resolveCollectionRelations(targetCollection);
// Find the owning relation on the target that points back to this collection
const correspondingRelation = Object.values(targetResolvedRelations).find(targetRel =>
targetRel.direction === "owning" &&
targetRel.cardinality === "one" &&
targetRel.target().slug === collection.slug
);
Iif (correspondingRelation && correspondingRelation.localKey) {
const sourceIdField = getPrimaryKeyName(collection);
tableRelations.push(` ${relationKey}: one(${targetTableVar}, {\n fields: [${tableVarName}.${sourceIdField}],\n references: [${targetTableVar}.${correspondingRelation.localKey}],\n relationName: \"${drizzleRelationName}\"\n })`);
}
} catch (e) {
console.warn(`Could not resolve inverse one-to-one relation '${relationKey}':`, e);
}
}
} else if (rel.cardinality === "many") {
if (rel.direction === "inverse" && rel.foreignKeyOnTarget) {
// One-to-many inverse relation
tableRelations.push(` ${relationKey}: many(${targetTableVar}, { relationName: \"${drizzleRelationName}\" })`);
} else if (rel.through) {
// Many-to-many owning relation with explicit junction table
const junctionTableVar = getTableVarName(rel.through.table);
tableRelations.push(` ${relationKey}: many(${junctionTableVar}, { relationName: \"${drizzleRelationName}\" })`);
} else Iif (rel.direction === "inverse" && rel.inverseRelationName) {
// Many-to-many inverse relation - find the corresponding owning relation's junction table
try {
const targetCollection = rel.target();
const targetResolvedRelations = resolveCollectionRelations(targetCollection);
// Find the corresponding owning many-to-many relation on the target
const correspondingRelation = Object.values(targetResolvedRelations).find(targetRel =>
targetRel.direction === "owning" &&
targetRel.cardinality === "many" &&
targetRel.through &&
targetRel.relationName === rel.inverseRelationName
);
if (correspondingRelation && correspondingRelation.through) {
const junctionTableVar = getTableVarName(correspondingRelation.through.table);
tableRelations.push(` ${relationKey}: many(${junctionTableVar}, { relationName: \"${drizzleRelationName}\" })`);
} else {
console.warn(`Could not find corresponding owning many-to-many relation for inverse relation '${relationKey}' on '${collection.name}'`);
}
} catch (e) {
console.warn(`Could not resolve inverse many-to-many relation '${relationKey}':`, e);
}
}
// joinPath relations don't generate Drizzle relations - they use existing user tables
}
} catch (e) {
console.warn(`Could not generate relation ${relationKey} for ${collection.name}:`, e);
}
}
}
if (tableRelations.length > 0) {
const relVarName = `${tableVarName}Relations`;
schemaContent += `export const ${relVarName} = drizzleRelations(${tableVarName}, ({ one, many }) => ({\n${tableRelations.join(",\n")}\n}));\n\n`;
if (!exportedRelationVars.includes(relVarName)) exportedRelationVars.push(relVarName);
}
}
// <<< ADDED: Final aggregated exports block
const tablesExport = `export const tables = { ${exportedTableVars.join(", ")} };\n`;
const enumsExport = `export const enums = { ${exportedEnumVars.join(", ")} };\n`;
const relationsExport = `export const relations = { ${exportedRelationVars.join(", ")} };\n\n`;
schemaContent += tablesExport + enumsExport + relationsExport;
return schemaContent;
};
|