-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
BaseDriver.js
406 lines (343 loc) Β· 10.4 KB
/
BaseDriver.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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
import { reduce } from 'ramda';
import fs from 'fs';
import { getEnv, isFilePath, isSslKey, isSslCert } from '@cubejs-backend/shared';
import { cancelCombinator } from './utils';
const sortByKeys = (unordered) => {
const ordered = {};
Object.keys(unordered).sort().forEach((key) => {
ordered[key] = unordered[key];
});
return ordered;
};
const DbTypeToGenericType = {
'timestamp without time zone': 'timestamp',
integer: 'int',
int8: 'int',
int4: 'int',
int2: 'int',
'character varying': 'text',
varchar: 'text',
nvarchar: 'text',
text: 'text',
string: 'text',
boolean: 'boolean',
bigint: 'bigint',
time: 'string',
datetime: 'timestamp',
date: 'date',
'double precision': 'decimal'
};
const DB_BIG_INT_MAX = BigInt('9223372036854775807');
const DB_BIG_INT_MIN = BigInt('-9223372036854775808');
const DB_INT_MAX = 2147483647;
const DB_INT_MIN = -2147483648;
// Order of keys is important here: from more specific to less specific
const DbTypeValueMatcher = {
timestamp: (v) => v instanceof Date || v.toString().match(/^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d/),
date: (v) => v instanceof Date || v.toString().match(/^\d\d\d\d-\d\d-\d\d$/),
int: (v) => {
if (Number.isInteger(v)) {
return (v <= DB_INT_MAX && v >= DB_INT_MIN);
}
if (v.toString().match(/^[-]?\d+$/)) {
const value = BigInt(v.toString());
return value <= DB_INT_MAX && value >= DB_INT_MIN;
}
return false;
},
bigint: (v) => {
if (Number.isInteger(v)) {
return (v <= DB_BIG_INT_MAX && v >= DB_BIG_INT_MIN);
}
if (v.toString().match(/^[-]?\d+$/)) {
const value = BigInt(v.toString());
return value <= DB_BIG_INT_MAX && value >= DB_BIG_INT_MIN;
}
return false;
},
decimal: (v) => {
if (v instanceof Number) {
return true;
}
return v.toString().match(/^[-]?\d+(\.\d+)?$/);
},
boolean: (v) => v === false || v === true || v.toString().toLowerCase() === 'true' || v.toString().toLowerCase() === 'false',
string: (v) => v.length < 256,
text: () => true
};
export class BaseDriver {
/**
* Workaround for Type 'BaseDriver' has no construct signatures.
*
* @param {Object} [options]
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
constructor(options) {
//
}
informationSchemaQuery() {
return `
SELECT columns.column_name as ${this.quoteIdentifier('column_name')},
columns.table_name as ${this.quoteIdentifier('table_name')},
columns.table_schema as ${this.quoteIdentifier('table_schema')},
columns.data_type as ${this.quoteIdentifier('data_type')}
FROM information_schema.columns
WHERE columns.table_schema NOT IN ('information_schema', 'mysql', 'performance_schema', 'sys')
`;
}
getSslOptions() {
let ssl;
const sslOptions = [
{ name: 'ca', canBeFile: true, envKey: 'CUBEJS_DB_SSL_CA', validate: isSslCert },
{ name: 'cert', canBeFile: true, envKey: 'CUBEJS_DB_SSL_CERT', validate: isSslCert },
{ name: 'key', canBeFile: true, envKey: 'CUBEJS_DB_SSL_KEY', validate: isSslKey },
{ name: 'ciphers', envKey: 'CUBEJS_DB_SSL_CIPHERS' },
{ name: 'passphrase', envKey: 'CUBEJS_DB_SSL_PASSPHRASE' },
{ name: 'servername', envKey: 'CUBEJS_DB_SSL_SERVERNAME' },
];
if (
getEnv('dbSsl') ||
getEnv('dbSslRejectUnauthorized') ||
sslOptions.find(o => !!process.env[o.value])
) {
ssl = sslOptions.reduce(
(agg, { name, envKey, canBeFile, validate }) => {
if (process.env[envKey]) {
const value = process.env[envKey];
if (validate(value)) {
return {
...agg,
...{ [name]: value }
};
}
if (canBeFile && isFilePath(value)) {
if (!fs.existsSync(value)) {
throw new Error(
`Unable to find ${name} from path: "${value}"`,
);
}
const file = fs.readFileSync(value, 'utf8');
if (validate(file)) {
return {
...agg,
...{ [name]: file }
};
}
throw new Error(
`Content of the file from ${envKey} is not a valid SSL ${name}.`,
);
}
throw new Error(
`${envKey} is not a valid SSL ${name}. If it's a path, please specify it correctly`,
);
}
return agg;
},
{}
);
ssl.rejectUnauthorized = getEnv('dbSslRejectUnauthorized');
}
return ssl;
}
/**
* @abstract
*/
async testConnection() {
throw new Error('Not implemented');
}
/**
* @abstract
* @param {string} query
* @param {Array<unknown>} [values]
* @return {Promise<Array<any>>}
*/
async query(query, values) {
throw new Error('Not implemented');
}
async downloadQueryResults(query, values) {
const rows = await this.query(query, values);
if (rows.length === 0) {
throw new Error('Unable to detect column types for pre-aggregation on empty values in readOnly mode');
}
const fields = Object.keys(rows[0]);
const types = fields.map(field => ({
name: field,
type: Object.keys(DbTypeValueMatcher).find(
type => !rows.filter(row => !!row[field]).find(row => !DbTypeValueMatcher[type](row[field])) &&
rows.find(row => !!row[field])
) || 'text'
}));
return {
rows,
types,
};
}
readOnly() {
return false;
}
tablesSchema() {
const query = this.informationSchemaQuery();
const reduceCb = (result, i) => {
let schema = (result[i.table_schema] || {});
const tables = (schema[i.table_name] || []);
tables.push({ name: i.column_name, type: i.data_type, attributes: i.key_type ? ['primaryKey'] : [] });
tables.sort();
schema[i.table_name] = tables;
schema = sortByKeys(schema);
result[i.table_schema] = schema;
return sortByKeys(result);
};
return this.query(query).then(data => reduce(reduceCb, {}, data));
}
/**
* @param {string} schemaName
* @return {Promise<Array<unknown>>}
*/
async createSchemaIfNotExists(schemaName) {
return this.query(
`SELECT schema_name FROM information_schema.schemata WHERE schema_name = ${this.param(0)}`,
[schemaName]
).then((schemas) => {
if (schemas.length === 0) {
return this.query(`CREATE SCHEMA IF NOT EXISTS ${schemaName}`);
}
return null;
});
}
getTablesQuery(schemaName) {
return this.query(
`SELECT table_name FROM information_schema.tables WHERE table_schema = ${this.param(0)}`,
[schemaName]
);
}
loadPreAggregationIntoTable(preAggregationTableName, loadSql, params, options) {
return this.query(loadSql, params, options);
}
/**
* @param {string} tableName
* @param {unknown} [options]
* @return {Promise<unknown>}
*/
dropTable(tableName, options) {
return this.query(`DROP TABLE ${tableName}`, [], options);
}
/**
* @param {number} paramIndex
* @return {string}
*/
param(paramIndex) {
return '?';
}
testConnectionTimeout() {
return 10000;
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
async downloadTable(table, options) {
return { rows: await this.query(`SELECT * FROM ${table}`) };
}
async uploadTable(table, columns, tableData) {
return this.uploadTableWithIndexes(table, columns, tableData, []);
}
async uploadTableWithIndexes(table, columns, tableData, indexesSql) {
if (!tableData.rows) {
throw new Error(`${this.constructor} driver supports only rows upload`);
}
await this.createTable(table, columns);
try {
for (let i = 0; i < tableData.rows.length; i++) {
await this.query(
`INSERT INTO ${table}
(${columns.map(c => this.quoteIdentifier(c.name)).join(', ')})
VALUES (${columns.map((c, paramIndex) => this.param(paramIndex)).join(', ')})`,
columns.map(c => this.toColumnValue(tableData.rows[i][c.name], c.type))
);
}
for (let i = 0; i < indexesSql.length; i++) {
const [query, params] = indexesSql[i].sql;
await this.query(query, params);
}
} catch (e) {
await this.dropTable(table);
throw e;
}
}
// eslint-disable-next-line no-unused-vars
toColumnValue(value, genericType) {
return value;
}
async tableColumnTypes(table) {
const [schema, name] = table.split('.');
const columns = await this.query(
`SELECT columns.column_name,
columns.table_name,
columns.table_schema,
columns.data_type
FROM information_schema.columns
WHERE table_name = ${this.param(0)} AND table_schema = ${this.param(1)}`,
[name, schema]
);
return columns.map(c => ({ name: c.column_name, type: this.toGenericType(c.data_type) }));
}
createTable(quotedTableName, columns) {
const createTableSql = this.createTableSql(quotedTableName, columns);
return this.query(createTableSql, []).catch(e => {
e.message = `Error during create table: ${createTableSql}: ${e.message}`;
throw e;
});
}
createTableSql(quotedTableName, columns) {
columns = columns.map(c => `${this.quoteIdentifier(c.name)} ${this.fromGenericType(c.type)}`);
return `CREATE TABLE ${quotedTableName} (${columns.join(', ')})`;
}
/**
* @param {string} columnType
* @return {string}
*/
toGenericType(columnType) {
return DbTypeToGenericType[columnType.toLowerCase()] || columnType;
}
/**
* @param {string} columnType
* @return {string}
*/
fromGenericType(columnType) {
return columnType;
}
/**
* @param {string} identifier
* @return {string}
*/
quoteIdentifier(identifier) {
return `"${identifier}"`;
}
cancelCombinator(fn) {
return cancelCombinator(fn);
}
setLogger(logger) {
this.logger = logger;
}
reportQueryUsage(usage, queryOptions) {
if (this.logger) {
this.logger('SQL Query Usage', {
...usage,
...queryOptions
});
}
}
databasePoolError(error) {
if (this.logger) {
this.logger('Database Pool Error', {
error: (error.stack || error).toString()
});
}
}
/**
* @public
*/
async release() {
// override, if it's needed
}
capabilities() {
return {};
}
}