-
-
Notifications
You must be signed in to change notification settings - Fork 145
Expand file tree
/
Copy pathprisma-builder.ts
More file actions
343 lines (295 loc) · 10.1 KB
/
prisma-builder.ts
File metadata and controls
343 lines (295 loc) · 10.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
import indentString from './indent-string';
/**
* Prisma schema builder
*/
export class PrismaModel {
private datasources: DataSource[] = [];
private generators: Generator[] = [];
private models: Model[] = [];
private enums: Enum[] = [];
addDataSource(name: string, provider: string, url: DataSourceUrl, shadowDatabaseUrl?: DataSourceUrl): DataSource {
const ds = new DataSource(name, provider, url, shadowDatabaseUrl);
this.datasources.push(ds);
return ds;
}
addGenerator(name: string, fields: Array<{ name: string; value: string | string[] }>): Generator {
const generator = new Generator(name, fields);
this.generators.push(generator);
return generator;
}
addModel(name: string): Model {
const model = new Model(name);
this.models.push(model);
return model;
}
addEnum(name: string): Enum {
const e = new Enum(name);
this.enums.push(e);
return e;
}
toString(): string {
return [...this.datasources, ...this.generators, ...this.enums, ...this.models]
.map((d) => d.toString())
.join('\n\n');
}
}
export class DataSource {
constructor(
public name: string,
public provider: string,
public url: DataSourceUrl,
public shadowDatabaseUrl?: DataSourceUrl
) {}
toString(): string {
return (
`datasource ${this.name} {\n` +
indentString(`provider="${this.provider}"\n`) +
indentString(`url=${this.url}\n`) +
(this.shadowDatabaseUrl ? indentString(`shadowDatabaseurl=${this.shadowDatabaseUrl}\n`) : '') +
`}`
);
}
}
export class DataSourceUrl {
constructor(public value: string, public isEnv: boolean) {}
toString(): string {
return this.isEnv ? `env("${this.value}")` : `"${this.value}"`;
}
}
export class Generator {
constructor(public name: string, public fields: Array<{ name: string; value: string | string[] }>) {}
toString(): string {
return (
`generator ${this.name} {\n` +
this.fields.map((f) => indentString(`${f.name} = ${JSON.stringify(f.value)}`)).join('\n') +
`\n}`
);
}
}
export class DeclarationBase {
public documentations: string[] = [];
addComment(name: string): string {
this.documentations.push(name);
return name;
}
toString(): string {
return this.documentations.map((x) => `${x}\n`).join('');
}
}
export class Model extends DeclarationBase {
public fields: ModelField[] = [];
public attributes: ModelAttribute[] = [];
constructor(public name: string, public documentations: string[] = []) {
super();
}
addField(
name: string,
type: ModelFieldType | string,
attributes: FieldAttribute[] = [],
documentations: string[] = []
): ModelField {
const field = new ModelField(name, type, attributes, documentations);
this.fields.push(field);
return field;
}
addAttribute(name: string, args: AttributeArg[] = []): ModelAttribute {
const attr = new ModelAttribute(name, args);
this.attributes.push(attr);
return attr;
}
toString(): string {
return (
super.toString() +
`model ${this.name} {\n` +
indentString([...this.fields, ...this.attributes].map((d) => d.toString()).join('\n')) +
`\n}`
);
}
}
export type ScalarTypes =
| 'String'
| 'Boolean'
| 'Int'
| 'BigInt'
| 'Float'
| 'Decimal'
| 'DateTime'
| 'Json'
| 'Bytes'
| 'Unsupported';
export class ModelFieldType {
constructor(public type: ScalarTypes | string, public array?: boolean, public optional?: boolean) {}
toString(): string {
return `${this.type}${this.array ? '[]' : ''}${this.optional ? '?' : ''}`;
}
}
export class ModelField extends DeclarationBase {
constructor(
public name: string,
public type: ModelFieldType | string,
public attributes: FieldAttribute[] = [],
public documentations: string[] = []
) {
super();
}
addAttribute(name: string, args: AttributeArg[] = []): FieldAttribute {
const attr = new FieldAttribute(name, args);
this.attributes.push(attr);
return attr;
}
toString(): string {
return (
super.toString() +
`${this.name} ${this.type}` +
(this.attributes.length > 0 ? ' ' + this.attributes.map((a) => a.toString()).join(' ') : '')
);
}
}
export class FieldAttribute {
constructor(public name: string, public args: AttributeArg[] = []) {}
toString(): string {
return `${this.name}(` + this.args.map((a) => a.toString()).join(', ') + `)`;
}
}
export class ModelAttribute {
constructor(public name: string, public args: AttributeArg[] = []) {}
toString(): string {
return `${this.name}(` + this.args.map((a) => a.toString()).join(', ') + `)`;
}
}
export class AttributeArg {
constructor(public name: string | undefined, public value: AttributeArgValue) {}
toString(): string {
return this.name ? `${this.name}: ${this.value}` : this.value.toString();
}
}
export class AttributeArgValue {
constructor(
public type: 'String' | 'FieldReference' | 'Number' | 'Boolean' | 'Array' | 'FunctionCall',
public value: string | number | boolean | FieldReference | FunctionCall | AttributeArgValue[]
) {
switch (type) {
case 'String':
if (typeof value !== 'string') throw new Error('Value must be string');
break;
case 'Number':
if (typeof value !== 'number') throw new Error('Value must be number');
break;
case 'Boolean':
if (typeof value !== 'boolean') throw new Error('Value must be boolean');
break;
case 'Array':
if (!Array.isArray(value)) throw new Error('Value must be array');
break;
case 'FieldReference':
if (typeof value !== 'string' && !(value instanceof FieldReference))
throw new Error('Value must be string or FieldReference');
break;
case 'FunctionCall':
if (!(value instanceof FunctionCall)) throw new Error('Value must be FunctionCall');
break;
}
}
toString(): string {
switch (this.type) {
case 'String':
return `"${this.value}"`;
case 'Number':
return this.value.toString();
case 'FieldReference': {
if (typeof this.value === 'string') {
return this.value;
} else {
const fr = this.value as FieldReference;
let r = fr.field;
if (fr.args.length > 0) {
r += '(' + fr.args.map((a) => a.toString()).join(',') + ')';
}
return r;
}
}
case 'FunctionCall':
return this.value.toString();
case 'Boolean':
return this.value ? 'true' : 'false';
case 'Array':
return '[' + (this.value as AttributeArgValue[]).map((v) => v.toString()).join(', ') + ']';
default:
throw new Error(`Unknown attribute value type ${this.type}`);
}
}
}
export class FieldReference {
constructor(public field: string, public args: FieldReferenceArg[] = []) {}
}
export class FieldReferenceArg {
constructor(public name: 'sort', public value: 'Asc' | 'Desc') {}
toString(): string {
return `${this.name}: ${this.value}`;
}
}
export class FunctionCall {
constructor(public func: string, public args: FunctionCallArg[] = []) {}
toString(): string {
return `${this.func}` + '(' + this.args.map((a) => a.toString()).join(', ') + ')';
}
}
export class FunctionCallArg {
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any
constructor(public name: string | undefined, public value: any) {}
toString(): string {
const val =
this.value === null || this.value === undefined
? 'null'
: typeof this.value === 'string'
? `"${this.value}"`
: this.value.toString();
return this.name ? `${this.name}: ${val}` : val;
}
}
export class Enum extends DeclarationBase {
public fields: EnumField[] = [];
public attributes: ModelAttribute[] = [];
constructor(public name: string, public documentations: string[] = []) {
super();
}
addField(name: string, attributes: FieldAttribute[] = [], documentations: string[] = []): EnumField {
const field = new EnumField(name, attributes, documentations);
this.fields.push(field);
return field;
}
addAttribute(name: string, args: AttributeArg[] = []): ModelAttribute {
const attr = new ModelAttribute(name, args);
this.attributes.push(attr);
return attr;
}
addComment(name: string): string {
this.documentations.push(name);
return name;
}
toString(): string {
return (
super.toString() +
`enum ${this.name} {\n` +
indentString([...this.fields, ...this.attributes].map((d) => d.toString()).join('\n')) +
'\n}'
);
}
}
export class EnumField extends DeclarationBase {
constructor(public name: string, public attributes: FieldAttribute[] = [], public documentations: string[] = []) {
super();
}
addAttribute(name: string, args: AttributeArg[] = []): FieldAttribute {
const attr = new FieldAttribute(name, args);
this.attributes.push(attr);
return attr;
}
toString(): string {
return (
super.toString() +
this.name +
(this.attributes.length > 0 ? ' ' + this.attributes.map((a) => a.toString()).join(' ') : '')
);
}
}