@dbml/connector 3.7.2

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.
@@ -0,0 +1,391 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.fetchSchemaJson = fetchSchemaJson;
4
+ const promise_1 = require("mysql2/promise");
5
+ const lodash_1 = require("lodash");
6
+ const NUMBER_REGEX = '^-?[0-9]+(.[0-9]+)?$';
7
+ async function connectMySQL(connection) {
8
+ const client = await (0, promise_1.createConnection)(connection);
9
+ try {
10
+ await client.connect();
11
+ await client.query('SELECT 1');
12
+ return client;
13
+ }
14
+ catch (error) {
15
+ await client.end();
16
+ if (error instanceof Error) {
17
+ throw new Error(`MySQL connection error: ${error.message}`);
18
+ }
19
+ throw error;
20
+ }
21
+ }
22
+ function getEnumName(tableName, columnName) {
23
+ return `${tableName}_${columnName}_enum`;
24
+ }
25
+ function getGenerationExpression(extraType, generationExpression) {
26
+ if (extraType === 'VIRTUAL GENERATED') {
27
+ return `GENERATED ALWAYS AS (${generationExpression}) VIRTUAL`;
28
+ }
29
+ if (extraType === 'STORED GENERATED') {
30
+ return `GENERATED ALWAYS AS (${generationExpression}) STORED`;
31
+ }
32
+ // for timestamp data type
33
+ if (extraType.includes('on update CURRENT_TIMESTAMP')) {
34
+ return 'on update CURRENT_TIMESTAMP';
35
+ }
36
+ // others
37
+ return '';
38
+ }
39
+ function getDbDefault(columnDefault, defaultValueType) {
40
+ if (columnDefault === null) {
41
+ return null;
42
+ }
43
+ return { value: columnDefault, type: defaultValueType };
44
+ }
45
+ function getFieldType(tableName, columnName, columnType, columnDataType, columnExtra, generationExpression) {
46
+ if (columnDataType === 'enum') {
47
+ // enum must have static value -> no need to check the generation expression
48
+ return getEnumName(tableName, columnName);
49
+ }
50
+ const fieldGenerationExpression = getGenerationExpression(columnExtra, generationExpression);
51
+ if (fieldGenerationExpression) {
52
+ return `${columnType} ${fieldGenerationExpression}`;
53
+ }
54
+ return columnType;
55
+ }
56
+ function generateField(row) {
57
+ const { tableName, columnName, columnDefault, defaultValueType, columnIsNullable, columnType, columnDataType, columnComment, columnExtra, generationExpression, } = row;
58
+ const fieldType = getFieldType(tableName, columnName, columnType, columnDataType, columnExtra, generationExpression);
59
+ const fieldDefaultValue = getDbDefault(columnDefault, defaultValueType);
60
+ const isNullable = columnIsNullable === 'YES';
61
+ return {
62
+ name: columnName,
63
+ type: { type_name: fieldType, schemaName: null },
64
+ dbdefault: fieldDefaultValue,
65
+ not_null: !isNullable,
66
+ increment: columnExtra === 'auto_increment',
67
+ note: { value: columnComment || '' },
68
+ };
69
+ }
70
+ // Do not get the index sub part since in DBML, it is impossible to create index on part of column.
71
+ function getIndexColumn(columnName, idxExpression, idxSubPart) {
72
+ if (idxExpression) {
73
+ return { value: idxExpression, type: 'expression' };
74
+ }
75
+ if (idxSubPart) {
76
+ return { value: `${columnName}(${idxSubPart})`, type: 'expression' };
77
+ }
78
+ if (columnName) {
79
+ return { value: columnName, type: 'column' };
80
+ }
81
+ return null;
82
+ }
83
+ async function generateTablesAndFields(client, schemaName) {
84
+ const query = `
85
+ select
86
+ t.table_name as tableName,
87
+ t.table_comment as tableComment,
88
+ c.column_name as columnName,
89
+ c.column_default as columnDefault,
90
+ case
91
+ when c.column_default is null then 'boolean'
92
+ when c.data_type = 'enum' then 'string'
93
+ when c.column_default regexp ? then 'number'
94
+ when c.extra like '%DEFAULT_GENERATED%' then 'expression'
95
+ else 'string'
96
+ end as defaultValueType,
97
+ c.is_nullable as columnIsNullable,
98
+ c.data_type as columnDataType,
99
+ c.column_type as columnType,
100
+ c.extra as columnExtra,
101
+ c.column_comment as columnComment,
102
+ c.generation_expression as generationExpression
103
+ from information_schema.tables t
104
+ join information_schema.columns c
105
+ on t.table_schema = c.table_schema and t.table_name = c.table_name
106
+ where
107
+ t.table_schema = ? and t.table_type = 'BASE TABLE'
108
+ order by
109
+ t.table_name, c.ordinal_position;
110
+ `;
111
+ const queryResponse = await client.query(query, [NUMBER_REGEX, schemaName]);
112
+ const rows = queryResponse[0];
113
+ const tableMap = {};
114
+ const fieldMap = {};
115
+ rows.forEach((row) => {
116
+ const { tableName, tableComment } = row;
117
+ const key = tableName;
118
+ if (!tableMap[key]) {
119
+ tableMap[key] = {
120
+ name: tableName,
121
+ note: { value: tableComment || '' },
122
+ };
123
+ }
124
+ if (!fieldMap[key]) {
125
+ fieldMap[key] = [];
126
+ }
127
+ const field = generateField(row);
128
+ fieldMap[key].push(field);
129
+ });
130
+ return {
131
+ tableList: Object.values(tableMap),
132
+ fieldMap,
133
+ };
134
+ }
135
+ async function generateEnums(client, schemaName) {
136
+ const query = `
137
+ select
138
+ t.table_name as tableName,
139
+ c.column_name as columnName,
140
+ TRIM(LEADING 'enum' FROM c.column_type) AS rawValues
141
+ from information_schema.tables t
142
+ join information_schema.columns c
143
+ on t.table_schema = c.table_schema and t.table_name = c.table_name
144
+ where
145
+ t.table_schema = ? and t.table_type = 'BASE TABLE' and c.data_type = 'enum'
146
+ order by
147
+ t.table_name, c.ordinal_position;
148
+ `;
149
+ const queryResponse = await client.query(query, [schemaName]);
150
+ const rows = queryResponse[0];
151
+ const enumList = rows.map((row) => {
152
+ const { tableName, columnName, rawValues } = row;
153
+ // i.e. ('value1','value2')
154
+ const valueList = rawValues
155
+ .slice(1, -1)
156
+ .split(',')
157
+ .map((value) => ({ name: value.slice(1, -1) }));
158
+ const enumName = getEnumName(tableName, columnName);
159
+ return {
160
+ name: enumName,
161
+ values: valueList,
162
+ };
163
+ });
164
+ return enumList;
165
+ }
166
+ /**
167
+ * Mysql is automatically create index for primary keys, foreign keys, unique constraint. -> Ignore
168
+ */
169
+ async function generateIndexes(client, schemaName) {
170
+ const query = `
171
+ with
172
+ pk_fk_uniques as (
173
+ select constraint_name, table_name
174
+ from information_schema.table_constraints
175
+ where table_schema = ?
176
+ )
177
+ select
178
+ st.table_name as tableName,
179
+ case
180
+ when st.non_unique = 0 then true
181
+ else false
182
+ end as isIdxUnique,
183
+ st.index_name as idxName,
184
+ st.column_name as columnName,
185
+ st.sub_part as idxSubPart,
186
+ st.index_type as idxType,
187
+ replace(st.expression, '\`', '') as idxExpression
188
+ from information_schema.statistics st
189
+ where
190
+ st.table_schema = ?
191
+ and st.index_name not in (
192
+ select constraint_name
193
+ from pk_fk_uniques pfu
194
+ where pfu.table_name = st.table_name
195
+ )
196
+ and st.index_type in ('BTREE', 'HASH')
197
+ group by
198
+ st.table_name, st.non_unique, st.index_name, st.column_name, st.sub_part, st.index_type, st.expression
199
+ order by st.index_name;
200
+ `;
201
+ const queryResponse = await client.query(query, [schemaName, schemaName]);
202
+ const rows = queryResponse[0];
203
+ const tableIndexMap = rows.reduce((acc, row) => {
204
+ const { tableName, idxName, idxType, isIdxUnique, columnName, idxExpression, idxSubPart, } = row;
205
+ const key = tableName;
206
+ if (!acc[key]) {
207
+ acc[key] = {};
208
+ }
209
+ if (!acc[key][idxName]) {
210
+ // init first index
211
+ acc[key][idxName] = {
212
+ name: idxName,
213
+ type: idxType,
214
+ columns: [],
215
+ unique: !!isIdxUnique,
216
+ };
217
+ }
218
+ const currentIndex = acc[key][idxName];
219
+ const column = getIndexColumn(columnName, idxExpression, idxSubPart);
220
+ if (column) {
221
+ currentIndex.columns.push(column);
222
+ }
223
+ return acc;
224
+ }, {});
225
+ const indexMap = {};
226
+ Object.keys(tableIndexMap).forEach((tableName) => {
227
+ indexMap[tableName] = (0, lodash_1.flatten)(Object.values(tableIndexMap[tableName]));
228
+ });
229
+ return indexMap;
230
+ }
231
+ async function generatePrimaryAndUniqueConstraint(client, schemaName) {
232
+ const query = `
233
+ select
234
+ tc.table_name as tableName,
235
+ tc.constraint_name as constraintName,
236
+ group_concat(kcu.column_name order by kcu.ordinal_position separator ',') as columnNames,
237
+ count(kcu.column_name) as columnCount,
238
+ tc.constraint_type as constraintType
239
+ from information_schema.table_constraints tc
240
+ join information_schema.key_column_usage kcu
241
+ on
242
+ tc.constraint_schema = kcu.constraint_schema
243
+ and tc.constraint_name = kcu.constraint_name
244
+ and tc.table_name = kcu.table_name
245
+ where
246
+ (tc.constraint_type = 'PRIMARY KEY' or tc.constraint_type = 'UNIQUE')
247
+ and tc.table_schema = ?
248
+ group by tc.table_name, tc.constraint_name, tc.constraint_type
249
+ order by tc.table_name, tc.constraint_name;
250
+ `;
251
+ const queryResponse = await client.query(query, [schemaName]);
252
+ const rows = queryResponse[0];
253
+ const inlineConstraintList = rows.filter((constraint) => constraint.columnCount === 1);
254
+ const outOfConstraintList = rows.filter((constraint) => constraint.columnCount > 1);
255
+ const compositeTableConstraintMap = outOfConstraintList.reduce((acc, row) => {
256
+ const { tableName, constraintName, columnNames, constraintType, } = row;
257
+ const key = tableName;
258
+ if (!acc[key]) {
259
+ acc[key] = {};
260
+ }
261
+ if (!acc[key][constraintName]) {
262
+ acc[key][constraintName] = {
263
+ name: constraintName,
264
+ };
265
+ }
266
+ if (constraintType === 'PRIMARY KEY') {
267
+ acc[key][constraintName].primary = true;
268
+ }
269
+ if (constraintType === 'UNIQUE') {
270
+ acc[key][constraintName].unique = true;
271
+ }
272
+ const columnList = columnNames
273
+ .split(',')
274
+ .map((col) => ({ type: 'column', value: col }));
275
+ acc[key][constraintName].columns = columnList;
276
+ return acc;
277
+ }, {});
278
+ const compositeConstraintMap = {};
279
+ Object.keys(compositeTableConstraintMap).forEach((tableName) => {
280
+ compositeConstraintMap[tableName] = (0, lodash_1.flatten)(Object.values(compositeTableConstraintMap[tableName]));
281
+ });
282
+ const constraintMap = inlineConstraintList.reduce((acc, row) => {
283
+ const { tableName, columnNames, constraintType } = row;
284
+ const key = tableName;
285
+ if (!acc[key]) {
286
+ acc[key] = {};
287
+ }
288
+ const columnList = columnNames.split(',');
289
+ columnList.forEach((columnName) => {
290
+ if (!acc[key][columnName]) {
291
+ acc[key][columnName] = {};
292
+ }
293
+ if (constraintType === 'PRIMARY KEY') {
294
+ acc[key][columnName].pk = true;
295
+ }
296
+ if (constraintType === 'UNIQUE' && !acc[key][columnName].pk) {
297
+ acc[key][columnName].unique = true;
298
+ }
299
+ });
300
+ return acc;
301
+ }, {});
302
+ return { compositeConstraintMap, constraintMap };
303
+ }
304
+ async function generateForeignKeys(client, schemaName) {
305
+ const query = `
306
+ select
307
+ rc.constraint_name as constraintName,
308
+ rc.table_name as foreignTableName,
309
+ group_concat(kcu.column_name order by kcu.ordinal_position separator ',') as foreignColumnNames,
310
+ kcu.referenced_table_name as refTableName,
311
+ group_concat(kcu.referenced_column_name order by kcu.ordinal_position separator ',') as refColumnNames,
312
+ rc.update_rule as onUpdate,
313
+ rc.delete_rule as onDelete
314
+ from information_schema.referential_constraints rc
315
+ join information_schema.key_column_usage kcu
316
+ on
317
+ rc.constraint_name = kcu.constraint_name
318
+ and rc.table_name = kcu.table_name
319
+ and rc.constraint_schema = kcu.table_schema
320
+ where rc.constraint_schema = ?
321
+ group by
322
+ rc.constraint_name,
323
+ rc.table_name,
324
+ kcu.referenced_table_name,
325
+ rc.update_rule,
326
+ rc.delete_rule
327
+ order by
328
+ rc.table_name;
329
+ `;
330
+ const queryResponse = await client.query(query, [schemaName]);
331
+ const rows = queryResponse[0];
332
+ const foreignKeyList = rows.map((row) => {
333
+ const { constraintName, onDelete, onUpdate, foreignTableName, foreignColumnNames, refTableName, refColumnNames, } = row;
334
+ const endpoint1 = {
335
+ tableName: foreignTableName,
336
+ fieldNames: foreignColumnNames.split(','),
337
+ relation: '*',
338
+ };
339
+ const endpoint2 = {
340
+ tableName: refTableName,
341
+ fieldNames: refColumnNames.split(','),
342
+ relation: '1',
343
+ };
344
+ return {
345
+ name: constraintName,
346
+ endpoints: [endpoint1, endpoint2],
347
+ onDelete: onDelete === 'NO ACTION' ? null : onDelete,
348
+ onUpdate: onUpdate === 'NO ACTION' ? null : onUpdate,
349
+ };
350
+ });
351
+ return foreignKeyList;
352
+ }
353
+ function combineIndexAndCompositeConstraint(userDefinedIndexMap, compositeConstraintMap) {
354
+ const indexMap = Object.assign(userDefinedIndexMap, {});
355
+ Object.keys(compositeConstraintMap).forEach((tableName) => {
356
+ const compositeConstraint = compositeConstraintMap[tableName];
357
+ if (!indexMap[tableName]) {
358
+ indexMap[tableName] = compositeConstraint;
359
+ return;
360
+ }
361
+ indexMap[tableName].push(...compositeConstraint);
362
+ });
363
+ return indexMap;
364
+ }
365
+ async function fetchSchemaJson(connection) {
366
+ const client = await connectMySQL(connection);
367
+ // In MySQL, a schema is equal database
368
+ const { database: schemaName } = client.config;
369
+ if (!schemaName) {
370
+ throw new Error('Cannot get schema name from the connection');
371
+ }
372
+ const result = await Promise.all([
373
+ generateTablesAndFields(client, schemaName),
374
+ generateEnums(client, schemaName),
375
+ generateIndexes(client, schemaName),
376
+ generatePrimaryAndUniqueConstraint(client, schemaName),
377
+ generateForeignKeys(client, schemaName),
378
+ ]);
379
+ client.end();
380
+ const [{ tableList, fieldMap }, enumList, rawIndexMap, { constraintMap, compositeConstraintMap }, foreignKeyList,] = result;
381
+ // combine normal index and composite key
382
+ const indexMap = combineIndexAndCompositeConstraint(rawIndexMap, compositeConstraintMap);
383
+ return {
384
+ tables: tableList,
385
+ fields: fieldMap,
386
+ refs: foreignKeyList,
387
+ enums: enumList,
388
+ indexes: indexMap,
389
+ tableConstraints: constraintMap,
390
+ };
391
+ }
@@ -0,0 +1,3 @@
1
+ import { DatabaseSchema } from './types';
2
+ declare const fetchSchemaJson: (connection: string) => Promise<DatabaseSchema>;
3
+ export { fetchSchemaJson, };