appflare 0.2.25 → 0.2.26
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/Documentation.md +758 -758
- package/cli/commands/index.ts +238 -238
- package/cli/generate.ts +178 -178
- package/cli/index.ts +120 -120
- package/cli/load-config.ts +184 -184
- package/cli/schema-compiler.ts +1183 -1183
- package/cli/templates/auth/README.md +156 -156
- package/cli/templates/auth/config.ts +61 -61
- package/cli/templates/auth/route-config.ts +1 -1
- package/cli/templates/auth/route-handler.ts +1 -1
- package/cli/templates/auth/route-request-utils.ts +5 -5
- package/cli/templates/auth/route.config.ts +18 -18
- package/cli/templates/auth/route.handler.ts +18 -18
- package/cli/templates/auth/route.request-utils.ts +55 -55
- package/cli/templates/auth/route.ts +14 -14
- package/cli/templates/core/README.md +266 -266
- package/cli/templates/core/app-creation.ts +19 -19
- package/cli/templates/core/client/appflare.ts +112 -112
- package/cli/templates/core/client/handlers/index.ts +748 -748
- package/cli/templates/core/client/handlers.ts +1 -1
- package/cli/templates/core/client/index.ts +7 -7
- package/cli/templates/core/client/storage.ts +180 -180
- package/cli/templates/core/client/types.ts +184 -184
- package/cli/templates/core/client-modules/appflare.ts +1 -1
- package/cli/templates/core/client-modules/handlers.ts +1 -1
- package/cli/templates/core/client-modules/index.ts +1 -1
- package/cli/templates/core/client-modules/storage.ts +1 -1
- package/cli/templates/core/client-modules/types.ts +1 -1
- package/cli/templates/core/client.artifacts.ts +39 -39
- package/cli/templates/core/client.ts +4 -4
- package/cli/templates/core/drizzle.ts +15 -15
- package/cli/templates/core/export.ts +14 -14
- package/cli/templates/core/handlers.route.ts +24 -24
- package/cli/templates/core/handlers.ts +1 -1
- package/cli/templates/core/imports.ts +9 -9
- package/cli/templates/core/server.ts +38 -38
- package/cli/templates/core/types.ts +6 -6
- package/cli/templates/core/wrangler.ts +109 -109
- package/cli/templates/dashboard/builders/functions/index.ts +17 -17
- package/cli/templates/dashboard/builders/functions/render-page/header.ts +20 -20
- package/cli/templates/dashboard/builders/functions/render-page/index.ts +33 -33
- package/cli/templates/dashboard/builders/functions/render-page/request-panel.ts +171 -171
- package/cli/templates/dashboard/builders/functions/render-page/result-panel.ts +85 -85
- package/cli/templates/dashboard/builders/functions/render-page/scripts.ts +554 -554
- package/cli/templates/dashboard/builders/navigation.ts +122 -122
- package/cli/templates/dashboard/builders/storage/index.ts +13 -13
- package/cli/templates/dashboard/builders/storage/routes/create-directory-route.ts +29 -29
- package/cli/templates/dashboard/builders/storage/routes/delete-route.ts +18 -18
- package/cli/templates/dashboard/builders/storage/routes/download-route.ts +23 -23
- package/cli/templates/dashboard/builders/storage/routes/index.ts +22 -22
- package/cli/templates/dashboard/builders/storage/routes/list-route.ts +25 -25
- package/cli/templates/dashboard/builders/storage/routes/preview-route.ts +21 -21
- package/cli/templates/dashboard/builders/storage/routes/upload-route.ts +21 -21
- package/cli/templates/dashboard/builders/storage/runtime/helpers.ts +72 -72
- package/cli/templates/dashboard/builders/storage/runtime/storage-page.ts +130 -130
- package/cli/templates/dashboard/builders/table-routes/common/drawer-panel.ts +27 -27
- package/cli/templates/dashboard/builders/table-routes/common/pagination.ts +30 -30
- package/cli/templates/dashboard/builders/table-routes/common/search-bar.ts +23 -23
- package/cli/templates/dashboard/builders/table-routes/fragments.ts +217 -217
- package/cli/templates/dashboard/builders/table-routes/helpers.ts +45 -45
- package/cli/templates/dashboard/builders/table-routes/index.ts +8 -8
- package/cli/templates/dashboard/builders/table-routes/table/actions-cell.ts +71 -71
- package/cli/templates/dashboard/builders/table-routes/table/get-route.ts +291 -291
- package/cli/templates/dashboard/builders/table-routes/table/index.ts +80 -80
- package/cli/templates/dashboard/builders/table-routes/table/post-routes.ts +163 -163
- package/cli/templates/dashboard/builders/table-routes/table-route.ts +7 -7
- package/cli/templates/dashboard/builders/table-routes/users/get-route.ts +69 -69
- package/cli/templates/dashboard/builders/table-routes/users/html/modals.ts +57 -57
- package/cli/templates/dashboard/builders/table-routes/users/html/page.ts +27 -27
- package/cli/templates/dashboard/builders/table-routes/users/html/table.ts +128 -128
- package/cli/templates/dashboard/builders/table-routes/users/index.ts +32 -32
- package/cli/templates/dashboard/builders/table-routes/users/post-routes.ts +150 -150
- package/cli/templates/dashboard/builders/table-routes/users/redirect.ts +14 -14
- package/cli/templates/dashboard/builders/table-routes/users-route.ts +10 -10
- package/cli/templates/dashboard/components/dashboard-home.ts +23 -23
- package/cli/templates/dashboard/components/layout.ts +388 -388
- package/cli/templates/dashboard/components/login-page.ts +65 -65
- package/cli/templates/dashboard/index.ts +61 -61
- package/cli/templates/dashboard/types.ts +9 -9
- package/cli/templates/handlers/README.md +353 -353
- package/cli/templates/handlers/auth.ts +37 -37
- package/cli/templates/handlers/execution.ts +42 -42
- package/cli/templates/handlers/generators/context/context-creation.ts +101 -101
- package/cli/templates/handlers/generators/context/error-helpers.ts +11 -11
- package/cli/templates/handlers/generators/context/scheduler.ts +24 -24
- package/cli/templates/handlers/generators/context/storage-api.ts +134 -112
- package/cli/templates/handlers/generators/context/storage-helpers.ts +59 -59
- package/cli/templates/handlers/generators/context/types.ts +18 -18
- package/cli/templates/handlers/generators/context.ts +43 -43
- package/cli/templates/handlers/generators/execution.ts +15 -15
- package/cli/templates/handlers/generators/handlers.ts +13 -13
- package/cli/templates/handlers/generators/registration/modules/cron.ts +26 -26
- package/cli/templates/handlers/generators/registration/modules/realtime/auth.ts +75 -75
- package/cli/templates/handlers/generators/registration/modules/realtime/durable-object.ts +144 -144
- package/cli/templates/handlers/generators/registration/modules/realtime/index.ts +14 -14
- package/cli/templates/handlers/generators/registration/modules/realtime/publisher.ts +102 -102
- package/cli/templates/handlers/generators/registration/modules/realtime/routes.ts +164 -164
- package/cli/templates/handlers/generators/registration/modules/realtime/types.ts +30 -30
- package/cli/templates/handlers/generators/registration/modules/realtime/utils.ts +516 -516
- package/cli/templates/handlers/generators/registration/modules/scheduler.ts +56 -56
- package/cli/templates/handlers/generators/registration/modules/storage.ts +196 -194
- package/cli/templates/handlers/generators/registration/sections.ts +210 -210
- package/cli/templates/handlers/generators/types/context.ts +68 -66
- package/cli/templates/handlers/generators/types/core.ts +106 -106
- package/cli/templates/handlers/generators/types/operations.ts +135 -135
- package/cli/templates/handlers/generators/types/query-definitions/filter-and-where-types.ts +259 -259
- package/cli/templates/handlers/generators/types/query-definitions/query-api-types.ts +135 -135
- package/cli/templates/handlers/generators/types/query-definitions/query-helper-functions.ts +1031 -1031
- package/cli/templates/handlers/generators/types/query-definitions/schema-and-table-types.ts +246 -246
- package/cli/templates/handlers/generators/types/query-definitions.ts +13 -13
- package/cli/templates/handlers/generators/types/query-runtime/handled-error.ts +13 -13
- package/cli/templates/handlers/generators/types/query-runtime/runtime-aggregate-and-footer.ts +174 -174
- package/cli/templates/handlers/generators/types/query-runtime/runtime-read.ts +121 -121
- package/cli/templates/handlers/generators/types/query-runtime/runtime-setup.ts +45 -45
- package/cli/templates/handlers/generators/types/query-runtime/runtime-write.ts +676 -676
- package/cli/templates/handlers/generators/types/query-runtime.ts +15 -15
- package/cli/templates/handlers/index.ts +43 -43
- package/cli/templates/handlers/operations.ts +116 -116
- package/cli/templates/handlers/registration.ts +91 -91
- package/cli/templates/handlers/types.ts +15 -15
- package/cli/templates/handlers/utils.ts +48 -48
- package/cli/types.ts +110 -110
- package/cli/utils/handler-discovery.ts +466 -466
- package/cli/utils/json-utils.ts +24 -24
- package/cli/utils/path-utils.ts +19 -19
- package/cli/utils/schema-discovery.ts +399 -399
- package/dist/cli/index.js +43 -17
- package/dist/cli/index.mjs +43 -17
- package/index.ts +18 -18
- package/package.json +58 -58
- package/react/index.ts +5 -5
- package/react/use-infinite-query.ts +252 -252
- package/react/use-mutation.ts +89 -89
- package/react/use-query.ts +207 -207
- package/schema.ts +415 -415
- package/test-better-auth-hash.ts +2 -2
- package/tsconfig.json +6 -6
- package/tsup.config.ts +82 -82
- package/dist/cli/index.d.mts +0 -2
- package/dist/cli/index.d.ts +0 -2
package/cli/schema-compiler.ts
CHANGED
|
@@ -1,1183 +1,1183 @@
|
|
|
1
|
-
import { mkdir } from "node:fs/promises";
|
|
2
|
-
import { dirname, resolve } from "node:path";
|
|
3
|
-
import { pathToFileURL } from "node:url";
|
|
4
|
-
import type {
|
|
5
|
-
ColumnDefinition,
|
|
6
|
-
ColumnType,
|
|
7
|
-
ManyRelationDefinition,
|
|
8
|
-
ManyToManyRelationDefinition,
|
|
9
|
-
OneRelationDefinition,
|
|
10
|
-
SchemaDefinition,
|
|
11
|
-
TableDefinition,
|
|
12
|
-
} from "../schema";
|
|
13
|
-
import { isSchemaDefinition } from "../schema";
|
|
14
|
-
import type { LoadedAppflareConfig } from "./types";
|
|
15
|
-
|
|
16
|
-
export type CompiledSchemaArtifacts = {
|
|
17
|
-
schemaPath: string;
|
|
18
|
-
typesPath: string;
|
|
19
|
-
zodPath: string;
|
|
20
|
-
tableNames: string[];
|
|
21
|
-
};
|
|
22
|
-
|
|
23
|
-
function toSnakeCase(value: string): string {
|
|
24
|
-
return value
|
|
25
|
-
.replace(/([a-z0-9])([A-Z])/g, "$1_$2")
|
|
26
|
-
.replace(/[\s-]+/g, "_")
|
|
27
|
-
.toLowerCase();
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
function toPascalCase(value: string): string {
|
|
31
|
-
return value
|
|
32
|
-
.replace(/[_-]+/g, " ")
|
|
33
|
-
.replace(/\s+(.)/g, (_match, char: string) => char.toUpperCase())
|
|
34
|
-
.replace(/\s/g, "")
|
|
35
|
-
.replace(/^(.)/, (_match, char: string) => char.toUpperCase());
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
function singularize(value: string): string {
|
|
39
|
-
if (value.endsWith("ies")) {
|
|
40
|
-
return `${value.slice(0, -3)}y`;
|
|
41
|
-
}
|
|
42
|
-
if (value.endsWith("ses")) {
|
|
43
|
-
return value.slice(0, -2);
|
|
44
|
-
}
|
|
45
|
-
if (value.endsWith("s") && value.length > 1) {
|
|
46
|
-
return value.slice(0, -1);
|
|
47
|
-
}
|
|
48
|
-
return value;
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
function quote(value: string): string {
|
|
52
|
-
return JSON.stringify(value);
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
function toSqlLiteral(value: unknown): string {
|
|
56
|
-
if (typeof value === "string") {
|
|
57
|
-
return quote(value);
|
|
58
|
-
}
|
|
59
|
-
if (typeof value === "number" || typeof value === "boolean") {
|
|
60
|
-
return String(value);
|
|
61
|
-
}
|
|
62
|
-
if (value === null) {
|
|
63
|
-
return "null";
|
|
64
|
-
}
|
|
65
|
-
if (value instanceof Date) {
|
|
66
|
-
return quote(value.toISOString());
|
|
67
|
-
}
|
|
68
|
-
throw new Error(
|
|
69
|
-
`Unsupported SQL default value '${String(value)}'. Use string, number, boolean, null, or Date.`,
|
|
70
|
-
);
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
function cloneSchemaDefinition(definition: SchemaDefinition): SchemaDefinition {
|
|
74
|
-
return {
|
|
75
|
-
kind: "schema",
|
|
76
|
-
tables: Object.fromEntries(
|
|
77
|
-
Object.entries(definition.tables).map(([tableName, table]) => {
|
|
78
|
-
return [
|
|
79
|
-
tableName,
|
|
80
|
-
{
|
|
81
|
-
kind: "table",
|
|
82
|
-
sqlName: table.sqlName,
|
|
83
|
-
columns: Object.fromEntries(
|
|
84
|
-
Object.entries(table.columns).map(([columnName, column]) => {
|
|
85
|
-
return [columnName, { ...column }];
|
|
86
|
-
}),
|
|
87
|
-
),
|
|
88
|
-
relations: Object.fromEntries(
|
|
89
|
-
Object.entries(table.relations).map(
|
|
90
|
-
([relationName, relation]) => {
|
|
91
|
-
return [relationName, { ...relation }];
|
|
92
|
-
},
|
|
93
|
-
),
|
|
94
|
-
),
|
|
95
|
-
} satisfies TableDefinition,
|
|
96
|
-
];
|
|
97
|
-
}),
|
|
98
|
-
),
|
|
99
|
-
};
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
function getLocalReferenceType(
|
|
103
|
-
definition: SchemaDefinition,
|
|
104
|
-
targetTable: string,
|
|
105
|
-
referenceField: string,
|
|
106
|
-
): ColumnType | undefined {
|
|
107
|
-
const table = definition.tables[targetTable];
|
|
108
|
-
if (!table) {
|
|
109
|
-
return undefined;
|
|
110
|
-
}
|
|
111
|
-
const targetColumn = table.columns[referenceField];
|
|
112
|
-
return targetColumn?.type;
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
function ensureInferredReferenceColumn(
|
|
116
|
-
tableName: string,
|
|
117
|
-
table: TableDefinition,
|
|
118
|
-
columnName: string,
|
|
119
|
-
referenceTable: string,
|
|
120
|
-
referenceField: string,
|
|
121
|
-
options: {
|
|
122
|
-
fkType?: ColumnType;
|
|
123
|
-
sqlName?: string;
|
|
124
|
-
notNull?: boolean;
|
|
125
|
-
onDelete?: OneRelationDefinition["onDelete"];
|
|
126
|
-
onUpdate?: OneRelationDefinition["onUpdate"];
|
|
127
|
-
},
|
|
128
|
-
inferredType: ColumnType,
|
|
129
|
-
): void {
|
|
130
|
-
const existing = table.columns[columnName];
|
|
131
|
-
if (existing) {
|
|
132
|
-
if (
|
|
133
|
-
existing.references &&
|
|
134
|
-
(existing.references.table !== referenceTable ||
|
|
135
|
-
existing.references.column !== referenceField)
|
|
136
|
-
) {
|
|
137
|
-
throw new Error(
|
|
138
|
-
`Inferred relation '${tableName}.${columnName}' conflicts with explicit references(${existing.references.table}.${existing.references.column}).`,
|
|
139
|
-
);
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
table.columns[columnName] = {
|
|
143
|
-
...existing,
|
|
144
|
-
notNull:
|
|
145
|
-
existing.notNull ??
|
|
146
|
-
(existing.nullable === true ? false : options.notNull),
|
|
147
|
-
nullable:
|
|
148
|
-
existing.nullable ?? (options.notNull === false ? true : undefined),
|
|
149
|
-
references: {
|
|
150
|
-
table: referenceTable,
|
|
151
|
-
column: referenceField,
|
|
152
|
-
onDelete: existing.references?.onDelete ?? options.onDelete,
|
|
153
|
-
onUpdate: existing.references?.onUpdate ?? options.onUpdate,
|
|
154
|
-
},
|
|
155
|
-
};
|
|
156
|
-
return;
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
table.columns[columnName] = {
|
|
160
|
-
kind: "column",
|
|
161
|
-
type: options.fkType ?? inferredType,
|
|
162
|
-
sqlName: options.sqlName,
|
|
163
|
-
notNull: options.notNull ?? true,
|
|
164
|
-
nullable: options.notNull === false ? true : undefined,
|
|
165
|
-
references: {
|
|
166
|
-
table: referenceTable,
|
|
167
|
-
column: referenceField,
|
|
168
|
-
onDelete: options.onDelete,
|
|
169
|
-
onUpdate: options.onUpdate,
|
|
170
|
-
},
|
|
171
|
-
};
|
|
172
|
-
}
|
|
173
|
-
|
|
174
|
-
function resolveNotNullFromNullableFlags(
|
|
175
|
-
fieldPath: string,
|
|
176
|
-
flags: { notNull?: boolean; nullable?: boolean },
|
|
177
|
-
defaultNotNull: boolean,
|
|
178
|
-
): boolean {
|
|
179
|
-
if (flags.notNull === true && flags.nullable === true) {
|
|
180
|
-
throw new Error(
|
|
181
|
-
`Invalid nullable configuration on '${fieldPath}': cannot set both notNull and nullable to true.`,
|
|
182
|
-
);
|
|
183
|
-
}
|
|
184
|
-
|
|
185
|
-
if (flags.notNull === true) {
|
|
186
|
-
return true;
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
if (flags.nullable === true) {
|
|
190
|
-
return false;
|
|
191
|
-
}
|
|
192
|
-
|
|
193
|
-
if (flags.notNull === false) {
|
|
194
|
-
return false;
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
return defaultNotNull;
|
|
198
|
-
}
|
|
199
|
-
|
|
200
|
-
type ManyToManyPair = {
|
|
201
|
-
leftTable: string;
|
|
202
|
-
leftReferenceField: string;
|
|
203
|
-
rightTable: string;
|
|
204
|
-
rightReferenceField: string;
|
|
205
|
-
junctionTable: string;
|
|
206
|
-
leftField: string;
|
|
207
|
-
rightField: string;
|
|
208
|
-
leftSqlName?: string;
|
|
209
|
-
rightSqlName?: string;
|
|
210
|
-
onDelete?: OneRelationDefinition["onDelete"];
|
|
211
|
-
onUpdate?: OneRelationDefinition["onUpdate"];
|
|
212
|
-
};
|
|
213
|
-
|
|
214
|
-
function endpointKey(tableName: string, referenceField: string): string {
|
|
215
|
-
return `${tableName}:${referenceField}`;
|
|
216
|
-
}
|
|
217
|
-
|
|
218
|
-
function normalizeManyToManyPairKey(
|
|
219
|
-
sourceTable: string,
|
|
220
|
-
sourceReferenceField: string,
|
|
221
|
-
targetTable: string,
|
|
222
|
-
targetReferenceField: string,
|
|
223
|
-
): {
|
|
224
|
-
key: string;
|
|
225
|
-
leftTable: string;
|
|
226
|
-
leftReferenceField: string;
|
|
227
|
-
rightTable: string;
|
|
228
|
-
rightReferenceField: string;
|
|
229
|
-
sourceIsLeft: boolean;
|
|
230
|
-
} {
|
|
231
|
-
const source = endpointKey(sourceTable, sourceReferenceField);
|
|
232
|
-
const target = endpointKey(targetTable, targetReferenceField);
|
|
233
|
-
const sourceIsLeft = source <= target;
|
|
234
|
-
|
|
235
|
-
if (sourceIsLeft) {
|
|
236
|
-
return {
|
|
237
|
-
key: `${source}|${target}`,
|
|
238
|
-
leftTable: sourceTable,
|
|
239
|
-
leftReferenceField: sourceReferenceField,
|
|
240
|
-
rightTable: targetTable,
|
|
241
|
-
rightReferenceField: targetReferenceField,
|
|
242
|
-
sourceIsLeft: true,
|
|
243
|
-
};
|
|
244
|
-
}
|
|
245
|
-
|
|
246
|
-
return {
|
|
247
|
-
key: `${target}|${source}`,
|
|
248
|
-
leftTable: targetTable,
|
|
249
|
-
leftReferenceField: targetReferenceField,
|
|
250
|
-
rightTable: sourceTable,
|
|
251
|
-
rightReferenceField: sourceReferenceField,
|
|
252
|
-
sourceIsLeft: false,
|
|
253
|
-
};
|
|
254
|
-
}
|
|
255
|
-
|
|
256
|
-
function defaultManyToManyJunctionTable(
|
|
257
|
-
leftTable: string,
|
|
258
|
-
rightTable: string,
|
|
259
|
-
): string {
|
|
260
|
-
return `${leftTable}${toPascalCase(rightTable)}Links`;
|
|
261
|
-
}
|
|
262
|
-
|
|
263
|
-
function defaultManyToManyFieldName(
|
|
264
|
-
ownerTable: string,
|
|
265
|
-
otherTable: string,
|
|
266
|
-
suffix: "source" | "target",
|
|
267
|
-
): string {
|
|
268
|
-
const ownerSingular = singularize(ownerTable);
|
|
269
|
-
const otherSingular = singularize(otherTable);
|
|
270
|
-
|
|
271
|
-
if (ownerSingular === otherSingular) {
|
|
272
|
-
return `${suffix}${toPascalCase(ownerSingular)}Id`;
|
|
273
|
-
}
|
|
274
|
-
|
|
275
|
-
return `${ownerSingular}Id`;
|
|
276
|
-
}
|
|
277
|
-
|
|
278
|
-
function mergeManyToManyPairConfig(
|
|
279
|
-
existing: ManyToManyPair,
|
|
280
|
-
incoming: ManyToManyPair,
|
|
281
|
-
pairKey: string,
|
|
282
|
-
): ManyToManyPair {
|
|
283
|
-
if (existing.junctionTable !== incoming.junctionTable) {
|
|
284
|
-
throw new Error(
|
|
285
|
-
`manyToMany pair '${pairKey}' has conflicting junctionTable values ('${existing.junctionTable}' vs '${incoming.junctionTable}').`,
|
|
286
|
-
);
|
|
287
|
-
}
|
|
288
|
-
|
|
289
|
-
if (existing.leftField !== incoming.leftField) {
|
|
290
|
-
throw new Error(
|
|
291
|
-
`manyToMany pair '${pairKey}' has conflicting left field values ('${existing.leftField}' vs '${incoming.leftField}').`,
|
|
292
|
-
);
|
|
293
|
-
}
|
|
294
|
-
|
|
295
|
-
if (existing.rightField !== incoming.rightField) {
|
|
296
|
-
throw new Error(
|
|
297
|
-
`manyToMany pair '${pairKey}' has conflicting right field values ('${existing.rightField}' vs '${incoming.rightField}').`,
|
|
298
|
-
);
|
|
299
|
-
}
|
|
300
|
-
|
|
301
|
-
if (existing.leftSqlName !== incoming.leftSqlName) {
|
|
302
|
-
throw new Error(
|
|
303
|
-
`manyToMany pair '${pairKey}' has conflicting left sql name values ('${existing.leftSqlName}' vs '${incoming.leftSqlName}').`,
|
|
304
|
-
);
|
|
305
|
-
}
|
|
306
|
-
|
|
307
|
-
if (existing.rightSqlName !== incoming.rightSqlName) {
|
|
308
|
-
throw new Error(
|
|
309
|
-
`manyToMany pair '${pairKey}' has conflicting right sql name values ('${existing.rightSqlName}' vs '${incoming.rightSqlName}').`,
|
|
310
|
-
);
|
|
311
|
-
}
|
|
312
|
-
|
|
313
|
-
if (existing.onDelete !== incoming.onDelete) {
|
|
314
|
-
throw new Error(
|
|
315
|
-
`manyToMany pair '${pairKey}' has conflicting onDelete values ('${existing.onDelete}' vs '${incoming.onDelete}').`,
|
|
316
|
-
);
|
|
317
|
-
}
|
|
318
|
-
|
|
319
|
-
if (existing.onUpdate !== incoming.onUpdate) {
|
|
320
|
-
throw new Error(
|
|
321
|
-
`manyToMany pair '${pairKey}' has conflicting onUpdate values ('${existing.onUpdate}' vs '${incoming.onUpdate}').`,
|
|
322
|
-
);
|
|
323
|
-
}
|
|
324
|
-
|
|
325
|
-
return existing;
|
|
326
|
-
}
|
|
327
|
-
|
|
328
|
-
function normalizeManyToManyRelations(definition: SchemaDefinition): void {
|
|
329
|
-
const pairMap = new Map<string, ManyToManyPair>();
|
|
330
|
-
|
|
331
|
-
for (const [sourceTableName, sourceTable] of Object.entries(
|
|
332
|
-
definition.tables,
|
|
333
|
-
)) {
|
|
334
|
-
for (const relation of Object.values(sourceTable.relations)) {
|
|
335
|
-
if (relation.relation !== "manyToMany") {
|
|
336
|
-
continue;
|
|
337
|
-
}
|
|
338
|
-
|
|
339
|
-
const sourceReferenceField = relation.referenceField ?? "id";
|
|
340
|
-
const targetReferenceField = relation.targetReferenceField ?? "id";
|
|
341
|
-
|
|
342
|
-
const normalizedPair = normalizeManyToManyPairKey(
|
|
343
|
-
sourceTableName,
|
|
344
|
-
sourceReferenceField,
|
|
345
|
-
relation.targetTable,
|
|
346
|
-
targetReferenceField,
|
|
347
|
-
);
|
|
348
|
-
|
|
349
|
-
const defaultLeftField = defaultManyToManyFieldName(
|
|
350
|
-
normalizedPair.leftTable,
|
|
351
|
-
normalizedPair.rightTable,
|
|
352
|
-
"source",
|
|
353
|
-
);
|
|
354
|
-
const defaultRightField = defaultManyToManyFieldName(
|
|
355
|
-
normalizedPair.rightTable,
|
|
356
|
-
normalizedPair.leftTable,
|
|
357
|
-
"target",
|
|
358
|
-
);
|
|
359
|
-
|
|
360
|
-
const pair: ManyToManyPair = {
|
|
361
|
-
leftTable: normalizedPair.leftTable,
|
|
362
|
-
leftReferenceField: normalizedPair.leftReferenceField,
|
|
363
|
-
rightTable: normalizedPair.rightTable,
|
|
364
|
-
rightReferenceField: normalizedPair.rightReferenceField,
|
|
365
|
-
junctionTable:
|
|
366
|
-
relation.junctionTable ??
|
|
367
|
-
defaultManyToManyJunctionTable(
|
|
368
|
-
normalizedPair.leftTable,
|
|
369
|
-
normalizedPair.rightTable,
|
|
370
|
-
),
|
|
371
|
-
leftField: normalizedPair.sourceIsLeft
|
|
372
|
-
? (relation.sourceField ?? defaultLeftField)
|
|
373
|
-
: (relation.targetField ?? defaultLeftField),
|
|
374
|
-
rightField: normalizedPair.sourceIsLeft
|
|
375
|
-
? (relation.targetField ?? defaultRightField)
|
|
376
|
-
: (relation.sourceField ?? defaultRightField),
|
|
377
|
-
leftSqlName: normalizedPair.sourceIsLeft
|
|
378
|
-
? relation.sourceSqlName
|
|
379
|
-
: relation.targetSqlName,
|
|
380
|
-
rightSqlName: normalizedPair.sourceIsLeft
|
|
381
|
-
? relation.targetSqlName
|
|
382
|
-
: relation.sourceSqlName,
|
|
383
|
-
onDelete: relation.onDelete,
|
|
384
|
-
onUpdate: relation.onUpdate,
|
|
385
|
-
};
|
|
386
|
-
|
|
387
|
-
if (pair.leftField === pair.rightField) {
|
|
388
|
-
throw new Error(
|
|
389
|
-
`manyToMany pair '${normalizedPair.key}' resolves to duplicate junction fields '${pair.leftField}'. Set sourceField/targetField explicitly.`,
|
|
390
|
-
);
|
|
391
|
-
}
|
|
392
|
-
|
|
393
|
-
const existing = pairMap.get(normalizedPair.key);
|
|
394
|
-
if (existing) {
|
|
395
|
-
mergeManyToManyPairConfig(existing, pair, normalizedPair.key);
|
|
396
|
-
} else {
|
|
397
|
-
pairMap.set(normalizedPair.key, pair);
|
|
398
|
-
}
|
|
399
|
-
|
|
400
|
-
relation.referenceField = sourceReferenceField;
|
|
401
|
-
relation.targetReferenceField = targetReferenceField;
|
|
402
|
-
relation.junctionTable = pair.junctionTable;
|
|
403
|
-
relation.sourceField = normalizedPair.sourceIsLeft
|
|
404
|
-
? pair.leftField
|
|
405
|
-
: pair.rightField;
|
|
406
|
-
relation.targetField = normalizedPair.sourceIsLeft
|
|
407
|
-
? pair.rightField
|
|
408
|
-
: pair.leftField;
|
|
409
|
-
relation.sourceSqlName = normalizedPair.sourceIsLeft
|
|
410
|
-
? pair.leftSqlName
|
|
411
|
-
: pair.rightSqlName;
|
|
412
|
-
relation.targetSqlName = normalizedPair.sourceIsLeft
|
|
413
|
-
? pair.rightSqlName
|
|
414
|
-
: pair.leftSqlName;
|
|
415
|
-
}
|
|
416
|
-
}
|
|
417
|
-
|
|
418
|
-
for (const pair of pairMap.values()) {
|
|
419
|
-
if (pair.junctionTable in definition.tables) {
|
|
420
|
-
throw new Error(
|
|
421
|
-
`manyToMany auto junction table '${pair.junctionTable}' conflicts with an existing table. Set a different junctionTable name.`,
|
|
422
|
-
);
|
|
423
|
-
}
|
|
424
|
-
|
|
425
|
-
const leftType =
|
|
426
|
-
getLocalReferenceType(
|
|
427
|
-
definition,
|
|
428
|
-
pair.leftTable,
|
|
429
|
-
pair.leftReferenceField,
|
|
430
|
-
) ?? "string";
|
|
431
|
-
const rightType =
|
|
432
|
-
getLocalReferenceType(
|
|
433
|
-
definition,
|
|
434
|
-
pair.rightTable,
|
|
435
|
-
pair.rightReferenceField,
|
|
436
|
-
) ?? "string";
|
|
437
|
-
|
|
438
|
-
definition.tables[pair.junctionTable] = {
|
|
439
|
-
kind: "table",
|
|
440
|
-
columns: {
|
|
441
|
-
[pair.leftField]: {
|
|
442
|
-
kind: "column",
|
|
443
|
-
type: leftType,
|
|
444
|
-
sqlName: pair.leftSqlName,
|
|
445
|
-
notNull: true,
|
|
446
|
-
nullable: false,
|
|
447
|
-
references: {
|
|
448
|
-
table: pair.leftTable,
|
|
449
|
-
column: pair.leftReferenceField,
|
|
450
|
-
onDelete: pair.onDelete,
|
|
451
|
-
onUpdate: pair.onUpdate,
|
|
452
|
-
},
|
|
453
|
-
index: true,
|
|
454
|
-
},
|
|
455
|
-
[pair.rightField]: {
|
|
456
|
-
kind: "column",
|
|
457
|
-
type: rightType,
|
|
458
|
-
sqlName: pair.rightSqlName,
|
|
459
|
-
notNull: true,
|
|
460
|
-
nullable: false,
|
|
461
|
-
references: {
|
|
462
|
-
table: pair.rightTable,
|
|
463
|
-
column: pair.rightReferenceField,
|
|
464
|
-
onDelete: pair.onDelete,
|
|
465
|
-
onUpdate: pair.onUpdate,
|
|
466
|
-
},
|
|
467
|
-
index: true,
|
|
468
|
-
},
|
|
469
|
-
},
|
|
470
|
-
relations: {
|
|
471
|
-
[pair.leftTable]: {
|
|
472
|
-
kind: "relation",
|
|
473
|
-
relation: "one",
|
|
474
|
-
targetTable: pair.leftTable,
|
|
475
|
-
field: pair.leftField,
|
|
476
|
-
referenceField: pair.leftReferenceField,
|
|
477
|
-
},
|
|
478
|
-
[pair.rightTable]: {
|
|
479
|
-
kind: "relation",
|
|
480
|
-
relation: "one",
|
|
481
|
-
targetTable: pair.rightTable,
|
|
482
|
-
field: pair.rightField,
|
|
483
|
-
referenceField: pair.rightReferenceField,
|
|
484
|
-
},
|
|
485
|
-
},
|
|
486
|
-
};
|
|
487
|
-
}
|
|
488
|
-
}
|
|
489
|
-
|
|
490
|
-
function validateNullableFlags(definition: SchemaDefinition): void {
|
|
491
|
-
for (const [tableName, table] of Object.entries(definition.tables)) {
|
|
492
|
-
for (const [columnName, column] of Object.entries(table.columns)) {
|
|
493
|
-
if (column.notNull === true && column.nullable === true) {
|
|
494
|
-
throw new Error(
|
|
495
|
-
`Invalid nullable configuration on '${tableName}.${columnName}': cannot set both notNull and nullable to true.`,
|
|
496
|
-
);
|
|
497
|
-
}
|
|
498
|
-
}
|
|
499
|
-
|
|
500
|
-
for (const [relationName, relation] of Object.entries(table.relations)) {
|
|
501
|
-
if (
|
|
502
|
-
relation.relation !== "manyToMany" &&
|
|
503
|
-
relation.notNull === true &&
|
|
504
|
-
relation.nullable === true
|
|
505
|
-
) {
|
|
506
|
-
throw new Error(
|
|
507
|
-
`Invalid nullable configuration on '${tableName}.${relationName}': cannot set both notNull and nullable to true.`,
|
|
508
|
-
);
|
|
509
|
-
}
|
|
510
|
-
}
|
|
511
|
-
}
|
|
512
|
-
}
|
|
513
|
-
|
|
514
|
-
function normalizeSchemaDefinition(
|
|
515
|
-
definition: SchemaDefinition,
|
|
516
|
-
): SchemaDefinition {
|
|
517
|
-
validateNullableFlags(definition);
|
|
518
|
-
const normalized = cloneSchemaDefinition(definition);
|
|
519
|
-
|
|
520
|
-
for (const [tableName, table] of Object.entries(normalized.tables)) {
|
|
521
|
-
for (const [relationName, relation] of Object.entries(table.relations)) {
|
|
522
|
-
if (relation.relation !== "one") {
|
|
523
|
-
continue;
|
|
524
|
-
}
|
|
525
|
-
|
|
526
|
-
const referenceField = relation.referenceField ?? "id";
|
|
527
|
-
const inferredField = relation.field ?? `${relationName}Id`;
|
|
528
|
-
relation.field = inferredField;
|
|
529
|
-
|
|
530
|
-
const inferredType =
|
|
531
|
-
getLocalReferenceType(
|
|
532
|
-
normalized,
|
|
533
|
-
relation.targetTable,
|
|
534
|
-
referenceField,
|
|
535
|
-
) ??
|
|
536
|
-
relation.fkType ??
|
|
537
|
-
"string";
|
|
538
|
-
|
|
539
|
-
ensureInferredReferenceColumn(
|
|
540
|
-
tableName,
|
|
541
|
-
table,
|
|
542
|
-
inferredField,
|
|
543
|
-
relation.targetTable,
|
|
544
|
-
referenceField,
|
|
545
|
-
{
|
|
546
|
-
fkType: relation.fkType,
|
|
547
|
-
sqlName: relation.sqlName,
|
|
548
|
-
notNull: resolveNotNullFromNullableFlags(
|
|
549
|
-
`${tableName}.${relationName}`,
|
|
550
|
-
relation,
|
|
551
|
-
true,
|
|
552
|
-
),
|
|
553
|
-
onDelete: relation.onDelete,
|
|
554
|
-
onUpdate: relation.onUpdate,
|
|
555
|
-
},
|
|
556
|
-
inferredType,
|
|
557
|
-
);
|
|
558
|
-
}
|
|
559
|
-
}
|
|
560
|
-
|
|
561
|
-
for (const [sourceTableName, sourceTable] of Object.entries(
|
|
562
|
-
normalized.tables,
|
|
563
|
-
)) {
|
|
564
|
-
for (const relation of Object.values(sourceTable.relations)) {
|
|
565
|
-
if (relation.relation !== "many") {
|
|
566
|
-
continue;
|
|
567
|
-
}
|
|
568
|
-
|
|
569
|
-
const targetTable = normalized.tables[relation.targetTable];
|
|
570
|
-
if (!targetTable) {
|
|
571
|
-
continue;
|
|
572
|
-
}
|
|
573
|
-
|
|
574
|
-
const referenceField = relation.referenceField ?? "id";
|
|
575
|
-
const inferredField =
|
|
576
|
-
relation.field ?? `${singularize(sourceTableName)}Id`;
|
|
577
|
-
relation.field = inferredField;
|
|
578
|
-
const inferredType =
|
|
579
|
-
getLocalReferenceType(normalized, sourceTableName, referenceField) ??
|
|
580
|
-
relation.fkType ??
|
|
581
|
-
"string";
|
|
582
|
-
|
|
583
|
-
ensureInferredReferenceColumn(
|
|
584
|
-
relation.targetTable,
|
|
585
|
-
targetTable,
|
|
586
|
-
inferredField,
|
|
587
|
-
sourceTableName,
|
|
588
|
-
referenceField,
|
|
589
|
-
{
|
|
590
|
-
fkType: relation.fkType,
|
|
591
|
-
sqlName: relation.sqlName,
|
|
592
|
-
notNull: resolveNotNullFromNullableFlags(
|
|
593
|
-
`${sourceTableName}.${relation.targetTable}`,
|
|
594
|
-
relation,
|
|
595
|
-
true,
|
|
596
|
-
),
|
|
597
|
-
onDelete: relation.onDelete,
|
|
598
|
-
onUpdate: relation.onUpdate,
|
|
599
|
-
},
|
|
600
|
-
inferredType,
|
|
601
|
-
);
|
|
602
|
-
}
|
|
603
|
-
}
|
|
604
|
-
|
|
605
|
-
normalizeManyToManyRelations(normalized);
|
|
606
|
-
|
|
607
|
-
return normalized;
|
|
608
|
-
}
|
|
609
|
-
|
|
610
|
-
function isOptionalInsertColumn(column: ColumnDefinition): boolean {
|
|
611
|
-
return (
|
|
612
|
-
column.primaryKey === true ||
|
|
613
|
-
column.notNull !== true ||
|
|
614
|
-
column.autoIncrement === true ||
|
|
615
|
-
column.sqlDefault !== undefined ||
|
|
616
|
-
column.runtimeDefaultFn !== undefined
|
|
617
|
-
);
|
|
618
|
-
}
|
|
619
|
-
|
|
620
|
-
function isNullableSelectColumn(column: ColumnDefinition): boolean {
|
|
621
|
-
return column.notNull !== true;
|
|
622
|
-
}
|
|
623
|
-
|
|
624
|
-
function drizzleBaseColumn(
|
|
625
|
-
fieldName: string,
|
|
626
|
-
column: ColumnDefinition,
|
|
627
|
-
strategy: "camelToSnake",
|
|
628
|
-
): string {
|
|
629
|
-
const resolvedSqlName = column.sqlName ?? toSnakeCase(fieldName);
|
|
630
|
-
const needsExplicitName = resolvedSqlName !== fieldName;
|
|
631
|
-
|
|
632
|
-
if (column.type === "int") {
|
|
633
|
-
return needsExplicitName ? `t.int(${quote(resolvedSqlName)})` : "t.int()";
|
|
634
|
-
}
|
|
635
|
-
|
|
636
|
-
if (column.type === "string") {
|
|
637
|
-
if (column.length !== undefined) {
|
|
638
|
-
if (needsExplicitName) {
|
|
639
|
-
return `t.text(${quote(resolvedSqlName)}, { length: ${column.length} })`;
|
|
640
|
-
}
|
|
641
|
-
return `t.text({ length: ${column.length} })`;
|
|
642
|
-
}
|
|
643
|
-
|
|
644
|
-
return needsExplicitName ? `t.text(${quote(resolvedSqlName)})` : "t.text()";
|
|
645
|
-
}
|
|
646
|
-
|
|
647
|
-
if (column.type === "boolean") {
|
|
648
|
-
if (needsExplicitName) {
|
|
649
|
-
return `t.int(${quote(resolvedSqlName)}, { mode: "boolean" })`;
|
|
650
|
-
}
|
|
651
|
-
return 't.int({ mode: "boolean" })';
|
|
652
|
-
}
|
|
653
|
-
|
|
654
|
-
if (column.type === "date") {
|
|
655
|
-
if (needsExplicitName) {
|
|
656
|
-
return `t.int(${quote(resolvedSqlName)}, { mode: "timestamp_ms" })`;
|
|
657
|
-
}
|
|
658
|
-
return 't.int({ mode: "timestamp_ms" })';
|
|
659
|
-
}
|
|
660
|
-
|
|
661
|
-
if (strategy === "camelToSnake") {
|
|
662
|
-
return needsExplicitName ? `t.text(${quote(resolvedSqlName)})` : "t.text()";
|
|
663
|
-
}
|
|
664
|
-
|
|
665
|
-
return "t.text()";
|
|
666
|
-
}
|
|
667
|
-
|
|
668
|
-
function resolveOneRelationReference(
|
|
669
|
-
tableName: string,
|
|
670
|
-
table: TableDefinition,
|
|
671
|
-
relation: OneRelationDefinition,
|
|
672
|
-
): { sourceField: string; targetField: string } {
|
|
673
|
-
const sourceField = relation.field;
|
|
674
|
-
const targetField = relation.referenceField ?? "id";
|
|
675
|
-
|
|
676
|
-
if (!sourceField) {
|
|
677
|
-
throw new Error(
|
|
678
|
-
`Relation on '${tableName}' targeting '${relation.targetTable}' is missing a local field.`,
|
|
679
|
-
);
|
|
680
|
-
}
|
|
681
|
-
|
|
682
|
-
if (!(sourceField in table.columns)) {
|
|
683
|
-
throw new Error(
|
|
684
|
-
`Relation '${tableName}.${sourceField}' references missing local field '${sourceField}'.`,
|
|
685
|
-
);
|
|
686
|
-
}
|
|
687
|
-
|
|
688
|
-
return {
|
|
689
|
-
sourceField,
|
|
690
|
-
targetField,
|
|
691
|
-
};
|
|
692
|
-
}
|
|
693
|
-
|
|
694
|
-
function buildExternalTableImportLines(externals: Set<string>): string {
|
|
695
|
-
if (externals.size === 0) {
|
|
696
|
-
return "";
|
|
697
|
-
}
|
|
698
|
-
return `import { ${Array.from(externals).sort().join(", ")} } from \"./auth.schema\";\n`;
|
|
699
|
-
}
|
|
700
|
-
|
|
701
|
-
function getRelationImports(table: TableDefinition): string[] {
|
|
702
|
-
return Object.values(table.relations)
|
|
703
|
-
.filter((relation) => relation.relation === "one")
|
|
704
|
-
.map((relation) => relation.targetTable);
|
|
705
|
-
}
|
|
706
|
-
|
|
707
|
-
function resolveColumnReference(
|
|
708
|
-
fieldName: string,
|
|
709
|
-
column: ColumnDefinition,
|
|
710
|
-
table: TableDefinition,
|
|
711
|
-
): { tableName: string; fieldName: string } | undefined {
|
|
712
|
-
if (column.references) {
|
|
713
|
-
return {
|
|
714
|
-
tableName: column.references.table,
|
|
715
|
-
fieldName: column.references.column,
|
|
716
|
-
};
|
|
717
|
-
}
|
|
718
|
-
|
|
719
|
-
const matchingOne = Object.values(table.relations).find((relation) => {
|
|
720
|
-
return relation.relation === "one" && relation.field === fieldName;
|
|
721
|
-
}) as OneRelationDefinition | undefined;
|
|
722
|
-
|
|
723
|
-
if (!matchingOne) {
|
|
724
|
-
return undefined;
|
|
725
|
-
}
|
|
726
|
-
|
|
727
|
-
return {
|
|
728
|
-
tableName: matchingOne.targetTable,
|
|
729
|
-
fieldName: matchingOne.referenceField ?? "id",
|
|
730
|
-
};
|
|
731
|
-
}
|
|
732
|
-
|
|
733
|
-
function emitManyToManyRuntimeMetadata(definition: SchemaDefinition): string {
|
|
734
|
-
const tableEntries: string[] = [];
|
|
735
|
-
|
|
736
|
-
for (const [tableName, table] of Object.entries(definition.tables)) {
|
|
737
|
-
const relationEntries: string[] = [];
|
|
738
|
-
|
|
739
|
-
for (const [relationName, relation] of Object.entries(table.relations)) {
|
|
740
|
-
if (relation.relation !== "manyToMany") {
|
|
741
|
-
continue;
|
|
742
|
-
}
|
|
743
|
-
|
|
744
|
-
if (!relation.junctionTable) {
|
|
745
|
-
continue;
|
|
746
|
-
}
|
|
747
|
-
|
|
748
|
-
relationEntries.push(
|
|
749
|
-
`${quote(relationName)}: {
|
|
750
|
-
targetTable: ${quote(relation.targetTable)},
|
|
751
|
-
junctionTable: ${quote(relation.junctionTable)},
|
|
752
|
-
sourceField: ${quote(relation.sourceField ?? "")},
|
|
753
|
-
targetField: ${quote(relation.targetField ?? "")},
|
|
754
|
-
},`,
|
|
755
|
-
);
|
|
756
|
-
}
|
|
757
|
-
|
|
758
|
-
if (relationEntries.length === 0) {
|
|
759
|
-
continue;
|
|
760
|
-
}
|
|
761
|
-
|
|
762
|
-
tableEntries.push(
|
|
763
|
-
`${quote(tableName)}: {
|
|
764
|
-
${relationEntries.map((entry) => `\t${entry}`).join("\n")}
|
|
765
|
-
},`,
|
|
766
|
-
);
|
|
767
|
-
}
|
|
768
|
-
|
|
769
|
-
if (tableEntries.length === 0) {
|
|
770
|
-
return "export const __appflareManyToMany = {} as const;\n";
|
|
771
|
-
}
|
|
772
|
-
|
|
773
|
-
return `export const __appflareManyToMany = {
|
|
774
|
-
${tableEntries.map((entry) => `\t${entry}`).join("\n")}
|
|
775
|
-
} as const;
|
|
776
|
-
`;
|
|
777
|
-
}
|
|
778
|
-
|
|
779
|
-
function emitRuntimeRelationMetadata(definition: SchemaDefinition): string {
|
|
780
|
-
const tableEntries: string[] = [];
|
|
781
|
-
|
|
782
|
-
for (const [tableName, table] of Object.entries(definition.tables)) {
|
|
783
|
-
const relationEntries: string[] = [];
|
|
784
|
-
|
|
785
|
-
for (const [relationName, relation] of Object.entries(table.relations)) {
|
|
786
|
-
if (relation.relation === "one") {
|
|
787
|
-
relationEntries.push(
|
|
788
|
-
`${quote(relationName)}: {
|
|
789
|
-
kind: "one",
|
|
790
|
-
targetTable: ${quote(relation.targetTable)},
|
|
791
|
-
sourceField: ${quote(relation.field ?? "")},
|
|
792
|
-
referenceField: ${quote(relation.referenceField ?? "id")},
|
|
793
|
-
},`,
|
|
794
|
-
);
|
|
795
|
-
continue;
|
|
796
|
-
}
|
|
797
|
-
|
|
798
|
-
if (relation.relation === "many") {
|
|
799
|
-
relationEntries.push(
|
|
800
|
-
`${quote(relationName)}: {
|
|
801
|
-
kind: "many",
|
|
802
|
-
targetTable: ${quote(relation.targetTable)},
|
|
803
|
-
sourceField: ${quote(relation.field ?? "")},
|
|
804
|
-
referenceField: ${quote(relation.referenceField ?? "id")},
|
|
805
|
-
},`,
|
|
806
|
-
);
|
|
807
|
-
continue;
|
|
808
|
-
}
|
|
809
|
-
|
|
810
|
-
relationEntries.push(
|
|
811
|
-
`${quote(relationName)}: {
|
|
812
|
-
kind: "manyToMany",
|
|
813
|
-
targetTable: ${quote(relation.targetTable)},
|
|
814
|
-
junctionTable: ${quote(relation.junctionTable ?? "")},
|
|
815
|
-
sourceField: ${quote(relation.sourceField ?? "")},
|
|
816
|
-
targetField: ${quote(relation.targetField ?? "")},
|
|
817
|
-
referenceField: ${quote(relation.referenceField ?? "id")},
|
|
818
|
-
targetReferenceField: ${quote(relation.targetReferenceField ?? "id")},
|
|
819
|
-
},`,
|
|
820
|
-
);
|
|
821
|
-
}
|
|
822
|
-
|
|
823
|
-
if (relationEntries.length === 0) {
|
|
824
|
-
continue;
|
|
825
|
-
}
|
|
826
|
-
|
|
827
|
-
tableEntries.push(
|
|
828
|
-
`${quote(tableName)}: {
|
|
829
|
-
${relationEntries.map((entry) => `\t${entry}`).join("\n")}
|
|
830
|
-
},`,
|
|
831
|
-
);
|
|
832
|
-
}
|
|
833
|
-
|
|
834
|
-
if (tableEntries.length === 0) {
|
|
835
|
-
return "export const __appflareRelations = {} as const;\n";
|
|
836
|
-
}
|
|
837
|
-
|
|
838
|
-
return `export const __appflareRelations = {
|
|
839
|
-
${tableEntries.map((entry) => `\t${entry}`).join("\n")}
|
|
840
|
-
} as const;
|
|
841
|
-
`;
|
|
842
|
-
}
|
|
843
|
-
|
|
844
|
-
function emitDrizzleSchema(
|
|
845
|
-
definition: SchemaDefinition,
|
|
846
|
-
strategy: "camelToSnake",
|
|
847
|
-
): string {
|
|
848
|
-
const localTables = new Set(Object.keys(definition.tables));
|
|
849
|
-
const externalTables = new Set<string>();
|
|
850
|
-
|
|
851
|
-
for (const table of Object.values(definition.tables)) {
|
|
852
|
-
for (const relationTarget of getRelationImports(table)) {
|
|
853
|
-
if (!localTables.has(relationTarget)) {
|
|
854
|
-
externalTables.add(relationTarget);
|
|
855
|
-
}
|
|
856
|
-
}
|
|
857
|
-
for (const column of Object.values(table.columns)) {
|
|
858
|
-
if (column.references && !localTables.has(column.references.table)) {
|
|
859
|
-
externalTables.add(column.references.table);
|
|
860
|
-
}
|
|
861
|
-
}
|
|
862
|
-
}
|
|
863
|
-
|
|
864
|
-
const tableBlocks: string[] = [];
|
|
865
|
-
const relationBlocks: string[] = [];
|
|
866
|
-
|
|
867
|
-
for (const [tableName, table] of Object.entries(definition.tables)) {
|
|
868
|
-
const sqlTableName = table.sqlName ?? toSnakeCase(tableName);
|
|
869
|
-
const columnLines: string[] = [];
|
|
870
|
-
const indexes: string[] = [];
|
|
871
|
-
|
|
872
|
-
for (const [fieldName, column] of Object.entries(table.columns)) {
|
|
873
|
-
let expr = drizzleBaseColumn(fieldName, column, strategy);
|
|
874
|
-
|
|
875
|
-
if (column.uuidPrimaryKey) {
|
|
876
|
-
expr += ".$defaultFn(() => crypto.randomUUID())";
|
|
877
|
-
}
|
|
878
|
-
|
|
879
|
-
if (column.primaryKey) {
|
|
880
|
-
expr += column.autoIncrement
|
|
881
|
-
? ".primaryKey({ autoIncrement: true })"
|
|
882
|
-
: ".primaryKey()";
|
|
883
|
-
}
|
|
884
|
-
if (column.notNull) {
|
|
885
|
-
expr += ".notNull()";
|
|
886
|
-
}
|
|
887
|
-
if (column.sqlDefault !== undefined) {
|
|
888
|
-
expr += `.default(${toSqlLiteral(column.sqlDefault)})`;
|
|
889
|
-
}
|
|
890
|
-
|
|
891
|
-
const reference = resolveColumnReference(fieldName, column, table);
|
|
892
|
-
if (reference) {
|
|
893
|
-
if (column.references?.onDelete || column.references?.onUpdate) {
|
|
894
|
-
const actions: string[] = [];
|
|
895
|
-
if (column.references.onDelete) {
|
|
896
|
-
actions.push(`onDelete: ${quote(column.references.onDelete)}`);
|
|
897
|
-
}
|
|
898
|
-
if (column.references.onUpdate) {
|
|
899
|
-
actions.push(`onUpdate: ${quote(column.references.onUpdate)}`);
|
|
900
|
-
}
|
|
901
|
-
expr += `.references(() => ${reference.tableName}.${reference.fieldName}, { ${actions.join(", ")} })`;
|
|
902
|
-
} else {
|
|
903
|
-
expr += `.references(() => ${reference.tableName}.${reference.fieldName})`;
|
|
904
|
-
}
|
|
905
|
-
}
|
|
906
|
-
|
|
907
|
-
if (column.unique) {
|
|
908
|
-
const uniqueName =
|
|
909
|
-
typeof column.unique === "object" && column.unique.name
|
|
910
|
-
? column.unique.name
|
|
911
|
-
: `${sqlTableName}_${toSnakeCase(fieldName)}_unique_idx`;
|
|
912
|
-
indexes.push(
|
|
913
|
-
`\t\tt.uniqueIndex(${quote(uniqueName)}).on(table.${fieldName})`,
|
|
914
|
-
);
|
|
915
|
-
}
|
|
916
|
-
|
|
917
|
-
if (column.index) {
|
|
918
|
-
const indexName =
|
|
919
|
-
typeof column.index === "object" && column.index.name
|
|
920
|
-
? column.index.name
|
|
921
|
-
: `${sqlTableName}_${toSnakeCase(fieldName)}_idx`;
|
|
922
|
-
indexes.push(`\t\tt.index(${quote(indexName)}).on(table.${fieldName})`);
|
|
923
|
-
}
|
|
924
|
-
|
|
925
|
-
columnLines.push(`\t\t${fieldName}: ${expr},`);
|
|
926
|
-
}
|
|
927
|
-
|
|
928
|
-
if (indexes.length > 0) {
|
|
929
|
-
tableBlocks.push(
|
|
930
|
-
`export const ${tableName} = table(\n\t${quote(sqlTableName)},\n\t{\n${columnLines.join("\n")}\n\t},\n\t(table) => [\n${indexes.join(",\n")}\n\t],\n);`,
|
|
931
|
-
);
|
|
932
|
-
} else {
|
|
933
|
-
tableBlocks.push(
|
|
934
|
-
`export const ${tableName} = table(${quote(sqlTableName)}, {\n${columnLines.join("\n")}\n\t});`,
|
|
935
|
-
);
|
|
936
|
-
}
|
|
937
|
-
|
|
938
|
-
const oneRelations = Object.entries(table.relations).filter(
|
|
939
|
-
([, relation]) => {
|
|
940
|
-
return relation.relation === "one";
|
|
941
|
-
},
|
|
942
|
-
) as Array<[string, OneRelationDefinition]>;
|
|
943
|
-
const manyRelations = Object.entries(table.relations).filter(
|
|
944
|
-
([, relation]) => {
|
|
945
|
-
return relation.relation === "many";
|
|
946
|
-
},
|
|
947
|
-
) as Array<[string, ManyRelationDefinition]>;
|
|
948
|
-
const manyToManyRelations = Object.entries(table.relations).filter(
|
|
949
|
-
([, relation]) => {
|
|
950
|
-
return relation.relation === "manyToMany";
|
|
951
|
-
},
|
|
952
|
-
) as Array<[string, ManyToManyRelationDefinition]>;
|
|
953
|
-
|
|
954
|
-
if (
|
|
955
|
-
oneRelations.length === 0 &&
|
|
956
|
-
manyRelations.length === 0 &&
|
|
957
|
-
manyToManyRelations.length === 0
|
|
958
|
-
) {
|
|
959
|
-
continue;
|
|
960
|
-
}
|
|
961
|
-
|
|
962
|
-
const relationLines: string[] = [];
|
|
963
|
-
for (const [relationName, relation] of oneRelations) {
|
|
964
|
-
const resolved = resolveOneRelationReference(tableName, table, relation);
|
|
965
|
-
relationLines.push(
|
|
966
|
-
`\t${relationName}: one(${relation.targetTable}, {\n\t\tfields: [${tableName}.${resolved.sourceField}],\n\t\treferences: [${relation.targetTable}.${resolved.targetField}],\n\t}),`,
|
|
967
|
-
);
|
|
968
|
-
}
|
|
969
|
-
for (const [relationName, relation] of manyRelations) {
|
|
970
|
-
relationLines.push(`\t${relationName}: many(${relation.targetTable}),`);
|
|
971
|
-
}
|
|
972
|
-
for (const [relationName, relation] of manyToManyRelations) {
|
|
973
|
-
if (!relation.junctionTable) {
|
|
974
|
-
throw new Error(
|
|
975
|
-
`manyToMany relation '${tableName}.${relationName}' is missing junctionTable after normalization.`,
|
|
976
|
-
);
|
|
977
|
-
}
|
|
978
|
-
relationLines.push(`\t${relationName}: many(${relation.junctionTable}),`);
|
|
979
|
-
}
|
|
980
|
-
|
|
981
|
-
relationBlocks.push(
|
|
982
|
-
`export const ${tableName}Relations = relations(${tableName}, ({ one, many }) => ({\n${relationLines.join("\n")}\n}));`,
|
|
983
|
-
);
|
|
984
|
-
}
|
|
985
|
-
|
|
986
|
-
return `import * as t from "drizzle-orm/sqlite-core";
|
|
987
|
-
import { sqliteTable as table } from "drizzle-orm/sqlite-core";
|
|
988
|
-
import { relations } from "drizzle-orm";
|
|
989
|
-
${buildExternalTableImportLines(externalTables)}
|
|
990
|
-
${tableBlocks.join("\n\n")}
|
|
991
|
-
|
|
992
|
-
${relationBlocks.join("\n\n")}
|
|
993
|
-
|
|
994
|
-
${emitManyToManyRuntimeMetadata(definition)}
|
|
995
|
-
|
|
996
|
-
${emitRuntimeRelationMetadata(definition)}
|
|
997
|
-
`;
|
|
998
|
-
}
|
|
999
|
-
|
|
1000
|
-
function zodSchemaExpression(
|
|
1001
|
-
column: ColumnDefinition,
|
|
1002
|
-
optional: boolean,
|
|
1003
|
-
nullable: boolean,
|
|
1004
|
-
): string {
|
|
1005
|
-
let expr = "z.unknown()";
|
|
1006
|
-
if (column.type === "int") {
|
|
1007
|
-
expr = "z.number().int()";
|
|
1008
|
-
} else if (column.type === "string") {
|
|
1009
|
-
expr = "z.string()";
|
|
1010
|
-
if (column.length !== undefined) {
|
|
1011
|
-
expr += `.max(${column.length})`;
|
|
1012
|
-
}
|
|
1013
|
-
} else if (column.type === "boolean") {
|
|
1014
|
-
expr = "z.boolean()";
|
|
1015
|
-
} else if (column.type === "date") {
|
|
1016
|
-
expr = "z.date()";
|
|
1017
|
-
}
|
|
1018
|
-
|
|
1019
|
-
if (optional) {
|
|
1020
|
-
expr += ".optional()";
|
|
1021
|
-
}
|
|
1022
|
-
|
|
1023
|
-
if (nullable) {
|
|
1024
|
-
expr += ".nullable()";
|
|
1025
|
-
}
|
|
1026
|
-
|
|
1027
|
-
return expr;
|
|
1028
|
-
}
|
|
1029
|
-
|
|
1030
|
-
function emitZodSchemas(definition: SchemaDefinition): string {
|
|
1031
|
-
const blocks: string[] = [];
|
|
1032
|
-
|
|
1033
|
-
for (const [tableName, table] of Object.entries(definition.tables)) {
|
|
1034
|
-
const pascal = toPascalCase(tableName);
|
|
1035
|
-
const insertLines: string[] = [];
|
|
1036
|
-
const selectLines: string[] = [];
|
|
1037
|
-
|
|
1038
|
-
for (const [fieldName, column] of Object.entries(table.columns)) {
|
|
1039
|
-
insertLines.push(
|
|
1040
|
-
`\t${fieldName}: ${zodSchemaExpression(column, isOptionalInsertColumn(column), isNullableSelectColumn(column))},`,
|
|
1041
|
-
);
|
|
1042
|
-
selectLines.push(
|
|
1043
|
-
`\t${fieldName}: ${zodSchemaExpression(column, isNullableSelectColumn(column), isNullableSelectColumn(column))},`,
|
|
1044
|
-
);
|
|
1045
|
-
}
|
|
1046
|
-
|
|
1047
|
-
blocks.push(`export const ${tableName}InsertSchema = z.object({\n${insertLines.join("\n")}\n});
|
|
1048
|
-
export const ${tableName}SelectSchema = z.object({\n${selectLines.join("\n")}\n});
|
|
1049
|
-
|
|
1050
|
-
export type ${pascal}Insert = z.infer<typeof ${tableName}InsertSchema>;
|
|
1051
|
-
export type ${pascal}Select = z.infer<typeof ${tableName}SelectSchema>;
|
|
1052
|
-
`);
|
|
1053
|
-
}
|
|
1054
|
-
|
|
1055
|
-
return `import { z } from "zod";
|
|
1056
|
-
|
|
1057
|
-
${blocks.join("\n")}`;
|
|
1058
|
-
}
|
|
1059
|
-
|
|
1060
|
-
function toTypeScriptType(column: ColumnDefinition): string {
|
|
1061
|
-
if (column.type === "int") {
|
|
1062
|
-
return "number";
|
|
1063
|
-
}
|
|
1064
|
-
if (column.type === "string") {
|
|
1065
|
-
return "string";
|
|
1066
|
-
}
|
|
1067
|
-
if (column.type === "boolean") {
|
|
1068
|
-
return "boolean";
|
|
1069
|
-
}
|
|
1070
|
-
if (column.type === "date") {
|
|
1071
|
-
return "Date";
|
|
1072
|
-
}
|
|
1073
|
-
return "unknown";
|
|
1074
|
-
}
|
|
1075
|
-
|
|
1076
|
-
function emitTypes(definition: SchemaDefinition): string {
|
|
1077
|
-
const lines: string[] = [];
|
|
1078
|
-
|
|
1079
|
-
for (const [tableName, table] of Object.entries(definition.tables)) {
|
|
1080
|
-
const pascal = toPascalCase(tableName);
|
|
1081
|
-
const selectFields: string[] = [];
|
|
1082
|
-
const insertFields: string[] = [];
|
|
1083
|
-
|
|
1084
|
-
for (const [fieldName, column] of Object.entries(table.columns)) {
|
|
1085
|
-
const tsType = toTypeScriptType(column);
|
|
1086
|
-
const nullableSuffix = isNullableSelectColumn(column) ? " | null" : "";
|
|
1087
|
-
selectFields.push(
|
|
1088
|
-
`\t${fieldName}${isNullableSelectColumn(column) ? "?" : ""}: ${tsType}${nullableSuffix};`,
|
|
1089
|
-
);
|
|
1090
|
-
insertFields.push(
|
|
1091
|
-
`\t${fieldName}${isOptionalInsertColumn(column) ? "?" : ""}: ${tsType}${nullableSuffix};`,
|
|
1092
|
-
);
|
|
1093
|
-
}
|
|
1094
|
-
|
|
1095
|
-
lines.push(`export type ${pascal} = {\n${selectFields.join("\n")}\n};
|
|
1096
|
-
|
|
1097
|
-
export type New${pascal} = {\n${insertFields.join("\n")}\n};`);
|
|
1098
|
-
}
|
|
1099
|
-
|
|
1100
|
-
return `${lines.join("\n\n")}
|
|
1101
|
-
`;
|
|
1102
|
-
}
|
|
1103
|
-
|
|
1104
|
-
function findSchemaExport(
|
|
1105
|
-
moduleExports: Record<string, unknown>,
|
|
1106
|
-
exportName?: string,
|
|
1107
|
-
): SchemaDefinition {
|
|
1108
|
-
if (exportName) {
|
|
1109
|
-
const explicit = moduleExports[exportName];
|
|
1110
|
-
if (!isSchemaDefinition(explicit)) {
|
|
1111
|
-
throw new Error(
|
|
1112
|
-
`schemaDsl.exportName '${exportName}' does not point to a schema() export.`,
|
|
1113
|
-
);
|
|
1114
|
-
}
|
|
1115
|
-
return explicit;
|
|
1116
|
-
}
|
|
1117
|
-
|
|
1118
|
-
for (const candidate of Object.values(moduleExports)) {
|
|
1119
|
-
if (isSchemaDefinition(candidate)) {
|
|
1120
|
-
return candidate;
|
|
1121
|
-
}
|
|
1122
|
-
}
|
|
1123
|
-
|
|
1124
|
-
throw new Error(
|
|
1125
|
-
"No schema() export found in schemaDsl entry module. Set schemaDsl.exportName to the correct export.",
|
|
1126
|
-
);
|
|
1127
|
-
}
|
|
1128
|
-
|
|
1129
|
-
export async function compileSchemaDsl(
|
|
1130
|
-
loadedConfig: LoadedAppflareConfig,
|
|
1131
|
-
): Promise<CompiledSchemaArtifacts | undefined> {
|
|
1132
|
-
const schemaDsl = loadedConfig.config.schemaDsl;
|
|
1133
|
-
if (!schemaDsl) {
|
|
1134
|
-
return undefined;
|
|
1135
|
-
}
|
|
1136
|
-
|
|
1137
|
-
const namingStrategy = schemaDsl.namingStrategy ?? "camelToSnake";
|
|
1138
|
-
const entryPath = resolve(loadedConfig.configDir, schemaDsl.entry);
|
|
1139
|
-
const outSchemaPath = resolve(
|
|
1140
|
-
loadedConfig.configDir,
|
|
1141
|
-
schemaDsl.outFile ?? resolve(loadedConfig.outDirAbs, "schema.compiled.ts"),
|
|
1142
|
-
);
|
|
1143
|
-
const outTypesPath = resolve(
|
|
1144
|
-
loadedConfig.configDir,
|
|
1145
|
-
schemaDsl.typesOutFile ??
|
|
1146
|
-
resolve(loadedConfig.outDirAbs, "schema.types.ts"),
|
|
1147
|
-
);
|
|
1148
|
-
const outZodPath = resolve(
|
|
1149
|
-
loadedConfig.configDir,
|
|
1150
|
-
schemaDsl.zodOutFile ?? resolve(loadedConfig.outDirAbs, "schema.zod.ts"),
|
|
1151
|
-
);
|
|
1152
|
-
|
|
1153
|
-
const moduleUrl = `${pathToFileURL(entryPath).href}?t=${Date.now()}`;
|
|
1154
|
-
const schemaModule = (await import(moduleUrl)) as Record<string, unknown>;
|
|
1155
|
-
const schemaDefinition = findSchemaExport(schemaModule, schemaDsl.exportName);
|
|
1156
|
-
const normalizedSchema = normalizeSchemaDefinition(schemaDefinition);
|
|
1157
|
-
|
|
1158
|
-
await Promise.all([
|
|
1159
|
-
mkdir(dirname(outSchemaPath), { recursive: true }),
|
|
1160
|
-
mkdir(dirname(outTypesPath), { recursive: true }),
|
|
1161
|
-
mkdir(dirname(outZodPath), { recursive: true }),
|
|
1162
|
-
]);
|
|
1163
|
-
|
|
1164
|
-
const drizzleSchemaSource = emitDrizzleSchema(
|
|
1165
|
-
normalizedSchema,
|
|
1166
|
-
namingStrategy,
|
|
1167
|
-
);
|
|
1168
|
-
const typesSource = emitTypes(normalizedSchema);
|
|
1169
|
-
const zodSource = emitZodSchemas(normalizedSchema);
|
|
1170
|
-
|
|
1171
|
-
await Promise.all([
|
|
1172
|
-
Bun.write(outSchemaPath, drizzleSchemaSource),
|
|
1173
|
-
Bun.write(outTypesPath, typesSource),
|
|
1174
|
-
Bun.write(outZodPath, zodSource),
|
|
1175
|
-
]);
|
|
1176
|
-
|
|
1177
|
-
return {
|
|
1178
|
-
schemaPath: outSchemaPath,
|
|
1179
|
-
typesPath: outTypesPath,
|
|
1180
|
-
zodPath: outZodPath,
|
|
1181
|
-
tableNames: Object.keys(normalizedSchema.tables),
|
|
1182
|
-
};
|
|
1183
|
-
}
|
|
1
|
+
import { mkdir } from "node:fs/promises";
|
|
2
|
+
import { dirname, resolve } from "node:path";
|
|
3
|
+
import { pathToFileURL } from "node:url";
|
|
4
|
+
import type {
|
|
5
|
+
ColumnDefinition,
|
|
6
|
+
ColumnType,
|
|
7
|
+
ManyRelationDefinition,
|
|
8
|
+
ManyToManyRelationDefinition,
|
|
9
|
+
OneRelationDefinition,
|
|
10
|
+
SchemaDefinition,
|
|
11
|
+
TableDefinition,
|
|
12
|
+
} from "../schema";
|
|
13
|
+
import { isSchemaDefinition } from "../schema";
|
|
14
|
+
import type { LoadedAppflareConfig } from "./types";
|
|
15
|
+
|
|
16
|
+
export type CompiledSchemaArtifacts = {
|
|
17
|
+
schemaPath: string;
|
|
18
|
+
typesPath: string;
|
|
19
|
+
zodPath: string;
|
|
20
|
+
tableNames: string[];
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
function toSnakeCase(value: string): string {
|
|
24
|
+
return value
|
|
25
|
+
.replace(/([a-z0-9])([A-Z])/g, "$1_$2")
|
|
26
|
+
.replace(/[\s-]+/g, "_")
|
|
27
|
+
.toLowerCase();
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function toPascalCase(value: string): string {
|
|
31
|
+
return value
|
|
32
|
+
.replace(/[_-]+/g, " ")
|
|
33
|
+
.replace(/\s+(.)/g, (_match, char: string) => char.toUpperCase())
|
|
34
|
+
.replace(/\s/g, "")
|
|
35
|
+
.replace(/^(.)/, (_match, char: string) => char.toUpperCase());
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function singularize(value: string): string {
|
|
39
|
+
if (value.endsWith("ies")) {
|
|
40
|
+
return `${value.slice(0, -3)}y`;
|
|
41
|
+
}
|
|
42
|
+
if (value.endsWith("ses")) {
|
|
43
|
+
return value.slice(0, -2);
|
|
44
|
+
}
|
|
45
|
+
if (value.endsWith("s") && value.length > 1) {
|
|
46
|
+
return value.slice(0, -1);
|
|
47
|
+
}
|
|
48
|
+
return value;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function quote(value: string): string {
|
|
52
|
+
return JSON.stringify(value);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function toSqlLiteral(value: unknown): string {
|
|
56
|
+
if (typeof value === "string") {
|
|
57
|
+
return quote(value);
|
|
58
|
+
}
|
|
59
|
+
if (typeof value === "number" || typeof value === "boolean") {
|
|
60
|
+
return String(value);
|
|
61
|
+
}
|
|
62
|
+
if (value === null) {
|
|
63
|
+
return "null";
|
|
64
|
+
}
|
|
65
|
+
if (value instanceof Date) {
|
|
66
|
+
return quote(value.toISOString());
|
|
67
|
+
}
|
|
68
|
+
throw new Error(
|
|
69
|
+
`Unsupported SQL default value '${String(value)}'. Use string, number, boolean, null, or Date.`,
|
|
70
|
+
);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function cloneSchemaDefinition(definition: SchemaDefinition): SchemaDefinition {
|
|
74
|
+
return {
|
|
75
|
+
kind: "schema",
|
|
76
|
+
tables: Object.fromEntries(
|
|
77
|
+
Object.entries(definition.tables).map(([tableName, table]) => {
|
|
78
|
+
return [
|
|
79
|
+
tableName,
|
|
80
|
+
{
|
|
81
|
+
kind: "table",
|
|
82
|
+
sqlName: table.sqlName,
|
|
83
|
+
columns: Object.fromEntries(
|
|
84
|
+
Object.entries(table.columns).map(([columnName, column]) => {
|
|
85
|
+
return [columnName, { ...column }];
|
|
86
|
+
}),
|
|
87
|
+
),
|
|
88
|
+
relations: Object.fromEntries(
|
|
89
|
+
Object.entries(table.relations).map(
|
|
90
|
+
([relationName, relation]) => {
|
|
91
|
+
return [relationName, { ...relation }];
|
|
92
|
+
},
|
|
93
|
+
),
|
|
94
|
+
),
|
|
95
|
+
} satisfies TableDefinition,
|
|
96
|
+
];
|
|
97
|
+
}),
|
|
98
|
+
),
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function getLocalReferenceType(
|
|
103
|
+
definition: SchemaDefinition,
|
|
104
|
+
targetTable: string,
|
|
105
|
+
referenceField: string,
|
|
106
|
+
): ColumnType | undefined {
|
|
107
|
+
const table = definition.tables[targetTable];
|
|
108
|
+
if (!table) {
|
|
109
|
+
return undefined;
|
|
110
|
+
}
|
|
111
|
+
const targetColumn = table.columns[referenceField];
|
|
112
|
+
return targetColumn?.type;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function ensureInferredReferenceColumn(
|
|
116
|
+
tableName: string,
|
|
117
|
+
table: TableDefinition,
|
|
118
|
+
columnName: string,
|
|
119
|
+
referenceTable: string,
|
|
120
|
+
referenceField: string,
|
|
121
|
+
options: {
|
|
122
|
+
fkType?: ColumnType;
|
|
123
|
+
sqlName?: string;
|
|
124
|
+
notNull?: boolean;
|
|
125
|
+
onDelete?: OneRelationDefinition["onDelete"];
|
|
126
|
+
onUpdate?: OneRelationDefinition["onUpdate"];
|
|
127
|
+
},
|
|
128
|
+
inferredType: ColumnType,
|
|
129
|
+
): void {
|
|
130
|
+
const existing = table.columns[columnName];
|
|
131
|
+
if (existing) {
|
|
132
|
+
if (
|
|
133
|
+
existing.references &&
|
|
134
|
+
(existing.references.table !== referenceTable ||
|
|
135
|
+
existing.references.column !== referenceField)
|
|
136
|
+
) {
|
|
137
|
+
throw new Error(
|
|
138
|
+
`Inferred relation '${tableName}.${columnName}' conflicts with explicit references(${existing.references.table}.${existing.references.column}).`,
|
|
139
|
+
);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
table.columns[columnName] = {
|
|
143
|
+
...existing,
|
|
144
|
+
notNull:
|
|
145
|
+
existing.notNull ??
|
|
146
|
+
(existing.nullable === true ? false : options.notNull),
|
|
147
|
+
nullable:
|
|
148
|
+
existing.nullable ?? (options.notNull === false ? true : undefined),
|
|
149
|
+
references: {
|
|
150
|
+
table: referenceTable,
|
|
151
|
+
column: referenceField,
|
|
152
|
+
onDelete: existing.references?.onDelete ?? options.onDelete,
|
|
153
|
+
onUpdate: existing.references?.onUpdate ?? options.onUpdate,
|
|
154
|
+
},
|
|
155
|
+
};
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
table.columns[columnName] = {
|
|
160
|
+
kind: "column",
|
|
161
|
+
type: options.fkType ?? inferredType,
|
|
162
|
+
sqlName: options.sqlName,
|
|
163
|
+
notNull: options.notNull ?? true,
|
|
164
|
+
nullable: options.notNull === false ? true : undefined,
|
|
165
|
+
references: {
|
|
166
|
+
table: referenceTable,
|
|
167
|
+
column: referenceField,
|
|
168
|
+
onDelete: options.onDelete,
|
|
169
|
+
onUpdate: options.onUpdate,
|
|
170
|
+
},
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function resolveNotNullFromNullableFlags(
|
|
175
|
+
fieldPath: string,
|
|
176
|
+
flags: { notNull?: boolean; nullable?: boolean },
|
|
177
|
+
defaultNotNull: boolean,
|
|
178
|
+
): boolean {
|
|
179
|
+
if (flags.notNull === true && flags.nullable === true) {
|
|
180
|
+
throw new Error(
|
|
181
|
+
`Invalid nullable configuration on '${fieldPath}': cannot set both notNull and nullable to true.`,
|
|
182
|
+
);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
if (flags.notNull === true) {
|
|
186
|
+
return true;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
if (flags.nullable === true) {
|
|
190
|
+
return false;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
if (flags.notNull === false) {
|
|
194
|
+
return false;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
return defaultNotNull;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
type ManyToManyPair = {
|
|
201
|
+
leftTable: string;
|
|
202
|
+
leftReferenceField: string;
|
|
203
|
+
rightTable: string;
|
|
204
|
+
rightReferenceField: string;
|
|
205
|
+
junctionTable: string;
|
|
206
|
+
leftField: string;
|
|
207
|
+
rightField: string;
|
|
208
|
+
leftSqlName?: string;
|
|
209
|
+
rightSqlName?: string;
|
|
210
|
+
onDelete?: OneRelationDefinition["onDelete"];
|
|
211
|
+
onUpdate?: OneRelationDefinition["onUpdate"];
|
|
212
|
+
};
|
|
213
|
+
|
|
214
|
+
function endpointKey(tableName: string, referenceField: string): string {
|
|
215
|
+
return `${tableName}:${referenceField}`;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function normalizeManyToManyPairKey(
|
|
219
|
+
sourceTable: string,
|
|
220
|
+
sourceReferenceField: string,
|
|
221
|
+
targetTable: string,
|
|
222
|
+
targetReferenceField: string,
|
|
223
|
+
): {
|
|
224
|
+
key: string;
|
|
225
|
+
leftTable: string;
|
|
226
|
+
leftReferenceField: string;
|
|
227
|
+
rightTable: string;
|
|
228
|
+
rightReferenceField: string;
|
|
229
|
+
sourceIsLeft: boolean;
|
|
230
|
+
} {
|
|
231
|
+
const source = endpointKey(sourceTable, sourceReferenceField);
|
|
232
|
+
const target = endpointKey(targetTable, targetReferenceField);
|
|
233
|
+
const sourceIsLeft = source <= target;
|
|
234
|
+
|
|
235
|
+
if (sourceIsLeft) {
|
|
236
|
+
return {
|
|
237
|
+
key: `${source}|${target}`,
|
|
238
|
+
leftTable: sourceTable,
|
|
239
|
+
leftReferenceField: sourceReferenceField,
|
|
240
|
+
rightTable: targetTable,
|
|
241
|
+
rightReferenceField: targetReferenceField,
|
|
242
|
+
sourceIsLeft: true,
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
return {
|
|
247
|
+
key: `${target}|${source}`,
|
|
248
|
+
leftTable: targetTable,
|
|
249
|
+
leftReferenceField: targetReferenceField,
|
|
250
|
+
rightTable: sourceTable,
|
|
251
|
+
rightReferenceField: sourceReferenceField,
|
|
252
|
+
sourceIsLeft: false,
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
function defaultManyToManyJunctionTable(
|
|
257
|
+
leftTable: string,
|
|
258
|
+
rightTable: string,
|
|
259
|
+
): string {
|
|
260
|
+
return `${leftTable}${toPascalCase(rightTable)}Links`;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
function defaultManyToManyFieldName(
|
|
264
|
+
ownerTable: string,
|
|
265
|
+
otherTable: string,
|
|
266
|
+
suffix: "source" | "target",
|
|
267
|
+
): string {
|
|
268
|
+
const ownerSingular = singularize(ownerTable);
|
|
269
|
+
const otherSingular = singularize(otherTable);
|
|
270
|
+
|
|
271
|
+
if (ownerSingular === otherSingular) {
|
|
272
|
+
return `${suffix}${toPascalCase(ownerSingular)}Id`;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
return `${ownerSingular}Id`;
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
function mergeManyToManyPairConfig(
|
|
279
|
+
existing: ManyToManyPair,
|
|
280
|
+
incoming: ManyToManyPair,
|
|
281
|
+
pairKey: string,
|
|
282
|
+
): ManyToManyPair {
|
|
283
|
+
if (existing.junctionTable !== incoming.junctionTable) {
|
|
284
|
+
throw new Error(
|
|
285
|
+
`manyToMany pair '${pairKey}' has conflicting junctionTable values ('${existing.junctionTable}' vs '${incoming.junctionTable}').`,
|
|
286
|
+
);
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
if (existing.leftField !== incoming.leftField) {
|
|
290
|
+
throw new Error(
|
|
291
|
+
`manyToMany pair '${pairKey}' has conflicting left field values ('${existing.leftField}' vs '${incoming.leftField}').`,
|
|
292
|
+
);
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
if (existing.rightField !== incoming.rightField) {
|
|
296
|
+
throw new Error(
|
|
297
|
+
`manyToMany pair '${pairKey}' has conflicting right field values ('${existing.rightField}' vs '${incoming.rightField}').`,
|
|
298
|
+
);
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
if (existing.leftSqlName !== incoming.leftSqlName) {
|
|
302
|
+
throw new Error(
|
|
303
|
+
`manyToMany pair '${pairKey}' has conflicting left sql name values ('${existing.leftSqlName}' vs '${incoming.leftSqlName}').`,
|
|
304
|
+
);
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
if (existing.rightSqlName !== incoming.rightSqlName) {
|
|
308
|
+
throw new Error(
|
|
309
|
+
`manyToMany pair '${pairKey}' has conflicting right sql name values ('${existing.rightSqlName}' vs '${incoming.rightSqlName}').`,
|
|
310
|
+
);
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
if (existing.onDelete !== incoming.onDelete) {
|
|
314
|
+
throw new Error(
|
|
315
|
+
`manyToMany pair '${pairKey}' has conflicting onDelete values ('${existing.onDelete}' vs '${incoming.onDelete}').`,
|
|
316
|
+
);
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
if (existing.onUpdate !== incoming.onUpdate) {
|
|
320
|
+
throw new Error(
|
|
321
|
+
`manyToMany pair '${pairKey}' has conflicting onUpdate values ('${existing.onUpdate}' vs '${incoming.onUpdate}').`,
|
|
322
|
+
);
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
return existing;
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
function normalizeManyToManyRelations(definition: SchemaDefinition): void {
|
|
329
|
+
const pairMap = new Map<string, ManyToManyPair>();
|
|
330
|
+
|
|
331
|
+
for (const [sourceTableName, sourceTable] of Object.entries(
|
|
332
|
+
definition.tables,
|
|
333
|
+
)) {
|
|
334
|
+
for (const relation of Object.values(sourceTable.relations)) {
|
|
335
|
+
if (relation.relation !== "manyToMany") {
|
|
336
|
+
continue;
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
const sourceReferenceField = relation.referenceField ?? "id";
|
|
340
|
+
const targetReferenceField = relation.targetReferenceField ?? "id";
|
|
341
|
+
|
|
342
|
+
const normalizedPair = normalizeManyToManyPairKey(
|
|
343
|
+
sourceTableName,
|
|
344
|
+
sourceReferenceField,
|
|
345
|
+
relation.targetTable,
|
|
346
|
+
targetReferenceField,
|
|
347
|
+
);
|
|
348
|
+
|
|
349
|
+
const defaultLeftField = defaultManyToManyFieldName(
|
|
350
|
+
normalizedPair.leftTable,
|
|
351
|
+
normalizedPair.rightTable,
|
|
352
|
+
"source",
|
|
353
|
+
);
|
|
354
|
+
const defaultRightField = defaultManyToManyFieldName(
|
|
355
|
+
normalizedPair.rightTable,
|
|
356
|
+
normalizedPair.leftTable,
|
|
357
|
+
"target",
|
|
358
|
+
);
|
|
359
|
+
|
|
360
|
+
const pair: ManyToManyPair = {
|
|
361
|
+
leftTable: normalizedPair.leftTable,
|
|
362
|
+
leftReferenceField: normalizedPair.leftReferenceField,
|
|
363
|
+
rightTable: normalizedPair.rightTable,
|
|
364
|
+
rightReferenceField: normalizedPair.rightReferenceField,
|
|
365
|
+
junctionTable:
|
|
366
|
+
relation.junctionTable ??
|
|
367
|
+
defaultManyToManyJunctionTable(
|
|
368
|
+
normalizedPair.leftTable,
|
|
369
|
+
normalizedPair.rightTable,
|
|
370
|
+
),
|
|
371
|
+
leftField: normalizedPair.sourceIsLeft
|
|
372
|
+
? (relation.sourceField ?? defaultLeftField)
|
|
373
|
+
: (relation.targetField ?? defaultLeftField),
|
|
374
|
+
rightField: normalizedPair.sourceIsLeft
|
|
375
|
+
? (relation.targetField ?? defaultRightField)
|
|
376
|
+
: (relation.sourceField ?? defaultRightField),
|
|
377
|
+
leftSqlName: normalizedPair.sourceIsLeft
|
|
378
|
+
? relation.sourceSqlName
|
|
379
|
+
: relation.targetSqlName,
|
|
380
|
+
rightSqlName: normalizedPair.sourceIsLeft
|
|
381
|
+
? relation.targetSqlName
|
|
382
|
+
: relation.sourceSqlName,
|
|
383
|
+
onDelete: relation.onDelete,
|
|
384
|
+
onUpdate: relation.onUpdate,
|
|
385
|
+
};
|
|
386
|
+
|
|
387
|
+
if (pair.leftField === pair.rightField) {
|
|
388
|
+
throw new Error(
|
|
389
|
+
`manyToMany pair '${normalizedPair.key}' resolves to duplicate junction fields '${pair.leftField}'. Set sourceField/targetField explicitly.`,
|
|
390
|
+
);
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
const existing = pairMap.get(normalizedPair.key);
|
|
394
|
+
if (existing) {
|
|
395
|
+
mergeManyToManyPairConfig(existing, pair, normalizedPair.key);
|
|
396
|
+
} else {
|
|
397
|
+
pairMap.set(normalizedPair.key, pair);
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
relation.referenceField = sourceReferenceField;
|
|
401
|
+
relation.targetReferenceField = targetReferenceField;
|
|
402
|
+
relation.junctionTable = pair.junctionTable;
|
|
403
|
+
relation.sourceField = normalizedPair.sourceIsLeft
|
|
404
|
+
? pair.leftField
|
|
405
|
+
: pair.rightField;
|
|
406
|
+
relation.targetField = normalizedPair.sourceIsLeft
|
|
407
|
+
? pair.rightField
|
|
408
|
+
: pair.leftField;
|
|
409
|
+
relation.sourceSqlName = normalizedPair.sourceIsLeft
|
|
410
|
+
? pair.leftSqlName
|
|
411
|
+
: pair.rightSqlName;
|
|
412
|
+
relation.targetSqlName = normalizedPair.sourceIsLeft
|
|
413
|
+
? pair.rightSqlName
|
|
414
|
+
: pair.leftSqlName;
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
for (const pair of pairMap.values()) {
|
|
419
|
+
if (pair.junctionTable in definition.tables) {
|
|
420
|
+
throw new Error(
|
|
421
|
+
`manyToMany auto junction table '${pair.junctionTable}' conflicts with an existing table. Set a different junctionTable name.`,
|
|
422
|
+
);
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
const leftType =
|
|
426
|
+
getLocalReferenceType(
|
|
427
|
+
definition,
|
|
428
|
+
pair.leftTable,
|
|
429
|
+
pair.leftReferenceField,
|
|
430
|
+
) ?? "string";
|
|
431
|
+
const rightType =
|
|
432
|
+
getLocalReferenceType(
|
|
433
|
+
definition,
|
|
434
|
+
pair.rightTable,
|
|
435
|
+
pair.rightReferenceField,
|
|
436
|
+
) ?? "string";
|
|
437
|
+
|
|
438
|
+
definition.tables[pair.junctionTable] = {
|
|
439
|
+
kind: "table",
|
|
440
|
+
columns: {
|
|
441
|
+
[pair.leftField]: {
|
|
442
|
+
kind: "column",
|
|
443
|
+
type: leftType,
|
|
444
|
+
sqlName: pair.leftSqlName,
|
|
445
|
+
notNull: true,
|
|
446
|
+
nullable: false,
|
|
447
|
+
references: {
|
|
448
|
+
table: pair.leftTable,
|
|
449
|
+
column: pair.leftReferenceField,
|
|
450
|
+
onDelete: pair.onDelete,
|
|
451
|
+
onUpdate: pair.onUpdate,
|
|
452
|
+
},
|
|
453
|
+
index: true,
|
|
454
|
+
},
|
|
455
|
+
[pair.rightField]: {
|
|
456
|
+
kind: "column",
|
|
457
|
+
type: rightType,
|
|
458
|
+
sqlName: pair.rightSqlName,
|
|
459
|
+
notNull: true,
|
|
460
|
+
nullable: false,
|
|
461
|
+
references: {
|
|
462
|
+
table: pair.rightTable,
|
|
463
|
+
column: pair.rightReferenceField,
|
|
464
|
+
onDelete: pair.onDelete,
|
|
465
|
+
onUpdate: pair.onUpdate,
|
|
466
|
+
},
|
|
467
|
+
index: true,
|
|
468
|
+
},
|
|
469
|
+
},
|
|
470
|
+
relations: {
|
|
471
|
+
[pair.leftTable]: {
|
|
472
|
+
kind: "relation",
|
|
473
|
+
relation: "one",
|
|
474
|
+
targetTable: pair.leftTable,
|
|
475
|
+
field: pair.leftField,
|
|
476
|
+
referenceField: pair.leftReferenceField,
|
|
477
|
+
},
|
|
478
|
+
[pair.rightTable]: {
|
|
479
|
+
kind: "relation",
|
|
480
|
+
relation: "one",
|
|
481
|
+
targetTable: pair.rightTable,
|
|
482
|
+
field: pair.rightField,
|
|
483
|
+
referenceField: pair.rightReferenceField,
|
|
484
|
+
},
|
|
485
|
+
},
|
|
486
|
+
};
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
function validateNullableFlags(definition: SchemaDefinition): void {
|
|
491
|
+
for (const [tableName, table] of Object.entries(definition.tables)) {
|
|
492
|
+
for (const [columnName, column] of Object.entries(table.columns)) {
|
|
493
|
+
if (column.notNull === true && column.nullable === true) {
|
|
494
|
+
throw new Error(
|
|
495
|
+
`Invalid nullable configuration on '${tableName}.${columnName}': cannot set both notNull and nullable to true.`,
|
|
496
|
+
);
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
for (const [relationName, relation] of Object.entries(table.relations)) {
|
|
501
|
+
if (
|
|
502
|
+
relation.relation !== "manyToMany" &&
|
|
503
|
+
relation.notNull === true &&
|
|
504
|
+
relation.nullable === true
|
|
505
|
+
) {
|
|
506
|
+
throw new Error(
|
|
507
|
+
`Invalid nullable configuration on '${tableName}.${relationName}': cannot set both notNull and nullable to true.`,
|
|
508
|
+
);
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
function normalizeSchemaDefinition(
|
|
515
|
+
definition: SchemaDefinition,
|
|
516
|
+
): SchemaDefinition {
|
|
517
|
+
validateNullableFlags(definition);
|
|
518
|
+
const normalized = cloneSchemaDefinition(definition);
|
|
519
|
+
|
|
520
|
+
for (const [tableName, table] of Object.entries(normalized.tables)) {
|
|
521
|
+
for (const [relationName, relation] of Object.entries(table.relations)) {
|
|
522
|
+
if (relation.relation !== "one") {
|
|
523
|
+
continue;
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
const referenceField = relation.referenceField ?? "id";
|
|
527
|
+
const inferredField = relation.field ?? `${relationName}Id`;
|
|
528
|
+
relation.field = inferredField;
|
|
529
|
+
|
|
530
|
+
const inferredType =
|
|
531
|
+
getLocalReferenceType(
|
|
532
|
+
normalized,
|
|
533
|
+
relation.targetTable,
|
|
534
|
+
referenceField,
|
|
535
|
+
) ??
|
|
536
|
+
relation.fkType ??
|
|
537
|
+
"string";
|
|
538
|
+
|
|
539
|
+
ensureInferredReferenceColumn(
|
|
540
|
+
tableName,
|
|
541
|
+
table,
|
|
542
|
+
inferredField,
|
|
543
|
+
relation.targetTable,
|
|
544
|
+
referenceField,
|
|
545
|
+
{
|
|
546
|
+
fkType: relation.fkType,
|
|
547
|
+
sqlName: relation.sqlName,
|
|
548
|
+
notNull: resolveNotNullFromNullableFlags(
|
|
549
|
+
`${tableName}.${relationName}`,
|
|
550
|
+
relation,
|
|
551
|
+
true,
|
|
552
|
+
),
|
|
553
|
+
onDelete: relation.onDelete,
|
|
554
|
+
onUpdate: relation.onUpdate,
|
|
555
|
+
},
|
|
556
|
+
inferredType,
|
|
557
|
+
);
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
for (const [sourceTableName, sourceTable] of Object.entries(
|
|
562
|
+
normalized.tables,
|
|
563
|
+
)) {
|
|
564
|
+
for (const relation of Object.values(sourceTable.relations)) {
|
|
565
|
+
if (relation.relation !== "many") {
|
|
566
|
+
continue;
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
const targetTable = normalized.tables[relation.targetTable];
|
|
570
|
+
if (!targetTable) {
|
|
571
|
+
continue;
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
const referenceField = relation.referenceField ?? "id";
|
|
575
|
+
const inferredField =
|
|
576
|
+
relation.field ?? `${singularize(sourceTableName)}Id`;
|
|
577
|
+
relation.field = inferredField;
|
|
578
|
+
const inferredType =
|
|
579
|
+
getLocalReferenceType(normalized, sourceTableName, referenceField) ??
|
|
580
|
+
relation.fkType ??
|
|
581
|
+
"string";
|
|
582
|
+
|
|
583
|
+
ensureInferredReferenceColumn(
|
|
584
|
+
relation.targetTable,
|
|
585
|
+
targetTable,
|
|
586
|
+
inferredField,
|
|
587
|
+
sourceTableName,
|
|
588
|
+
referenceField,
|
|
589
|
+
{
|
|
590
|
+
fkType: relation.fkType,
|
|
591
|
+
sqlName: relation.sqlName,
|
|
592
|
+
notNull: resolveNotNullFromNullableFlags(
|
|
593
|
+
`${sourceTableName}.${relation.targetTable}`,
|
|
594
|
+
relation,
|
|
595
|
+
true,
|
|
596
|
+
),
|
|
597
|
+
onDelete: relation.onDelete,
|
|
598
|
+
onUpdate: relation.onUpdate,
|
|
599
|
+
},
|
|
600
|
+
inferredType,
|
|
601
|
+
);
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
normalizeManyToManyRelations(normalized);
|
|
606
|
+
|
|
607
|
+
return normalized;
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
function isOptionalInsertColumn(column: ColumnDefinition): boolean {
|
|
611
|
+
return (
|
|
612
|
+
column.primaryKey === true ||
|
|
613
|
+
column.notNull !== true ||
|
|
614
|
+
column.autoIncrement === true ||
|
|
615
|
+
column.sqlDefault !== undefined ||
|
|
616
|
+
column.runtimeDefaultFn !== undefined
|
|
617
|
+
);
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
function isNullableSelectColumn(column: ColumnDefinition): boolean {
|
|
621
|
+
return column.notNull !== true;
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
function drizzleBaseColumn(
|
|
625
|
+
fieldName: string,
|
|
626
|
+
column: ColumnDefinition,
|
|
627
|
+
strategy: "camelToSnake",
|
|
628
|
+
): string {
|
|
629
|
+
const resolvedSqlName = column.sqlName ?? toSnakeCase(fieldName);
|
|
630
|
+
const needsExplicitName = resolvedSqlName !== fieldName;
|
|
631
|
+
|
|
632
|
+
if (column.type === "int") {
|
|
633
|
+
return needsExplicitName ? `t.int(${quote(resolvedSqlName)})` : "t.int()";
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
if (column.type === "string") {
|
|
637
|
+
if (column.length !== undefined) {
|
|
638
|
+
if (needsExplicitName) {
|
|
639
|
+
return `t.text(${quote(resolvedSqlName)}, { length: ${column.length} })`;
|
|
640
|
+
}
|
|
641
|
+
return `t.text({ length: ${column.length} })`;
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
return needsExplicitName ? `t.text(${quote(resolvedSqlName)})` : "t.text()";
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
if (column.type === "boolean") {
|
|
648
|
+
if (needsExplicitName) {
|
|
649
|
+
return `t.int(${quote(resolvedSqlName)}, { mode: "boolean" })`;
|
|
650
|
+
}
|
|
651
|
+
return 't.int({ mode: "boolean" })';
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
if (column.type === "date") {
|
|
655
|
+
if (needsExplicitName) {
|
|
656
|
+
return `t.int(${quote(resolvedSqlName)}, { mode: "timestamp_ms" })`;
|
|
657
|
+
}
|
|
658
|
+
return 't.int({ mode: "timestamp_ms" })';
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
if (strategy === "camelToSnake") {
|
|
662
|
+
return needsExplicitName ? `t.text(${quote(resolvedSqlName)})` : "t.text()";
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
return "t.text()";
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
function resolveOneRelationReference(
|
|
669
|
+
tableName: string,
|
|
670
|
+
table: TableDefinition,
|
|
671
|
+
relation: OneRelationDefinition,
|
|
672
|
+
): { sourceField: string; targetField: string } {
|
|
673
|
+
const sourceField = relation.field;
|
|
674
|
+
const targetField = relation.referenceField ?? "id";
|
|
675
|
+
|
|
676
|
+
if (!sourceField) {
|
|
677
|
+
throw new Error(
|
|
678
|
+
`Relation on '${tableName}' targeting '${relation.targetTable}' is missing a local field.`,
|
|
679
|
+
);
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
if (!(sourceField in table.columns)) {
|
|
683
|
+
throw new Error(
|
|
684
|
+
`Relation '${tableName}.${sourceField}' references missing local field '${sourceField}'.`,
|
|
685
|
+
);
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
return {
|
|
689
|
+
sourceField,
|
|
690
|
+
targetField,
|
|
691
|
+
};
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
function buildExternalTableImportLines(externals: Set<string>): string {
|
|
695
|
+
if (externals.size === 0) {
|
|
696
|
+
return "";
|
|
697
|
+
}
|
|
698
|
+
return `import { ${Array.from(externals).sort().join(", ")} } from \"./auth.schema\";\n`;
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
function getRelationImports(table: TableDefinition): string[] {
|
|
702
|
+
return Object.values(table.relations)
|
|
703
|
+
.filter((relation) => relation.relation === "one")
|
|
704
|
+
.map((relation) => relation.targetTable);
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
function resolveColumnReference(
|
|
708
|
+
fieldName: string,
|
|
709
|
+
column: ColumnDefinition,
|
|
710
|
+
table: TableDefinition,
|
|
711
|
+
): { tableName: string; fieldName: string } | undefined {
|
|
712
|
+
if (column.references) {
|
|
713
|
+
return {
|
|
714
|
+
tableName: column.references.table,
|
|
715
|
+
fieldName: column.references.column,
|
|
716
|
+
};
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
const matchingOne = Object.values(table.relations).find((relation) => {
|
|
720
|
+
return relation.relation === "one" && relation.field === fieldName;
|
|
721
|
+
}) as OneRelationDefinition | undefined;
|
|
722
|
+
|
|
723
|
+
if (!matchingOne) {
|
|
724
|
+
return undefined;
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
return {
|
|
728
|
+
tableName: matchingOne.targetTable,
|
|
729
|
+
fieldName: matchingOne.referenceField ?? "id",
|
|
730
|
+
};
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
function emitManyToManyRuntimeMetadata(definition: SchemaDefinition): string {
|
|
734
|
+
const tableEntries: string[] = [];
|
|
735
|
+
|
|
736
|
+
for (const [tableName, table] of Object.entries(definition.tables)) {
|
|
737
|
+
const relationEntries: string[] = [];
|
|
738
|
+
|
|
739
|
+
for (const [relationName, relation] of Object.entries(table.relations)) {
|
|
740
|
+
if (relation.relation !== "manyToMany") {
|
|
741
|
+
continue;
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
if (!relation.junctionTable) {
|
|
745
|
+
continue;
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
relationEntries.push(
|
|
749
|
+
`${quote(relationName)}: {
|
|
750
|
+
targetTable: ${quote(relation.targetTable)},
|
|
751
|
+
junctionTable: ${quote(relation.junctionTable)},
|
|
752
|
+
sourceField: ${quote(relation.sourceField ?? "")},
|
|
753
|
+
targetField: ${quote(relation.targetField ?? "")},
|
|
754
|
+
},`,
|
|
755
|
+
);
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
if (relationEntries.length === 0) {
|
|
759
|
+
continue;
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
tableEntries.push(
|
|
763
|
+
`${quote(tableName)}: {
|
|
764
|
+
${relationEntries.map((entry) => `\t${entry}`).join("\n")}
|
|
765
|
+
},`,
|
|
766
|
+
);
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
if (tableEntries.length === 0) {
|
|
770
|
+
return "export const __appflareManyToMany = {} as const;\n";
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
return `export const __appflareManyToMany = {
|
|
774
|
+
${tableEntries.map((entry) => `\t${entry}`).join("\n")}
|
|
775
|
+
} as const;
|
|
776
|
+
`;
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
function emitRuntimeRelationMetadata(definition: SchemaDefinition): string {
|
|
780
|
+
const tableEntries: string[] = [];
|
|
781
|
+
|
|
782
|
+
for (const [tableName, table] of Object.entries(definition.tables)) {
|
|
783
|
+
const relationEntries: string[] = [];
|
|
784
|
+
|
|
785
|
+
for (const [relationName, relation] of Object.entries(table.relations)) {
|
|
786
|
+
if (relation.relation === "one") {
|
|
787
|
+
relationEntries.push(
|
|
788
|
+
`${quote(relationName)}: {
|
|
789
|
+
kind: "one",
|
|
790
|
+
targetTable: ${quote(relation.targetTable)},
|
|
791
|
+
sourceField: ${quote(relation.field ?? "")},
|
|
792
|
+
referenceField: ${quote(relation.referenceField ?? "id")},
|
|
793
|
+
},`,
|
|
794
|
+
);
|
|
795
|
+
continue;
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
if (relation.relation === "many") {
|
|
799
|
+
relationEntries.push(
|
|
800
|
+
`${quote(relationName)}: {
|
|
801
|
+
kind: "many",
|
|
802
|
+
targetTable: ${quote(relation.targetTable)},
|
|
803
|
+
sourceField: ${quote(relation.field ?? "")},
|
|
804
|
+
referenceField: ${quote(relation.referenceField ?? "id")},
|
|
805
|
+
},`,
|
|
806
|
+
);
|
|
807
|
+
continue;
|
|
808
|
+
}
|
|
809
|
+
|
|
810
|
+
relationEntries.push(
|
|
811
|
+
`${quote(relationName)}: {
|
|
812
|
+
kind: "manyToMany",
|
|
813
|
+
targetTable: ${quote(relation.targetTable)},
|
|
814
|
+
junctionTable: ${quote(relation.junctionTable ?? "")},
|
|
815
|
+
sourceField: ${quote(relation.sourceField ?? "")},
|
|
816
|
+
targetField: ${quote(relation.targetField ?? "")},
|
|
817
|
+
referenceField: ${quote(relation.referenceField ?? "id")},
|
|
818
|
+
targetReferenceField: ${quote(relation.targetReferenceField ?? "id")},
|
|
819
|
+
},`,
|
|
820
|
+
);
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
if (relationEntries.length === 0) {
|
|
824
|
+
continue;
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
tableEntries.push(
|
|
828
|
+
`${quote(tableName)}: {
|
|
829
|
+
${relationEntries.map((entry) => `\t${entry}`).join("\n")}
|
|
830
|
+
},`,
|
|
831
|
+
);
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
if (tableEntries.length === 0) {
|
|
835
|
+
return "export const __appflareRelations = {} as const;\n";
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
return `export const __appflareRelations = {
|
|
839
|
+
${tableEntries.map((entry) => `\t${entry}`).join("\n")}
|
|
840
|
+
} as const;
|
|
841
|
+
`;
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
function emitDrizzleSchema(
|
|
845
|
+
definition: SchemaDefinition,
|
|
846
|
+
strategy: "camelToSnake",
|
|
847
|
+
): string {
|
|
848
|
+
const localTables = new Set(Object.keys(definition.tables));
|
|
849
|
+
const externalTables = new Set<string>();
|
|
850
|
+
|
|
851
|
+
for (const table of Object.values(definition.tables)) {
|
|
852
|
+
for (const relationTarget of getRelationImports(table)) {
|
|
853
|
+
if (!localTables.has(relationTarget)) {
|
|
854
|
+
externalTables.add(relationTarget);
|
|
855
|
+
}
|
|
856
|
+
}
|
|
857
|
+
for (const column of Object.values(table.columns)) {
|
|
858
|
+
if (column.references && !localTables.has(column.references.table)) {
|
|
859
|
+
externalTables.add(column.references.table);
|
|
860
|
+
}
|
|
861
|
+
}
|
|
862
|
+
}
|
|
863
|
+
|
|
864
|
+
const tableBlocks: string[] = [];
|
|
865
|
+
const relationBlocks: string[] = [];
|
|
866
|
+
|
|
867
|
+
for (const [tableName, table] of Object.entries(definition.tables)) {
|
|
868
|
+
const sqlTableName = table.sqlName ?? toSnakeCase(tableName);
|
|
869
|
+
const columnLines: string[] = [];
|
|
870
|
+
const indexes: string[] = [];
|
|
871
|
+
|
|
872
|
+
for (const [fieldName, column] of Object.entries(table.columns)) {
|
|
873
|
+
let expr = drizzleBaseColumn(fieldName, column, strategy);
|
|
874
|
+
|
|
875
|
+
if (column.uuidPrimaryKey) {
|
|
876
|
+
expr += ".$defaultFn(() => crypto.randomUUID())";
|
|
877
|
+
}
|
|
878
|
+
|
|
879
|
+
if (column.primaryKey) {
|
|
880
|
+
expr += column.autoIncrement
|
|
881
|
+
? ".primaryKey({ autoIncrement: true })"
|
|
882
|
+
: ".primaryKey()";
|
|
883
|
+
}
|
|
884
|
+
if (column.notNull) {
|
|
885
|
+
expr += ".notNull()";
|
|
886
|
+
}
|
|
887
|
+
if (column.sqlDefault !== undefined) {
|
|
888
|
+
expr += `.default(${toSqlLiteral(column.sqlDefault)})`;
|
|
889
|
+
}
|
|
890
|
+
|
|
891
|
+
const reference = resolveColumnReference(fieldName, column, table);
|
|
892
|
+
if (reference) {
|
|
893
|
+
if (column.references?.onDelete || column.references?.onUpdate) {
|
|
894
|
+
const actions: string[] = [];
|
|
895
|
+
if (column.references.onDelete) {
|
|
896
|
+
actions.push(`onDelete: ${quote(column.references.onDelete)}`);
|
|
897
|
+
}
|
|
898
|
+
if (column.references.onUpdate) {
|
|
899
|
+
actions.push(`onUpdate: ${quote(column.references.onUpdate)}`);
|
|
900
|
+
}
|
|
901
|
+
expr += `.references(() => ${reference.tableName}.${reference.fieldName}, { ${actions.join(", ")} })`;
|
|
902
|
+
} else {
|
|
903
|
+
expr += `.references(() => ${reference.tableName}.${reference.fieldName})`;
|
|
904
|
+
}
|
|
905
|
+
}
|
|
906
|
+
|
|
907
|
+
if (column.unique) {
|
|
908
|
+
const uniqueName =
|
|
909
|
+
typeof column.unique === "object" && column.unique.name
|
|
910
|
+
? column.unique.name
|
|
911
|
+
: `${sqlTableName}_${toSnakeCase(fieldName)}_unique_idx`;
|
|
912
|
+
indexes.push(
|
|
913
|
+
`\t\tt.uniqueIndex(${quote(uniqueName)}).on(table.${fieldName})`,
|
|
914
|
+
);
|
|
915
|
+
}
|
|
916
|
+
|
|
917
|
+
if (column.index) {
|
|
918
|
+
const indexName =
|
|
919
|
+
typeof column.index === "object" && column.index.name
|
|
920
|
+
? column.index.name
|
|
921
|
+
: `${sqlTableName}_${toSnakeCase(fieldName)}_idx`;
|
|
922
|
+
indexes.push(`\t\tt.index(${quote(indexName)}).on(table.${fieldName})`);
|
|
923
|
+
}
|
|
924
|
+
|
|
925
|
+
columnLines.push(`\t\t${fieldName}: ${expr},`);
|
|
926
|
+
}
|
|
927
|
+
|
|
928
|
+
if (indexes.length > 0) {
|
|
929
|
+
tableBlocks.push(
|
|
930
|
+
`export const ${tableName} = table(\n\t${quote(sqlTableName)},\n\t{\n${columnLines.join("\n")}\n\t},\n\t(table) => [\n${indexes.join(",\n")}\n\t],\n);`,
|
|
931
|
+
);
|
|
932
|
+
} else {
|
|
933
|
+
tableBlocks.push(
|
|
934
|
+
`export const ${tableName} = table(${quote(sqlTableName)}, {\n${columnLines.join("\n")}\n\t});`,
|
|
935
|
+
);
|
|
936
|
+
}
|
|
937
|
+
|
|
938
|
+
const oneRelations = Object.entries(table.relations).filter(
|
|
939
|
+
([, relation]) => {
|
|
940
|
+
return relation.relation === "one";
|
|
941
|
+
},
|
|
942
|
+
) as Array<[string, OneRelationDefinition]>;
|
|
943
|
+
const manyRelations = Object.entries(table.relations).filter(
|
|
944
|
+
([, relation]) => {
|
|
945
|
+
return relation.relation === "many";
|
|
946
|
+
},
|
|
947
|
+
) as Array<[string, ManyRelationDefinition]>;
|
|
948
|
+
const manyToManyRelations = Object.entries(table.relations).filter(
|
|
949
|
+
([, relation]) => {
|
|
950
|
+
return relation.relation === "manyToMany";
|
|
951
|
+
},
|
|
952
|
+
) as Array<[string, ManyToManyRelationDefinition]>;
|
|
953
|
+
|
|
954
|
+
if (
|
|
955
|
+
oneRelations.length === 0 &&
|
|
956
|
+
manyRelations.length === 0 &&
|
|
957
|
+
manyToManyRelations.length === 0
|
|
958
|
+
) {
|
|
959
|
+
continue;
|
|
960
|
+
}
|
|
961
|
+
|
|
962
|
+
const relationLines: string[] = [];
|
|
963
|
+
for (const [relationName, relation] of oneRelations) {
|
|
964
|
+
const resolved = resolveOneRelationReference(tableName, table, relation);
|
|
965
|
+
relationLines.push(
|
|
966
|
+
`\t${relationName}: one(${relation.targetTable}, {\n\t\tfields: [${tableName}.${resolved.sourceField}],\n\t\treferences: [${relation.targetTable}.${resolved.targetField}],\n\t}),`,
|
|
967
|
+
);
|
|
968
|
+
}
|
|
969
|
+
for (const [relationName, relation] of manyRelations) {
|
|
970
|
+
relationLines.push(`\t${relationName}: many(${relation.targetTable}),`);
|
|
971
|
+
}
|
|
972
|
+
for (const [relationName, relation] of manyToManyRelations) {
|
|
973
|
+
if (!relation.junctionTable) {
|
|
974
|
+
throw new Error(
|
|
975
|
+
`manyToMany relation '${tableName}.${relationName}' is missing junctionTable after normalization.`,
|
|
976
|
+
);
|
|
977
|
+
}
|
|
978
|
+
relationLines.push(`\t${relationName}: many(${relation.junctionTable}),`);
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
relationBlocks.push(
|
|
982
|
+
`export const ${tableName}Relations = relations(${tableName}, ({ one, many }) => ({\n${relationLines.join("\n")}\n}));`,
|
|
983
|
+
);
|
|
984
|
+
}
|
|
985
|
+
|
|
986
|
+
return `import * as t from "drizzle-orm/sqlite-core";
|
|
987
|
+
import { sqliteTable as table } from "drizzle-orm/sqlite-core";
|
|
988
|
+
import { relations } from "drizzle-orm";
|
|
989
|
+
${buildExternalTableImportLines(externalTables)}
|
|
990
|
+
${tableBlocks.join("\n\n")}
|
|
991
|
+
|
|
992
|
+
${relationBlocks.join("\n\n")}
|
|
993
|
+
|
|
994
|
+
${emitManyToManyRuntimeMetadata(definition)}
|
|
995
|
+
|
|
996
|
+
${emitRuntimeRelationMetadata(definition)}
|
|
997
|
+
`;
|
|
998
|
+
}
|
|
999
|
+
|
|
1000
|
+
function zodSchemaExpression(
|
|
1001
|
+
column: ColumnDefinition,
|
|
1002
|
+
optional: boolean,
|
|
1003
|
+
nullable: boolean,
|
|
1004
|
+
): string {
|
|
1005
|
+
let expr = "z.unknown()";
|
|
1006
|
+
if (column.type === "int") {
|
|
1007
|
+
expr = "z.number().int()";
|
|
1008
|
+
} else if (column.type === "string") {
|
|
1009
|
+
expr = "z.string()";
|
|
1010
|
+
if (column.length !== undefined) {
|
|
1011
|
+
expr += `.max(${column.length})`;
|
|
1012
|
+
}
|
|
1013
|
+
} else if (column.type === "boolean") {
|
|
1014
|
+
expr = "z.boolean()";
|
|
1015
|
+
} else if (column.type === "date") {
|
|
1016
|
+
expr = "z.date()";
|
|
1017
|
+
}
|
|
1018
|
+
|
|
1019
|
+
if (optional) {
|
|
1020
|
+
expr += ".optional()";
|
|
1021
|
+
}
|
|
1022
|
+
|
|
1023
|
+
if (nullable) {
|
|
1024
|
+
expr += ".nullable()";
|
|
1025
|
+
}
|
|
1026
|
+
|
|
1027
|
+
return expr;
|
|
1028
|
+
}
|
|
1029
|
+
|
|
1030
|
+
function emitZodSchemas(definition: SchemaDefinition): string {
|
|
1031
|
+
const blocks: string[] = [];
|
|
1032
|
+
|
|
1033
|
+
for (const [tableName, table] of Object.entries(definition.tables)) {
|
|
1034
|
+
const pascal = toPascalCase(tableName);
|
|
1035
|
+
const insertLines: string[] = [];
|
|
1036
|
+
const selectLines: string[] = [];
|
|
1037
|
+
|
|
1038
|
+
for (const [fieldName, column] of Object.entries(table.columns)) {
|
|
1039
|
+
insertLines.push(
|
|
1040
|
+
`\t${fieldName}: ${zodSchemaExpression(column, isOptionalInsertColumn(column), isNullableSelectColumn(column))},`,
|
|
1041
|
+
);
|
|
1042
|
+
selectLines.push(
|
|
1043
|
+
`\t${fieldName}: ${zodSchemaExpression(column, isNullableSelectColumn(column), isNullableSelectColumn(column))},`,
|
|
1044
|
+
);
|
|
1045
|
+
}
|
|
1046
|
+
|
|
1047
|
+
blocks.push(`export const ${tableName}InsertSchema = z.object({\n${insertLines.join("\n")}\n});
|
|
1048
|
+
export const ${tableName}SelectSchema = z.object({\n${selectLines.join("\n")}\n});
|
|
1049
|
+
|
|
1050
|
+
export type ${pascal}Insert = z.infer<typeof ${tableName}InsertSchema>;
|
|
1051
|
+
export type ${pascal}Select = z.infer<typeof ${tableName}SelectSchema>;
|
|
1052
|
+
`);
|
|
1053
|
+
}
|
|
1054
|
+
|
|
1055
|
+
return `import { z } from "zod";
|
|
1056
|
+
|
|
1057
|
+
${blocks.join("\n")}`;
|
|
1058
|
+
}
|
|
1059
|
+
|
|
1060
|
+
function toTypeScriptType(column: ColumnDefinition): string {
|
|
1061
|
+
if (column.type === "int") {
|
|
1062
|
+
return "number";
|
|
1063
|
+
}
|
|
1064
|
+
if (column.type === "string") {
|
|
1065
|
+
return "string";
|
|
1066
|
+
}
|
|
1067
|
+
if (column.type === "boolean") {
|
|
1068
|
+
return "boolean";
|
|
1069
|
+
}
|
|
1070
|
+
if (column.type === "date") {
|
|
1071
|
+
return "Date";
|
|
1072
|
+
}
|
|
1073
|
+
return "unknown";
|
|
1074
|
+
}
|
|
1075
|
+
|
|
1076
|
+
function emitTypes(definition: SchemaDefinition): string {
|
|
1077
|
+
const lines: string[] = [];
|
|
1078
|
+
|
|
1079
|
+
for (const [tableName, table] of Object.entries(definition.tables)) {
|
|
1080
|
+
const pascal = toPascalCase(tableName);
|
|
1081
|
+
const selectFields: string[] = [];
|
|
1082
|
+
const insertFields: string[] = [];
|
|
1083
|
+
|
|
1084
|
+
for (const [fieldName, column] of Object.entries(table.columns)) {
|
|
1085
|
+
const tsType = toTypeScriptType(column);
|
|
1086
|
+
const nullableSuffix = isNullableSelectColumn(column) ? " | null" : "";
|
|
1087
|
+
selectFields.push(
|
|
1088
|
+
`\t${fieldName}${isNullableSelectColumn(column) ? "?" : ""}: ${tsType}${nullableSuffix};`,
|
|
1089
|
+
);
|
|
1090
|
+
insertFields.push(
|
|
1091
|
+
`\t${fieldName}${isOptionalInsertColumn(column) ? "?" : ""}: ${tsType}${nullableSuffix};`,
|
|
1092
|
+
);
|
|
1093
|
+
}
|
|
1094
|
+
|
|
1095
|
+
lines.push(`export type ${pascal} = {\n${selectFields.join("\n")}\n};
|
|
1096
|
+
|
|
1097
|
+
export type New${pascal} = {\n${insertFields.join("\n")}\n};`);
|
|
1098
|
+
}
|
|
1099
|
+
|
|
1100
|
+
return `${lines.join("\n\n")}
|
|
1101
|
+
`;
|
|
1102
|
+
}
|
|
1103
|
+
|
|
1104
|
+
function findSchemaExport(
|
|
1105
|
+
moduleExports: Record<string, unknown>,
|
|
1106
|
+
exportName?: string,
|
|
1107
|
+
): SchemaDefinition {
|
|
1108
|
+
if (exportName) {
|
|
1109
|
+
const explicit = moduleExports[exportName];
|
|
1110
|
+
if (!isSchemaDefinition(explicit)) {
|
|
1111
|
+
throw new Error(
|
|
1112
|
+
`schemaDsl.exportName '${exportName}' does not point to a schema() export.`,
|
|
1113
|
+
);
|
|
1114
|
+
}
|
|
1115
|
+
return explicit;
|
|
1116
|
+
}
|
|
1117
|
+
|
|
1118
|
+
for (const candidate of Object.values(moduleExports)) {
|
|
1119
|
+
if (isSchemaDefinition(candidate)) {
|
|
1120
|
+
return candidate;
|
|
1121
|
+
}
|
|
1122
|
+
}
|
|
1123
|
+
|
|
1124
|
+
throw new Error(
|
|
1125
|
+
"No schema() export found in schemaDsl entry module. Set schemaDsl.exportName to the correct export.",
|
|
1126
|
+
);
|
|
1127
|
+
}
|
|
1128
|
+
|
|
1129
|
+
export async function compileSchemaDsl(
|
|
1130
|
+
loadedConfig: LoadedAppflareConfig,
|
|
1131
|
+
): Promise<CompiledSchemaArtifacts | undefined> {
|
|
1132
|
+
const schemaDsl = loadedConfig.config.schemaDsl;
|
|
1133
|
+
if (!schemaDsl) {
|
|
1134
|
+
return undefined;
|
|
1135
|
+
}
|
|
1136
|
+
|
|
1137
|
+
const namingStrategy = schemaDsl.namingStrategy ?? "camelToSnake";
|
|
1138
|
+
const entryPath = resolve(loadedConfig.configDir, schemaDsl.entry);
|
|
1139
|
+
const outSchemaPath = resolve(
|
|
1140
|
+
loadedConfig.configDir,
|
|
1141
|
+
schemaDsl.outFile ?? resolve(loadedConfig.outDirAbs, "schema.compiled.ts"),
|
|
1142
|
+
);
|
|
1143
|
+
const outTypesPath = resolve(
|
|
1144
|
+
loadedConfig.configDir,
|
|
1145
|
+
schemaDsl.typesOutFile ??
|
|
1146
|
+
resolve(loadedConfig.outDirAbs, "schema.types.ts"),
|
|
1147
|
+
);
|
|
1148
|
+
const outZodPath = resolve(
|
|
1149
|
+
loadedConfig.configDir,
|
|
1150
|
+
schemaDsl.zodOutFile ?? resolve(loadedConfig.outDirAbs, "schema.zod.ts"),
|
|
1151
|
+
);
|
|
1152
|
+
|
|
1153
|
+
const moduleUrl = `${pathToFileURL(entryPath).href}?t=${Date.now()}`;
|
|
1154
|
+
const schemaModule = (await import(moduleUrl)) as Record<string, unknown>;
|
|
1155
|
+
const schemaDefinition = findSchemaExport(schemaModule, schemaDsl.exportName);
|
|
1156
|
+
const normalizedSchema = normalizeSchemaDefinition(schemaDefinition);
|
|
1157
|
+
|
|
1158
|
+
await Promise.all([
|
|
1159
|
+
mkdir(dirname(outSchemaPath), { recursive: true }),
|
|
1160
|
+
mkdir(dirname(outTypesPath), { recursive: true }),
|
|
1161
|
+
mkdir(dirname(outZodPath), { recursive: true }),
|
|
1162
|
+
]);
|
|
1163
|
+
|
|
1164
|
+
const drizzleSchemaSource = emitDrizzleSchema(
|
|
1165
|
+
normalizedSchema,
|
|
1166
|
+
namingStrategy,
|
|
1167
|
+
);
|
|
1168
|
+
const typesSource = emitTypes(normalizedSchema);
|
|
1169
|
+
const zodSource = emitZodSchemas(normalizedSchema);
|
|
1170
|
+
|
|
1171
|
+
await Promise.all([
|
|
1172
|
+
Bun.write(outSchemaPath, drizzleSchemaSource),
|
|
1173
|
+
Bun.write(outTypesPath, typesSource),
|
|
1174
|
+
Bun.write(outZodPath, zodSource),
|
|
1175
|
+
]);
|
|
1176
|
+
|
|
1177
|
+
return {
|
|
1178
|
+
schemaPath: outSchemaPath,
|
|
1179
|
+
typesPath: outTypesPath,
|
|
1180
|
+
zodPath: outZodPath,
|
|
1181
|
+
tableNames: Object.keys(normalizedSchema.tables),
|
|
1182
|
+
};
|
|
1183
|
+
}
|