-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathrelations.ts
More file actions
905 lines (844 loc) · 29.1 KB
/
relations.ts
File metadata and controls
905 lines (844 loc) · 29.1 KB
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
import {
createTableRelationsHelpers,
getTableName,
is,
Many,
One,
Relations,
Table,
} from "drizzle-orm";
import { getTableConfigForDatabase } from "./db";
import {
createZeroTableSchema,
type ColumnsConfig,
type CreateZeroTableSchema,
type ZeroColumns,
} from "./tables";
import type {
AtLeastOne,
ColumnName,
Columns,
FindPrimaryKeyFromTable,
FindRelationsForTable,
FindTableByName,
Flatten,
RelationsConfig,
TableName,
} from "./types";
import { typedEntries } from "./util";
/**
* Represents a Zero schema with optional relationships.
* @template TTable - The Drizzle table type
* @template TColumnConfig - Configuration for the table's columns
* @template TRelations - Type of relationships (if any)
*/
type ZeroSchemaWithRelations<
TTable extends Table,
TColumnConfig extends ColumnsConfig<TTable>,
TRelations extends Record<string, unknown> | never,
> = Readonly<
CreateZeroTableSchema<TTable, TColumnConfig> &
(keyof TRelations extends never
? {}
: [TRelations] extends [never]
? {}
: {
readonly relationships: TRelations;
})
>;
/**
* Configuration type for specifying which tables and columns to include in the Zero schema.
* @template TDrizzleSchema - The complete Drizzle schema
*/
type TableColumnsConfig<TDrizzleSchema extends Record<string, unknown>> = {
/**
* The columns to include in the Zero schema.
*/
readonly [K in keyof TDrizzleSchema as TDrizzleSchema[K] extends Table<any>
? TableName<TDrizzleSchema[K]>
: never]?: TDrizzleSchema[K] extends Table<any>
? ColumnsConfig<TDrizzleSchema[K]>
: never;
};
/**
* Gets the keys of columns that can be used as indexes (string or number types).
* @template TTable - The table to get index keys from
*/
type ColumnIndexKeys<TTable extends Table> = Readonly<
{
[K in keyof Columns<TTable>]: Columns<TTable>[K] extends {
dataType: "string" | "number";
}
? ColumnName<Columns<TTable>[K]>
: never;
}[keyof Columns<TTable>]
>;
/**
* Extracts the table name from a configuration object or string.
* @template TTableConfig - The configuration object or string
*/
type ExtractTableConfigName<TTableConfig> = TTableConfig extends {
readonly destTable: string;
}
? TTableConfig["destTable"]
: TTableConfig extends string
? TTableConfig
: never;
/**
* Represents the structure of a many-to-many relationship through a junction table.
* @template TDrizzleSchema - The complete Drizzle schema
* @template TColumnConfig - Configuration for the tables
* @template TManyConfig - Configuration for many-to-many relationships
* @template TCurrentTable - The current table being processed
*/
type ManyToManyRelationship<
TDrizzleSchema extends Record<string, unknown>,
TColumnConfig extends TableColumnsConfig<TDrizzleSchema>,
TManyConfig extends ManyConfig<TDrizzleSchema, TColumnConfig>,
TCurrentTable extends Table,
> =
TableName<TCurrentTable> extends keyof TColumnConfig & keyof TManyConfig
? TManyConfig[TableName<TCurrentTable>] extends ManyTableConfig<
TDrizzleSchema,
TColumnConfig,
TableName<TCurrentTable>
>
? {
readonly [K in keyof TManyConfig[TableName<TCurrentTable>]]: Readonly<
[
{
readonly sourceField: AtLeastOne<
ColumnIndexKeys<TCurrentTable>
>;
readonly destField: AtLeastOne<
ColumnIndexKeys<
FindTableByName<
TDrizzleSchema,
ExtractTableConfigName<
TManyConfig[TableName<TCurrentTable>][K][0]
>
>
>
>;
readonly destSchema: () => ZeroSchemaWithRelations<
FindTableByName<
TDrizzleSchema,
ExtractTableConfigName<
TManyConfig[TableName<TCurrentTable>][K][0]
>
>,
ResolveColumnConfig<
TDrizzleSchema,
TColumnConfig,
FindTableByName<
TDrizzleSchema,
ExtractTableConfigName<
TManyConfig[TableName<TCurrentTable>][K][0]
>
>
>,
ReferencedZeroSchemas<
TDrizzleSchema,
TColumnConfig,
TManyConfig,
FindTableByName<
TDrizzleSchema,
ExtractTableConfigName<
TManyConfig[TableName<TCurrentTable>][K][0]
>
>
>
>;
},
{
readonly sourceField: AtLeastOne<
ColumnIndexKeys<
FindTableByName<
TDrizzleSchema,
ExtractTableConfigName<
TManyConfig[TableName<TCurrentTable>][K][0]
>
>
>
>;
readonly destField: AtLeastOne<
ColumnIndexKeys<
FindTableByName<
TDrizzleSchema,
ExtractTableConfigName<
TManyConfig[TableName<TCurrentTable>][K][1]
>
>
>
>;
readonly destSchema: () => ZeroSchemaWithRelations<
FindTableByName<
TDrizzleSchema,
ExtractTableConfigName<
TManyConfig[TableName<TCurrentTable>][K][1]
>
>,
ResolveColumnConfig<
TDrizzleSchema,
TColumnConfig,
FindTableByName<
TDrizzleSchema,
ExtractTableConfigName<
TManyConfig[TableName<TCurrentTable>][K][1]
>
>
>,
ReferencedZeroSchemas<
TDrizzleSchema,
TColumnConfig,
TManyConfig,
FindTableByName<
TDrizzleSchema,
ExtractTableConfigName<
TManyConfig[TableName<TCurrentTable>][K][1]
>
>
>
>;
},
]
>;
}
: {}
: {};
/**
* Gets the valid direct relation keys for a table that have corresponding table configurations.
* @template TDrizzleSchema - The complete Drizzle schema
* @template TColumnConfig - Configuration for the tables
* @template TCurrentTableRelations - Relations defined for the current table
*/
type ValidDirectRelationKeys<
TDrizzleSchema extends Record<string, unknown>,
TColumnConfig extends TableColumnsConfig<TDrizzleSchema>,
TCurrentTableRelations extends Relations,
> = keyof RelationsConfig<TCurrentTableRelations> &
{
[K in keyof RelationsConfig<TCurrentTableRelations>]: FindTableByName<
TDrizzleSchema,
RelationsConfig<TCurrentTableRelations>[K]["referencedTableName"]
> extends Table<any>
? TColumnConfig[TableName<
FindTableByName<
TDrizzleSchema,
RelationsConfig<TCurrentTableRelations>[K]["referencedTableName"]
>
>] extends object
? K
: never
: never;
}[keyof RelationsConfig<TCurrentTableRelations>];
/**
* Helper type to safely resolve column config for a table.
* @template TDrizzleSchema - The complete Drizzle schema
* @template TColumnConfig - Configuration for the tables
* @template TTable - The table to resolve column config for
*/
type ResolveColumnConfig<
TDrizzleSchema extends Record<string, unknown>,
TColumnConfig extends TableColumnsConfig<TDrizzleSchema>,
TTable extends Table,
> =
TableName<TTable> extends keyof TColumnConfig
? TColumnConfig[TableName<TTable>] extends ColumnsConfig<TTable>
? TColumnConfig[TableName<TTable>]
: never
: never;
/**
* Represents a direct relationship between tables.
* @template TDrizzleSchema - The complete Drizzle schema
* @template TColumnConfig - Configuration for the tables
* @template TManyConfig - Configuration for many-to-many relationships
* @template TCurrentTable - The current table being processed
* @template TCurrentTableRelations - Relations defined for the current table
*/
type DirectRelationships<
TDrizzleSchema extends Record<string, unknown>,
TColumnConfig extends TableColumnsConfig<TDrizzleSchema>,
TManyConfig extends ManyConfig<TDrizzleSchema, TColumnConfig>,
TCurrentTable extends Table,
TCurrentTableRelations extends Relations,
> = [TCurrentTableRelations] extends [never]
? {}
: {
readonly [K in ValidDirectRelationKeys<
TDrizzleSchema,
TColumnConfig,
TCurrentTableRelations
>]: {
readonly sourceField: AtLeastOne<ColumnIndexKeys<TCurrentTable>>;
readonly destField: AtLeastOne<
ColumnIndexKeys<
FindTableByName<
TDrizzleSchema,
RelationsConfig<TCurrentTableRelations>[K]["referencedTableName"]
>
>
>;
readonly destSchema: () => ZeroSchemaWithRelations<
FindTableByName<
TDrizzleSchema,
RelationsConfig<TCurrentTableRelations>[K]["referencedTableName"]
>,
ResolveColumnConfig<
TDrizzleSchema,
TColumnConfig,
FindTableByName<
TDrizzleSchema,
RelationsConfig<TCurrentTableRelations>[K]["referencedTableName"]
>
>,
ReferencedZeroSchemas<
TDrizzleSchema,
TColumnConfig,
TManyConfig,
FindTableByName<
TDrizzleSchema,
RelationsConfig<TCurrentTableRelations>[K]["referencedTableName"]
>
>
>;
};
};
/**
* Configuration type for many-to-many relationships for a specific table.
* @template TDrizzleSchema - The complete Drizzle schema
* @template TColumnConfig - Configuration for the tables
* @template TSourceTableName - The name of the source table
*/
type ManyTableConfig<
TDrizzleSchema extends Record<string, unknown>,
TColumnConfig extends TableColumnsConfig<TDrizzleSchema>,
TSourceTableName extends keyof TColumnConfig,
> = {
readonly [TRelationName: string]:
| {
[K in Exclude<keyof TColumnConfig, TSourceTableName>]: readonly [
K,
Exclude<keyof TColumnConfig, TSourceTableName | K>,
];
}[Exclude<keyof TColumnConfig, TSourceTableName>]
| {
[K in Exclude<keyof TColumnConfig, TSourceTableName>]: {
[L in Exclude<keyof TColumnConfig, K>]: readonly [
{
readonly sourceField: keyof TColumnConfig[TSourceTableName];
readonly destTable: K;
readonly destField: keyof TColumnConfig[K];
},
{
readonly sourceField: keyof TColumnConfig[K];
readonly destTable: L;
readonly destField: keyof TColumnConfig[L];
},
];
}[Exclude<keyof TColumnConfig, K>];
}[Exclude<keyof TColumnConfig, TSourceTableName>];
};
/**
* Configuration for many-to-many relationships across all tables.
* Organized by source table, with each relationship specifying a tuple of [junction table name, destination table name].
* The junction table and destination table must be different from the source table and each other.
*/
type ManyConfig<
TDrizzleSchema extends Record<string, unknown>,
TColumnConfig extends TableColumnsConfig<TDrizzleSchema>,
> = [keyof TColumnConfig] extends [never]
? never
: {
readonly [TSourceTableName in keyof TColumnConfig]?: ManyTableConfig<
TDrizzleSchema,
TColumnConfig,
TSourceTableName
>;
};
/**
* Represents all referenced Zero schemas for a table, including both direct and many-to-many relationships.
* @template TDrizzleSchema - The complete Drizzle schema
* @template TColumnConfig - Configuration for the tables
* @template TManyConfig - Configuration for many-to-many relationships
* @template TCurrentTable - The current table being processed
* @template TCurrentTableRelations - Relations defined for the current table
*/
type ReferencedZeroSchemas<
TDrizzleSchema extends Record<string, unknown>,
TColumnConfig extends TableColumnsConfig<TDrizzleSchema>,
TManyConfig extends ManyConfig<TDrizzleSchema, TColumnConfig>,
TCurrentTable extends Table,
> = Readonly<
DirectRelationships<
TDrizzleSchema,
TColumnConfig,
TManyConfig,
TCurrentTable,
FindRelationsForTable<TDrizzleSchema, TCurrentTable>
> &
ManyToManyRelationship<
TDrizzleSchema,
TColumnConfig,
TManyConfig,
TCurrentTable
>
>;
/**
* The complete Zero schema type with version and tables.
* @template TSchemaVersion - The schema version number
* @template TDrizzleSchema - The complete Drizzle schema
* @template TColumnConfig - Configuration for the tables
*/
type CreateZeroSchema<
TSchemaVersion extends number,
TDrizzleSchema extends Record<string, unknown>,
TColumnConfig extends TableColumnsConfig<TDrizzleSchema>,
TManyConfig extends ManyConfig<TDrizzleSchema, TColumnConfig>,
> = {
readonly version: TSchemaVersion;
readonly tables: {
readonly [K in keyof TDrizzleSchema as TDrizzleSchema[K] extends Table<any>
? TColumnConfig[TableName<TDrizzleSchema[K]>] extends object
? TableName<TDrizzleSchema[K]>
: never
: never]: TDrizzleSchema[K] extends Table<any>
? ZeroSchemaWithRelations<
TDrizzleSchema[K],
TColumnConfig[TableName<TDrizzleSchema[K]>],
ReferencedZeroSchemas<
TDrizzleSchema,
TColumnConfig,
TManyConfig,
TDrizzleSchema[K]
>
>
: never;
};
};
/**
* Create a Zero schema from a Drizzle schema.
*
* @param schema - The Drizzle schema to create a Zero schema from.
* @param schemaConfig - The configuration for the Zero schema.
* @returns The generated Zero schema.
*/
const createZeroSchema = <
const TSchemaVersion extends number,
const TDrizzleSchema extends Record<string, unknown>,
const TColumnConfig extends
TableColumnsConfig<TDrizzleSchema> = TableColumnsConfig<TDrizzleSchema>,
const TManyConfig extends ManyConfig<
TDrizzleSchema,
TColumnConfig
> = ManyConfig<TDrizzleSchema, TColumnConfig>,
>(
/**
* The Drizzle schema to create a Zero schema from.
*/
schema: TDrizzleSchema,
/**
* The configuration for the Zero schema.
*
* @param schemaConfig.version - The version of the schema.
* @param schemaConfig.tables - The tables to include in the Zero schema.
* @param schemaConfig.many - Configuration for many-to-many relationships.
*/
schemaConfig: {
/**
* The version of the schema, used for schema migrations.
*/
readonly version: TSchemaVersion;
/**
* Specify the tables to include in the Zero schema.
* This can include type overrides for columns, using `column.json()` for example.
*
* @example
* ```ts
* {
* user: {
* id: true,
* name: true,
* },
* profile_info: {
* id: true,
* user_id: true,
* metadata: column.json(),
* },
* }
* ```
*/
readonly tables: TColumnConfig;
/**
* Configuration for many-to-many relationships.
* Organized by source table, with each relationship specifying a tuple of [junction table name, destination table name].
*
* @example
* ```ts
* {
* user: {
* comments: ['message', 'comment']
* }
* }
* ```
*/
readonly manyToMany?: TManyConfig;
},
): Flatten<
CreateZeroSchema<TSchemaVersion, TDrizzleSchema, TColumnConfig, TManyConfig>
> => {
let relationships = {} as Record<
keyof typeof schemaConfig.tables,
Record<string, unknown>
>;
for (const tableOrRelations of Object.values(schema)) {
if (is(tableOrRelations, Table)) {
const tableName = getTableName(tableOrRelations);
relationships[tableName as keyof typeof relationships] =
relationships[tableName as keyof typeof relationships] || {};
}
}
// Map many-to-many relationships
if (schemaConfig.manyToMany) {
for (const [sourceTableName, manyConfig] of Object.entries(
schemaConfig.manyToMany,
)) {
if (!manyConfig) continue;
for (const [
relationName,
[junctionTableNameOrObject, destTableNameOrObject],
] of Object.entries(manyConfig)) {
if (
typeof junctionTableNameOrObject === "string" &&
typeof destTableNameOrObject === "string"
) {
const junctionTableName = junctionTableNameOrObject;
const destTableName = destTableNameOrObject;
const sourceTable = Object.values(schema).find(
(t): t is Table =>
is(t, Table) && getTableName(t) === sourceTableName,
);
const destTable = Object.values(schema).find(
(t): t is Table =>
is(t, Table) && getTableName(t) === destTableName,
);
if (!sourceTable || !destTable) {
throw new Error(
`drizzle-zero: Invalid many-to-many configuration for ${String(sourceTableName)}.${relationName}: Could not find ${!sourceTable ? "source" : !destTable ? "destination" : "junction"} table`,
);
}
// Find source->junction and junction->dest relationships
const sourceJunctionFields = findForeignKeySourceAndDestFields(
schema,
{
sourceTable: sourceTable,
referencedTableName: junctionTableName,
},
);
const junctionDestFields = findForeignKeySourceAndDestFields(schema, {
sourceTable: destTable,
referencedTableName: junctionTableName,
});
if (
!sourceJunctionFields.sourceFieldNames.length ||
!junctionDestFields.sourceFieldNames.length ||
!junctionDestFields.destFieldNames.length ||
!sourceJunctionFields.destFieldNames.length
) {
throw new Error(
`drizzle-zero: Invalid many-to-many configuration for ${String(sourceTableName)}.${relationName}: Could not find foreign key relationships in junction table ${junctionTableName}`,
);
}
(
relationships[
sourceTableName as keyof typeof relationships
] as Record<string, unknown>
)[relationName] = [
{
sourceField: sourceJunctionFields.sourceFieldNames,
destField: sourceJunctionFields.destFieldNames,
destSchemaTableName: junctionTableName,
},
{
sourceField: junctionDestFields.destFieldNames,
destField: junctionDestFields.sourceFieldNames,
destSchemaTableName: destTableName,
},
];
} else {
const junctionTableName =
junctionTableNameOrObject?.destTable ?? null;
const junctionSourceField =
junctionTableNameOrObject?.sourceField ?? null;
const junctionDestField =
junctionTableNameOrObject?.destField ?? null;
const destTableName = destTableNameOrObject?.destTable ?? null;
const destSourceField = destTableNameOrObject?.sourceField ?? null;
const destDestField = destTableNameOrObject?.destField ?? null;
if (
!junctionSourceField ||
!junctionDestField ||
!destSourceField ||
!destDestField ||
!junctionTableName ||
!destTableName
) {
throw new Error(
`drizzle-zero: Invalid many-to-many configuration for ${String(sourceTableName)}.${relationName}: Not all required fields were provided.`,
);
}
(
relationships[
sourceTableName as keyof typeof relationships
] as Record<string, unknown>
)[relationName] = [
{
sourceField: [junctionSourceField],
destField: [junctionDestField],
destSchemaTableName: junctionTableName,
},
{
sourceField: [destSourceField],
destField: [destDestField],
destSchemaTableName: destTableName,
},
];
}
}
}
}
for (const tableOrRelations of Object.values(schema)) {
if (is(tableOrRelations, Relations)) {
const tableName = getTableName(tableOrRelations.table);
const relationsConfig = getRelationsConfig(tableOrRelations);
Object.values(relationsConfig).forEach((relation) => {
let sourceFieldNames: string[] = [];
let destFieldNames: string[] = [];
if (is(relation, One)) {
sourceFieldNames =
relation?.config?.fields?.map((f) => f?.name) ?? [];
destFieldNames =
relation?.config?.references?.map((f) => f?.name) ?? [];
}
if (!sourceFieldNames.length || !destFieldNames.length) {
if (relation.relationName) {
const sourceAndDestFields = findNamedSourceAndDestFields(
schema,
relation,
);
sourceFieldNames = sourceAndDestFields.sourceFieldNames;
destFieldNames = sourceAndDestFields.destFieldNames;
} else {
const sourceAndDestFields = findForeignKeySourceAndDestFields(
schema,
relation,
);
sourceFieldNames = sourceAndDestFields.sourceFieldNames;
destFieldNames = sourceAndDestFields.destFieldNames;
}
}
if (!sourceFieldNames.length || !destFieldNames.length) {
throw new Error(
`drizzle-zero: No relationship found for: ${relation.fieldName} (${is(relation, One) ? "One" : "Many"} from ${tableName} to ${relation.referencedTableName}). Did you forget to define foreign keys${relation.relationName ? ` for named relation "${relation.relationName}"` : ""}?`,
);
}
if (
relationships[tableName as keyof typeof relationships]?.[
relation.fieldName
]
) {
throw new Error(
`drizzle-zero: Duplicate relationship found for: ${relation.fieldName} (${is(relation, One) ? "One" : "Many"} from ${tableName} to ${relation.referencedTableName}).`,
);
}
relationships[tableName as keyof typeof relationships] = {
...(relationships?.[tableName as keyof typeof relationships] ?? {}),
[relation.fieldName]: {
sourceField: sourceFieldNames,
destField: destFieldNames,
destSchemaTableName: relation.referencedTableName,
},
} as unknown as (typeof relationships)[keyof typeof relationships];
});
}
}
let tablesWithoutDestSchema: Record<
string,
{
tableName: string;
columns: ZeroColumns<Table, ColumnsConfig<Table>>;
primaryKey: FindPrimaryKeyFromTable<Table>;
relationships?: Record<
string,
| {
sourceField: string;
destField: string;
destSchemaTableName: string;
}
| [
{
sourceField: string;
destField: string;
destSchemaTableName: string;
},
{
sourceField: string;
destField: string;
destSchemaTableName: string;
},
]
>;
}
> = {};
for (const tableOrRelations of Object.values(schema)) {
if (is(tableOrRelations, Table)) {
const table = tableOrRelations;
const tableName = getTableName(table);
const tableConfig = schemaConfig.tables[tableName as keyof TColumnConfig];
// skip tables that don't have a config
if (!tableConfig) {
continue;
}
const tableSchema = createZeroTableSchema(table, tableConfig);
const relations = relationships[tableName as keyof typeof relationships];
tablesWithoutDestSchema[
tableName as keyof typeof tablesWithoutDestSchema
] = {
...tableSchema,
...(relations ? { relationships: relations } : {}),
} as unknown as (typeof tablesWithoutDestSchema)[keyof typeof tablesWithoutDestSchema];
}
}
let tables: Record<string, unknown> = {};
for (const tableWithoutDestSchema of Object.values(tablesWithoutDestSchema)) {
const tableName = tableWithoutDestSchema.tableName;
const relationships = typedEntries(
tableWithoutDestSchema.relationships ?? {},
)
// filter out relationships that don't have a corresponding table
.filter(([_key, relationship]) =>
Boolean(
Array.isArray(relationship)
? relationship.every((r) =>
Boolean(tablesWithoutDestSchema[r.destSchemaTableName]),
)
: Boolean(
tablesWithoutDestSchema[relationship.destSchemaTableName],
),
),
)
.reduce(
(acc, [key, relationship]) => {
acc[key] = Array.isArray(relationship)
? relationship.map((r) => ({
sourceField: r.sourceField,
destField: r.destField,
destSchema: () => tables[r.destSchemaTableName],
}))
: {
sourceField: relationship.sourceField,
destField: relationship.destField,
destSchema: () => tables[relationship.destSchemaTableName],
};
return acc;
},
{} as Record<string, unknown>,
);
tables[tableName as keyof typeof tables] = {
tableName: tableWithoutDestSchema.tableName,
columns: tableWithoutDestSchema.columns,
primaryKey: tableWithoutDestSchema.primaryKey,
...(Object.keys(relationships).length ? { relationships } : {}),
} as unknown as (typeof tables)[keyof typeof tables];
}
return {
version: schemaConfig.version,
tables,
} as CreateZeroSchema<
TSchemaVersion,
TDrizzleSchema,
TColumnConfig,
TManyConfig
>;
};
/**
* Helper function to find source and destination fields for foreign key relationships.
* @param schema - The complete Drizzle schema
* @param relation - The minimal relation info needed to find fields
* @returns Object containing source and destination field names
*/
const findForeignKeySourceAndDestFields = (
schema: Record<string, unknown>,
relation: {
sourceTable: Table;
referencedTableName: string;
},
) => {
for (const tableOrRelations of Object.values(schema)) {
if (is(tableOrRelations, Table)) {
const tableName = getTableName(tableOrRelations);
if (tableName === relation.referencedTableName) {
const tableConfig = getTableConfigForDatabase(tableOrRelations);
for (const foreignKey of tableConfig.foreignKeys) {
const reference = foreignKey.reference();
const foreignTableName = getTableName(reference.foreignTable);
const sourceTableName = getTableName(relation.sourceTable);
if (foreignTableName === sourceTableName) {
return {
sourceFieldNames: reference.foreignColumns.map((c) => c.name),
destFieldNames: reference.columns.map((c) => c.name),
};
}
}
}
}
}
return {
sourceFieldNames: [],
destFieldNames: [],
};
};
/**
* Helper function to find source and destination fields for named relationships.
* @param schema - The complete Drizzle schema
* @param relation - The One or Many relation to find fields for
* @returns Object containing source and destination field names
*/
const findNamedSourceAndDestFields = (
schema: Record<string, unknown>,
relation: One | Many<any>,
) => {
for (const tableOrRelations of Object.values(schema)) {
if (is(tableOrRelations, Relations)) {
const relationsConfig = getRelationsConfig(tableOrRelations);
for (const relationConfig of Object.values(relationsConfig)) {
if (
is(relationConfig, One) &&
relationConfig.relationName === relation.relationName
) {
return {
destFieldNames:
relationConfig.config?.fields?.map((f) => f.name) ?? [],
sourceFieldNames:
relationConfig.config?.references?.map((f) => f.name) ?? [],
};
}
}
}
}
return {
sourceFieldNames: [],
destFieldNames: [],
};
};
/**
* Helper function to get the relations configuration from a Relations object.
* @param relations - The Relations object to get configuration from
* @returns Record of relation configurations
*/
const getRelationsConfig = (relations: Relations) => {
return relations.config(
createTableRelationsHelpers(relations.table),
) as Record<string, One | Many<any>>;
};
export { createZeroSchema, type CreateZeroSchema };