This repository has been archived by the owner on Jun 4, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 281
/
Copy pathSql.js
243 lines (218 loc) · 7.79 KB
/
Sql.js
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
import Sequelize from 'sequelize';
import {parseSQL} from '../../parse';
import {
dissoc,
gt,
has,
merge,
omit,
sort,
trim,
uniq,
values
} from 'ramda';
import {DIALECTS} from '../../../app/constants/constants';
import Logger from '../../logger';
import fs from 'fs';
// http://stackoverflow.com/questions/32037385/using-sequelize-with-redshift
const REDSHIFT_OPTIONS = {
dialect: 'postgres',
pool: false,
keepDefaultTimezone: true, // avoid SET TIMEZONE
databaseVersion: '8.0.2', // avoid SHOW SERVER_VERSION
dialectOptions: {
ssl: true
}
};
const SHOW_TABLES_QUERY = {
[DIALECTS.MYSQL]: 'SHOW TABLES',
[DIALECTS.MARIADB]: 'SHOW TABLES',
[DIALECTS.SQLITE]: 'SELECT name FROM sqlite_master WHERE type="table"',
[DIALECTS.MSSQL]: (
'SELECT TABLE_NAME FROM ' +
'information_schema.tables'
),
[DIALECTS.POSTGRES]: `
SELECT table_schema || '."' || table_name || '"'
FROM information_schema.tables
WHERE table_type != 'VIEW'
AND table_schema != 'pg_catalog'
AND table_schema != 'information_schema'
ORDER BY table_schema, table_name
`,
[DIALECTS.REDSHIFT]: `
SELECT table_schema || '."' || table_name || '"'
FROM information_schema.tables
WHERE table_type != 'VIEW'
AND table_schema != 'pg_catalog'
AND table_schema != 'information_schema'
ORDER BY table_schema, table_name
`
};
function createClient(connection) {
const {
username, password, database, port, dialect, storage, host, ssl
} = connection;
let options = {
dialect, host, port, storage,
dialectOptions: {ssl},
logging: Logger.log,
benchmark: true
};
if (dialect === 'redshift') {
Sequelize.HSTORE.types.postgres.oids.push('dummy');
options = merge(options, REDSHIFT_OPTIONS);
} else if (dialect === 'mssql') {
/*
* See all options here:
* http://tediousjs.github.io/tedious/api-connection.html
*/
options.dialectOptions.encrypt = connection.encrypt;
const trimmedInstanceName = trim(connection.instanceName || '');
if (trimmedInstanceName) {
/*
* port is mutually exclusive with instance name
* see https://github.com/sequelize/sequelize/issues/3097
*/
options = omit(['port'], options);
options.dialectOptions.instanceName = trimmedInstanceName;
}
['connectTimeout', 'requestTimeout'].forEach(timeoutSetting => {
if (has(timeoutSetting, connection) &&
!isNaN(parseInt(connection[timeoutSetting], 10))) {
options.dialectOptions[timeoutSetting] =
connection[timeoutSetting];
}
});
}
return new Sequelize(
database, username, password, options,
);
}
export function connect(connection) {
Logger.log('' +
'Attempting to authenticate with connection ' +
`${JSON.stringify(dissoc('password', connection), null, 2)} ` +
'(password omitted)'
);
if (connection.dialect !== 'sqlite') {
return createClient(connection).authenticate();
}
/*
* sqlite's createClient will create a sqlite file even if it
* doesn't exist. that means that bad storage parameters won't
* reject. Instead of trying `authenticate`, just check if
* the file exists.
*/
return new Promise(function(resolve, reject) {
if (fs.existsSync(connection.storage)) {
resolve();
} else {
reject(new Error(`SQLite file at path "${connection.storage}" does not exist.`));
}
});
}
export function query(queryString, connection) {
return createClient(connection).query(
queryString,
{type: Sequelize.QueryTypes.SELECT}
).then(results => {
return parseSQL(results);
});
}
export function tables(connection) {
return createClient(connection).query(
SHOW_TABLES_QUERY[connection.dialect],
{type: Sequelize.QueryTypes.SELECT}
).then(tableList => {
let tableNames;
if (connection.dialect === 'postgres' || connection.dialect === 'redshift') {
tableNames = tableList.map(data => {
let tableName = String(data['?column?']);
// if schema is public, remove it from table name
if (tableName.startsWith('public.')) {
tableName = tableName.substring(7);
// if table name is lowercase, remove unnecessary quote marks
const lowercase = tableName.toLowerCase();
if (tableName === lowercase) {
tableName = lowercase.substring(1, lowercase.length - 1);
}
}
return tableName;
});
} else if (connection.dialect === 'sqlite') {
tableNames = tableList;
} else {
tableNames = tableList.map(object => values(object)[0]);
}
return uniq(sort((a, b) => gt(a, b) ? 1 : -1, tableNames));
});
}
export function schemas(connection) {
const {database, dialect} = connection;
// Suppressing ESLint cause single quote strings beside template strings
// would be inconvenient when changed queries
/* eslint-disable quotes */
let queryString;
switch (dialect) {
case DIALECTS.MYSQL:
case DIALECTS.MARIADB:
queryString = `SELECT table_name, column_name, data_type FROM information_schema.columns ` +
`WHERE table_schema = '${database}' ORDER BY table_name`;
break;
case DIALECTS.SQLITE:
return sqlite_schemas(connection);
case DIALECTS.POSTGRES:
case DIALECTS.REDSHIFT:
queryString = `
SELECT table_schema || '."' || table_name || '"', column_name, data_type
FROM information_schema.columns
WHERE table_catalog = '${database}'
AND table_schema != 'pg_catalog'
AND table_schema != 'information_schema'
ORDER BY table_schema, table_name, column_name
`;
break;
case DIALECTS.MSSQL:
queryString = `
SELECT T.name AS Table_Name, C.name AS Column_Name, P.name AS Data_Type
FROM sys.objects AS T
JOIN sys.columns AS C ON T.object_id = C.object_id
JOIN sys.types AS P ON C.system_type_id = P.system_type_id
WHERE T.type_desc = 'USER_TABLE';
`;
break;
default:
throw new Error(`Dialect ${dialect} is not one of the SQL DIALECTS`);
}
/* eslint-enable quotes */
return query(queryString, connection);
}
function sqlite_schemas(connection) {
// Unfortunately, we need to make one query per table
return tables(connection).then(tableNames => {
const queries = tableNames.map(tableName => {
return createClient(connection).query(
`PRAGMA table_info(${tableName})`,
{type: Sequelize.QueryTypes.SELECT}
);
});
return Promise.all(queries).then(responses => {
const schemasResponse = {
columnnames: ['table_name', 'column_name', 'data_type'],
rows: []
};
responses.forEach((response, index) => {
const tableName = tableNames[index];
response.forEach(row => {
schemasResponse.rows.push([
tableName,
row.name,
row.type
]);
});
});
return schemasResponse;
});
});
}