pecunia-cli 0.1.8 → 0.2.0
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/dist/api.d.mts +1 -0
- package/dist/api.mjs +1 -1
- package/dist/generators-DjXYs9VN.mjs +1268 -0
- package/dist/index.mjs +1 -1
- package/package.json +3 -3
- package/dist/generators-DtWk04TQ.mjs +0 -615
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { i as getPackageInfo, n as generateSchema } from "./generators-
|
|
2
|
+
import { i as getPackageInfo, n as generateSchema } from "./generators-DjXYs9VN.mjs";
|
|
3
3
|
import { Command } from "commander";
|
|
4
4
|
import fs, { existsSync, readFileSync } from "node:fs";
|
|
5
5
|
import fs$1 from "node:fs/promises";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pecunia-cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"module": "dist/index.mjs",
|
|
6
6
|
"main": "./dist/index.mjs",
|
|
@@ -64,8 +64,8 @@
|
|
|
64
64
|
"dotenv": "^17.2.2",
|
|
65
65
|
"drizzle-orm": "^0.33.0",
|
|
66
66
|
"open": "^10.2.0",
|
|
67
|
-
"pecunia-core": "^0.1.
|
|
68
|
-
"pecunia-root": "^0.1
|
|
67
|
+
"pecunia-core": "^0.1.2",
|
|
68
|
+
"pecunia-root": "^0.2.1",
|
|
69
69
|
"pg": "^8.16.3",
|
|
70
70
|
"prettier": "^3.6.2",
|
|
71
71
|
"prompts": "^2.4.2",
|
|
@@ -1,615 +0,0 @@
|
|
|
1
|
-
import fs, { existsSync } from "node:fs";
|
|
2
|
-
import fs$1 from "node:fs/promises";
|
|
3
|
-
import path from "node:path";
|
|
4
|
-
import { getMigrations } from "pecunia-root";
|
|
5
|
-
import { capitalizeFirstLetter, getPaymentTables, initGetFieldName, initGetModelName } from "pecunia-core";
|
|
6
|
-
import prettier from "prettier";
|
|
7
|
-
import { produceSchema } from "@mrleebo/prisma-ast";
|
|
8
|
-
|
|
9
|
-
//#region src/generators/drizzle.ts
|
|
10
|
-
function convertToSnakeCase(str, camelCase) {
|
|
11
|
-
if (camelCase) return str;
|
|
12
|
-
return str.replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2").replace(/([a-z\d])([A-Z])/g, "$1_$2").toLowerCase();
|
|
13
|
-
}
|
|
14
|
-
const generateDrizzleSchema = async ({ options, file, adapter }) => {
|
|
15
|
-
const tables = getPaymentTables(options);
|
|
16
|
-
const filePath = file || "./payment-schema.ts";
|
|
17
|
-
const databaseType = adapter.options?.provider;
|
|
18
|
-
if (!databaseType) throw new Error("Database provider type is undefined during Drizzle schema generation. Please define a `provider` in the Drizzle adapter config.");
|
|
19
|
-
const fileExist = existsSync(filePath);
|
|
20
|
-
let code = generateImport({
|
|
21
|
-
databaseType,
|
|
22
|
-
tables,
|
|
23
|
-
options
|
|
24
|
-
});
|
|
25
|
-
const getModelName = initGetModelName({
|
|
26
|
-
schema: tables,
|
|
27
|
-
usePlural: adapter.options?.adapterConfig?.usePlural
|
|
28
|
-
});
|
|
29
|
-
const getFieldName = initGetFieldName({
|
|
30
|
-
schema: tables,
|
|
31
|
-
usePlural: adapter.options?.adapterConfig?.usePlural
|
|
32
|
-
});
|
|
33
|
-
const tableNameMap = /* @__PURE__ */ new Map();
|
|
34
|
-
for (const tableKey in tables) tableNameMap.set(tableKey, getModelName(tableKey));
|
|
35
|
-
function getType(name, field, databaseType$1) {
|
|
36
|
-
name = convertToSnakeCase(name, adapter.options?.camelCase);
|
|
37
|
-
if (field.references?.field === "id") {
|
|
38
|
-
if (databaseType$1 === "mysql") return `varchar('${name}', { length: 36 })`;
|
|
39
|
-
return `text('${name}')`;
|
|
40
|
-
}
|
|
41
|
-
const type = field.type;
|
|
42
|
-
if (typeof type !== "string") {
|
|
43
|
-
if (Array.isArray(type) && type.every((x) => typeof x === "string")) return {
|
|
44
|
-
sqlite: `text({ enum: [${type.map((x) => `'${x}'`).join(", ")}] })`,
|
|
45
|
-
pg: `text('${name}', { enum: [${type.map((x) => `'${x}'`).join(", ")}] })`,
|
|
46
|
-
mysql: `mysqlEnum([${type.map((x) => `'${x}'`).join(", ")}])`
|
|
47
|
-
}[databaseType$1];
|
|
48
|
-
throw new TypeError(`Invalid field type for field ${name}`);
|
|
49
|
-
}
|
|
50
|
-
const dbTypeMap = {
|
|
51
|
-
string: {
|
|
52
|
-
sqlite: `text('${name}')`,
|
|
53
|
-
pg: `text('${name}')`,
|
|
54
|
-
mysql: field.unique ? `varchar('${name}', { length: 255 })` : field.references ? `varchar('${name}', { length: 36 })` : field.sortable ? `varchar('${name}', { length: 255 })` : field.index ? `varchar('${name}', { length: 255 })` : `text('${name}')`
|
|
55
|
-
},
|
|
56
|
-
boolean: {
|
|
57
|
-
sqlite: `integer('${name}', { mode: 'boolean' })`,
|
|
58
|
-
pg: `boolean('${name}')`,
|
|
59
|
-
mysql: `boolean('${name}')`
|
|
60
|
-
},
|
|
61
|
-
number: {
|
|
62
|
-
sqlite: `integer('${name}')`,
|
|
63
|
-
pg: field.bigint ? `bigint('${name}', { mode: 'number' })` : `integer('${name}')`,
|
|
64
|
-
mysql: field.bigint ? `bigint('${name}', { mode: 'number' })` : `int('${name}')`
|
|
65
|
-
},
|
|
66
|
-
date: {
|
|
67
|
-
sqlite: `integer('${name}', { mode: 'timestamp_ms' })`,
|
|
68
|
-
pg: `timestamp('${name}')`,
|
|
69
|
-
mysql: `timestamp('${name}', { fsp: 3 })`
|
|
70
|
-
},
|
|
71
|
-
"number[]": {
|
|
72
|
-
sqlite: `text('${name}', { mode: "json" })`,
|
|
73
|
-
pg: field.bigint ? `bigint('${name}', { mode: 'number' }).array()` : `integer('${name}').array()`,
|
|
74
|
-
mysql: `text('${name}', { mode: 'json' })`
|
|
75
|
-
},
|
|
76
|
-
"string[]": {
|
|
77
|
-
sqlite: `text('${name}', { mode: "json" })`,
|
|
78
|
-
pg: `text('${name}').array()`,
|
|
79
|
-
mysql: `text('${name}', { mode: "json" })`
|
|
80
|
-
},
|
|
81
|
-
json: {
|
|
82
|
-
sqlite: `text('${name}', { mode: "json" })`,
|
|
83
|
-
pg: `jsonb('${name}')`,
|
|
84
|
-
mysql: `json('${name}', { mode: "json" })`
|
|
85
|
-
},
|
|
86
|
-
uuid: {
|
|
87
|
-
sqlite: `text('${name}')`,
|
|
88
|
-
pg: `uuid('${name}')`,
|
|
89
|
-
mysql: `varchar('${name}', { length: 36 })`
|
|
90
|
-
}
|
|
91
|
-
}[type];
|
|
92
|
-
if (!dbTypeMap) throw new Error(`Unsupported field type '${field.type}' for field '${name}'.`);
|
|
93
|
-
return dbTypeMap[databaseType$1];
|
|
94
|
-
}
|
|
95
|
-
const tableDefinitions = [];
|
|
96
|
-
for (const tableKey in tables) {
|
|
97
|
-
const table = tables[tableKey];
|
|
98
|
-
const modelName = getModelName(tableKey);
|
|
99
|
-
const fields = table.fields;
|
|
100
|
-
const idFieldType = table.fields.id?.type;
|
|
101
|
-
let id;
|
|
102
|
-
if (databaseType === "pg" && idFieldType === "uuid") id = `uuid('id').primaryKey()`;
|
|
103
|
-
else if (databaseType === "mysql") id = `varchar('id', { length: 36 }).primaryKey()`;
|
|
104
|
-
else id = `text('id').primaryKey()`;
|
|
105
|
-
const indexes = [];
|
|
106
|
-
const references = [];
|
|
107
|
-
for (const field of Object.keys(fields)) {
|
|
108
|
-
if (field === "id") continue;
|
|
109
|
-
const attr = fields[field];
|
|
110
|
-
const fieldName = attr.fieldName || field;
|
|
111
|
-
if (attr.index && !attr.unique) indexes.push({
|
|
112
|
-
type: "index",
|
|
113
|
-
name: `${modelName}_${fieldName}_idx`,
|
|
114
|
-
on: fieldName
|
|
115
|
-
});
|
|
116
|
-
else if (attr.index && attr.unique) indexes.push({
|
|
117
|
-
type: "uniqueIndex",
|
|
118
|
-
name: `${modelName}_${fieldName}_uidx`,
|
|
119
|
-
on: fieldName
|
|
120
|
-
});
|
|
121
|
-
if (attr.references) {
|
|
122
|
-
const referencedModelName = tableNameMap.get(attr.references.model) || getModelName(attr.references.model);
|
|
123
|
-
references.push({
|
|
124
|
-
fieldName,
|
|
125
|
-
referencedTable: referencedModelName,
|
|
126
|
-
referencedField: getFieldName({
|
|
127
|
-
model: attr.references.model,
|
|
128
|
-
field: attr.references.field
|
|
129
|
-
}),
|
|
130
|
-
onDelete: attr.references.onDelete || "cascade",
|
|
131
|
-
required: attr.required || false,
|
|
132
|
-
originalModel: attr.references.model
|
|
133
|
-
});
|
|
134
|
-
}
|
|
135
|
-
}
|
|
136
|
-
tableDefinitions.push({
|
|
137
|
-
modelName,
|
|
138
|
-
tableKey,
|
|
139
|
-
fields,
|
|
140
|
-
id,
|
|
141
|
-
indexes,
|
|
142
|
-
references
|
|
143
|
-
});
|
|
144
|
-
}
|
|
145
|
-
const modelKeyToTableKey = /* @__PURE__ */ new Map();
|
|
146
|
-
for (const tableKey in tables) {
|
|
147
|
-
const table = tables[tableKey];
|
|
148
|
-
const modelName = getModelName(tableKey);
|
|
149
|
-
modelKeyToTableKey.set(tableKey, tableKey);
|
|
150
|
-
modelKeyToTableKey.set(modelName, tableKey);
|
|
151
|
-
modelKeyToTableKey.set(table.modelName, tableKey);
|
|
152
|
-
}
|
|
153
|
-
const referenceGraph = /* @__PURE__ */ new Map();
|
|
154
|
-
for (const tableDef of tableDefinitions) for (const ref of tableDef.references) {
|
|
155
|
-
const referencedTableKey = modelKeyToTableKey.get(ref.originalModel);
|
|
156
|
-
if (!referencedTableKey) continue;
|
|
157
|
-
const key = `${tableDef.tableKey}->${referencedTableKey}`;
|
|
158
|
-
referenceGraph.set(key, {
|
|
159
|
-
...ref,
|
|
160
|
-
sourceTable: tableDef.tableKey,
|
|
161
|
-
sourceModelName: tableDef.modelName
|
|
162
|
-
});
|
|
163
|
-
}
|
|
164
|
-
const skipReferences = /* @__PURE__ */ new Set();
|
|
165
|
-
for (const tableDef of tableDefinitions) for (const ref of tableDef.references) {
|
|
166
|
-
const referencedTableKey = modelKeyToTableKey.get(ref.originalModel);
|
|
167
|
-
if (!referencedTableKey) continue;
|
|
168
|
-
const reverseKey = `${referencedTableKey}->${tableDef.tableKey}`;
|
|
169
|
-
const reverseRef = referenceGraph.get(reverseKey);
|
|
170
|
-
if (reverseRef) {
|
|
171
|
-
if (!ref.required && ref.onDelete === "set null" && (reverseRef.required || reverseRef.onDelete !== "set null")) skipReferences.add(`${tableDef.tableKey}.${ref.fieldName}`);
|
|
172
|
-
}
|
|
173
|
-
}
|
|
174
|
-
for (const tableDef of tableDefinitions) {
|
|
175
|
-
const { modelName, fields, id, indexes, references } = tableDef;
|
|
176
|
-
const assignIndexes = (indexesToAssign) => {
|
|
177
|
-
if (!indexesToAssign.length) return "";
|
|
178
|
-
const parts = [`, (table) => [`];
|
|
179
|
-
for (const index of indexesToAssign) parts.push(` ${index.type}("${index.name}").on(table.${index.on}),`);
|
|
180
|
-
parts.push(`]`);
|
|
181
|
-
return parts.join("\n");
|
|
182
|
-
};
|
|
183
|
-
const referenceMap = /* @__PURE__ */ new Map();
|
|
184
|
-
for (const ref of references) referenceMap.set(ref.fieldName, ref);
|
|
185
|
-
const fieldDefinitions = Object.keys(fields).filter((field) => field !== "id").map((field) => {
|
|
186
|
-
const attr = fields[field];
|
|
187
|
-
const fieldName = attr.fieldName || field;
|
|
188
|
-
let type = getType(fieldName, attr, databaseType);
|
|
189
|
-
let comment = "";
|
|
190
|
-
if (attr.defaultValue !== null && typeof attr.defaultValue !== "undefined") if (typeof attr.defaultValue === "function") {
|
|
191
|
-
if (attr.type === "date" && attr.defaultValue.toString().includes("new Date()")) if (databaseType === "sqlite") type += `.default(sql\`(cast(unixepoch('subsecond') * 1000 as integer))\`)`;
|
|
192
|
-
else type += `.defaultNow()`;
|
|
193
|
-
} else if (typeof attr.defaultValue === "string") type += `.default("${attr.defaultValue}")`;
|
|
194
|
-
else type += `.default(${attr.defaultValue})`;
|
|
195
|
-
if (attr.onUpdate && attr.type === "date") {
|
|
196
|
-
if (typeof attr.onUpdate === "function") type += `.$onUpdate(${attr.onUpdate})`;
|
|
197
|
-
}
|
|
198
|
-
const ref = referenceMap.get(fieldName);
|
|
199
|
-
const shouldSkipReference = skipReferences.has(`${tableDef.tableKey}.${fieldName}`);
|
|
200
|
-
let referenceChain = "";
|
|
201
|
-
if (ref && !shouldSkipReference) referenceChain = `.references(() => ${ref.referencedTable}.${ref.referencedField}, { onDelete: '${ref.onDelete}' })`;
|
|
202
|
-
else if (ref && shouldSkipReference) {
|
|
203
|
-
const reverseKey = `${ref.originalModel}->${tableDef.tableKey}`;
|
|
204
|
-
const reverseRef = referenceGraph.get(reverseKey);
|
|
205
|
-
if (reverseRef) comment = `\n // FK constraint removed to break circular dependency with ${ref.referencedTable}\n // Primary FK: ${reverseRef.sourceModelName}.${reverseRef.fieldName} -> ${modelName}.${fieldName}\n // This field still maintains referential integrity via application logic and Drizzle relations`;
|
|
206
|
-
else comment = `\n // FK constraint removed to break circular dependency with ${ref.referencedTable}\n // This field still maintains referential integrity via application logic and Drizzle relations`;
|
|
207
|
-
}
|
|
208
|
-
const fieldDef = `${fieldName}: ${type}${attr.required ? ".notNull()" : ""}${attr.unique ? ".unique()" : ""}${referenceChain}`;
|
|
209
|
-
return comment ? `${comment}\n ${fieldDef}` : fieldDef;
|
|
210
|
-
});
|
|
211
|
-
const schema = `export const ${modelName} = ${databaseType}Table("${convertToSnakeCase(modelName, adapter.options?.camelCase)}", {
|
|
212
|
-
id: ${id},
|
|
213
|
-
${fieldDefinitions.join(",\n ")}
|
|
214
|
-
}${assignIndexes(indexes)});`;
|
|
215
|
-
code += `\n${schema}\n`;
|
|
216
|
-
}
|
|
217
|
-
let relationsString = "";
|
|
218
|
-
for (const tableKey in tables) {
|
|
219
|
-
const table = tables[tableKey];
|
|
220
|
-
const modelName = getModelName(tableKey);
|
|
221
|
-
const oneRelations = [];
|
|
222
|
-
const manyRelations = [];
|
|
223
|
-
const manyRelationsSet = /* @__PURE__ */ new Set();
|
|
224
|
-
const foreignFields = Object.entries(table.fields).filter(([_, field]) => field.references);
|
|
225
|
-
for (const [fieldName, field] of foreignFields) {
|
|
226
|
-
const referencedModel = field.references.model;
|
|
227
|
-
const relationKey = getModelName(referencedModel);
|
|
228
|
-
const fieldRef = `${getModelName(tableKey)}.${getFieldName({
|
|
229
|
-
model: tableKey,
|
|
230
|
-
field: fieldName
|
|
231
|
-
})}`;
|
|
232
|
-
const referenceRef = `${getModelName(referencedModel)}.${getFieldName({
|
|
233
|
-
model: referencedModel,
|
|
234
|
-
field: field.references.field || "id"
|
|
235
|
-
})}`;
|
|
236
|
-
oneRelations.push({
|
|
237
|
-
key: relationKey,
|
|
238
|
-
model: getModelName(referencedModel),
|
|
239
|
-
type: "one",
|
|
240
|
-
reference: {
|
|
241
|
-
field: fieldRef,
|
|
242
|
-
references: referenceRef,
|
|
243
|
-
fieldName
|
|
244
|
-
}
|
|
245
|
-
});
|
|
246
|
-
}
|
|
247
|
-
const otherModels = Object.entries(tables).filter(([otherName]) => otherName !== tableKey);
|
|
248
|
-
const modelRelationsMap = /* @__PURE__ */ new Map();
|
|
249
|
-
for (const [otherModelName, otherTable] of otherModels) {
|
|
250
|
-
const foreignKeysPointingHere = Object.entries(otherTable.fields).filter(([_, field]) => field.references?.model === tableKey || field.references?.model === getModelName(tableKey));
|
|
251
|
-
if (foreignKeysPointingHere.length === 0) continue;
|
|
252
|
-
const hasUnique = foreignKeysPointingHere.some(([_, field]) => !!field.unique);
|
|
253
|
-
const hasMany$1 = foreignKeysPointingHere.some(([_, field]) => !field.unique);
|
|
254
|
-
modelRelationsMap.set(otherModelName, {
|
|
255
|
-
modelName: otherModelName,
|
|
256
|
-
hasUnique,
|
|
257
|
-
hasMany: hasMany$1
|
|
258
|
-
});
|
|
259
|
-
}
|
|
260
|
-
for (const { modelName: otherModelName, hasMany: hasMany$1 } of modelRelationsMap.values()) {
|
|
261
|
-
const relationType = hasMany$1 ? "many" : "one";
|
|
262
|
-
let relationKey = getModelName(otherModelName);
|
|
263
|
-
if (!adapter.options?.adapterConfig?.usePlural && relationType === "many") relationKey = `${relationKey}s`;
|
|
264
|
-
if (!manyRelationsSet.has(relationKey)) {
|
|
265
|
-
manyRelationsSet.add(relationKey);
|
|
266
|
-
manyRelations.push({
|
|
267
|
-
key: relationKey,
|
|
268
|
-
model: getModelName(otherModelName),
|
|
269
|
-
type: relationType
|
|
270
|
-
});
|
|
271
|
-
}
|
|
272
|
-
}
|
|
273
|
-
const relationsByModel = /* @__PURE__ */ new Map();
|
|
274
|
-
for (const relation of oneRelations) {
|
|
275
|
-
if (!relation.reference) continue;
|
|
276
|
-
const modelKey = relation.key;
|
|
277
|
-
if (!relationsByModel.has(modelKey)) relationsByModel.set(modelKey, []);
|
|
278
|
-
relationsByModel.get(modelKey).push(relation);
|
|
279
|
-
}
|
|
280
|
-
const duplicateRelations = [];
|
|
281
|
-
const singleRelations = [];
|
|
282
|
-
for (const [_modelKey, rels] of relationsByModel.entries()) if (rels.length > 1) duplicateRelations.push(...rels);
|
|
283
|
-
else singleRelations.push(rels[0]);
|
|
284
|
-
for (const relation of duplicateRelations) {
|
|
285
|
-
if (!relation.reference) continue;
|
|
286
|
-
const fieldName = relation.reference.fieldName;
|
|
287
|
-
const tableRelation = `export const ${`${modelName}${fieldName.charAt(0).toUpperCase() + fieldName.slice(1)}Relations`} = relations(${modelName}, ({ one }) => ({
|
|
288
|
-
${relation.key}: one(${relation.model}, {
|
|
289
|
-
fields: [${relation.reference.field}],
|
|
290
|
-
references: [${relation.reference.references}],
|
|
291
|
-
})
|
|
292
|
-
}))`;
|
|
293
|
-
relationsString += `\n${tableRelation}\n`;
|
|
294
|
-
}
|
|
295
|
-
const hasOne = singleRelations.length > 0;
|
|
296
|
-
const hasMany = manyRelations.length > 0;
|
|
297
|
-
if (hasOne && hasMany) {
|
|
298
|
-
const tableRelation = `export const ${modelName}Relations = relations(${modelName}, ({ one, many }) => ({
|
|
299
|
-
${singleRelations.map((relation) => relation.reference ? ` ${relation.key}: one(${relation.model}, {
|
|
300
|
-
fields: [${relation.reference.field}],
|
|
301
|
-
references: [${relation.reference.references}],
|
|
302
|
-
})` : "").filter((x) => x !== "").join(",\n ")}${singleRelations.length > 0 && manyRelations.length > 0 ? "," : ""}
|
|
303
|
-
${manyRelations.map(({ key, model }) => ` ${key}: many(${model})`).join(",\n ")}
|
|
304
|
-
}))`;
|
|
305
|
-
relationsString += `\n${tableRelation}\n`;
|
|
306
|
-
} else if (hasOne) {
|
|
307
|
-
const tableRelation = `export const ${modelName}Relations = relations(${modelName}, ({ one }) => ({
|
|
308
|
-
${singleRelations.map((relation) => relation.reference ? ` ${relation.key}: one(${relation.model}, {
|
|
309
|
-
fields: [${relation.reference.field}],
|
|
310
|
-
references: [${relation.reference.references}],
|
|
311
|
-
})` : "").filter((x) => x !== "").join(",\n ")}
|
|
312
|
-
}))`;
|
|
313
|
-
relationsString += `\n${tableRelation}\n`;
|
|
314
|
-
} else if (hasMany) {
|
|
315
|
-
const tableRelation = `export const ${modelName}Relations = relations(${modelName}, ({ many }) => ({
|
|
316
|
-
${manyRelations.map(({ key, model }) => ` ${key}: many(${model})`).join(",\n ")}
|
|
317
|
-
}))`;
|
|
318
|
-
relationsString += `\n${tableRelation}\n`;
|
|
319
|
-
}
|
|
320
|
-
}
|
|
321
|
-
code += `\n${relationsString}`;
|
|
322
|
-
return {
|
|
323
|
-
code: await prettier.format(code, { parser: "typescript" }),
|
|
324
|
-
fileName: filePath,
|
|
325
|
-
overwrite: fileExist
|
|
326
|
-
};
|
|
327
|
-
};
|
|
328
|
-
function generateImport({ databaseType, tables }) {
|
|
329
|
-
const rootImports = ["relations"];
|
|
330
|
-
const coreImports = [];
|
|
331
|
-
let hasBigint = false;
|
|
332
|
-
let hasJson = false;
|
|
333
|
-
let hasUuid = false;
|
|
334
|
-
for (const table of Object.values(tables)) {
|
|
335
|
-
for (const field of Object.values(table.fields)) {
|
|
336
|
-
if (field.bigint) hasBigint = true;
|
|
337
|
-
if (field.type === "json") hasJson = true;
|
|
338
|
-
if (field.type === "uuid") hasUuid = true;
|
|
339
|
-
}
|
|
340
|
-
if (hasJson && hasBigint && hasUuid) break;
|
|
341
|
-
}
|
|
342
|
-
coreImports.push(`${databaseType}Table`);
|
|
343
|
-
coreImports.push(databaseType === "mysql" ? "varchar, text" : databaseType === "pg" ? "text" : "text");
|
|
344
|
-
coreImports.push(hasBigint ? databaseType !== "sqlite" ? "bigint" : "" : "");
|
|
345
|
-
coreImports.push(databaseType !== "sqlite" ? "timestamp, boolean" : "");
|
|
346
|
-
if (databaseType === "mysql") {
|
|
347
|
-
if (Object.values(tables).some((table) => Object.values(table.fields).some((field) => (field.type === "number" || field.type === "number[]") && !field.bigint))) coreImports.push("int");
|
|
348
|
-
if (Object.values(tables).some((table) => Object.values(table.fields).some((field) => typeof field.type !== "string" && Array.isArray(field.type) && field.type.every((x) => typeof x === "string")))) coreImports.push("mysqlEnum");
|
|
349
|
-
} else if (databaseType === "pg") {
|
|
350
|
-
if (Object.values(tables).some((table) => Object.values(table.fields).some((field) => (field.type === "number" || field.type === "number[]") && !field.bigint))) coreImports.push("integer");
|
|
351
|
-
if (hasUuid) coreImports.push("uuid");
|
|
352
|
-
} else coreImports.push("integer");
|
|
353
|
-
if (hasJson) {
|
|
354
|
-
if (databaseType === "pg") coreImports.push("jsonb");
|
|
355
|
-
if (databaseType === "mysql") coreImports.push("json");
|
|
356
|
-
}
|
|
357
|
-
if (databaseType === "sqlite" && Object.values(tables).some((table) => Object.values(table.fields).some((field) => field.type === "date" && field.defaultValue && typeof field.defaultValue === "function" && field.defaultValue.toString().includes("new Date()")))) rootImports.push("sql");
|
|
358
|
-
const hasIndexes = Object.values(tables).some((table) => Object.values(table.fields).some((field) => field.index && !field.unique));
|
|
359
|
-
const hasUniqueIndexes = Object.values(tables).some((table) => Object.values(table.fields).some((field) => field.unique && field.index));
|
|
360
|
-
if (hasIndexes) coreImports.push("index");
|
|
361
|
-
if (hasUniqueIndexes) coreImports.push("uniqueIndex");
|
|
362
|
-
return `${rootImports.length > 0 ? `import { ${rootImports.join(", ")} } from "drizzle-orm";\n` : ""}import { ${coreImports.map((x) => x.trim()).filter((x) => x !== "").join(", ")} } from "drizzle-orm/${databaseType}-core";\n`;
|
|
363
|
-
}
|
|
364
|
-
|
|
365
|
-
//#endregion
|
|
366
|
-
//#region src/generators/kysely.ts
|
|
367
|
-
const generateKyselySchema = async ({ options, file }) => {
|
|
368
|
-
const { compileMigrations } = await getMigrations(options);
|
|
369
|
-
const migrations = await compileMigrations();
|
|
370
|
-
return {
|
|
371
|
-
code: migrations.trim() === ";" ? "" : migrations,
|
|
372
|
-
fileName: file || `./better-auth_migrations/${(/* @__PURE__ */ new Date()).toISOString().replace(/:/g, "-")}.sql`
|
|
373
|
-
};
|
|
374
|
-
};
|
|
375
|
-
|
|
376
|
-
//#endregion
|
|
377
|
-
//#region src/utils/get-package-info.ts
|
|
378
|
-
function getPackageInfo(cwd) {
|
|
379
|
-
const packageJsonPath = cwd ? path.join(cwd, "package.json") : path.join("package.json");
|
|
380
|
-
return JSON.parse(fs.readFileSync(packageJsonPath, "utf-8"));
|
|
381
|
-
}
|
|
382
|
-
function getPrismaVersion(cwd) {
|
|
383
|
-
try {
|
|
384
|
-
const packageInfo = getPackageInfo(cwd);
|
|
385
|
-
const prismaVersion = packageInfo.dependencies?.prisma || packageInfo.devDependencies?.prisma || packageInfo.dependencies?.["@prisma/client"] || packageInfo.devDependencies?.["@prisma/client"];
|
|
386
|
-
if (!prismaVersion) return null;
|
|
387
|
-
const match = prismaVersion.match(/(\d+)/);
|
|
388
|
-
return match ? parseInt(match[1], 10) : null;
|
|
389
|
-
} catch {
|
|
390
|
-
return null;
|
|
391
|
-
}
|
|
392
|
-
}
|
|
393
|
-
|
|
394
|
-
//#endregion
|
|
395
|
-
//#region src/generators/prisma.ts
|
|
396
|
-
const generatePrismaSchema = async ({ adapter, options, file }) => {
|
|
397
|
-
const provider = adapter.options?.provider || "postgresql";
|
|
398
|
-
const tables = getPaymentTables(options);
|
|
399
|
-
const filePath = file || "./prisma/schema.prisma";
|
|
400
|
-
const schemaPrismaExist = existsSync(path.join(process.cwd(), filePath));
|
|
401
|
-
const getModelName = initGetModelName({
|
|
402
|
-
schema: getPaymentTables(options),
|
|
403
|
-
usePlural: adapter.options?.adapterConfig?.usePlural
|
|
404
|
-
});
|
|
405
|
-
const getFieldName = initGetFieldName({
|
|
406
|
-
schema: getPaymentTables(options),
|
|
407
|
-
usePlural: false
|
|
408
|
-
});
|
|
409
|
-
let schemaPrisma = "";
|
|
410
|
-
if (schemaPrismaExist) schemaPrisma = await fs$1.readFile(path.join(process.cwd(), filePath), "utf-8");
|
|
411
|
-
else schemaPrisma = getNewPrisma(provider, process.cwd());
|
|
412
|
-
const prismaVersion = getPrismaVersion(process.cwd());
|
|
413
|
-
if (prismaVersion && prismaVersion >= 7 && schemaPrismaExist) schemaPrisma = produceSchema(schemaPrisma, (builder) => {
|
|
414
|
-
const generator = builder.findByType("generator", { name: "client" });
|
|
415
|
-
if (generator && generator.properties) {
|
|
416
|
-
const providerProp = generator.properties.find((prop) => prop.type === "assignment" && prop.key === "provider");
|
|
417
|
-
if (providerProp && providerProp.value === "\"prisma-client-js\"") providerProp.value = "\"prisma-client\"";
|
|
418
|
-
}
|
|
419
|
-
});
|
|
420
|
-
const manyToManyRelations = /* @__PURE__ */ new Map();
|
|
421
|
-
for (const table in tables) {
|
|
422
|
-
const fields = tables[table]?.fields;
|
|
423
|
-
for (const field in fields) {
|
|
424
|
-
const attr = fields[field];
|
|
425
|
-
if (attr.references) {
|
|
426
|
-
const referencedOriginalModel = attr.references.model;
|
|
427
|
-
const referencedModelNameCap = capitalizeFirstLetter(getModelName(tables[referencedOriginalModel]?.modelName || referencedOriginalModel));
|
|
428
|
-
if (!manyToManyRelations.has(referencedModelNameCap)) manyToManyRelations.set(referencedModelNameCap, /* @__PURE__ */ new Set());
|
|
429
|
-
const currentModelNameCap = capitalizeFirstLetter(getModelName(tables[table]?.modelName || table));
|
|
430
|
-
manyToManyRelations.get(referencedModelNameCap).add(currentModelNameCap);
|
|
431
|
-
}
|
|
432
|
-
}
|
|
433
|
-
}
|
|
434
|
-
const indexedFields = /* @__PURE__ */ new Map();
|
|
435
|
-
for (const table in tables) {
|
|
436
|
-
const fields = tables[table]?.fields;
|
|
437
|
-
const modelName = capitalizeFirstLetter(getModelName(tables[table]?.modelName || table));
|
|
438
|
-
indexedFields.set(modelName, []);
|
|
439
|
-
for (const field in fields) {
|
|
440
|
-
const attr = fields[field];
|
|
441
|
-
if (attr.index && !attr.unique) {
|
|
442
|
-
const fieldName = attr.fieldName || field;
|
|
443
|
-
indexedFields.get(modelName).push(fieldName);
|
|
444
|
-
}
|
|
445
|
-
}
|
|
446
|
-
}
|
|
447
|
-
const schema = produceSchema(schemaPrisma, (builder) => {
|
|
448
|
-
for (const table in tables) {
|
|
449
|
-
const originalTableName = table;
|
|
450
|
-
const customModelName = tables[table]?.modelName || table;
|
|
451
|
-
const modelName = capitalizeFirstLetter(getModelName(customModelName));
|
|
452
|
-
const fields = tables[table]?.fields;
|
|
453
|
-
function getType({ isBigint, isOptional, type }) {
|
|
454
|
-
if (type === "string") return isOptional ? "String?" : "String";
|
|
455
|
-
if (type === "number" && isBigint) return isOptional ? "BigInt?" : "BigInt";
|
|
456
|
-
if (type === "number") return isOptional ? "Int?" : "Int";
|
|
457
|
-
if (type === "boolean") return isOptional ? "Boolean?" : "Boolean";
|
|
458
|
-
if (type === "date") return isOptional ? "DateTime?" : "DateTime";
|
|
459
|
-
if (type === "json") {
|
|
460
|
-
if (provider === "sqlite" || provider === "mysql") return isOptional ? "String?" : "String";
|
|
461
|
-
return isOptional ? "Json?" : "Json";
|
|
462
|
-
}
|
|
463
|
-
if (type === "string[]") {
|
|
464
|
-
if (provider === "sqlite" || provider === "mysql") return isOptional ? "String?" : "String";
|
|
465
|
-
return "String[]";
|
|
466
|
-
}
|
|
467
|
-
if (type === "number[]") {
|
|
468
|
-
if (provider === "sqlite" || provider === "mysql") return "String";
|
|
469
|
-
return "Int[]";
|
|
470
|
-
}
|
|
471
|
-
}
|
|
472
|
-
const prismaModel = builder.findByType("model", { name: modelName });
|
|
473
|
-
if (!prismaModel) builder.model(modelName).field("id", "String").attribute("id");
|
|
474
|
-
for (const field in fields) {
|
|
475
|
-
const attr = fields[field];
|
|
476
|
-
const fieldName = attr.fieldName || field;
|
|
477
|
-
if (prismaModel) {
|
|
478
|
-
if (builder.findByType("field", {
|
|
479
|
-
name: fieldName,
|
|
480
|
-
within: prismaModel.properties
|
|
481
|
-
})) continue;
|
|
482
|
-
}
|
|
483
|
-
const fieldBuilder = builder.model(modelName).field(fieldName, getType({
|
|
484
|
-
isBigint: attr?.bigint || false,
|
|
485
|
-
isOptional: !attr?.required,
|
|
486
|
-
type: "string"
|
|
487
|
-
}));
|
|
488
|
-
if (field === "id") fieldBuilder.attribute("id");
|
|
489
|
-
if (attr.unique) builder.model(modelName).blockAttribute(`unique([${fieldName}])`);
|
|
490
|
-
if (attr.defaultValue !== void 0) {
|
|
491
|
-
if (Array.isArray(attr.defaultValue)) {
|
|
492
|
-
if (attr.type === "json") {
|
|
493
|
-
if (Object.prototype.toString.call(attr.defaultValue[0]) === "[object Object]") {
|
|
494
|
-
fieldBuilder.attribute(`default("${JSON.stringify(attr.defaultValue).replace(/\\/g, "\\\\").replace(/"/g, "\\\"")}")`);
|
|
495
|
-
continue;
|
|
496
|
-
}
|
|
497
|
-
let jsonArray = [];
|
|
498
|
-
for (const value of attr.defaultValue) jsonArray.push(value);
|
|
499
|
-
fieldBuilder.attribute(`default("${JSON.stringify(jsonArray).replace(/"/g, "\\\"")}")`);
|
|
500
|
-
continue;
|
|
501
|
-
}
|
|
502
|
-
if (attr.defaultValue.length === 0) {
|
|
503
|
-
fieldBuilder.attribute(`default([])`);
|
|
504
|
-
continue;
|
|
505
|
-
} else if (typeof attr.defaultValue[0] === "string" && attr.type === "string[]") {
|
|
506
|
-
let valueArray = [];
|
|
507
|
-
for (const value of attr.defaultValue) valueArray.push(JSON.stringify(value));
|
|
508
|
-
fieldBuilder.attribute(`default([${valueArray}])`);
|
|
509
|
-
} else if (typeof attr.defaultValue[0] === "number") {
|
|
510
|
-
let valueArray = [];
|
|
511
|
-
for (const value of attr.defaultValue) valueArray.push(`${value}`);
|
|
512
|
-
fieldBuilder.attribute(`default([${valueArray}])`);
|
|
513
|
-
}
|
|
514
|
-
} else if (typeof attr.defaultValue === "object" && !Array.isArray(attr.defaultValue) && attr.defaultValue !== null) {
|
|
515
|
-
if (Object.entries(attr.defaultValue).length === 0) {
|
|
516
|
-
fieldBuilder.attribute(`default("{}")`);
|
|
517
|
-
continue;
|
|
518
|
-
}
|
|
519
|
-
fieldBuilder.attribute(`default("${JSON.stringify(attr.defaultValue).replace(/\\/g, "\\\\").replace(/"/g, "\\\"")}")`);
|
|
520
|
-
}
|
|
521
|
-
if (field === "createdAt") fieldBuilder.attribute("default(now())");
|
|
522
|
-
else if (typeof attr.defaultValue === "string" && provider !== "mysql") fieldBuilder.attribute(`default("${attr.defaultValue}")`);
|
|
523
|
-
else if (typeof attr.defaultValue === "boolean" || typeof attr.defaultValue === "number") fieldBuilder.attribute(`default(${attr.defaultValue})`);
|
|
524
|
-
else if (typeof attr.defaultValue === "function") {}
|
|
525
|
-
}
|
|
526
|
-
if (field === "updatedAt" && attr.onUpdate) fieldBuilder.attribute("updatedAt");
|
|
527
|
-
else if (attr.onUpdate) {}
|
|
528
|
-
if (attr.references) {
|
|
529
|
-
const referencedOriginalModelName = getModelName(attr.references.model);
|
|
530
|
-
const referencedCustomModelName = tables[referencedOriginalModelName]?.modelName || referencedOriginalModelName;
|
|
531
|
-
let action = "Cascade";
|
|
532
|
-
if (attr.references.onDelete === "no action") action = "NoAction";
|
|
533
|
-
else if (attr.references.onDelete === "set null") action = "SetNull";
|
|
534
|
-
else if (attr.references.onDelete === "set default") action = "SetDefault";
|
|
535
|
-
else if (attr.references.onDelete === "restrict") action = "Restrict";
|
|
536
|
-
const relationField = `relation(fields: [${getFieldName({
|
|
537
|
-
model: originalTableName,
|
|
538
|
-
field: fieldName
|
|
539
|
-
})}], references: [${getFieldName({
|
|
540
|
-
model: attr.references.model,
|
|
541
|
-
field: attr.references.field
|
|
542
|
-
})}], onDelete: ${action})`;
|
|
543
|
-
builder.model(modelName).field(referencedCustomModelName.toLowerCase(), `${capitalizeFirstLetter(referencedCustomModelName)}${!attr.required ? "?" : ""}`).attribute(relationField);
|
|
544
|
-
}
|
|
545
|
-
if (!attr.unique && !attr.references && provider === "mysql" && attr.type === "string") builder.model(modelName).field(fieldName).attribute("db.Text");
|
|
546
|
-
}
|
|
547
|
-
if (manyToManyRelations.has(modelName)) for (const relatedModel of manyToManyRelations.get(modelName)) {
|
|
548
|
-
const relatedTableName = Object.keys(tables).find((key) => capitalizeFirstLetter(tables[key]?.modelName || key) === relatedModel);
|
|
549
|
-
const relatedFields = relatedTableName ? tables[relatedTableName]?.fields : {};
|
|
550
|
-
const [_fieldKey, fkFieldAttr] = Object.entries(relatedFields || {}).find(([_fieldName, fieldAttr]) => fieldAttr.references && getModelName(fieldAttr.references.model) === getModelName(originalTableName)) || [];
|
|
551
|
-
const isUnique = fkFieldAttr?.unique === true;
|
|
552
|
-
const fieldName = isUnique || adapter.options?.usePlural === true ? `${relatedModel.toLowerCase()}` : `${relatedModel.toLowerCase()}s`;
|
|
553
|
-
if (!builder.findByType("field", {
|
|
554
|
-
name: fieldName,
|
|
555
|
-
within: prismaModel?.properties
|
|
556
|
-
})) builder.model(modelName).field(fieldName, `${relatedModel}${isUnique ? "?" : "[]"}`);
|
|
557
|
-
}
|
|
558
|
-
const indexedFieldsForModel = indexedFields.get(modelName);
|
|
559
|
-
if (indexedFieldsForModel && indexedFieldsForModel.length > 0) for (const fieldName of indexedFieldsForModel) {
|
|
560
|
-
if (prismaModel) {
|
|
561
|
-
if (prismaModel.properties.some((v) => v.type === "attribute" && v.name === "index" && JSON.stringify(v.args[0]?.value).includes(fieldName))) continue;
|
|
562
|
-
}
|
|
563
|
-
const field = Object.entries(fields).find(([key, attr]) => (attr.fieldName || key) === fieldName)?.[1];
|
|
564
|
-
let indexField = fieldName;
|
|
565
|
-
if (provider === "mysql" && field && field.type === "string") indexField = `${fieldName}(length: 191)`;
|
|
566
|
-
builder.model(modelName).blockAttribute(`index([${indexField}])`);
|
|
567
|
-
}
|
|
568
|
-
const hasAttribute = builder.findByType("attribute", {
|
|
569
|
-
name: "map",
|
|
570
|
-
within: prismaModel?.properties
|
|
571
|
-
});
|
|
572
|
-
const hasChanged = customModelName !== originalTableName;
|
|
573
|
-
if (!hasAttribute) builder.model(modelName).blockAttribute("map", `${getModelName(hasChanged ? customModelName : originalTableName)}`);
|
|
574
|
-
}
|
|
575
|
-
});
|
|
576
|
-
const schemaChanged = schema.trim() !== schemaPrisma.trim();
|
|
577
|
-
return {
|
|
578
|
-
code: schemaChanged ? schema : "",
|
|
579
|
-
fileName: filePath,
|
|
580
|
-
overwrite: schemaPrismaExist && schemaChanged
|
|
581
|
-
};
|
|
582
|
-
};
|
|
583
|
-
const getNewPrisma = (provider, cwd) => {
|
|
584
|
-
const prismaVersion = getPrismaVersion(cwd);
|
|
585
|
-
return `generator client {
|
|
586
|
-
provider = "${prismaVersion && prismaVersion >= 7 ? "prisma-client" : "prisma-client-js"}"
|
|
587
|
-
}
|
|
588
|
-
|
|
589
|
-
datasource db {
|
|
590
|
-
provider = "${provider}"
|
|
591
|
-
url = ${provider === "sqlite" ? `"file:./dev.db"` : `env("DATABASE_URL")`}
|
|
592
|
-
}`;
|
|
593
|
-
};
|
|
594
|
-
|
|
595
|
-
//#endregion
|
|
596
|
-
//#region src/generators/index.ts
|
|
597
|
-
const adapters = {
|
|
598
|
-
prisma: generatePrismaSchema,
|
|
599
|
-
drizzle: generateDrizzleSchema,
|
|
600
|
-
kysely: generateKyselySchema
|
|
601
|
-
};
|
|
602
|
-
const generateSchema = async (opts) => {
|
|
603
|
-
const adapter = opts.adapter;
|
|
604
|
-
const generator = adapter.id in adapters ? adapters[adapter.id] : null;
|
|
605
|
-
if (generator) return generator(opts);
|
|
606
|
-
if (adapter.createSchema) return adapter.createSchema(opts.options, opts.file).then(({ code, path: fileName, overwrite }) => ({
|
|
607
|
-
code,
|
|
608
|
-
fileName,
|
|
609
|
-
overwrite
|
|
610
|
-
}));
|
|
611
|
-
throw new Error(`${adapter.id} is not supported. If it is a custom adapter, please request the maintainer to implement createSchema`);
|
|
612
|
-
};
|
|
613
|
-
|
|
614
|
-
//#endregion
|
|
615
|
-
export { generateKyselySchema as a, getPackageInfo as i, generateSchema as n, generateDrizzleSchema as o, generatePrismaSchema as r, adapters as t };
|