gg-mysql-connector 1.0.5

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,233 @@
1
+ import chalk from "chalk"
2
+ import fs from "fs"
3
+ import path from "path"
4
+ import ModelGenerator from "./ModelGenerator"
5
+ import { columnType, MyModel } from "./myModel"
6
+
7
+ export default class MyDBMigration<Main> {
8
+ MyDB: ModelGenerator
9
+ onetimeLoadColumnContent: {
10
+ COLUMN_NAME: string
11
+ DATA_TYPE: columnType
12
+ TABLE_NAME: string
13
+ COLUMN_DEFAULT: string
14
+ COLUMN_KEY: string
15
+ }[]
16
+ constructor(connection: ModelGenerator) {
17
+ this.MyDB = connection
18
+ this.onetimeLoadColumnContent = []
19
+ }
20
+
21
+ async migrateTable(model: MyModel[]) {
22
+ let data = model.filter(
23
+ (row) =>
24
+ row.tableName !== "sessions" && row.tableName.search("prisma") < 0
25
+ )
26
+ let index = 1
27
+ for (let row of data) {
28
+ console.log(chalk.bgBlue(`${index}/${data.length} ${row.tableName}`))
29
+ await this.createTableIfNotExist(row.tableName)
30
+ this.onetimeLoadColumnContent = []
31
+ await this.loadColumnContentIfEmpty()
32
+ index++
33
+
34
+ for (let col of row.columns) {
35
+ console.log(`${row.tableName} (${col.DATA_TYPE}) - ${col.COLUMN_NAME} `)
36
+
37
+ if (col.COLUMN_NAME === "id" && col.AUTO_INCREMENT === true) {
38
+ if (
39
+ (await this.checkIsPrimaryKey(
40
+ this.MyDB.dbInfo.database,
41
+ row.tableName,
42
+ col.COLUMN_NAME
43
+ )) === false
44
+ )
45
+ await this.MyDB.query(
46
+ `ALTER TABLE ${row.tableName} ADD PRIMARY KEY(id);`
47
+ )
48
+ }
49
+
50
+ const AutoIncrement = col.AUTO_INCREMENT ? "AUTO_INCREMENT" : ""
51
+ const columnDefault = col.COLUMN_DEFAULT
52
+ ? `DEFAULT ${col.COLUMN_DEFAULT}`
53
+ : ""
54
+ const isColumnChange = await this.checkIsColumnDataTypeChange(
55
+ row.tableName,
56
+ col.COLUMN_NAME,
57
+ col.DATA_TYPE,
58
+ col.COLUMN_DEFAULT
59
+ )
60
+ if (isColumnChange) {
61
+ const isColumnExist = await this.columnInTableExist(
62
+ row.tableName,
63
+ col.COLUMN_NAME
64
+ )
65
+ if (!isColumnExist) {
66
+ await this.MyDB.query(
67
+ `ALTER TABLE ${row.tableName} ADD COLUMN ${col.COLUMN_NAME} ${col.DATA_TYPE} ${AutoIncrement} ${columnDefault}`
68
+ )
69
+ } else {
70
+ await this.MyDB.query(
71
+ `ALTER TABLE ${row.tableName} MODIFY COLUMN ${col.COLUMN_NAME} ${col.DATA_TYPE} ${AutoIncrement} ${columnDefault}`
72
+ )
73
+ }
74
+ }
75
+ await this.alterUniqueKey(row.tableName, col.COLUMN_NAME, col.IS_UNIQUE)
76
+ await this.alterIndex(row.tableName, col.COLUMN_NAME, col.IS_INDEX)
77
+ }
78
+ }
79
+ console.log("migrate table done")
80
+ }
81
+
82
+ private async createTableIfNotExist(tableName: string) {
83
+ await this.MyDB.query(
84
+ `CREATE TABLE IF NOT EXISTS ${tableName} (id INT(11) AUTO_INCREMENT PRIMARY KEY)`
85
+ )
86
+ }
87
+
88
+ private async columnInTableExist(tableName: string, columnName: string) {
89
+ await this.loadColumnContentIfEmpty()
90
+ let result = this.onetimeLoadColumnContent.filter(
91
+ (row) => row.COLUMN_NAME === columnName && row.TABLE_NAME === tableName
92
+ )
93
+ if (result.length) return true
94
+ else return false
95
+ }
96
+ private async loadColumnContentIfEmpty() {
97
+ if (this.onetimeLoadColumnContent.length === 0) {
98
+ this.onetimeLoadColumnContent = (await this.MyDB.query(
99
+ `SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '${this.MyDB.dbInfo.database}'`,
100
+ undefined,
101
+ false
102
+ )) as any
103
+ }
104
+ }
105
+
106
+ private async checkIsColumnDataTypeChange(
107
+ tableName: string,
108
+ columnName: string,
109
+ dataType: columnType,
110
+ columnDefault: string | null | undefined | number
111
+ ) {
112
+ await this.loadColumnContentIfEmpty()
113
+ let temp = this.onetimeLoadColumnContent.filter(
114
+ (row: any) =>
115
+ row.TABLE_NAME === tableName && row.COLUMN_NAME === columnName
116
+ )
117
+ if (columnDefault === undefined) columnDefault = "NULL"
118
+ if (columnDefault === null) columnDefault = "NULL"
119
+
120
+ if (temp.length > 0) {
121
+ if (temp[0].DATA_TYPE !== dataType) {
122
+ console.log(chalk.green`${temp[0].DATA_TYPE} change to ${dataType}`)
123
+ return true
124
+ }
125
+ if (temp[0].COLUMN_DEFAULT !== columnDefault) {
126
+ console.log(
127
+ chalk.green`${temp[0].COLUMN_DEFAULT} change to ${columnDefault}`
128
+ )
129
+ return true
130
+ }
131
+ return false
132
+ } else {
133
+ console.log(chalk.red`${columnName} not found`)
134
+ return true
135
+ }
136
+ }
137
+ async alterUniqueKey(
138
+ tableName: string,
139
+ columnName: string,
140
+ IS_UNIQUE: boolean | undefined
141
+ ) {
142
+ const data = this.onetimeLoadColumnContent.find(
143
+ (row) => row.COLUMN_NAME === columnName && row.TABLE_NAME === tableName
144
+ )
145
+ if (data) {
146
+ if (
147
+ (data.COLUMN_KEY === "UNI" && !IS_UNIQUE) ||
148
+ (data.COLUMN_KEY !== "UNI" && IS_UNIQUE === true)
149
+ )
150
+ if (IS_UNIQUE === true) {
151
+ await this.MyDB.query(
152
+ `ALTER TABLE ${tableName} ADD UNIQUE (${columnName});`
153
+ )
154
+ } else {
155
+ await this.MyDB.query(
156
+ `ALTER TABLE ${tableName} DROP INDEX ${columnName};`
157
+ )
158
+ }
159
+ }
160
+ }
161
+
162
+ async alterIndex(
163
+ tableName: string,
164
+ columnName: string,
165
+ IS_INDEX: boolean | undefined
166
+ ) {
167
+ const data = this.onetimeLoadColumnContent.find(
168
+ (row) => row.COLUMN_NAME === columnName && row.TABLE_NAME === tableName
169
+ )
170
+ if (data) {
171
+ if (
172
+ (data.COLUMN_KEY === "MUL" && !IS_INDEX) ||
173
+ (data.COLUMN_KEY !== "MUL" && IS_INDEX === true)
174
+ )
175
+ if (IS_INDEX === true) {
176
+ await this.MyDB.query(
177
+ `ALTER TABLE ${tableName} ADD INDEX (${columnName});`
178
+ )
179
+ } else {
180
+ await this.MyDB.query(`DROP INDEX ${columnName} ON ${tableName};`)
181
+ }
182
+ }
183
+ }
184
+
185
+ async migrateView(viewDirectory: string) {
186
+ if (!fs.existsSync(viewDirectory)) {
187
+ return 0
188
+ }
189
+ let fileList: string[] = (await fs.readdirSync(
190
+ path.join(viewDirectory)
191
+ )) as string[]
192
+ let unSuccessUpdateViewList: string[] = fileList
193
+ let loopCount = 0
194
+ while (unSuccessUpdateViewList.length > 0) {
195
+ for (const viewFileName of unSuccessUpdateViewList) {
196
+ const filePath = path.join(viewDirectory, viewFileName)
197
+ const content = fs.readFileSync(filePath, "utf8")
198
+ process.stdout.write(
199
+ `loop : ${loopCount} unUpdate : ${unSuccessUpdateViewList.length} update view ${viewFileName}`
200
+ )
201
+ await this.MyDB.query(content)
202
+ .then((result) => {
203
+ process.stdout.write(" " + chalk.bgGreen(`success`))
204
+ unSuccessUpdateViewList = unSuccessUpdateViewList.filter(
205
+ (row) => row !== viewFileName
206
+ )
207
+ })
208
+ .catch((_error) => {
209
+ process.stdout.write(" " + chalk.bgRed(`fail`))
210
+ })
211
+ .finally(() => {
212
+ console.log("")
213
+ })
214
+ }
215
+ }
216
+ }
217
+ async checkIsPrimaryKey(
218
+ databaseName: string,
219
+ tableName: string,
220
+ columnName: string
221
+ ) {
222
+ let result: any = await this.MyDB.query(`SELECT *
223
+ FROM INFORMATION_SCHEMA.COLUMNS
224
+ WHERE TABLE_SCHEMA='${databaseName}'
225
+ AND TABLE_NAME='${tableName}'
226
+ AND COLUMN_NAME='${columnName}'`)
227
+ console.log("result", result)
228
+ if (result.length) {
229
+ if (result[0].COLUMN_KEY === "PRI") return true
230
+ else return false
231
+ } else return false
232
+ }
233
+ }
package/src/app_INF.ts ADDED
@@ -0,0 +1,12 @@
1
+ export default interface app_INF { item : {
2
+ id: number;
3
+ name: "pen" | "ruler";
4
+ price: number;
5
+ description: string; }
6
+ user : {
7
+ id: number;
8
+ name: string; }
9
+ test_view : {
10
+ id: number;
11
+ name: string;
12
+ itemName: string; } }
package/src/index.ts ADDED
@@ -0,0 +1,4 @@
1
+ export { MyModel, columnContent, columnType } from "./myModel"
2
+ export { DatabaseConfigInterface } from "./ModelGenerator"
3
+ export { default as ModelGenerator } from "./ModelGenerator"
4
+ export { default as GGMySQLConnector } from "./GGMySQLConnector"
package/src/myModel.ts ADDED
@@ -0,0 +1,38 @@
1
+
2
+ export type columnType =
3
+ | "int"
4
+ | "tinyint"
5
+ | "float"
6
+ | "double"
7
+ | "text"
8
+ | "varchar(8)"
9
+ | "varchar(16)"
10
+ | "varchar(32)"
11
+ | "varchar(64)"
12
+ | "varchar(128)"
13
+ | "varchar(256)"
14
+ | "varchar(512)"
15
+ | "longtext"
16
+ | "date"
17
+ | "time"
18
+ | "datetime"
19
+ export interface columnContent {
20
+ COLUMN_NAME: string
21
+ DATA_TYPE: columnType
22
+ COLUMN_DEFAULT?: string | number | null
23
+ AUTO_INCREMENT?: boolean
24
+ POSSIBLE_VALUE?: any[]
25
+ IS_UNIQUE?: boolean
26
+ IS_INDEX?: boolean
27
+ }
28
+ export interface MyModel {
29
+ tableName: string
30
+ columns: [
31
+ ...columnContent[]
32
+ ]
33
+ meaning?: string
34
+ }
35
+ // export interface MyModelView {
36
+ // viewName: string
37
+ // relatedTableName: (keyof hotel_INF)[]
38
+ // }
@@ -0,0 +1,4 @@
1
+ CREATE
2
+ OR REPLACE VIEW test_view AS
3
+ SELECT user.*,item.name AS itemName FROM user
4
+ LEFT JOIN item on user.name = item.name
package/tsconfig.json ADDED
@@ -0,0 +1,110 @@
1
+ {
2
+ "compilerOptions": {
3
+ /* Visit https://aka.ms/tsconfig to read more about this file */
4
+
5
+ /* Projects */
6
+ // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
7
+ // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
8
+ // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
9
+ // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
10
+ // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
11
+ // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
12
+
13
+ /* Language and Environment */
14
+ "target": "es2017", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
15
+ // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
16
+ // "jsx": "preserve", /* Specify what JSX code is generated. */
17
+ // "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
18
+ // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
19
+ // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
20
+ // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
21
+ // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
22
+ // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
23
+ // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
24
+ // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
25
+ // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
26
+
27
+ /* Modules */
28
+ "module": "commonjs", /* Specify what module code is generated. */
29
+ // "rootDir": "./", /* Specify the root folder within your source files. */
30
+ // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
31
+ // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
32
+ // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
33
+ // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
34
+ // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
35
+ // "types": [], /* Specify type package names to be included without being referenced in a source file. */
36
+ // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
37
+ // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
38
+ // "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
39
+ // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
40
+ // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
41
+ // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
42
+ // "resolveJsonModule": true, /* Enable importing .json files. */
43
+ // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
44
+ // "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
45
+
46
+ /* JavaScript Support */
47
+ // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
48
+ // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
49
+ // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
50
+
51
+ /* Emit */
52
+ "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
53
+ // "declarationMap": true, /* Create sourcemaps for d.ts files. */
54
+ // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
55
+ // "sourceMap": true, /* Create source map files for emitted JavaScript files. */
56
+ // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
57
+ // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
58
+ // "outDir": "./", /* Specify an output folder for all emitted files. */
59
+ // "removeComments": true, /* Disable emitting comments. */
60
+ // "noEmit": true, /* Disable emitting files from a compilation. */
61
+ // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
62
+ // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
63
+ // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
64
+ // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
65
+ // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
66
+ // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
67
+ // "newLine": "crlf", /* Set the newline character for emitting files. */
68
+ // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
69
+ // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
70
+ // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
71
+ // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
72
+ // "declarationDir": "./", /* Specify the output directory for generated declaration files. */
73
+
74
+ /* Interop Constraints */
75
+ // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
76
+ // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
77
+ // "isolatedDeclarations": true, /* Require sufficient annotation on exports so other tools can trivially generate declaration files. */
78
+ // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
79
+ "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
80
+ // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
81
+ "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
82
+
83
+ /* Type Checking */
84
+ "strict": true, /* Enable all strict type-checking options. */
85
+ // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
86
+ // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
87
+ // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
88
+ // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
89
+ // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
90
+ // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
91
+ // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
92
+ // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
93
+ // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
94
+ // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
95
+ // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
96
+ // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
97
+ // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
98
+ // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
99
+ // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
100
+ // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
101
+ // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
102
+ // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
103
+
104
+ /* Completeness */
105
+ // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
106
+ "skipLibCheck": true /* Skip type checking all .d.ts files. */,
107
+ "outDir": "./dist"
108
+
109
+ }
110
+ }