-
Notifications
You must be signed in to change notification settings - Fork 0
/
model.ts
409 lines (368 loc) · 9.51 KB
/
model.ts
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
// noinspection JSUnusedGlobalSymbols
import {Knex} from "knex";
import Value = Knex.Value;
// noinspection JSUnusedGlobalSymbols
export enum DataTypes {
STRING = 'string',
VARCHAR = 'varchar',
INTEGER = 'integer',
INT = 'int',
BIG_INTEGER = 'bigInteger',
BIG_INT = 'bigInt',
BLOB = 'blob',
MEDIUM_BLOB = 'mediumblob',
LONG_BLOB = 'longblob',
TEXT = 'text',
MEDIUM_TEXT = 'mediumtext',
LONG_TEXT = 'longtext',
FLOAT = 'float',
DECIMAL = 'decimal',
BOOLEAN = 'boolean',
DATE = 'date',
DATETIME = 'datetime',
TIME = 'time',
TIMESTAMP = 'timestamp',
BINARY = 'binary',
ENUM = 'enum',
ENU = 'enu',
JSON = 'json',
JSONB = 'jsonb',
UUID = 'uuid',
}
// noinspection JSUnusedGlobalSymbols
export enum ReferenceOption {
RESTRICT = 'RESTRICT',
CASCADE = 'CASCADE',
SET_NULL = 'SET NULL',
NO_ACTION = 'NO ACTION',
}
/**
* Create foreign reference for the column
*/
export interface Reference {
/**
* Reference table name
*/
table: string;
/**
* Reference column name,
* use id by default if not given.
*/
column?: string;
/**
* A default key name using the columns is used unless foreignKeyName is specified.
*/
foreignKeyName?: string;
/**
* If true, will not create foreign key constraint. Document only.
*/
softReference?: boolean;
onUpdate?: ReferenceOption;
onDelete?: ReferenceOption;
}
/**
* Type for column
*/
export interface Column {
/**
* type supported
*/
type: DataTypes
| 'string' | 'varchar'
| 'integer' | 'int'
| 'bigInteger' | 'bigInt'
| 'blob' | 'mediumblob' | 'longblob'
| 'text' | 'mediumtext' | 'longtext'
| 'float' | 'decimal'
| 'boolean'
| 'date' | 'datetime' | 'timestamp' | 'time'
| 'binary'
| 'enum' | 'enu'
| 'json'
| 'jsonb'
| 'uuid'
| string;
/**
* enable autoIncrement
*/
autoIncrement?: boolean | 'bigIncrements';
/**
* column length
*/
length?: number;
/**
* Specifies an integer as unsigned. No-op if this is chained off of a non-integer field.
*/
unsigned?: boolean;
/**
* column is nullable
*/
nullable?: boolean;
/**
* column is primaryKey
*/
primaryKey?: boolean | string;
/**
* add UNIQUE index to column
*/
unique?: boolean | string;
/**
* column's comment
*/
comment?: string;
/**
* default value
*/
defaultValue?: Value;
/**
* datetime and timestamp options.
* used only when type is datetime or timestamp.
*/
datetimeOptions?: DatetimeOptions;
/**
* float options.
* used only when type is float or decimal
*/
floatOptions?: FloatOptions;
enumType?: EnumType;
reference?: Reference;
}
interface EnumType {
/**
* enum values for the column.
* used only when type is enu or enum
*/
enumValues: readonly Value[];
/**
*
*/
enumOptions?: EnumOptions;
}
interface EnumOptions {
useNative: boolean;
existingType?: boolean;
schemaName?: string;
enumName: string;
}
/**
* Type for model columns, it's a map,
* and each member should be typeof Column,
* the map's keys shall be column name in table.
*/
export interface Columns {
[columnName: string]: Column;
}
/**
* Model auto timestamps options
*/
export interface ModelTimestamps {
useTimestampType?: boolean;
makeDefaultNow?: boolean;
camelCase?: boolean;
}
/**
* datetime options, also work for type timestamp
*/
export interface DatetimeOptions {
precision?: number;
useTz?: boolean;
}
/**
* options for type float,
* also work for type decimal
*/
export interface FloatOptions {
precision?: number;
scale?: number;
}
/**
* Index type
*/
export interface NamedIndex {
/**
* Columns to create index with, if index is to be created with one single element, then pass one element to the array.
*/
columns: Array<string>;
/**
* Specify name of index
*
* If not given, index will be created with default name.
*/
indexName?: string;
/**
* If not given, a normal index will be created.
*/
indexType?: 'unique' | 'fulltext' | string;
}
/**
* An ORM model for knex
* http://knexjs.org/#Schema-Building
*/
export interface Model {
tableName: string;
columns: Columns;
autoId?: boolean;
comment?: string;
engine?: string;
charset?: string;
collate?: string;
inherits?: string;
timestamps?: boolean | ModelTimestamps;
indexes?: Array<Array<string> | NamedIndex>;
}
export interface CodeGenerationOptions {
indent?: number;
lineBreaker?: string;
}
/**
* Code generation tool function to convert model to TypeScript's type
* @param model The model to be converted
* @param indent
* @param lineBreaker
* return {string} TypeScript code in string
*/
export function toTypeScriptInterface(model: Model, {
indent = 4,
lineBreaker = '\n'
}: CodeGenerationOptions = {}): string {
const {tableName, columns} = model;
let codes = new Array<string>();
const indentSpace = ((indents) => {
let indentStr = '';
for (let i = 0; i < indents; i++) {
indentStr += ' ';
}
return indentStr;
})(indent);
codes.push(`export interface ${tableName}{`);
if (typeof columns === "object") {
Object.keys(columns).forEach(fieldName => {
const field = columns[fieldName];
const nullable = field.nullable === true ? '?' : '';
const type = ((t: DataTypes | string) => {
switch (t.toString().toLocaleLowerCase()) {
case DataTypes.STRING:
case DataTypes.VARCHAR:
case DataTypes.TEXT:
case DataTypes.MEDIUM_TEXT:
case DataTypes.LONG_TEXT:
case DataTypes.UUID:
case 'char':
return 'string';
case DataTypes.INTEGER:
case DataTypes.INT:
case DataTypes.BIG_INTEGER:
case DataTypes.BIG_INT:
case DataTypes.FLOAT:
case DataTypes.DECIMAL:
return 'number';
case DataTypes.BOOLEAN:
return 'boolean';
case DataTypes.DATE:
case DataTypes.DATETIME:
case DataTypes.TIME:
case DataTypes.TIMESTAMP:
return 'Date';
default:
return 'any';
}
})(field.type);
// add comment
if (field.comment) {
codes.push(`${indentSpace}/**`);
codes.push(`${indentSpace} * ${field.comment}`);
codes.push(`${indentSpace} */`);
}
codes.push(`${indentSpace}${fieldName}${nullable}: ${type};`);
});
}
codes.push(`}`);
return codes.join(lineBreaker);
}
export interface MarkdownTableOptions {
tableColumnNames?: MarkdownTableColumnNames;
lineBreaker?: string;
}
export interface MarkdownTableColumnNames {
name?: string;
type?: string;
pk?: string;
autoIncrement?: string;
nullable?: string;
unique?: string;
default?: string;
index?: string;
reference?: string;
comment?: string;
}
export function toMarkdownTable(
model: Model,
options: MarkdownTableOptions = {}) {
const {
tableColumnNames = {
name: 'name',
type: 'type',
pk: 'PK',
autoIncrement: 'auto inc',
nullable: 'nullable',
unique: 'unique',
default: 'default',
index: 'index',
reference: 'reference',
comment: 'comment',
},
lineBreaker = '\n',
} = options;
const lines = new Array<string>();
lines.push(`| ${tableColumnNames.name} | ${tableColumnNames.type} | ${tableColumnNames.pk} | ${tableColumnNames.autoIncrement} | ${tableColumnNames.nullable} | ${tableColumnNames.unique} | ${tableColumnNames.default} | ${tableColumnNames.index} | ${tableColumnNames.reference} | ${tableColumnNames.comment} |`);
lines.push('| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |');
if (model.autoId === true) {
lines.push(`| id | int unsigned | pk | auto inc | | | | | | |`)
}
if (typeof model.columns === 'object') {
Object.keys(model.columns).forEach(columnName => {
const column = model.columns[columnName];
const cells = new Array<string>();
cells.push(columnName);
cells.push(((c) => {
const typeParts = new Array<string>();
typeParts.push(c.type.toString())
if (c.length) {
typeParts.push(`(${c.length})`);
} else if (c.datetimeOptions) {
typeParts.push(`(${c.datetimeOptions.precision})`)
} else if (c.floatOptions) {
typeParts.push(`(${c.floatOptions.precision},${c.floatOptions.scale})`)
}
return typeParts.join('');
})(column))
cells.push(column.primaryKey ? 'PK' : '');
cells.push(column.autoIncrement === true ? 'auto inc' : '');
cells.push(column.nullable === true ? 'null' : 'not null');
cells.push(column.unique === true ? 'unique' : '');
cells.push(column.defaultValue ? `${column.defaultValue}` : '');
cells.push((({indexes = []}: Model, c) => {
let indexType = '';
for (let i = 0; i < indexes.length; i++) {
const index = indexes[i];
if (Array.isArray(index)) {
if (index.indexOf(c) >= 0) {
indexType = 'index';
break;
}
} else {
if (index.columns.indexOf(c) >= 0) {
indexType = index.indexType || 'index';
break;
}
}
}
return indexType;
})(model, columnName)); // index
cells.push(column.reference ? `${column.reference.table}.${column.reference.column || 'id'}` : '');
cells.push(column.comment ? column.comment : '');
lines.push(`| ${cells.join(' | ')} |`);
});
}
return lines.join(lineBreaker);
}