gg-mysql-connector 1.0.41 → 1.0.46

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.
@@ -1,296 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- const chalk_1 = __importDefault(require("chalk"));
7
- const crypto_1 = require("crypto");
8
- const mysql2_1 = __importDefault(require("mysql2"));
9
- class GGMySQLConnector {
10
- constructor(DBInfo) {
11
- this.printResultLength = (results, executionTime, queryResult) => {
12
- if (results.length) {
13
- const executionTimeMessage = executionTime > 1000
14
- ? chalk_1.default.bgRed(`${executionTime} ` + " ms")
15
- : chalk_1.default.yellow(`${executionTime} ` + " ms");
16
- console.log(`${this.DBInfo.database} > ${chalk_1.default.green(queryResult.sql)} ${chalk_1.default.cyan(`found ${results.length} rows.`)} ${executionTimeMessage}`);
17
- }
18
- };
19
- this.isPrintStatement = false;
20
- this.tableAndViewNameList = [];
21
- this.columnAndTableListCache = null;
22
- this.DBInfo = DBInfo;
23
- this.isConnected = false;
24
- }
25
- async createDatabaseIfNotExist(tempConnection) {
26
- const currentDatabaseName = this.DBInfo.database;
27
- console.log("currentDatabaseName", currentDatabaseName);
28
- return new Promise((resolve, reject) => {
29
- tempConnection.query(`CREATE DATABASE IF NOT EXISTS ${currentDatabaseName}`, () => {
30
- resolve();
31
- });
32
- });
33
- }
34
- async selectBySearchTextInRow(tableName, textToSearch) {
35
- const result = (await this.query(`SELECT * FROM ${tableName}`));
36
- const wordList = textToSearch.split(" ");
37
- const temp = result.filter((row) => {
38
- const rawText = Object.values(row).flat().join(" ");
39
- const wordFilterResult = wordList.filter((wRow) => rawText.search(wRow) >= 0);
40
- if (wordFilterResult.length === wordList.length)
41
- return true;
42
- return false;
43
- });
44
- return temp;
45
- }
46
- async loadTableAndViewNameList() {
47
- let result = (await this.query("SELECT TABLE_NAME FROM information_schema.tables WHERE table_schema = ?", [this.DBInfo.database], false));
48
- this.tableAndViewNameList = result.map((row) => row.TABLE_NAME);
49
- return this.tableAndViewNameList;
50
- }
51
- async getViewNameIfExist(tableName) {
52
- const tableList = this.tableAndViewNameList;
53
- const viewPostFixArray = ["_view", "__view", "__view_list"];
54
- for (let i = 0; i < viewPostFixArray.length; i++) {
55
- const expectViewName = tableName + viewPostFixArray[i];
56
- for (let j = 0; j < tableList.length; j++) {
57
- const row = tableList[j];
58
- if (row === expectViewName) {
59
- return expectViewName;
60
- }
61
- else if (i == viewPostFixArray.length - 1 &&
62
- j == tableList.length - 1) {
63
- return tableName;
64
- }
65
- }
66
- }
67
- return tableName;
68
- }
69
- async selectByMatchParams(tableName, params) {
70
- const columnList = await this.getColumnList(tableName);
71
- const keyList = Object.keys(params);
72
- const keyToSearchList = [];
73
- const valueToSearchList = [];
74
- for (const key of keyList) {
75
- const temp = columnList.find((fkey) => key === fkey);
76
- if (temp) {
77
- keyToSearchList.push(` ${key} = ? `);
78
- valueToSearchList.push(params[key]);
79
- }
80
- }
81
- if (keyToSearchList.length === 0) {
82
- return [];
83
- }
84
- let result = (await this.query(`SELECT * FROM ${tableName} WHERE ${keyToSearchList.join(" AND ")}`, valueToSearchList));
85
- return result;
86
- }
87
- async selectByID(tableName, id) {
88
- let result = (await this.query(`SELECT * FROM ${tableName} WHERE id = ? LIMIT 1`, [id]));
89
- return result;
90
- }
91
- async select(tableName) {
92
- let result = (await this.query(`SELECT * FROM ${tableName}`));
93
- return result;
94
- }
95
- async getTableNameList() {
96
- let data = [];
97
- let result = (await this.query("SELECT * FROM information_schema.tables WHERE table_schema = ? AND TABLE_TYPE = 'BASE TABLE'", [this.DBInfo.database], false));
98
- for (let row of result)
99
- data.push(row.TABLE_NAME || row.row.table_name);
100
- return data;
101
- }
102
- async getViewNameList() {
103
- let data = [];
104
- let result = (await this.query("SELECT * FROM information_schema.tables WHERE table_schema = ? AND TABLE_TYPE = 'VIEW'", [this.DBInfo.database], false));
105
- for (let row of result)
106
- data.push(row.TABLE_NAME || row.row.table_name);
107
- return data;
108
- }
109
- async deleteByMatchParams(tableName, params) {
110
- const columnList = await this.getColumnList(tableName);
111
- const keyList = Object.keys(params);
112
- const keyToSearchList = [];
113
- const valueToSearchList = [];
114
- for (const key of keyList) {
115
- const temp = columnList.find((fkey) => key === fkey);
116
- if (temp) {
117
- keyToSearchList.push(` ${key} = ? `);
118
- valueToSearchList.push(params[key]);
119
- }
120
- }
121
- if (keyToSearchList.length === 0)
122
- return null;
123
- let result = (await this.query(`DELETE FROM ${tableName} WHERE ${keyToSearchList.join(" AND ")}`, valueToSearchList));
124
- // this.webSocket.sendByURL("/websocket/watchTableChange", tableName)
125
- return result;
126
- }
127
- async deleteByID(tableName, id) {
128
- let result = (await this.query(`DELETE FROM ${tableName} WHERE id = ?`, [
129
- id,
130
- ]));
131
- console.log("Delete Success");
132
- // this.webSocket.sendByURL("/websocket/watchTableChange", tableName)
133
- return result;
134
- }
135
- async insert(tableName, parameter) {
136
- let params = [];
137
- if (Array.isArray(parameter) === true) {
138
- params = parameter;
139
- }
140
- else
141
- params = [parameter];
142
- const columnList = await this.getColumnList(tableName);
143
- const exampleParams = params[0];
144
- const keyList = Object.keys(exampleParams);
145
- const keyListToInsert = [];
146
- for (const row of keyList) {
147
- const temp = columnList.find((fRow) => row === fRow);
148
- if (temp)
149
- keyListToInsert.push(row);
150
- }
151
- const valueArrayToInsertInQuery = [];
152
- for (let i = 0; i < params.length; i++) {
153
- const valueListToInsert = [];
154
- for (const row of keyList) {
155
- const temp = columnList.find((fRow) => row === fRow);
156
- if (temp) {
157
- valueListToInsert.push(params[i][row]);
158
- }
159
- }
160
- valueArrayToInsertInQuery.push(valueListToInsert);
161
- }
162
- console.log(valueArrayToInsertInQuery.slice(0, 5));
163
- const result = (await this.query(`INSERT INTO ${tableName} (${keyListToInsert.join(",")}) VALUES ?`, [valueArrayToInsertInQuery]));
164
- console.log("Insert Success");
165
- // this.webSocket.sendByURL("/websocket/watchTableChange", String(tableName))
166
- return result;
167
- }
168
- async updateOnlyID(tableName, params) {
169
- const isNewIdExist = await this.query(`SELECT * FROM ${tableName} WHERE id = ? `, [params.newID]);
170
- if (isNewIdExist.length >= 1) {
171
- console.log(`error : newID (${params.newID}) is already exist`);
172
- return null;
173
- }
174
- let result = (await this.query(`UPDATE ${tableName} SET id = ? WHERE id = ?`, [params.newID, params.oldID], false));
175
- console.log("UpdateOnlyID Success");
176
- // this.webSocket.sendByURL("/websocket/watchTableChange", String(tableName))
177
- return result;
178
- }
179
- async update(tableName, parameter) {
180
- const columnList = await this.getColumnList(tableName);
181
- console.log(parameter);
182
- const keyList = Object.keys(parameter);
183
- const keyListToInsert = [];
184
- const valueListToInsert = [];
185
- for (const row of keyList) {
186
- const temp = columnList.find((fRow) => row === fRow);
187
- if (temp) {
188
- keyListToInsert.push(row);
189
- valueListToInsert.push(parameter[row]);
190
- }
191
- }
192
- // build set sql
193
- const temp = [];
194
- let index = 0;
195
- for (const row of keyListToInsert) {
196
- if (valueListToInsert[index] === null) {
197
- temp.push(`${row} = NULL`);
198
- }
199
- else {
200
- let value = valueListToInsert[index];
201
- if (typeof value === "string") {
202
- value = value.replace(/'/g, "");
203
- }
204
- temp.push(`${row} = '${value}'`);
205
- }
206
- index++;
207
- }
208
- let result = (await this.query(`UPDATE ${tableName} SET ${temp.join(",")} WHERE id = ${parameter.id}`, [], false));
209
- console.log("Update Success");
210
- // this.webSocket.sendByURL("/websocket/watchTableChange", String(tableName))
211
- return result;
212
- }
213
- async init() {
214
- const currentConnection = mysql2_1.default.createConnection({
215
- host: this.DBInfo.host,
216
- user: this.DBInfo.user,
217
- password: this.DBInfo.password,
218
- });
219
- this.isConnected = true;
220
- await this.createDatabaseIfNotExist(currentConnection);
221
- // await currentConnection.end()
222
- this.connection = mysql2_1.default.createConnection(Object.assign({}, this.DBInfo));
223
- // await this.query("SET global sql_mode=''")
224
- // await this.query("SET global query_cache_type='ON'")
225
- // await this.query("SET global query_cache_size=16777216")
226
- // await this.query("SET global query_cache_limit=16777216")
227
- await this.loadTableAndViewNameList();
228
- await this.loadColumnListToCache();
229
- }
230
- async loadColumnListToCache() {
231
- const result = (await this.query(`SELECT COLUMN_NAME,TABLE_NAME,DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '${this.DBInfo.database}'`, undefined, false));
232
- this.columnAndTableListCache = result;
233
- }
234
- async getColumnList(tableName) {
235
- if (this.columnAndTableListCache !== null) {
236
- return this.columnAndTableListCache
237
- .filter((row) => row.TABLE_NAME === tableName)
238
- .map((row) => row.COLUMN_NAME);
239
- }
240
- const result = await this.query(`SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '${this.DBInfo.database}' AND TABLE_NAME = '${tableName}'`, undefined, false);
241
- return result.map((row) => row.COLUMN_NAME);
242
- }
243
- async getColumnFullList(tableName) {
244
- const result = (await this.query(`SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '${this.DBInfo.database}' AND TABLE_NAME = '${tableName}'`, undefined, false));
245
- return result;
246
- }
247
- waitUntilInitSuccess(interval) {
248
- if (this.isConnected === true)
249
- return true;
250
- return new Promise((resolve, reject) => {
251
- setTimeout(() => {
252
- if (this.isConnected === false) {
253
- console.log(`${this.DBInfo.database} > wait for database connection . . .`);
254
- this.waitUntilInitSuccess(interval);
255
- }
256
- else {
257
- return resolve(true);
258
- }
259
- }, interval);
260
- });
261
- }
262
- async query(statment, parameter, isPrint) {
263
- await this.waitUntilInitSuccess(1000);
264
- return new Promise((resolve, reject) => {
265
- const uniqueTime = `${(0, crypto_1.randomUUID)()} ${statment}`;
266
- console.time(uniqueTime);
267
- const startTime = new Date();
268
- const queryResult = this.connection.query(statment, parameter, (error, results, fields) => {
269
- if (error) {
270
- // _getCallerFile()
271
- console.log(chalk_1.default.bgRed("Query Error"));
272
- console.log(chalk_1.default.bgRed(error));
273
- console.log(chalk_1.default.bgRed("Statement : "));
274
- console.log(statment);
275
- console.log(chalk_1.default.bgRed("Parameter : "));
276
- console.log(parameter);
277
- console.log("------------------------------------------------");
278
- console.log(chalk_1.default.bgRed(queryResult.sql));
279
- reject(error);
280
- }
281
- else {
282
- const endTime = new Date();
283
- const executionTime = endTime.getTime() - startTime.getTime();
284
- if (isPrint === true) {
285
- this.printResultLength(results, executionTime, queryResult);
286
- }
287
- else if (this.isPrintStatement) {
288
- this.printResultLength(results, executionTime, queryResult);
289
- }
290
- resolve(results);
291
- }
292
- });
293
- });
294
- }
295
- }
296
- exports.default = GGMySQLConnector;
@@ -1,38 +0,0 @@
1
- import mysql from "mysql2/promise";
2
- import { MyModel } from "../myModel";
3
- export interface DatabaseConfigInterface {
4
- host: string;
5
- user: string;
6
- password: string;
7
- database: string;
8
- }
9
- export default class ModelGenerator {
10
- model: MyModel[];
11
- dbInfo: DatabaseConfigInterface;
12
- connection: mysql.Connection;
13
- isConnected: boolean;
14
- constructor(dbInfo: DatabaseConfigInterface, model: MyModel[]);
15
- init(): Promise<void>;
16
- private createDatabaseIfNotExist;
17
- pushModelToDB(): Promise<void>;
18
- pushViewToDB(viewDirectory: string): Promise<void>;
19
- waitUntilInitSuccess(interval: number): true | Promise<unknown>;
20
- query<T>(statment: string, parameter?: any[], isPrint?: boolean): Promise<T>;
21
- private printResultLength;
22
- getTableNameList(): Promise<string[]>;
23
- getViewNameList(): Promise<string[]>;
24
- getColumnFullList(tableName: string): Promise<mysql.RowDataPacket[]>;
25
- private isTableNameExistInModel;
26
- private isColumnExistInModel;
27
- getPossibleColumnValue(model: MyModel[], tableName: string, columnName: string): false | any[] | undefined;
28
- generateModelInterface(params: {
29
- appName: string;
30
- model: MyModel[];
31
- outputDirectory: string[];
32
- }): Promise<string>;
33
- generateModelConstStructure(params: {
34
- appName: string;
35
- model: MyModel[];
36
- outputDirectory: string[];
37
- }): Promise<string>;
38
- }
@@ -1,299 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- const chalk_1 = __importDefault(require("chalk"));
7
- const crypto_1 = require("crypto");
8
- const fs_1 = __importDefault(require("fs"));
9
- const promise_1 = __importDefault(require("mysql2/promise"));
10
- const path_1 = __importDefault(require("path"));
11
- const MyDBMigrator_1 = __importDefault(require("../MyDBMigrator/MyDBMigrator"));
12
- class ModelGenerator {
13
- constructor(dbInfo, model) {
14
- this.printResultLength = (results, executionTime, queryResult) => {
15
- if (results.length) {
16
- const executionTimeMessage = executionTime > 1000
17
- ? chalk_1.default.bgRed(`${executionTime} ` + " ms")
18
- : chalk_1.default.yellow(`${executionTime} ` + " ms");
19
- console.log(`${chalk_1.default.green(queryResult.sql)} ${chalk_1.default.cyan(`found ${results.length} rows.`)} ${executionTimeMessage}`);
20
- }
21
- };
22
- this.model = model;
23
- this.dbInfo = dbInfo;
24
- this.isConnected = false;
25
- }
26
- async init() {
27
- console.log("init");
28
- this.connection = await promise_1.default.createConnection({
29
- host: this.dbInfo.host,
30
- user: this.dbInfo.user,
31
- password: this.dbInfo.password,
32
- });
33
- this.isConnected = true;
34
- await this.createDatabaseIfNotExist();
35
- }
36
- async createDatabaseIfNotExist() {
37
- const databaseName = this.dbInfo.database;
38
- await this.connection.query(`CREATE DATABASE IF NOT EXISTS ${databaseName}`);
39
- await this.connection.query(`USE ${databaseName}`);
40
- }
41
- async pushModelToDB() {
42
- const migrator = new MyDBMigrator_1.default(this);
43
- await migrator.migrateTable(this.model);
44
- }
45
- async pushViewToDB(viewDirectory) {
46
- const migrator = new MyDBMigrator_1.default(this);
47
- await migrator.migrateView(viewDirectory);
48
- }
49
- waitUntilInitSuccess(interval) {
50
- if (this.isConnected === true)
51
- return true;
52
- return new Promise((resolve, reject) => {
53
- setTimeout(() => {
54
- if (this.isConnected === false) {
55
- console.log(`${this.dbInfo.database} > wait for database connection . . .`);
56
- this.waitUntilInitSuccess(interval);
57
- }
58
- else {
59
- return resolve(true);
60
- }
61
- }, interval);
62
- });
63
- }
64
- async query(statment, parameter, isPrint) {
65
- await this.waitUntilInitSuccess(1000);
66
- return new Promise((resolve, reject) => {
67
- const uniqueTime = `${(0, crypto_1.randomUUID)()} ${statment}`;
68
- console.time(uniqueTime);
69
- const startTime = new Date();
70
- const queryResult = this.connection
71
- .query(statment, parameter)
72
- .then((result) => {
73
- const endTime = new Date();
74
- const executionTime = endTime.getTime() - startTime.getTime();
75
- if (isPrint === true)
76
- this.printResultLength(result, executionTime, queryResult);
77
- resolve(result[0]);
78
- })
79
- .catch((error) => {
80
- // _getCallerFile()
81
- console.log(chalk_1.default.bgRed("Query Error"));
82
- console.log(chalk_1.default.bgRed(error));
83
- console.log(chalk_1.default.bgRed("Statement : "));
84
- console.log(statment);
85
- console.log(chalk_1.default.bgRed("Parameter : "));
86
- console.log(parameter);
87
- console.log("------------------------------------------------");
88
- console.log(chalk_1.default.bgRed(queryResult.sql));
89
- reject(error);
90
- });
91
- });
92
- }
93
- async getTableNameList() {
94
- let data = [];
95
- let result = (await this.query("SELECT * FROM information_schema.tables WHERE table_schema = ? AND TABLE_TYPE = 'BASE TABLE'", [this.dbInfo.database], false));
96
- for (let row of result)
97
- data.push(row.TABLE_NAME || row.row.table_name);
98
- return data;
99
- }
100
- async getViewNameList() {
101
- let data = [];
102
- let result = (await this.query("SELECT * FROM information_schema.tables WHERE table_schema = ? AND TABLE_TYPE = 'VIEW'", [this.dbInfo.database], false));
103
- for (let row of result)
104
- data.push(row.TABLE_NAME || row.row.table_name);
105
- return data;
106
- }
107
- async getColumnFullList(tableName) {
108
- const result = (await this.query(`SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '${this.dbInfo.database}' AND TABLE_NAME = '${tableName}'`, undefined, false));
109
- return result;
110
- }
111
- isTableNameExistInModel(model, tableName) {
112
- if (tableName === "sessions")
113
- return true;
114
- const table = model.find((row) => row.tableName === tableName);
115
- return table ? true : false;
116
- }
117
- isColumnExistInModel(model, tableName, columnName) {
118
- if (tableName === "sessions")
119
- return true;
120
- const table = model.find((row) => row.tableName === tableName);
121
- if (table) {
122
- const column = table.columns.find((row) => row.COLUMN_NAME === columnName);
123
- if (column)
124
- return true;
125
- }
126
- return false;
127
- }
128
- getPossibleColumnValue(model, tableName, columnName) {
129
- const foundTable = model.find((row) => row.tableName === tableName);
130
- if (foundTable) {
131
- const foundColumn = foundTable["columns"].find((row) => row.COLUMN_NAME === columnName);
132
- if (foundColumn) {
133
- if (foundColumn.POSSIBLE_VALUE)
134
- return foundColumn.POSSIBLE_VALUE;
135
- }
136
- else
137
- return false;
138
- }
139
- }
140
- async generateModelInterface(params) {
141
- const tableList = [
142
- ...(await this.getTableNameList()),
143
- ...(await this.getViewNameList()),
144
- ];
145
- const arrayOfColumnKeyValue = [];
146
- const arrayOfSeedColumnKeyValue = [];
147
- for (let i = 0; i < tableList.length; i++) {
148
- const tableName = tableList[i];
149
- if (this.isTableNameExistInModel(params.model, tableName) ||
150
- tableName.search("_view") >= 0) {
151
- const columnList = await this.getColumnFullList(tableName);
152
- let stringOfRawColumnKeyAndValue = "";
153
- for (const cRow of columnList) {
154
- const isColumnExistInModel = this.isColumnExistInModel(params.model, tableName, cRow.COLUMN_NAME);
155
- if (isColumnExistInModel || tableName.search("_view") >= 0) {
156
- const possibleValue = this.getPossibleColumnValue(params.model, cRow.TABLE_NAME, cRow.COLUMN_NAME);
157
- if (possibleValue) {
158
- stringOfRawColumnKeyAndValue = `${stringOfRawColumnKeyAndValue} \n ${cRow.COLUMN_NAME}: ${possibleValue.map((row) => `"${row}"`).join(" | ")};`;
159
- }
160
- else {
161
- stringOfRawColumnKeyAndValue = `${stringOfRawColumnKeyAndValue} \n ${cRow.COLUMN_NAME}: ${convertDataType(cRow.DATA_TYPE)};`;
162
- }
163
- }
164
- else {
165
- console.log(`${tableName}-${cRow.COLUMN_NAME} not exist in model `);
166
- }
167
- }
168
- // normal app model code
169
- const str = ` ${tableName} : { ${stringOfRawColumnKeyAndValue} }`;
170
- arrayOfColumnKeyValue.push(str);
171
- // only seed model code
172
- const tempSeedModel = params.model.find((row) => row.tableName === tableName && row.isSeed);
173
- if (tempSeedModel)
174
- arrayOfSeedColumnKeyValue.push(str);
175
- }
176
- }
177
- // normal app model code
178
- const fileName = `${params.appName}_INF.ts`;
179
- const seedFileName = `seed_INF.ts`;
180
- const code = `export default interface ${params.appName}_INF { ${arrayOfColumnKeyValue.join("\n")} }`;
181
- const seedCode = `export default interface seed_INF { ${arrayOfSeedColumnKeyValue.join("\n")} }`;
182
- for (let row of params.outputDirectory) {
183
- // normal app model code
184
- const serverFilePath = path_1.default.join(row, fileName);
185
- await fs_1.default.writeFileSync(serverFilePath, code);
186
- console.log("save app model to ", serverFilePath);
187
- // only seed model code
188
- const seedServerFilePath = path_1.default.join(row, seedFileName);
189
- await fs_1.default.writeFileSync(seedServerFilePath, seedCode);
190
- console.log("save seed model to ", seedServerFilePath);
191
- }
192
- console.log(`generate interface ${params.appName} ${chalk_1.default.bgGreen(" SUCCESS ")}`);
193
- return code;
194
- }
195
- async generateModelConstStructure(params) {
196
- const isTableNameExistInModel = (tableName) => {
197
- if (tableName === "sessions")
198
- return true;
199
- const table = params.model.find((row) => row.tableName === tableName);
200
- if (table)
201
- return true;
202
- return false;
203
- };
204
- const isColumnExistInModel = (tableName, columnName) => {
205
- if (tableName === "sessions")
206
- return true;
207
- const table = params.model.find((row) => row.tableName === tableName);
208
- if (table) {
209
- const column = table.columns.find((row) => row.COLUMN_NAME === columnName);
210
- if (column)
211
- return true;
212
- }
213
- return false;
214
- };
215
- const getPossibleColumnValue = (tableName, columnName) => {
216
- const foundTable = params.model.find((row) => row.tableName === tableName);
217
- if (foundTable) {
218
- const foundColumn = foundTable["columns"].find((row) => row.COLUMN_NAME === columnName);
219
- if (foundColumn) {
220
- if (foundColumn.POSSIBLE_VALUE)
221
- return foundColumn.POSSIBLE_VALUE;
222
- }
223
- else
224
- return false;
225
- }
226
- };
227
- const tableList = [
228
- ...(await this.getTableNameList()),
229
- ...(await this.getViewNameList()),
230
- ];
231
- const array = [];
232
- for (let i = 0; i < tableList.length; i++) {
233
- const tableName = tableList[i];
234
- if (isTableNameExistInModel(tableName) ||
235
- tableName.search("_view") >= 0) {
236
- const columnList = await this.getColumnFullList(tableName);
237
- let value = "";
238
- for (const cRow of columnList) {
239
- const columnChecker = isColumnExistInModel(tableName, cRow.COLUMN_NAME);
240
- if (columnChecker || tableName.search("_view") >= 0) {
241
- const possibleValue = getPossibleColumnValue(cRow.TABLE_NAME, cRow.COLUMN_NAME);
242
- if (possibleValue) {
243
- value = `${value} \n ${cRow.COLUMN_NAME}: [${possibleValue
244
- .map((row) => {
245
- if (typeof row === "string")
246
- return `"${row}"`;
247
- else if (typeof row === "number")
248
- return `${row}`;
249
- })
250
- .join(" , ")}] as ${typeof possibleValue[0]}[],`;
251
- }
252
- else {
253
- value = `${value} \n ${cRow.COLUMN_NAME}: "${convertDataType(cRow.DATA_TYPE)}",`;
254
- }
255
- }
256
- else {
257
- console.log(`${tableName}-${cRow.COLUMN_NAME} not exist in model `);
258
- }
259
- }
260
- const str = ` ${tableName} : { ${value} }`;
261
- array.push(str);
262
- // console.log(`generate interface from ${tableName}`)
263
- }
264
- }
265
- const fileName = `${params.appName}_model_const.ts`;
266
- const code = `
267
- export const ${params.appName}_model_const = { ${array.join(",")} } as const`;
268
- for (let row of params.outputDirectory) {
269
- const serverFilePath = path_1.default.join(row, fileName);
270
- await fs_1.default.writeFileSync(serverFilePath, code);
271
- console.log("save to ", serverFilePath);
272
- }
273
- console.log(`generate interface ${params.appName} ${chalk_1.default.bgGreen(" SUCCESS ")}`);
274
- return code;
275
- }
276
- }
277
- exports.default = ModelGenerator;
278
- function convertDataType(inputDataType) {
279
- let result = "string";
280
- if (inputDataType === "int") {
281
- result = "number";
282
- }
283
- else if (inputDataType === "tinyint") {
284
- result = "number";
285
- }
286
- else if (inputDataType === "bigint") {
287
- result = "number";
288
- }
289
- else if (inputDataType === "date") {
290
- result = "string";
291
- }
292
- else if (inputDataType === "float") {
293
- result = "number";
294
- }
295
- else if (inputDataType === "double") {
296
- result = "number";
297
- }
298
- return result;
299
- }
@@ -1 +0,0 @@
1
- export {};
@@ -1,3 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- function generateSeedInterface(model) { }
@@ -1,35 +0,0 @@
1
- import mysql from "mysql2/promise";
2
- import { MyModel } from "./myModel";
3
- export interface DatabaseConfigInterface {
4
- host: string;
5
- user: string;
6
- password: string;
7
- database: string;
8
- }
9
- export default class ModelGenerator {
10
- model: MyModel[];
11
- dbInfo: DatabaseConfigInterface;
12
- connection: mysql.Connection;
13
- isConnected: boolean;
14
- constructor(dbInfo: DatabaseConfigInterface, model: MyModel[]);
15
- init(): Promise<void>;
16
- private createDatabaseIfNotExist;
17
- pushModelToDB(): Promise<void>;
18
- pushViewToDB(viewDirectory: string): Promise<void>;
19
- waitUntilInitSuccess(interval: number): true | Promise<unknown>;
20
- query<T>(statment: string, parameter?: any[], isPrint?: boolean): Promise<T>;
21
- private printResultLength;
22
- getTableNameList(): Promise<string[]>;
23
- getViewNameList(): Promise<string[]>;
24
- getColumnFullList(tableName: string): Promise<mysql.RowDataPacket[]>;
25
- generateModelInterface(params: {
26
- appName: string;
27
- model: MyModel[];
28
- outputDirectory: string[];
29
- }): Promise<string>;
30
- generateModelConstStructure(params: {
31
- appName: string;
32
- model: MyModel[];
33
- outputDirectory: string[];
34
- }): Promise<string>;
35
- }