-
Notifications
You must be signed in to change notification settings - Fork 73
Expand file tree
/
Copy pathresult_set.ts
More file actions
216 lines (187 loc) · 6.17 KB
/
Copy pathresult_set.ts
File metadata and controls
216 lines (187 loc) · 6.17 KB
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
import type {
BaseResultSet,
DataFormat,
JSONHandling,
ResponseHeaders,
ResultJSONType,
ResultStream,
Row,
} from '@clickhouse/client-common'
import {
CARET_RETURN,
extractErrorAtTheEndOfChunk,
} from '@clickhouse/client-common'
import {
isNotStreamableJSONFamily,
isStreamableJSONFamily,
validateStreamFormat,
} from '@clickhouse/client-common'
import { getAsText } from './utils'
const NEWLINE = 0x0a as const
export class ResultSet<
Format extends DataFormat | unknown,
> implements BaseResultSet<ReadableStream<Row[]>, Format> {
public readonly response_headers: ResponseHeaders
private readonly exceptionTag: string | undefined = undefined
private isAlreadyConsumed = false
private readonly jsonHandling: JSONHandling
constructor(
private _stream: ReadableStream,
private readonly format: Format,
public readonly query_id: string,
_response_headers?: ResponseHeaders,
jsonHandling: JSONHandling = {
parse: JSON.parse,
stringify: JSON.stringify,
},
) {
this.response_headers =
_response_headers !== undefined ? Object.freeze(_response_headers) : {}
this.exceptionTag = this.response_headers['x-clickhouse-exception-tag'] as
| string
| undefined
this.jsonHandling = jsonHandling
}
/** See {@link BaseResultSet.text} */
async text(): Promise<string> {
this.markAsConsumed()
return getAsText(this._stream)
}
/** See {@link BaseResultSet.json} */
async json<T>(): Promise<ResultJSONType<T, Format>> {
// JSONEachRow, etc.
if (isStreamableJSONFamily(this.format as DataFormat)) {
const result: T[] = []
const reader = this.stream<T>().getReader()
while (true) {
const { done, value } = await reader.read()
if (done) {
break
}
for (const row of value) {
result.push(row.json() as T)
}
}
return result as any
}
// JSON, JSONObjectEachRow, etc.
if (isNotStreamableJSONFamily(this.format as DataFormat)) {
const text = await getAsText(this._stream)
return this.jsonHandling.parse(text)
}
// should not be called for CSV, etc.
throw new Error(`Cannot decode ${this.format} as JSON`)
}
/** See {@link BaseResultSet.stream} */
stream<T>(): ResultStream<Format, ReadableStream<Row<T, Format>[]>> {
this.markAsConsumed()
validateStreamFormat(this.format)
const incompleteChunks: Uint8Array[] = []
let totalIncompleteLength = 0
const exceptionTag = this.exceptionTag
const jsonHandling = this.jsonHandling
const decoder = new TextDecoder('utf-8')
const transform = new TransformStream({
start() {
//
},
transform: (chunk: Uint8Array, controller) => {
if (chunk === null) {
controller.terminate()
}
const rows: Row[] = []
let idx: number
let lastIdx = 0
while (true) {
// an unescaped newline character denotes the end of a row,
// or at least the beginning of the exception marker
idx = chunk.indexOf(NEWLINE, lastIdx)
if (idx === -1) {
// there is no complete row in the rest of the current chunk
// to be processed during the next transform iteration
const incompleteChunk = chunk.slice(lastIdx)
incompleteChunks.push(incompleteChunk)
totalIncompleteLength += incompleteChunk.length
// send the extracted rows to the consumer, if any
if (rows.length > 0) {
controller.enqueue(rows)
}
break
} else {
let bytesToDecode: Uint8Array
// Check for exception in the chunk (only after 25.11)
if (
exceptionTag !== undefined &&
idx >= 1 &&
chunk[idx - 1] === CARET_RETURN
) {
controller.error(extractErrorAtTheEndOfChunk(chunk, exceptionTag))
}
// using the incomplete chunks from the previous iterations
if (incompleteChunks.length > 0) {
const completeRowBytes = new Uint8Array(
totalIncompleteLength + idx,
)
let offset = 0
incompleteChunks.forEach((incompleteChunk) => {
completeRowBytes.set(incompleteChunk, offset)
offset += incompleteChunk.length
})
// finalize the row with the current chunk slice that ends with a newline
const finalChunk = chunk.slice(0, idx)
completeRowBytes.set(finalChunk, offset)
// Reset the incomplete chunks.
// Removing used buffers and reusing the already allocated memory
// by setting length to 0
incompleteChunks.length = 0
totalIncompleteLength = 0
bytesToDecode = completeRowBytes
} else {
bytesToDecode = chunk.slice(lastIdx, idx)
}
const text = decoder.decode(bytesToDecode)
rows.push({
text,
json<T>(): T {
return jsonHandling.parse(text)
},
})
lastIdx = idx + 1 // skipping newline character
}
}
},
})
const pipeline = this._stream.pipeThrough(transform, {
preventClose: false,
preventAbort: false,
preventCancel: false,
})
return pipeline as any
}
/** See {@link BaseResultSet.rawStream}. */
rawStream(): ReadableStream {
this.markAsConsumed()
return this._stream
}
async close(): Promise<void> {
this.markAsConsumed()
await this._stream.cancel()
}
/**
* Closes the `ResultSet`.
*
* Automatically called when using `using` statement in supported environments.
* @see {@link ResultSet.close}
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/using
*/
async [Symbol.asyncDispose]() {
await this.close()
}
private markAsConsumed() {
if (this.isAlreadyConsumed) {
throw new Error(streamAlreadyConsumedMessage)
}
this.isAlreadyConsumed = true
}
}
const streamAlreadyConsumedMessage = 'Stream has been already consumed'