|
| 1 | +import { Buffer } from 'buffer'; |
| 2 | +import { |
| 3 | + Table, |
| 4 | + Schema, |
| 5 | + Field, |
| 6 | + TypeMap, |
| 7 | + DataType, |
| 8 | + Type, |
| 9 | + StructRow, |
| 10 | + MapRow, |
| 11 | + Vector, |
| 12 | + RecordBatch, |
| 13 | + RecordBatchReader, |
| 14 | + util as arrowUtils, |
| 15 | +} from 'apache-arrow'; |
| 16 | +import { TTableSchema, TColumnDesc } from '../../thrift/TCLIService_types'; |
| 17 | +import IClientContext from '../contracts/IClientContext'; |
| 18 | +import IResultsProvider, { ResultsProviderFetchNextOptions } from './IResultsProvider'; |
| 19 | +import { getSchemaColumns, convertThriftValue } from './utils'; |
| 20 | + |
| 21 | +const { isArrowBigNumSymbol, bigNumToBigInt } = arrowUtils; |
| 22 | + |
| 23 | +type ArrowSchema = Schema<TypeMap>; |
| 24 | +type ArrowSchemaField = Field<DataType<Type, TypeMap>>; |
| 25 | + |
| 26 | +export default class ArrowResultConverter implements IResultsProvider<Array<any>> { |
| 27 | + protected readonly context: IClientContext; |
| 28 | + |
| 29 | + private readonly source: IResultsProvider<Array<Buffer>>; |
| 30 | + |
| 31 | + private readonly schema: Array<TColumnDesc>; |
| 32 | + |
| 33 | + private reader?: IterableIterator<RecordBatch<TypeMap>>; |
| 34 | + |
| 35 | + private pendingRecordBatch?: RecordBatch<TypeMap>; |
| 36 | + |
| 37 | + constructor(context: IClientContext, source: IResultsProvider<Array<Buffer>>, schema?: TTableSchema) { |
| 38 | + this.context = context; |
| 39 | + this.source = source; |
| 40 | + this.schema = getSchemaColumns(schema); |
| 41 | + } |
| 42 | + |
| 43 | + public async hasMore() { |
| 44 | + if (this.schema.length === 0) { |
| 45 | + return false; |
| 46 | + } |
| 47 | + if (this.pendingRecordBatch) { |
| 48 | + return true; |
| 49 | + } |
| 50 | + return this.source.hasMore(); |
| 51 | + } |
| 52 | + |
| 53 | + public async fetchNext(options: ResultsProviderFetchNextOptions) { |
| 54 | + if (this.schema.length === 0) { |
| 55 | + return []; |
| 56 | + } |
| 57 | + |
| 58 | + // eslint-disable-next-line no-constant-condition |
| 59 | + while (true) { |
| 60 | + // It's not possible to know if iterator has more items until trying |
| 61 | + // to get the next item. But we need to know if iterator is empty right |
| 62 | + // after getting the next item. Therefore, after creating the iterator, |
| 63 | + // we get one item more and store it in `pendingRecordBatch`. Next time, |
| 64 | + // we use that stored item, and prefetch the next one. Prefetched item |
| 65 | + // is therefore the next item we are going to return, so it can be used |
| 66 | + // to know if we actually can return anything next time |
| 67 | + const recordBatch = this.pendingRecordBatch; |
| 68 | + this.pendingRecordBatch = this.prefetch(); |
| 69 | + |
| 70 | + if (recordBatch) { |
| 71 | + const table = new Table(recordBatch); |
| 72 | + return this.getRows(table.schema, table.toArray()); |
| 73 | + } |
| 74 | + |
| 75 | + // eslint-disable-next-line no-await-in-loop |
| 76 | + const batches = await this.source.fetchNext(options); |
| 77 | + if (batches.length === 0) { |
| 78 | + this.reader = undefined; |
| 79 | + break; |
| 80 | + } |
| 81 | + |
| 82 | + const reader = RecordBatchReader.from<TypeMap>(batches); |
| 83 | + this.reader = reader[Symbol.iterator](); |
| 84 | + this.pendingRecordBatch = this.prefetch(); |
| 85 | + } |
| 86 | + |
| 87 | + return []; |
| 88 | + } |
| 89 | + |
| 90 | + private prefetch(): RecordBatch<TypeMap> | undefined { |
| 91 | + const item = this.reader?.next() ?? { done: true, value: undefined }; |
| 92 | + |
| 93 | + if (item.done || item.value === undefined) { |
| 94 | + this.reader = undefined; |
| 95 | + return undefined; |
| 96 | + } |
| 97 | + |
| 98 | + return item.value; |
| 99 | + } |
| 100 | + |
| 101 | + private getRows(schema: ArrowSchema, rows: Array<StructRow | MapRow>): Array<any> { |
| 102 | + return rows.map((row) => { |
| 103 | + // First, convert native Arrow values to corresponding plain JS objects |
| 104 | + const record = this.convertArrowTypes(row, undefined, schema.fields); |
| 105 | + // Second, cast all the values to original Thrift types |
| 106 | + return this.convertThriftTypes(record); |
| 107 | + }); |
| 108 | + } |
| 109 | + |
| 110 | + private convertArrowTypes(value: any, valueType: DataType | undefined, fields: Array<ArrowSchemaField> = []): any { |
| 111 | + if (value === null) { |
| 112 | + return value; |
| 113 | + } |
| 114 | + |
| 115 | + const fieldsMap: Record<string, ArrowSchemaField> = {}; |
| 116 | + for (const field of fields) { |
| 117 | + fieldsMap[field.name] = field; |
| 118 | + } |
| 119 | + |
| 120 | + // Convert structures to plain JS object and process all its fields recursively |
| 121 | + if (value instanceof StructRow) { |
| 122 | + const result = value.toJSON(); |
| 123 | + for (const key of Object.keys(result)) { |
| 124 | + const field: ArrowSchemaField | undefined = fieldsMap[key]; |
| 125 | + result[key] = this.convertArrowTypes(result[key], field?.type, field?.type.children || []); |
| 126 | + } |
| 127 | + return result; |
| 128 | + } |
| 129 | + if (value instanceof MapRow) { |
| 130 | + const result = value.toJSON(); |
| 131 | + // Map type consists of its key and value types. We need only value type here, key will be cast to string anyway |
| 132 | + const field = fieldsMap.entries?.type.children.find((item) => item.name === 'value'); |
| 133 | + for (const key of Object.keys(result)) { |
| 134 | + result[key] = this.convertArrowTypes(result[key], field?.type, field?.type.children || []); |
| 135 | + } |
| 136 | + return result; |
| 137 | + } |
| 138 | + |
| 139 | + // Convert lists to JS array and process items recursively |
| 140 | + if (value instanceof Vector) { |
| 141 | + const result = value.toJSON(); |
| 142 | + // Array type contains the only child which defines a type of each array's element |
| 143 | + const field = fieldsMap.element; |
| 144 | + return result.map((item) => this.convertArrowTypes(item, field?.type, field?.type.children || [])); |
| 145 | + } |
| 146 | + |
| 147 | + if (DataType.isTimestamp(valueType)) { |
| 148 | + return new Date(value); |
| 149 | + } |
| 150 | + |
| 151 | + // Convert big number values to BigInt |
| 152 | + // Decimals are also represented as big numbers in Arrow, so additionally process them (convert to float) |
| 153 | + if (value instanceof Object && value[isArrowBigNumSymbol]) { |
| 154 | + const result = bigNumToBigInt(value); |
| 155 | + if (DataType.isDecimal(valueType)) { |
| 156 | + return Number(result) / 10 ** valueType.scale; |
| 157 | + } |
| 158 | + return result; |
| 159 | + } |
| 160 | + |
| 161 | + // Convert binary data to Buffer |
| 162 | + if (value instanceof Uint8Array) { |
| 163 | + return Buffer.from(value); |
| 164 | + } |
| 165 | + |
| 166 | + // Return other values as is |
| 167 | + return typeof value === 'bigint' ? Number(value) : value; |
| 168 | + } |
| 169 | + |
| 170 | + private convertThriftTypes(record: Record<string, any>): any { |
| 171 | + const result: Record<string, any> = {}; |
| 172 | + |
| 173 | + this.schema.forEach((column) => { |
| 174 | + const typeDescriptor = column.typeDesc.types[0]?.primitiveEntry; |
| 175 | + const field = column.columnName; |
| 176 | + const value = record[field]; |
| 177 | + result[field] = value === null ? null : convertThriftValue(typeDescriptor, value); |
| 178 | + }); |
| 179 | + |
| 180 | + return result; |
| 181 | + } |
| 182 | +} |
0 commit comments