-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathDBSQLSession.ts
588 lines (524 loc) · 19.9 KB
/
DBSQLSession.ts
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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
import * as fs from 'fs';
import * as path from 'path';
import stream from 'node:stream';
import util from 'node:util';
import { stringify, NIL } from 'uuid';
import Int64 from 'node-int64';
import fetch, { HeadersInit } from 'node-fetch';
import {
TSessionHandle,
TStatus,
TOperationHandle,
TSparkDirectResults,
TSparkArrowTypes,
TSparkParameter,
} from '../thrift/TCLIService_types';
import IDBSQLSession, {
ExecuteStatementOptions,
TypeInfoRequest,
CatalogsRequest,
SchemasRequest,
TablesRequest,
TableTypesRequest,
ColumnsRequest,
FunctionsRequest,
PrimaryKeysRequest,
CrossReferenceRequest,
} from './contracts/IDBSQLSession';
import IOperation from './contracts/IOperation';
import DBSQLOperation from './DBSQLOperation';
import Status from './dto/Status';
import InfoValue from './dto/InfoValue';
import { definedOrError, LZ4 } from './utils';
import CloseableCollection from './utils/CloseableCollection';
import { LogLevel } from './contracts/IDBSQLLogger';
import HiveDriverError from './errors/HiveDriverError';
import StagingError from './errors/StagingError';
import { DBSQLParameter, DBSQLParameterValue } from './DBSQLParameter';
import ParameterError from './errors/ParameterError';
import IClientContext, { ClientConfig } from './contracts/IClientContext';
// Explicitly promisify a callback-style `pipeline` because `node:stream/promises` is not available in Node 14
const pipeline = util.promisify(stream.pipeline);
interface OperationResponseShape {
status: TStatus;
operationHandle?: TOperationHandle;
directResults?: TSparkDirectResults;
}
export function numberToInt64(value: number | bigint | Int64): Int64 {
if (value instanceof Int64) {
return value;
}
if (typeof value === 'bigint') {
const buffer = new ArrayBuffer(BigInt64Array.BYTES_PER_ELEMENT);
const view = new DataView(buffer);
view.setBigInt64(0, value, false); // `false` to use big-endian order
return new Int64(Buffer.from(buffer));
}
return new Int64(value);
}
function getDirectResultsOptions(maxRows: number | bigint | Int64 | null | undefined, config: ClientConfig) {
if (maxRows === null) {
return {};
}
return {
getDirectResults: {
maxRows: numberToInt64(maxRows ?? config.directResultsDefaultMaxRows),
},
};
}
function getArrowOptions(config: ClientConfig): {
canReadArrowResult: boolean;
useArrowNativeTypes?: TSparkArrowTypes;
} {
const { arrowEnabled = true, useArrowNativeTypes = true } = config;
if (!arrowEnabled) {
return {
canReadArrowResult: false,
};
}
return {
canReadArrowResult: true,
useArrowNativeTypes: {
timestampAsArrow: useArrowNativeTypes,
decimalAsArrow: useArrowNativeTypes,
complexTypesAsArrow: useArrowNativeTypes,
// TODO: currently unsupported by `apache-arrow` (see https://github.com/streamlit/streamlit/issues/4489)
intervalTypesAsArrow: false,
},
};
}
function getQueryParameters(
namedParameters?: Record<string, DBSQLParameter | DBSQLParameterValue>,
ordinalParameters?: Array<DBSQLParameter | DBSQLParameterValue>,
): Array<TSparkParameter> {
const namedParametersProvided = namedParameters !== undefined && Object.keys(namedParameters).length > 0;
const ordinalParametersProvided = ordinalParameters !== undefined && ordinalParameters.length > 0;
if (namedParametersProvided && ordinalParametersProvided) {
throw new ParameterError('Driver does not support both ordinal and named parameters.');
}
if (!namedParametersProvided && !ordinalParametersProvided) {
return [];
}
const result: Array<TSparkParameter> = [];
if (namedParameters !== undefined) {
for (const name of Object.keys(namedParameters)) {
const value = namedParameters[name];
const param = value instanceof DBSQLParameter ? value : new DBSQLParameter({ value });
result.push(param.toSparkParameter({ name }));
}
}
if (ordinalParameters !== undefined) {
for (const value of ordinalParameters) {
const param = value instanceof DBSQLParameter ? value : new DBSQLParameter({ value });
result.push(param.toSparkParameter());
}
}
return result;
}
interface DBSQLSessionConstructorOptions {
handle: TSessionHandle;
context: IClientContext;
}
export default class DBSQLSession implements IDBSQLSession {
private readonly context: IClientContext;
private readonly sessionHandle: TSessionHandle;
private isOpen = true;
public onClose?: () => void;
private operations = new CloseableCollection<DBSQLOperation>();
constructor({ handle, context }: DBSQLSessionConstructorOptions) {
this.sessionHandle = handle;
this.context = context;
this.context.getLogger().log(LogLevel.debug, `Session created with id: ${this.id}`);
}
public get id() {
const sessionId = this.sessionHandle?.sessionId?.guid;
return sessionId ? stringify(sessionId) : NIL;
}
/**
* Fetches info
* @public
* @param infoType - One of the values TCLIService_types.TGetInfoType
* @returns Value corresponding to info type requested
* @example
* const response = await session.getInfo(thrift.TCLIService_types.TGetInfoType.CLI_DBMS_VER);
*/
public async getInfo(infoType: number): Promise<InfoValue> {
await this.failIfClosed();
const driver = await this.context.getDriver();
const operationPromise = driver.getInfo({
sessionHandle: this.sessionHandle,
infoType,
});
const response = await this.handleResponse(operationPromise);
Status.assert(response.status);
return new InfoValue(response.infoValue);
}
/**
* Executes statement
* @public
* @param statement - SQL statement to be executed
* @param options - maxRows field is used to specify Direct Results
* @returns DBSQLOperation
* @example
* const operation = await session.executeStatement(query);
*/
public async executeStatement(statement: string, options: ExecuteStatementOptions = {}): Promise<IOperation> {
await this.failIfClosed();
const driver = await this.context.getDriver();
const clientConfig = this.context.getConfig();
const operationPromise = driver.executeStatement({
sessionHandle: this.sessionHandle,
statement,
queryTimeout: options.queryTimeout ? numberToInt64(options.queryTimeout) : undefined,
runAsync: true,
...getDirectResultsOptions(options.maxRows, clientConfig),
...getArrowOptions(clientConfig),
canDownloadResult: options.useCloudFetch ?? clientConfig.useCloudFetch,
parameters: getQueryParameters(options.namedParameters, options.ordinalParameters),
canDecompressLZ4Result: (options.useLZ4Compression ?? clientConfig.useLZ4Compression) && Boolean(LZ4),
});
const response = await this.handleResponse(operationPromise);
const operation = this.createOperation(response);
// If `stagingAllowedLocalPath` is provided - assume that operation possibly may be a staging operation.
// To know for sure, fetch metadata and check a `isStagingOperation` flag. If it happens that it wasn't
// a staging operation - not a big deal, we just fetched metadata earlier, but operation is still usable
// and user can get data from it.
// If `stagingAllowedLocalPath` is not provided - don't do anything to the operation. In a case of regular
// operation, everything will work as usual. In a case of staging operation, it will be processed like any
// other query - it will be possible to get data from it as usual, or use other operation methods.
if (options.stagingAllowedLocalPath !== undefined) {
const metadata = await operation.getMetadata();
if (metadata.isStagingOperation) {
const allowedLocalPath = Array.isArray(options.stagingAllowedLocalPath)
? options.stagingAllowedLocalPath
: [options.stagingAllowedLocalPath];
return this.handleStagingOperation(operation, allowedLocalPath);
}
}
return operation;
}
private async handleStagingOperation(operation: IOperation, allowedLocalPath: Array<string>): Promise<IOperation> {
type StagingResponse = {
presignedUrl: string;
localFile?: string;
headers: HeadersInit;
operation: string;
};
const rows = await operation.fetchAll();
if (rows.length !== 1) {
throw new StagingError('Staging operation: expected only one row in result');
}
const row = rows[0] as StagingResponse;
// For REMOVE operation local file is not available, so no need to validate it
if (row.localFile !== undefined) {
let allowOperation = false;
for (const filepath of allowedLocalPath) {
const relativePath = path.relative(filepath, row.localFile);
if (!relativePath.startsWith('..') && !path.isAbsolute(relativePath)) {
allowOperation = true;
}
}
if (!allowOperation) {
throw new StagingError('Staging path not a subset of allowed local paths.');
}
}
const { localFile, presignedUrl, headers } = row;
switch (row.operation) {
case 'GET':
await this.handleStagingGet(localFile, presignedUrl, headers);
return operation;
case 'PUT':
await this.handleStagingPut(localFile, presignedUrl, headers);
return operation;
case 'REMOVE':
await this.handleStagingRemove(presignedUrl, headers);
return operation;
default:
throw new StagingError(`Staging query operation is not supported: ${row.operation}`);
}
}
private async handleStagingGet(
localFile: string | undefined,
presignedUrl: string,
headers: HeadersInit,
): Promise<void> {
if (localFile === undefined) {
throw new StagingError('Local file path not provided');
}
const connectionProvider = await this.context.getConnectionProvider();
const agent = await connectionProvider.getAgent();
const response = await fetch(presignedUrl, { method: 'GET', headers, agent });
if (!response.ok) {
throw new StagingError(`HTTP error ${response.status} ${response.statusText}`);
}
const fileStream = fs.createWriteStream(localFile);
// `pipeline` will do all the dirty job for us, including error handling and closing all the streams properly
return pipeline(response.body, fileStream);
}
private async handleStagingRemove(presignedUrl: string, headers: HeadersInit): Promise<void> {
const connectionProvider = await this.context.getConnectionProvider();
const agent = await connectionProvider.getAgent();
const response = await fetch(presignedUrl, { method: 'DELETE', headers, agent });
// Looks that AWS and Azure have a different behavior of HTTP `DELETE` for non-existing files.
// AWS assumes that - since file already doesn't exist - the goal is achieved, and returns HTTP 200.
// Azure, on the other hand, is somewhat stricter and check if file exists before deleting it. And if
// file doesn't exist - Azure returns HTTP 404.
//
// For us, it's totally okay if file didn't exist before removing. So when we get an HTTP 404 -
// just ignore it and report success. This way we can have a uniform library behavior for all clouds
if (!response.ok && response.status !== 404) {
throw new StagingError(`HTTP error ${response.status} ${response.statusText}`);
}
}
private async handleStagingPut(
localFile: string | undefined,
presignedUrl: string,
headers: HeadersInit,
): Promise<void> {
if (localFile === undefined) {
throw new StagingError('Local file path not provided');
}
const connectionProvider = await this.context.getConnectionProvider();
const agent = await connectionProvider.getAgent();
const fileStream = fs.createReadStream(localFile);
const fileInfo = fs.statSync(localFile, { bigint: true });
const response = await fetch(presignedUrl, {
method: 'PUT',
headers: {
...headers,
// This header is required by server
'Content-Length': fileInfo.size.toString(),
},
agent,
body: fileStream,
});
if (!response.ok) {
throw new StagingError(`HTTP error ${response.status} ${response.statusText}`);
}
}
/**
* Information about supported data types
* @public
* @param request
* @returns DBSQLOperation
*/
public async getTypeInfo(request: TypeInfoRequest = {}): Promise<IOperation> {
await this.failIfClosed();
const driver = await this.context.getDriver();
const clientConfig = this.context.getConfig();
const operationPromise = driver.getTypeInfo({
sessionHandle: this.sessionHandle,
runAsync: true,
...getDirectResultsOptions(request.maxRows, clientConfig),
});
const response = await this.handleResponse(operationPromise);
return this.createOperation(response);
}
/**
* Get list of catalogs
* @public
* @param request
* @returns DBSQLOperation
*/
public async getCatalogs(request: CatalogsRequest = {}): Promise<IOperation> {
await this.failIfClosed();
const driver = await this.context.getDriver();
const clientConfig = this.context.getConfig();
const operationPromise = driver.getCatalogs({
sessionHandle: this.sessionHandle,
runAsync: true,
...getDirectResultsOptions(request.maxRows, clientConfig),
});
const response = await this.handleResponse(operationPromise);
return this.createOperation(response);
}
/**
* Get list of schemas
* @public
* @param request
* @returns DBSQLOperation
*/
public async getSchemas(request: SchemasRequest = {}): Promise<IOperation> {
await this.failIfClosed();
const driver = await this.context.getDriver();
const clientConfig = this.context.getConfig();
const operationPromise = driver.getSchemas({
sessionHandle: this.sessionHandle,
catalogName: request.catalogName,
schemaName: request.schemaName,
runAsync: true,
...getDirectResultsOptions(request.maxRows, clientConfig),
});
const response = await this.handleResponse(operationPromise);
return this.createOperation(response);
}
/**
* Get list of tables
* @public
* @param request
* @returns DBSQLOperation
*/
public async getTables(request: TablesRequest = {}): Promise<IOperation> {
await this.failIfClosed();
const driver = await this.context.getDriver();
const clientConfig = this.context.getConfig();
const operationPromise = driver.getTables({
sessionHandle: this.sessionHandle,
catalogName: request.catalogName,
schemaName: request.schemaName,
tableName: request.tableName,
tableTypes: request.tableTypes,
runAsync: true,
...getDirectResultsOptions(request.maxRows, clientConfig),
});
const response = await this.handleResponse(operationPromise);
return this.createOperation(response);
}
/**
* Get list of supported table types
* @public
* @param request
* @returns DBSQLOperation
*/
public async getTableTypes(request: TableTypesRequest = {}): Promise<IOperation> {
await this.failIfClosed();
const driver = await this.context.getDriver();
const clientConfig = this.context.getConfig();
const operationPromise = driver.getTableTypes({
sessionHandle: this.sessionHandle,
runAsync: true,
...getDirectResultsOptions(request.maxRows, clientConfig),
});
const response = await this.handleResponse(operationPromise);
return this.createOperation(response);
}
/**
* Get full information about columns of the table
* @public
* @param request
* @returns DBSQLOperation
*/
public async getColumns(request: ColumnsRequest = {}): Promise<IOperation> {
await this.failIfClosed();
const driver = await this.context.getDriver();
const clientConfig = this.context.getConfig();
const operationPromise = driver.getColumns({
sessionHandle: this.sessionHandle,
catalogName: request.catalogName,
schemaName: request.schemaName,
tableName: request.tableName,
columnName: request.columnName,
runAsync: true,
...getDirectResultsOptions(request.maxRows, clientConfig),
});
const response = await this.handleResponse(operationPromise);
return this.createOperation(response);
}
/**
* Get information about function
* @public
* @param request
* @returns DBSQLOperation
*/
public async getFunctions(request: FunctionsRequest): Promise<IOperation> {
await this.failIfClosed();
const driver = await this.context.getDriver();
const clientConfig = this.context.getConfig();
const operationPromise = driver.getFunctions({
sessionHandle: this.sessionHandle,
catalogName: request.catalogName,
schemaName: request.schemaName,
functionName: request.functionName,
runAsync: true,
...getDirectResultsOptions(request.maxRows, clientConfig),
});
const response = await this.handleResponse(operationPromise);
return this.createOperation(response);
}
public async getPrimaryKeys(request: PrimaryKeysRequest): Promise<IOperation> {
await this.failIfClosed();
const driver = await this.context.getDriver();
const clientConfig = this.context.getConfig();
const operationPromise = driver.getPrimaryKeys({
sessionHandle: this.sessionHandle,
catalogName: request.catalogName,
schemaName: request.schemaName,
tableName: request.tableName,
runAsync: true,
...getDirectResultsOptions(request.maxRows, clientConfig),
});
const response = await this.handleResponse(operationPromise);
return this.createOperation(response);
}
/**
* Request information about foreign keys between two tables
* @public
* @param request
* @returns DBSQLOperation
*/
public async getCrossReference(request: CrossReferenceRequest): Promise<IOperation> {
await this.failIfClosed();
const driver = await this.context.getDriver();
const clientConfig = this.context.getConfig();
const operationPromise = driver.getCrossReference({
sessionHandle: this.sessionHandle,
parentCatalogName: request.parentCatalogName,
parentSchemaName: request.parentSchemaName,
parentTableName: request.parentTableName,
foreignCatalogName: request.foreignCatalogName,
foreignSchemaName: request.foreignSchemaName,
foreignTableName: request.foreignTableName,
runAsync: true,
...getDirectResultsOptions(request.maxRows, clientConfig),
});
const response = await this.handleResponse(operationPromise);
return this.createOperation(response);
}
/**
* Closes the session
* @public
* @returns Operation status
*/
public async close(): Promise<Status> {
if (!this.isOpen) {
return Status.success();
}
// Close owned operations one by one, removing successfully closed ones from the list
await this.operations.closeAll();
const driver = await this.context.getDriver();
const response = await driver.closeSession({
sessionHandle: this.sessionHandle,
});
// check status for being successful
Status.assert(response.status);
// notify owner connection
this.onClose?.();
this.isOpen = false;
this.context.getLogger().log(LogLevel.debug, `Session closed with id: ${this.id}`);
return new Status(response.status);
}
private createOperation(response: OperationResponseShape): DBSQLOperation {
Status.assert(response.status);
const handle = definedOrError(response.operationHandle);
const operation = new DBSQLOperation({
handle,
directResults: response.directResults,
context: this.context,
});
this.operations.add(operation);
return operation;
}
private async failIfClosed(): Promise<void> {
if (!this.isOpen) {
throw new HiveDriverError('The session was closed or has expired');
}
}
private async handleResponse<T>(requestPromise: Promise<T>): Promise<T> {
// Currently, after being closed sessions remains usable - server will not
// error out when trying to run operations on closed session. So it's
// basically useless to process any errors here
const result = await requestPromise;
await this.failIfClosed();
return result;
}
}