-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathtableRelations.ts
More file actions
90 lines (85 loc) · 2.08 KB
/
Copy pathtableRelations.ts
File metadata and controls
90 lines (85 loc) · 2.08 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
/**
* Type representing a table relation configuration
*/
export interface TableRelation {
/** SQL condition for joining the tables */
joinCondition: string;
/** Optional foreign key override if not following standard naming */
foreignKey?: string;
}
/**
* Type representing all possible relations for a table
*/
export type TableRelations = {
[tableName: string]: {
[relatedTable: string]: TableRelation;
};
};
/**
* Database table relationship configurations
* Defines how tables are related to each other for nested queries
*/
export const TABLE_RELATIONS: TableRelations = {
metadata: {
claims: {
joinCondition: "metadata.uri = claims.uri",
},
},
claims: {
metadata: {
joinCondition: "claims.uri = metadata.uri",
},
fractions_view: {
joinCondition: "claims.hypercert_id = fractions_view.hypercert_id",
},
},
claims_view: {
metadata: {
joinCondition: "metadata.uri = claims_view.uri",
},
fractions_view: {
joinCondition: "fractions_view.hypercert_id = claims_view.hypercert_id",
},
},
sales: {
claims: {
joinCondition: "claims.hypercert_id = sales.hypercert_id",
},
},
} as const;
/**
* Type guard to check if a relation exists between tables
*/
export function hasRelation(
tableName: string,
relatedTable: string,
): relatedTable is Extract<
keyof (typeof TABLE_RELATIONS)[typeof tableName],
string
> {
return (
tableName in TABLE_RELATIONS &&
relatedTable in (TABLE_RELATIONS[tableName] ?? {})
);
}
/**
* Get the relation configuration between two tables
* @throws {Error} If relation doesn't exist
*/
export function getRelation(
tableName: string,
relatedTable: string,
): TableRelation {
if (!hasRelation(tableName, relatedTable)) {
throw new Error(
`No relation defined between ${tableName} and ${relatedTable}`,
);
}
return TABLE_RELATIONS[tableName][relatedTable];
}
/**
* Default foreign key pattern if not specified in relation
*/
export function getDefaultForeignKey(relatedTable: string): string {
return `${relatedTable}_id`;
}