|
| 1 | +import { |
| 2 | + DataSource, |
| 3 | + DataResult, |
| 4 | + ExecuteOptions, |
| 5 | + InternalError, |
| 6 | + RequestParameter, |
| 7 | + VulcanExtensionId, |
| 8 | +} from '@vulcan-sql/core'; |
| 9 | +import { Readable } from 'stream'; |
| 10 | +import { buildSQL } from './sqlBuilder'; |
| 11 | +import { mapFromRedShiftTypeId } from './typeMapper'; |
| 12 | +import { |
| 13 | + RedshiftDataClient, |
| 14 | + RedshiftDataClientConfig, |
| 15 | + ExecuteStatementCommand, |
| 16 | + ExecuteStatementCommandInput, |
| 17 | + ExecuteStatementCommandOutput, |
| 18 | + DescribeStatementCommandInput, |
| 19 | + DescribeStatementResponse, |
| 20 | + DescribeStatementCommand, |
| 21 | + GetStatementResultCommandInput, |
| 22 | + GetStatementResultCommand, |
| 23 | + SqlParameter, |
| 24 | +} from '@aws-sdk/client-redshift-data'; |
| 25 | + |
| 26 | +export type RedshiftOptions = RedshiftDataClientConfig & Omit<ExecuteStatementCommandInput, "Sql" | "Parameters">; |
| 27 | + |
| 28 | +type RedShiftDataRow = { |
| 29 | + [column: string]: any; |
| 30 | +} |
| 31 | + |
| 32 | +@VulcanExtensionId('redshift') |
| 33 | +export class RedShiftDataSource extends DataSource<any, RedshiftOptions> { |
| 34 | + private logger = this.getLogger(); |
| 35 | + private redshiftClientMapping = new Map< |
| 36 | + string, |
| 37 | + { |
| 38 | + redshiftClient: RedshiftDataClient; |
| 39 | + options?: RedshiftOptions; |
| 40 | + } |
| 41 | + >(); |
| 42 | + public override async onActivate() { |
| 43 | + const profiles = this.getProfiles().values(); |
| 44 | + for (const profile of profiles) { |
| 45 | + this.logger.debug( |
| 46 | + `Initializing profile: ${profile.name} using redshift driver` |
| 47 | + ); |
| 48 | + |
| 49 | + const redshiftClient = new RedshiftDataClient(profile.connection!); |
| 50 | + this.redshiftClientMapping.set(profile.name, { |
| 51 | + redshiftClient: redshiftClient, |
| 52 | + options: profile.connection, |
| 53 | + }); |
| 54 | + |
| 55 | + await this.testConnection(profile.name); |
| 56 | + this.logger.debug(`Profile ${profile.name} initialized`); |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + public async execute({ |
| 61 | + statement: sql, |
| 62 | + bindParams, |
| 63 | + profileName, |
| 64 | + operations, |
| 65 | + }: ExecuteOptions): Promise<DataResult> { |
| 66 | + this.checkProfileExist(profileName); |
| 67 | + const { redshiftClient, options } = this.redshiftClientMapping.get(profileName)!; |
| 68 | + |
| 69 | + try { |
| 70 | + const sqlParams: SqlParameter[] = []; |
| 71 | + bindParams.forEach((value, key) => { |
| 72 | + sqlParams.push({ name: key.replace(':', ''), value: String(value) }); |
| 73 | + }); |
| 74 | + |
| 75 | + const builtSQL = buildSQL(sql, operations); |
| 76 | + let executeStatementCommandParams: ExecuteStatementCommandInput = { |
| 77 | + Sql: builtSQL, |
| 78 | + Database: options!.Database, |
| 79 | + WorkgroupName: options!.WorkgroupName, |
| 80 | + }; |
| 81 | + if (sqlParams.length) { |
| 82 | + executeStatementCommandParams = {...executeStatementCommandParams, Parameters: sqlParams} |
| 83 | + } |
| 84 | + |
| 85 | + const executeStatementCommand = new ExecuteStatementCommand(executeStatementCommandParams); |
| 86 | + const statementCommandResult = await redshiftClient.send(executeStatementCommand); |
| 87 | + return await this.getResultFromExecuteStatement(statementCommandResult, redshiftClient); |
| 88 | + } catch (e: any) { |
| 89 | + this.logger.debug( |
| 90 | + `Errors occurred, release connection from ${profileName}` |
| 91 | + ); |
| 92 | + redshiftClient.destroy(); |
| 93 | + throw e; |
| 94 | + } |
| 95 | + } |
| 96 | + |
| 97 | + public async prepare({ parameterIndex }: RequestParameter) { |
| 98 | + // see the section of Running SQL statements with parameters when calling the Amazon Redshift Data API |
| 99 | + // https://docs.aws.amazon.com/redshift/latest/mgmt/data-api.html |
| 100 | + return `:${parameterIndex}`; |
| 101 | + } |
| 102 | + |
| 103 | + private async testConnection(profileName: string): Promise<DataResult | undefined> { |
| 104 | + const { redshiftClient, options } = this.redshiftClientMapping.get(profileName)!; |
| 105 | + const executeStatementCommandParams: ExecuteStatementCommandInput = { |
| 106 | + Sql: 'select 1', |
| 107 | + Database: options!.Database, |
| 108 | + WorkgroupName: options!.WorkgroupName, |
| 109 | + }; |
| 110 | + |
| 111 | + const executeStatementCommand = new ExecuteStatementCommand(executeStatementCommandParams); |
| 112 | + |
| 113 | + try { |
| 114 | + const statementCommandResult = await redshiftClient.send(executeStatementCommand); |
| 115 | + return await this.getResultFromExecuteStatement(statementCommandResult, redshiftClient); |
| 116 | + } catch (e) { |
| 117 | + redshiftClient.destroy(); |
| 118 | + throw e; |
| 119 | + } |
| 120 | + } |
| 121 | + |
| 122 | + private async getResultFromExecuteStatement( |
| 123 | + statementCommandResult: ExecuteStatementCommandOutput, |
| 124 | + redshiftClient: RedshiftDataClient |
| 125 | + ): Promise<DataResult> { |
| 126 | + let describeStatementResponse: DescribeStatementResponse | undefined; |
| 127 | + const describeStatementRequestInput: DescribeStatementCommandInput = { |
| 128 | + Id: statementCommandResult.Id, |
| 129 | + }; |
| 130 | + |
| 131 | + // definition of describeStatementResponse.Status |
| 132 | + // https://github.com/aws/aws-sdk-js-v3/blob/29056f4ca545f7e5cf951b915bb52178305fc305/clients/client-redshift-data/src/models/models_0.ts#L604 |
| 133 | + while (!describeStatementResponse || describeStatementResponse.Status !== 'FINISHED') { |
| 134 | + const describeStatementCommand = new DescribeStatementCommand(describeStatementRequestInput); |
| 135 | + describeStatementResponse = await redshiftClient.send(describeStatementCommand); |
| 136 | + |
| 137 | + if ( |
| 138 | + describeStatementResponse.Status === 'ABORTED' || |
| 139 | + describeStatementResponse.Status === 'FAILED' |
| 140 | + ) { |
| 141 | + throw describeStatementResponse.Error |
| 142 | + } |
| 143 | + } |
| 144 | + |
| 145 | + const getStatementResultCommandParams: GetStatementResultCommandInput = { |
| 146 | + "Id": describeStatementResponse.Id |
| 147 | + }; |
| 148 | + const getStatementResultCommand = new GetStatementResultCommand(getStatementResultCommandParams); |
| 149 | + const getStatementResultResponse = await redshiftClient.send(getStatementResultCommand); |
| 150 | + |
| 151 | + return { |
| 152 | + getColumns: () => { |
| 153 | + const columns = getStatementResultResponse.ColumnMetadata || []; |
| 154 | + return columns.map((column) => ({ |
| 155 | + name: column.name || '', |
| 156 | + type: mapFromRedShiftTypeId(column.typeName?.toLowerCase() || ''), |
| 157 | + })); |
| 158 | + }, |
| 159 | + getData: () => new Readable({ |
| 160 | + objectMode: true, |
| 161 | + read() { |
| 162 | + const records = getStatementResultResponse.Records! || []; |
| 163 | + const columns = getStatementResultResponse.ColumnMetadata || []; |
| 164 | + for (const record of records) { |
| 165 | + const row: RedShiftDataRow = {}; |
| 166 | + for (const [i, recordField] of record.entries()) { |
| 167 | + row[columns[i].name!] = Object.values(recordField)[0]; |
| 168 | + } |
| 169 | + this.push(row); |
| 170 | + } |
| 171 | + this.push(null); |
| 172 | + }, |
| 173 | + // automatically destroy() the stream when it emits 'finish' or errors. Node > 10.16 |
| 174 | + autoDestroy: true, |
| 175 | + }), |
| 176 | + }; |
| 177 | + } |
| 178 | + |
| 179 | + private checkProfileExist(profileName: string): void { |
| 180 | + if (!this.redshiftClientMapping.has(profileName)) { |
| 181 | + throw new InternalError(`Profile instance ${profileName} not found`); |
| 182 | + } |
| 183 | + } |
| 184 | +} |
0 commit comments