@quillsql/node 0.3.7 → 0.4.0

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,201 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.getSchemaColumnInfoBigQuery = exports.getForeignKeysBigQuery = exports.getColumnsByTableBigQuery = exports.getTablesBySchemaBigQuery = exports.getSchemaBigQuery = exports.runQueryBigQuery = exports.connectToBigQuery = exports.formatBigQueryConfig = void 0;
13
+ const bigquery_1 = require("@google-cloud/bigquery");
14
+ const textProcessing_1 = require("../utils/textProcessing");
15
+ function formatBigQueryConfig(connectionString) {
16
+ const jsonStartIndex = connectionString.indexOf("{");
17
+ if (jsonStartIndex === -1) {
18
+ throw new Error("Invalid input string. No JSON data found.");
19
+ }
20
+ const datasetName = connectionString.substring(0, jsonStartIndex).trim();
21
+ const jsonString = connectionString.substring(jsonStartIndex);
22
+ try {
23
+ const serviceAccount = JSON.parse(jsonString);
24
+ // Validate if required fields are present
25
+ if (!serviceAccount.project_id || !serviceAccount.private_key) {
26
+ throw new Error("Invalid service account JSON. Required fields are missing.");
27
+ }
28
+ return {
29
+ datasetName,
30
+ projectId: serviceAccount.project_id,
31
+ credentials: serviceAccount,
32
+ };
33
+ }
34
+ catch (error) {
35
+ throw new Error("Failed to parse JSON string: " + error);
36
+ }
37
+ }
38
+ exports.formatBigQueryConfig = formatBigQueryConfig;
39
+ function connectToBigQuery(config) {
40
+ return new bigquery_1.BigQuery(config);
41
+ }
42
+ exports.connectToBigQuery = connectToBigQuery;
43
+ function runQueryBigQuery(sql, bigQuery) {
44
+ return __awaiter(this, void 0, void 0, function* () {
45
+ const rows = yield bigQuery.query(sql);
46
+ if (!rows[0] || rows[0].length === 0)
47
+ return { fields: [], rows: [] };
48
+ const typedRows = rows[0];
49
+ const fields = Object.keys(typedRows[0]).map((name) => ({
50
+ name,
51
+ dataTypeID: 1043,
52
+ }));
53
+ fields.forEach((field) => {
54
+ typedRows.some((row) => {
55
+ if (row[field.name] === null)
56
+ return false;
57
+ field.dataTypeID = inferType(row[field.name]);
58
+ return true;
59
+ });
60
+ });
61
+ return {
62
+ fields: fields,
63
+ rows: typedRows,
64
+ };
65
+ });
66
+ }
67
+ exports.runQueryBigQuery = runQueryBigQuery;
68
+ function getSchemaBigQuery(bigQuery) {
69
+ return __awaiter(this, void 0, void 0, function* () {
70
+ const [datasets] = yield bigQuery.getDatasets();
71
+ const definedDatasets = datasets.map((dataset) => dataset.id);
72
+ const filtered = [];
73
+ definedDatasets.forEach((dataset) => {
74
+ if (dataset !== undefined) {
75
+ filtered.push(dataset);
76
+ }
77
+ });
78
+ return filtered;
79
+ });
80
+ }
81
+ exports.getSchemaBigQuery = getSchemaBigQuery;
82
+ function getTablesBySchemaBigQuery(bigQuery, schemaNames) {
83
+ return __awaiter(this, void 0, void 0, function* () {
84
+ const allColumns = yield Promise.all(schemaNames.map((schema) => __awaiter(this, void 0, void 0, function* () {
85
+ const sql = `SELECT table_name FROM ${schema}.INFORMATION_SCHEMA.TABLES WHERE table_type = 'BASE TABLE'`;
86
+ const rows = yield bigQuery.query(sql);
87
+ return rows[0].map((row) => {
88
+ return { tableName: row.table_name, schemaName: schema };
89
+ });
90
+ })));
91
+ return allColumns.flat();
92
+ });
93
+ }
94
+ exports.getTablesBySchemaBigQuery = getTablesBySchemaBigQuery;
95
+ function getColumnsByTableBigQuery(bigQuery, schemaName, tableName) {
96
+ return __awaiter(this, void 0, void 0, function* () {
97
+ const sql = `SELECT column_name FROM ${schemaName}.INFORMATION_SCHEMA.COLUMNS WHERE table_name = '${tableName}'`;
98
+ const rows = yield bigQuery.query(sql);
99
+ return rows[0].map((row) => row.column_name);
100
+ });
101
+ }
102
+ exports.getColumnsByTableBigQuery = getColumnsByTableBigQuery;
103
+ function getForeignKeysBigQuery(connection, schemaName, tableName, primaryKey) {
104
+ return __awaiter(this, void 0, void 0, function* () {
105
+ const depluralizedTableName = (0, textProcessing_1.depluralize)(tableName);
106
+ let sql = `SELECT column_name FROM ${schemaName}.INFORMATION_SCHEMA.COLUMNS
107
+ WHERE table_name != '${tableName}'
108
+ and (column_name = '${primaryKey}'
109
+ or column_name = '${depluralizedTableName}_${primaryKey}'
110
+ or column_name = '${depluralizedTableName}${(0, textProcessing_1.capitalize)(primaryKey)}')`;
111
+ const results = yield runQueryBigQuery(sql, connection);
112
+ let foreignKeysString = results.rows.map((key) => {
113
+ return key.column_name;
114
+ });
115
+ foreignKeysString = foreignKeysString.filter((key) => key !== "id" && key !== "_id_");
116
+ foreignKeysString = [...new Set(foreignKeysString)];
117
+ if (foreignKeysString.length === 0) {
118
+ sql = `SELECT column_name FROM ${schemaName}.INFORMATION_SCHEMA.COLUMNS
119
+ WHERE table_name != '${tableName}'
120
+ and (column_name like '${depluralizedTableName}%'
121
+ or column_name like '%_id'
122
+ or column_name like '%Id'
123
+ or column_name like '%_${primaryKey}'
124
+ or column_name like '%${(0, textProcessing_1.capitalize)(primaryKey)}')`;
125
+ const results = yield runQueryBigQuery(sql, connection);
126
+ foreignKeysString = results.rows.map((key) => {
127
+ return key.column_name;
128
+ });
129
+ foreignKeysString = [...new Set(foreignKeysString)];
130
+ }
131
+ return foreignKeysString;
132
+ });
133
+ }
134
+ exports.getForeignKeysBigQuery = getForeignKeysBigQuery;
135
+ function getSchemaColumnInfoBigQuery(connection, schemaName, tableNames) {
136
+ return __awaiter(this, void 0, void 0, function* () {
137
+ const allColumns = yield Promise.all(tableNames.map((tableName) => __awaiter(this, void 0, void 0, function* () {
138
+ const query = `
139
+ SELECT column_name as columnName, data_type as dataType
140
+ FROM ${tableName.schemaName}.INFORMATION_SCHEMA.COLUMNS
141
+ WHERE table_name = '${tableName.tableName}'
142
+ ORDER BY ordinal_position;
143
+ `;
144
+ const results = yield runQueryBigQuery(query, connection);
145
+ return {
146
+ tableName: `${tableName.schemaName}.${tableName.tableName}`,
147
+ displayName: `${tableName.schemaName}.${tableName.tableName}`,
148
+ columns: results.rows.map((row) => ({
149
+ columnName: row.columnName,
150
+ displayName: row.columnName,
151
+ dataTypeID: convertBigQueryTypeToPostgresOID(row.dataType),
152
+ fieldType: row.dataType,
153
+ })),
154
+ };
155
+ })));
156
+ return allColumns;
157
+ });
158
+ }
159
+ exports.getSchemaColumnInfoBigQuery = getSchemaColumnInfoBigQuery;
160
+ function convertBigQueryTypeToPostgresOID(type) {
161
+ const typeToOidMap = {
162
+ VARCHAR: 1043,
163
+ INTEGER: 23,
164
+ FLOAT: 700,
165
+ TIMESTAMP: 1114,
166
+ DATE: 1082,
167
+ };
168
+ const postgresType = typeToOidMap[type.toUpperCase()] || "VARCHAR"; // Default to 'text' if the type is not recognized
169
+ return typeToOidMap[postgresType] || 1043; // Default to OID for 'text' if the type is not recognized
170
+ }
171
+ function inferType(elem) {
172
+ if (typeof elem === "number") {
173
+ // Check if the number is a float or an integer
174
+ return Number.isInteger(elem) ? 23 : 700; // 23: integer, 700: real
175
+ }
176
+ if (typeof elem === "object") {
177
+ if (/^\d{4}-\d{2}-\d{2}$/.test(elem.value))
178
+ return 1082; // date
179
+ }
180
+ if (typeof elem === "string") {
181
+ // Attempt to infer date, time, and timestamp formats
182
+ // Date in YYYY-MM-DD format
183
+ if (/^\d{4}-\d{2}-\d{2}$/.test(elem))
184
+ return 1082; // date
185
+ // Date in MM\DD\YYYY or MM\DD\YY format
186
+ if (/^\d{2}\/\d{2}\/\d{2,4}$/.test(elem))
187
+ return 1082; // date
188
+ // Timestamp in YYYY-MM-DDTHH:MM:SS[.fraction] format
189
+ if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?$/.test(elem))
190
+ return 1114; // timestamp without timezone
191
+ // Timestamp in YYYY-MM-DDTHH:MM:SS[.fraction]Z format
192
+ if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/.test(elem))
193
+ return 1184; // timestamp with timezone
194
+ // Time in HH:MM:SS format
195
+ if (/^\d{2}:\d{2}:\d{2}$/.test(elem))
196
+ return 1083; // time
197
+ return 1043; // varchar
198
+ }
199
+ // Add more specific cases or different data types as needed
200
+ return 1043; // default or unknown type
201
+ }
@@ -9,10 +9,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
9
9
  });
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.CachedPool = void 0;
13
- const pg_1 = require("pg");
12
+ exports.CachedConnection = void 0;
14
13
  const redis_1 = require("redis");
15
14
  const Error_1 = require("../utils/Error");
15
+ const DatabaseHelper_1 = require("./DatabaseHelper");
16
16
  class PgError extends Error {
17
17
  // Add other properties if needed
18
18
  constructor(detail, hint, position) {
@@ -24,10 +24,11 @@ class PgError extends Error {
24
24
  }
25
25
  /** The TTL for new cache entries (default: 1h) */
26
26
  const DEFAULT_CACHE_TTL = 24 * 60 * 60;
27
- class CachedPool {
28
- constructor(config, cacheConfig = {}) {
27
+ class CachedConnection {
28
+ constructor(databaseType, config, cacheConfig = {}) {
29
29
  var _a;
30
- this.pool = new pg_1.Pool(config);
30
+ this.databaseType = databaseType;
31
+ this.pool = (0, DatabaseHelper_1.connectToDatabase)(databaseType, config);
31
32
  this.ttl = (_a = cacheConfig === null || cacheConfig === void 0 ? void 0 : cacheConfig.ttl) !== null && _a !== void 0 ? _a : DEFAULT_CACHE_TTL;
32
33
  this.cache = this.getCache(cacheConfig);
33
34
  }
@@ -35,14 +36,7 @@ class CachedPool {
35
36
  return __awaiter(this, void 0, void 0, function* () {
36
37
  try {
37
38
  if (!this.cache) {
38
- const results = yield this.pool.query(text, values);
39
- return {
40
- fields: results.fields.map((field) => ({
41
- name: field.name,
42
- dataTypeID: field.dataTypeID,
43
- })),
44
- rows: results.rows,
45
- };
39
+ return yield (0, DatabaseHelper_1.runQueryByDatabase)(this.databaseType, this.pool, text);
46
40
  }
47
41
  const key = `${this.orgId}:${text}`;
48
42
  const cachedResult = yield this.cache.get(key);
@@ -50,16 +44,10 @@ class CachedPool {
50
44
  return JSON.parse(cachedResult);
51
45
  }
52
46
  else {
53
- const newResult = yield this.pool.query(text, values);
47
+ const newResult = yield (0, DatabaseHelper_1.runQueryByDatabase)(this.databaseType, this.pool, text);
54
48
  const newResultString = JSON.stringify(newResult);
55
49
  yield this.cache.set(key, newResultString, "EX", DEFAULT_CACHE_TTL);
56
- return {
57
- fields: newResult.fields.map((field) => ({
58
- name: field.name,
59
- dataTypeID: field.dataTypeID,
60
- })),
61
- rows: newResult.rows,
62
- };
50
+ return newResult;
63
51
  }
64
52
  }
65
53
  catch (err) {
@@ -84,8 +72,8 @@ class CachedPool {
84
72
  }
85
73
  close() {
86
74
  return __awaiter(this, void 0, void 0, function* () {
87
- yield this.pool.end();
75
+ yield (0, DatabaseHelper_1.disconnectFromDatabase)(this.databaseType, this.pool);
88
76
  });
89
77
  }
90
78
  }
91
- exports.CachedPool = CachedPool;
79
+ exports.CachedConnection = CachedConnection;
@@ -0,0 +1,187 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.getColumnInfoBySchemaByDatabase = exports.getForiegnKeysByDatabase = exports.getColumnsByTableByDatabase = exports.getTablesBySchemaByDatabase = exports.getSchemasByDatabase = exports.disconnectFromDatabase = exports.runQueryByDatabase = exports.connectToDatabase = exports.getDatabaseCredentials = exports.DatabaseType = void 0;
13
+ const Postgres_1 = require("./Postgres");
14
+ const Snowflake_1 = require("./Snowflake");
15
+ const BigQuery_1 = require("./BigQuery");
16
+ const Mysql_1 = require("./Mysql");
17
+ var DatabaseType;
18
+ (function (DatabaseType) {
19
+ DatabaseType["postgres"] = "postgres";
20
+ DatabaseType["postgresql"] = "postgresql";
21
+ DatabaseType["snowflake"] = "snowflake";
22
+ DatabaseType["bigquery"] = "bigquery";
23
+ DatabaseType["mysql"] = "mysql";
24
+ })(DatabaseType || (exports.DatabaseType = DatabaseType = {}));
25
+ function getDatabaseCredentials(databaseType, connectionString) {
26
+ switch (databaseType.toLowerCase()) {
27
+ case "postgres":
28
+ return (0, Postgres_1.formatPostgresConfig)(connectionString);
29
+ case "postgresql":
30
+ return (0, Postgres_1.formatPostgresConfig)(connectionString);
31
+ case "snowflake":
32
+ return (0, Snowflake_1.formatSnowflakeConfig)(connectionString);
33
+ case "bigquery":
34
+ return (0, BigQuery_1.formatBigQueryConfig)(connectionString);
35
+ case "mysql":
36
+ return (0, Mysql_1.formatMysqlConfig)(connectionString);
37
+ default:
38
+ return undefined;
39
+ }
40
+ }
41
+ exports.getDatabaseCredentials = getDatabaseCredentials;
42
+ function connectToDatabase(databaseType, config) {
43
+ switch (databaseType.toLowerCase()) {
44
+ case "postgres":
45
+ return (0, Postgres_1.connectToPostgres)(config);
46
+ case "postgresql":
47
+ return (0, Postgres_1.connectToPostgres)(config);
48
+ case "snowflake":
49
+ return (0, Snowflake_1.connectToSnowflake)(config);
50
+ case "bigquery":
51
+ return (0, BigQuery_1.connectToBigQuery)(config);
52
+ case "mysql":
53
+ return (0, Mysql_1.connectToMysql)(config);
54
+ default:
55
+ return (0, Postgres_1.connectToPostgres)(config);
56
+ }
57
+ }
58
+ exports.connectToDatabase = connectToDatabase;
59
+ function runQueryByDatabase(databaseType, connection, sql) {
60
+ switch (databaseType.toLowerCase()) {
61
+ case "postgres":
62
+ return (0, Postgres_1.runQueryPostgres)(sql, connection);
63
+ case "postgresql":
64
+ return (0, Postgres_1.runQueryPostgres)(sql, connection);
65
+ case "snowflake":
66
+ return (0, Snowflake_1.runQuerySnowflake)(sql, connection);
67
+ case "bigquery":
68
+ return (0, BigQuery_1.runQueryBigQuery)(sql, connection);
69
+ case "mysql":
70
+ return (0, Mysql_1.runQueryMysql)(sql, connection);
71
+ default:
72
+ return undefined;
73
+ }
74
+ }
75
+ exports.runQueryByDatabase = runQueryByDatabase;
76
+ function disconnectFromDatabase(databaseType, database) {
77
+ switch (databaseType.toLowerCase()) {
78
+ case "postgres":
79
+ return (0, Postgres_1.disconnectFromPostgres)(database);
80
+ case "postgresql":
81
+ return (0, Postgres_1.disconnectFromPostgres)(database);
82
+ case "snowflake":
83
+ return (0, Snowflake_1.disconnectFromSnowflake)(database);
84
+ case "bigquery":
85
+ return; // BigQuery does not need to be disconnected
86
+ case "mysql":
87
+ return (0, Mysql_1.disconnectFromMysql)(database);
88
+ default:
89
+ return undefined;
90
+ }
91
+ }
92
+ exports.disconnectFromDatabase = disconnectFromDatabase;
93
+ function getSchemasByDatabase(databaseType, connection) {
94
+ return __awaiter(this, void 0, void 0, function* () {
95
+ switch (databaseType.toLowerCase()) {
96
+ case "postgres":
97
+ return (0, Postgres_1.getSchemasPostgres)(connection);
98
+ case "postgresql":
99
+ return (0, Postgres_1.getSchemasPostgres)(connection);
100
+ case "snowflake":
101
+ return (0, Snowflake_1.getSchemasSnowflake)(connection);
102
+ case "bigquery":
103
+ return (0, BigQuery_1.getSchemaBigQuery)(connection);
104
+ case "mysql":
105
+ return (0, Mysql_1.getSchemasMysql)(connection);
106
+ default:
107
+ return undefined;
108
+ }
109
+ });
110
+ }
111
+ exports.getSchemasByDatabase = getSchemasByDatabase;
112
+ // INFORMATION SCHEMA SELECTS
113
+ function getTablesBySchemaByDatabase(databaseType, connection, schemaName) {
114
+ return __awaiter(this, void 0, void 0, function* () {
115
+ switch (databaseType.toLowerCase()) {
116
+ case "postgres":
117
+ return (0, Postgres_1.getTablesBySchemaPostgres)(connection, schemaName);
118
+ case "postgresql":
119
+ return (0, Postgres_1.getTablesBySchemaPostgres)(connection, schemaName);
120
+ case "snowflake":
121
+ return (0, Snowflake_1.getTablesBySchemaSnowflake)(connection, schemaName);
122
+ case "bigquery":
123
+ return (0, BigQuery_1.getTablesBySchemaBigQuery)(connection, schemaName);
124
+ case "mysql":
125
+ return (0, Mysql_1.getTablesBySchemaMysql)(connection, schemaName);
126
+ default:
127
+ return undefined;
128
+ }
129
+ });
130
+ }
131
+ exports.getTablesBySchemaByDatabase = getTablesBySchemaByDatabase;
132
+ // INFORMATION SCHEMA SELECTS
133
+ function getColumnsByTableByDatabase(databaseType, connection, schemaName, tableName) {
134
+ return __awaiter(this, void 0, void 0, function* () {
135
+ switch (databaseType.toLowerCase()) {
136
+ case "postgres":
137
+ return (0, Postgres_1.getColumnsByTablePostgres)(connection, schemaName, tableName);
138
+ case "postgresql":
139
+ return (0, Postgres_1.getColumnsByTablePostgres)(connection, schemaName, tableName);
140
+ case "snowflake":
141
+ return (0, Snowflake_1.getColumnsByTableSnowflake)(connection, schemaName, tableName);
142
+ case "bigquery":
143
+ return (0, BigQuery_1.getColumnsByTableBigQuery)(connection, schemaName, tableName);
144
+ case "mysql":
145
+ return (0, Mysql_1.getColumnsByTableMysql)(connection, schemaName, tableName);
146
+ default:
147
+ return undefined;
148
+ }
149
+ });
150
+ }
151
+ exports.getColumnsByTableByDatabase = getColumnsByTableByDatabase;
152
+ function getForiegnKeysByDatabase(databaseType, connection, schemaName, tableName, primaryKey) {
153
+ return __awaiter(this, void 0, void 0, function* () {
154
+ switch (databaseType.toLowerCase()) {
155
+ case "postgres":
156
+ return (0, Postgres_1.getForeignKeysPostgres)(connection, schemaName, tableName, primaryKey);
157
+ case "postgresql":
158
+ return (0, Postgres_1.getForeignKeysPostgres)(connection, schemaName, tableName, primaryKey);
159
+ case "snowflake":
160
+ return (0, Snowflake_1.getForeignKeysSnowflake)(connection, schemaName, tableName, primaryKey);
161
+ case "bigquery":
162
+ return (0, BigQuery_1.getForeignKeysBigQuery)(connection, schemaName, tableName, primaryKey);
163
+ case "mysql":
164
+ return (0, Mysql_1.getForeignKeysMysql)(connection, schemaName, tableName, primaryKey);
165
+ default:
166
+ return undefined;
167
+ }
168
+ });
169
+ }
170
+ exports.getForiegnKeysByDatabase = getForiegnKeysByDatabase;
171
+ function getColumnInfoBySchemaByDatabase(databaseType, connection, schemaName, tables) {
172
+ switch (databaseType.toLowerCase()) {
173
+ case "postgres":
174
+ return (0, Postgres_1.getSchemaColumnInfoPostgress)(connection, schemaName, tables);
175
+ case "postgresql":
176
+ return (0, Postgres_1.getSchemaColumnInfoPostgress)(connection, schemaName, tables);
177
+ case "snowflake":
178
+ return (0, Snowflake_1.getSchemaColumnInfoSnowflake)(connection, schemaName, tables);
179
+ case "bigquery":
180
+ return (0, BigQuery_1.getSchemaColumnInfoBigQuery)(connection, schemaName, tables);
181
+ case "mysql":
182
+ return (0, Mysql_1.getSchemaColumnInfoMysql)(connection, schemaName, tables);
183
+ default:
184
+ return undefined;
185
+ }
186
+ }
187
+ exports.getColumnInfoBySchemaByDatabase = getColumnInfoBySchemaByDatabase;
@@ -0,0 +1,192 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.getSchemaColumnInfoMysql = exports.getForeignKeysMysql = exports.getColumnsByTableMysql = exports.getTablesBySchemaMysql = exports.getSchemasMysql = exports.runQueryMysql = exports.disconnectFromMysql = exports.connectToMysql = exports.formatMysqlConfig = void 0;
16
+ const mysql2_1 = __importDefault(require("mysql2"));
17
+ const url_1 = __importDefault(require("url"));
18
+ const textProcessing_1 = require("../utils/textProcessing");
19
+ function formatMysqlConfig(connectionString) {
20
+ const parsedUrl = url_1.default.parse(connectionString);
21
+ const [user, password] = (parsedUrl.auth || "").split(":");
22
+ return {
23
+ host: parsedUrl.hostname || "",
24
+ user: user || "",
25
+ password: password || "",
26
+ database: (parsedUrl.pathname || "").slice(1),
27
+ };
28
+ }
29
+ exports.formatMysqlConfig = formatMysqlConfig;
30
+ function connectToMysql(config) {
31
+ const pool = mysql2_1.default.createPool(Object.assign(Object.assign({}, config), { waitForConnections: true, connectionLimit: 10, queueLimit: 0 }));
32
+ return pool;
33
+ }
34
+ exports.connectToMysql = connectToMysql;
35
+ function disconnectFromMysql(connection) {
36
+ connection.end();
37
+ }
38
+ exports.disconnectFromMysql = disconnectFromMysql;
39
+ function runQueryMysql(sql, connection) {
40
+ return __awaiter(this, void 0, void 0, function* () {
41
+ const result = yield new Promise((resolve, reject) => {
42
+ connection.query(sql, (error, results, fields) => {
43
+ if (error) {
44
+ reject(error);
45
+ return;
46
+ }
47
+ const mappedFields = fields
48
+ ? fields.map((field) => ({
49
+ name: field.name,
50
+ dataTypeID: mysqlDataTypeIdToPostgresType(field.type || 1043), // Provide a default value for dataTypeID
51
+ }))
52
+ : [];
53
+ const processRows = Array.isArray(results)
54
+ ? results.map((row) => {
55
+ return JSON.parse(JSON.stringify(row));
56
+ })
57
+ : [];
58
+ resolve({ fields: mappedFields, rows: processRows });
59
+ });
60
+ });
61
+ return result;
62
+ });
63
+ }
64
+ exports.runQueryMysql = runQueryMysql;
65
+ function getSchemasMysql(connection) {
66
+ return __awaiter(this, void 0, void 0, function* () {
67
+ const sql = `SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA
68
+ WHERE schema_name != 'information_schema'
69
+ AND schema_name != 'performance_schema'
70
+ and schema_name != 'sys';`;
71
+ const results = yield runQueryMysql(sql, connection);
72
+ return results.rows.map((row) => row.SCHEMA_NAME);
73
+ });
74
+ }
75
+ exports.getSchemasMysql = getSchemasMysql;
76
+ function getTablesBySchemaMysql(connection, schemaNames) {
77
+ return __awaiter(this, void 0, void 0, function* () {
78
+ const allColumns = yield Promise.all(schemaNames.map((schema) => __awaiter(this, void 0, void 0, function* () {
79
+ const sql = `SELECT TABLE_NAME, TABLE_SCHEMA FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '${schema}'`;
80
+ const results = yield runQueryMysql(sql, connection);
81
+ return results.rows.map((row) => {
82
+ return { tableName: row.TABLE_NAME, schemaName: row.TABLE_SCHEMA };
83
+ });
84
+ })));
85
+ return allColumns.flat();
86
+ });
87
+ }
88
+ exports.getTablesBySchemaMysql = getTablesBySchemaMysql;
89
+ function getColumnsByTableMysql(connection, schemaName, tableName) {
90
+ return __awaiter(this, void 0, void 0, function* () {
91
+ const sql = `SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '${schemaName}' AND TABLE_NAME = '${tableName}'`;
92
+ const results = yield runQueryMysql(sql, connection);
93
+ return results.rows.map((row) => row.COLUMN_NAME);
94
+ });
95
+ }
96
+ exports.getColumnsByTableMysql = getColumnsByTableMysql;
97
+ function getForeignKeysMysql(connection, schemaName, tableName, primaryKey) {
98
+ return __awaiter(this, void 0, void 0, function* () {
99
+ const depluralizedTableName = (0, textProcessing_1.depluralize)(tableName);
100
+ let sql = `SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS
101
+ WHERE TABLE_SCHEMA = '${schemaName}'
102
+ and table_name != '${tableName}'
103
+ and (column_name = '${primaryKey}'
104
+ or column_name = '${depluralizedTableName}\\_${primaryKey}'
105
+ or column_name = '${depluralizedTableName}${(0, textProcessing_1.capitalize)(primaryKey)}' )`;
106
+ const results = yield runQueryMysql(sql, connection);
107
+ let foreignKeysString = results.rows.map((key) => {
108
+ return key.COLUMN_NAME;
109
+ });
110
+ // remove any foreignKeyStrings that are just 'id'
111
+ foreignKeysString = foreignKeysString.filter((key) => key !== "id" && key !== "_id_");
112
+ foreignKeysString = [...new Set(foreignKeysString)];
113
+ if (foreignKeysString.length === 0) {
114
+ sql = `SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS
115
+ WHERE TABLE_SCHEMA = '${schemaName}'
116
+ and table_name != '${tableName}'
117
+ and (column_name like '${depluralizedTableName}%'
118
+ or column_name like '%\\_id'
119
+ or column_name like '%Id'
120
+ or column_name like '%\\_${primaryKey}'
121
+ or column_name like '%${(0, textProcessing_1.capitalize)(primaryKey)}')`;
122
+ const results = yield runQueryMysql(sql, connection);
123
+ foreignKeysString = results.rows.map((key) => {
124
+ return key.COLUMN_NAME;
125
+ });
126
+ foreignKeysString = [...new Set(foreignKeysString)];
127
+ }
128
+ return foreignKeysString;
129
+ });
130
+ }
131
+ exports.getForeignKeysMysql = getForeignKeysMysql;
132
+ function getSchemaColumnInfoMysql(connection, schemaName, tableNames) {
133
+ return __awaiter(this, void 0, void 0, function* () {
134
+ const allColumns = yield Promise.all(tableNames.map((tableName) => __awaiter(this, void 0, void 0, function* () {
135
+ const query = `
136
+ SELECT COLUMN_NAME as columnName,
137
+ DATA_TYPE as dataType FROM INFORMATION_SCHEMA.COLUMNS
138
+ WHERE TABLE_SCHEMA = '${tableName.schemaName}'
139
+ AND TABLE_NAME = '${tableName.tableName}'
140
+ `;
141
+ const results = yield runQueryMysql(query, connection);
142
+ return {
143
+ tableName: `${tableName.schemaName}.${tableName.tableName}`,
144
+ displayName: `${tableName.schemaName}.${tableName.tableName}`,
145
+ columns: results.rows.map((row) => ({
146
+ columnName: row.columnName,
147
+ displayName: row.columnName,
148
+ dataTypeID: mysqlTextDataTypeToPostgresOID(row.dataType),
149
+ fieldType: row.dataType,
150
+ })),
151
+ };
152
+ })));
153
+ return allColumns;
154
+ });
155
+ }
156
+ exports.getSchemaColumnInfoMysql = getSchemaColumnInfoMysql;
157
+ function mysqlTextDataTypeToPostgresOID(type) {
158
+ switch (type) {
159
+ case "bigint": // int
160
+ return 23;
161
+ case "tinyint": // int
162
+ return 23;
163
+ case "float": // float
164
+ return 700;
165
+ case "varchar": // varchar
166
+ return 1043;
167
+ case "timestamp": // date
168
+ return 1082;
169
+ default: // varchar
170
+ return 1043;
171
+ }
172
+ }
173
+ function mysqlDataTypeIdToPostgresType(type) {
174
+ switch (type) {
175
+ case 8: // int
176
+ return 23;
177
+ case 3: // int
178
+ return 23;
179
+ case 2: // int
180
+ return 23;
181
+ case 5: // float
182
+ return 700;
183
+ case 253: // varchar
184
+ return 1043;
185
+ case 7: // date
186
+ return 1082;
187
+ case 7: // date
188
+ return 1082;
189
+ default: // varchar
190
+ return 1043;
191
+ }
192
+ }