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