-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathclient-common.ts
More file actions
1777 lines (1588 loc) · 57 KB
/
Copy pathclient-common.ts
File metadata and controls
1777 lines (1588 loc) · 57 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
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
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Common SpiceClient implementation supporting both Node.js and Browser environments
*/
import { Table, tableFromIPC } from 'apache-arrow';
import type { PlatformAdapter } from './platform/types';
import { FlightData, FlightStatus, getIpcMessage } from './flight';
import {
type SpiceClientConfig,
type SqlV1JsonResponse,
type RefreshAccelerationOptions,
type RefreshAccelerationResponse,
type NsqlOptions,
type NsqlResponse,
type SqlQueryOptions,
type QueryParameters,
type SearchOptions,
type SearchResponse,
type WireSearchResponse,
type ActiveQuery,
type ActiveQueriesResponse,
type CancelActiveQueryResponse,
} from './interfaces';
import type { GrpcFlightClient } from './grpc/client.node';
import {
jsonToArrowTable,
convertToSqlV1Format,
normalizeSchema,
serializeArrowField,
} from './arrow-utils';
import { normalizeSearchResponse } from './search-utils';
import { Logger } from './logger';
import { Param } from './param';
// Retry will be imported by the platform-specific entry point
export interface RetryModule {
FLIGHT_QUERY_MAX_RETRIES: number;
dontRetry(err: any): void;
retryWithExponentialBackoff<T>(
operation: any,
maxRetries: number,
): Promise<T>;
}
/**
* Helper function to recursively convert timestamps in nested structures
*/
function convertTimestampsInValue(value: any, field?: any): any {
if (value === null || value === undefined) {
return value;
}
// Handle arrays (Lists)
if (Array.isArray(value) && field?.children?.[0]) {
const childField = field.children[0];
const childType =
typeof childField.data_type === 'string' ? childField.data_type : '';
if (childType.startsWith('Timestamp') || childType.startsWith('Date')) {
// Parse timezone from data_type string like "Timestamp(Nanosecond, Some("UTC"))"
const match = childType.match(/Some\("([^"]+)"\)/);
const hasTimezone = match !== null;
return value.map((item: any) => {
if (typeof item === 'string') {
let isoString = item;
// Remove milliseconds if .000
isoString = isoString.replace(/\.000Z$/, '');
isoString = isoString.replace(/\.000$/, '');
// Add Z back if has timezone, otherwise leave without Z
if (hasTimezone && !isoString.endsWith('Z')) {
isoString += 'Z';
}
return isoString;
}
return item;
});
}
}
// Handle objects (Structs)
if (typeof value === 'object' && !Array.isArray(value) && field?.children) {
const converted: any = {};
let hasChanges = false;
for (const key in value) {
const childField = field.children.find((f: any) => f.name === key);
if (childField) {
const childType =
typeof childField.data_type === 'string' ? childField.data_type : '';
if (
(childType.startsWith('Timestamp') || childType.startsWith('Date')) &&
typeof value[key] === 'string'
) {
// Parse timezone from data_type string
const match = childType.match(/Some\("([^"]+)"\)/);
const hasTimezone = match !== null;
let isoString = value[key];
// Remove milliseconds if .000
isoString = isoString.replace(/\.000Z$/, '');
isoString = isoString.replace(/\.000$/, '');
// Add Z back if has timezone, otherwise leave without Z
if (hasTimezone && !isoString.endsWith('Z')) {
isoString += 'Z';
}
converted[key] = isoString;
hasChanges = true;
} else {
converted[key] = value[key];
}
} else {
converted[key] = value[key];
}
}
return hasChanges ? converted : value;
}
return value;
}
/**
* Helper function to recursively convert Arrow structures to plain JavaScript
*/
function convertArrowValue(value: any, field?: any): any {
if (value === null || value === undefined) {
return value;
}
// Handle string timestamps (from JSON responses)
if (typeof value === 'string' && field?.type) {
const typeStr = field.type.toString();
if (typeStr.startsWith('Timestamp') || typeStr.startsWith('Date')) {
const hasTimezone = field.type.timezone != null;
let isoString = value;
// Remove milliseconds if .000
isoString = isoString.replace(/\.000Z$/, '');
isoString = isoString.replace(/\.000$/, '');
// Add Z back if has timezone, otherwise leave without Z
if (hasTimezone && !isoString.endsWith('Z')) {
isoString += 'Z';
}
return isoString;
}
}
// Handle Date objects - check if field has timezone info
if (value instanceof Date) {
const hasTimezone = field?.type?.timezone != null;
let isoString = value.toISOString();
// Remove milliseconds if .000
isoString = isoString.replace(/\.000Z$/, '');
// Add Z back if has timezone, otherwise leave without Z
if (hasTimezone) {
isoString += 'Z';
}
return isoString;
}
// Check if it's an Arrow Vector (has toArray method and length property)
// Arrow Vectors have specific characteristics that distinguish them from regular objects
if (
typeof value === 'object' &&
typeof value.toArray === 'function' &&
typeof value.length === 'number' &&
typeof value.get === 'function'
) {
// Convert Arrow Vector to JavaScript array
const arr = value.toArray();
// Pass field.type.children[0] for list element types
const childField = field?.type?.children?.[0];
return arr.map((item: any) => convertArrowValue(item, childField));
}
// Handle plain objects recursively (for Struct types)
// Only convert if it's a plain object, not Date or other built-in types
if (
typeof value === 'object' &&
value.constructor === Object &&
!Array.isArray(value)
) {
const converted: any = {};
// Get field mapping for struct children
const fieldMap = field?.type?.children
? new Map(field.type.children.map((f: any) => [f.name, f]))
: null;
for (const key in value) {
const childField = fieldMap?.get(key);
converted[key] = convertArrowValue(value[key], childField);
}
return converted;
}
return value;
}
/**
* Wraps an Arrow Table to handle type conversions in toArray()
* - Decimal types: Converts DecimalBigNum objects to numbers
* - Timestamp types: Converts Date objects to ISO 8601 strings (without Z for timestamps without timezone)
* - List types: Converts Arrow Vector objects to JavaScript arrays
*/
/**
* Coerces a `/v1/nsql` payload into the documented {@link NsqlResponse} shape.
*
* The runtime omits `schema` entirely when the generated query returned no rows,
* and a runtime that does not honor the `application/vnd.spiceai.nsql.v1+json`
* Accept header answers with a bare array of rows. Both are normalized here so
* callers can always read `sql`, `data`, `schema.fields` and `row_count`.
*/
function normalizeNsqlResponse(payload: unknown): NsqlResponse {
if (Array.isArray(payload)) {
return {
row_count: payload.length,
schema: { fields: [] },
data: payload,
sql: '',
};
}
const result = (payload ?? {}) as Partial<NsqlResponse>;
const data = result.data ?? [];
return {
row_count: result.row_count ?? data.length,
schema: { fields: result.schema?.fields ?? [] },
data,
sql: result.sql ?? '',
};
}
function wrapTableForDecimalConversion(table: Table): Table {
const originalToArray = table.toArray.bind(table);
// Override toArray to convert special types
(table as any).toArray = function () {
const rows = originalToArray();
// Use original schema if available (from jsonToArrowTable)
const originalSchema = (table as any)._originalSchema;
// Check which fields need conversion
const decimalFields = table.schema.fields.filter((f) =>
f.type.toString().startsWith('Decimal'),
);
// For timestamp fields, use original schema metadata if available
let timestampFields: any[];
if (originalSchema && Array.isArray(originalSchema)) {
timestampFields = originalSchema
.filter((f: any) => {
const dataType = typeof f.data_type === 'string' ? f.data_type : '';
return (
dataType.startsWith('Timestamp') || dataType.startsWith('Date')
);
})
.map((f: any) => {
// Parse timezone from data_type string like "Timestamp(Nanosecond, Some("UTC"))"
const dataType = f.data_type;
let timezone = null;
if (typeof dataType === 'string') {
const match = dataType.match(/Some\("([^"]+)"\)/);
if (match) {
timezone = match[1];
}
}
return {
name: f.name,
type: {
toString: () => f.data_type,
timezone: timezone,
},
};
});
} else {
timestampFields = table.schema.fields.filter(
(f) =>
f.type.toString().startsWith('Timestamp') ||
f.type.toString().startsWith('Date'),
);
}
// For list/struct fields, use original schema if available
let listFields: any[];
let structFields: any[];
if (originalSchema && Array.isArray(originalSchema)) {
listFields = originalSchema.filter((f: any) => {
const dataType = typeof f.data_type === 'string' ? f.data_type : '';
return dataType === 'List' || dataType.startsWith('List<');
});
structFields = originalSchema.filter((f: any) => {
const dataType = typeof f.data_type === 'string' ? f.data_type : '';
return dataType === 'Struct' || dataType.startsWith('Struct<');
});
} else {
listFields = table.schema.fields.filter(
(f) =>
f.type.toString().startsWith('List<') || f.type.toString() === 'List',
);
structFields = table.schema.fields.filter(
(f) =>
f.type.toString().startsWith('Struct<') ||
f.type.toString() === 'Struct',
);
}
// If no special fields, return rows as-is to avoid unnecessary processing
if (
decimalFields.length === 0 &&
timestampFields.length === 0 &&
listFields.length === 0 &&
structFields.length === 0
) {
return rows;
}
// Process rows only if we have fields that need conversion
return rows.map((row: any) => {
let hasConversions = false;
let convertedRow = row;
// Only create a new row object if we actually need to convert something
const ensureConvertedRow = () => {
if (!hasConversions) {
convertedRow = { ...row };
hasConversions = true;
}
};
// Convert decimal values
for (const field of decimalFields) {
const value = row[field.name];
if (
value !== null &&
value !== undefined &&
value.constructor?.name === 'DecimalBigNum'
) {
ensureConvertedRow();
try {
const decimalStr = value.toString();
const scale = field.type.scale || 0;
convertedRow[field.name] =
scale > 0
? parseFloat(decimalStr) / Math.pow(10, scale)
: parseFloat(decimalStr);
} catch (error) {
convertedRow[field.name] = value.toString();
}
}
}
// Convert timestamp/date values to ISO 8601 strings
for (const field of timestampFields) {
const value = row[field.name];
if (value !== null && value !== undefined) {
const hasTimezone = field.type.timezone != null;
if (value instanceof Date) {
ensureConvertedRow();
let isoString = value.toISOString();
// Remove milliseconds if .000
isoString = isoString.replace(/\.000Z$/, '');
// Add Z back if has timezone and doesn't already have it
if (hasTimezone && !isoString.endsWith('Z')) {
isoString += 'Z';
}
convertedRow[field.name] = isoString;
} else if (typeof value === 'number') {
ensureConvertedRow();
// Handle numeric timestamps
const date = new Date(value);
let isoString = date.toISOString();
// Remove milliseconds if .000
isoString = isoString.replace(/\.000Z$/, '');
// Add Z back if has timezone and doesn't already have it
if (hasTimezone && !isoString.endsWith('Z')) {
isoString += 'Z';
}
convertedRow[field.name] = isoString;
} else if (typeof value === 'string') {
ensureConvertedRow();
// Handle string timestamps (from JSON responses)
let isoString = value;
// Remove milliseconds if .000
isoString = isoString.replace(/\.000Z$/, '');
isoString = isoString.replace(/\.000$/, '');
// Add Z back if has timezone, otherwise leave without Z
if (hasTimezone && !isoString.endsWith('Z')) {
isoString += 'Z';
}
convertedRow[field.name] = isoString;
}
}
}
// Convert List/Struct fields (Arrow Vectors to JavaScript arrays/objects)
for (const field of listFields.concat(structFields)) {
const value = row[field.name];
if (value !== null && value !== undefined) {
// Find corresponding field in original schema
const originalField = originalSchema?.find(
(f: any) => f.name === field.name,
);
// If value is a JSON string, parse it first, convert timestamps, then stringify back
if (typeof value === 'string') {
try {
const parsed = JSON.parse(value);
const converted = convertTimestampsInValue(parsed, originalField);
// Always update if we successfully parsed and converted
const shouldUpdate =
JSON.stringify(converted) !== JSON.stringify(parsed);
if (shouldUpdate) {
ensureConvertedRow();
convertedRow[field.name] = JSON.stringify(converted);
}
} catch (e) {
// Not valid JSON, keep as-is
}
} else if (
typeof value === 'object' &&
(Array.isArray(value) ||
value.constructor === Object ||
value.constructor?.name === 'StructRow')
) {
// If value is already an object/array (not stringified), convert it directly
const converted = convertTimestampsInValue(value, originalField);
const shouldUpdate =
JSON.stringify(converted) !== JSON.stringify(value);
if (shouldUpdate) {
ensureConvertedRow();
convertedRow[field.name] = converted;
}
} else {
const converted = convertArrowValue(value, field);
// Only update if conversion actually changed the value
if (converted !== value) {
ensureConvertedRow();
convertedRow[field.name] = converted;
}
}
}
}
return convertedRow;
});
};
return table;
}
export class SpiceClient {
private _apiKey?: string;
private _flightUrl: string;
private _httpUrl: string;
private _userAgent: string;
private _flightTlsEnabled: boolean = true;
private _tlsClientCertFile?: string;
private _tlsClientKeyFile?: string;
private _tlsRootCertFile?: string;
private _maxRetries: number;
private _customHeaders?: { [key: string]: string };
private _platform: PlatformAdapter;
private _grpcClient: GrpcFlightClient | null = null;
private _retry: RetryModule;
private _isSpiceCloud: boolean = false;
private _flightOnly: boolean = false;
private _httpOnly: boolean = false;
private _logger: Logger;
// Default Spice Cloud endpoints
private static readonly DEFAULT_CLOUD_HTTP = 'https://data.spiceai.io';
private static readonly DEFAULT_CLOUD_FLIGHT = 'flight.spiceai.io:443';
public constructor(
params: string | SpiceClientConfig = {},
platform: PlatformAdapter,
retry: RetryModule,
GrpcClientClass?: typeof GrpcFlightClient,
) {
this._retry = retry;
this._maxRetries = retry.FLIGHT_QUERY_MAX_RETRIES;
this._platform = platform;
// support legacy constructor with api_key as first argument
if (typeof params === 'string') {
this._apiKey = params;
this._httpUrl = SpiceClient.DEFAULT_CLOUD_HTTP;
this._flightUrl = SpiceClient.DEFAULT_CLOUD_FLIGHT;
this._userAgent = platform.getUserAgent();
this._flightOnly = false;
this._logger = new Logger(true); // Default: logging enabled
} else {
const {
apiKey,
httpUrl,
flightUrl,
flightTlsEnabled,
userAgent,
customHeaders,
flightOnly,
httpOnly,
logging,
tlsClientCertFile,
tlsClientKeyFile,
tlsRootCertFile,
} = params;
// Initialize logger (default: enabled)
this._logger = new Logger(logging !== false);
this._apiKey = apiKey;
this._flightOnly = flightOnly || false;
this._httpOnly = httpOnly || false;
// Validate mutually exclusive options
if (this._flightOnly && this._httpOnly) {
throw new Error('flightOnly and httpOnly cannot both be true');
}
// Determine default endpoints based on whether API key is provided
const isCloudMode = apiKey && !httpUrl && !flightUrl;
this._httpUrl =
httpUrl ||
(isCloudMode
? SpiceClient.DEFAULT_CLOUD_HTTP
: 'http://127.0.0.1:8090');
this._flightUrl =
flightUrl ||
(isCloudMode ? SpiceClient.DEFAULT_CLOUD_FLIGHT : '127.0.0.1:50051');
// More explicit TLS check to avoid false positives
const isLocalhost =
this._flightUrl.startsWith('127.0.0.1:') ||
this._flightUrl === '127.0.0.1' ||
this._flightUrl.startsWith('localhost:') ||
this._flightUrl === 'localhost';
this._flightTlsEnabled =
flightTlsEnabled !== undefined ? flightTlsEnabled : !isLocalhost;
// Prepend the user-supplied user agent (if any) with the default user agent
this._userAgent = userAgent
? `${userAgent} ${platform.getUserAgent()}`
: platform.getUserAgent();
this._customHeaders = customHeaders;
this._tlsClientCertFile = tlsClientCertFile;
this._tlsClientKeyFile = tlsClientKeyFile;
this._tlsRootCertFile = tlsRootCertFile;
}
// Determine if this is Spice Cloud endpoint (compute once)
try {
const url = new URL(this._httpUrl);
const hostname = url.hostname.toLowerCase();
this._isSpiceCloud = hostname.endsWith('.spiceai.io');
} catch {
this._isSpiceCloud = false;
}
// Initialize gRPC client if platform supports it and not in httpOnly mode
if (platform.supportsGrpc() && GrpcClientClass && !this._httpOnly) {
this._grpcClient = new GrpcClientClass(
this._apiKey,
this._flightUrl,
this._userAgent,
this._flightTlsEnabled,
this._logger,
this._tlsClientCertFile,
this._tlsClientKeyFile,
this._tlsRootCertFile,
);
}
// Log runtime configuration
this.logConfiguration();
}
private logConfiguration(): void {
// Only log in development/debug mode (not in production, unless SPICE_DEBUG is set)
const isProduction = process.env.NODE_ENV === 'production';
const isDebugEnabled = process.env.SPICE_DEBUG === 'true';
if (isProduction && !isDebugEnabled) {
return;
}
const platformName = this._platform.getPlatformName();
const supportsGrpc = this._platform.supportsGrpc();
// Determine transport mode
let transportMode: string;
if (this._httpOnly) {
transportMode = 'HTTP only (httpOnly mode)';
} else if (supportsGrpc && this._grpcClient) {
const protocols: string[] = [];
protocols.push('Arrow Flight');
if (!this._flightOnly) protocols.push('HTTP');
transportMode = protocols.join(' → ');
} else if (supportsGrpc && !this._grpcClient) {
transportMode = 'HTTP only (Flight client not initialized)';
} else {
transportMode = 'HTTP only';
}
// Determine endpoint (use cached value)
const endpoint = this._isSpiceCloud
? `Spice Cloud (${new URL(this._httpUrl).hostname})`
: this._httpUrl;
// Build configuration message
const configLines = [
`🌶️ Spice.js initialized`,
` Platform: ${platformName}`,
` Transport: ${transportMode}`,
` Endpoint: ${endpoint}`,
];
if (this._grpcClient && this._flightUrl) {
configLines.push(
` Flight URL: ${this._flightUrl}${
this._flightTlsEnabled ? ' (TLS)' : ''
}`,
);
}
if (this._apiKey) {
configLines.push(` Auth: API Key configured`);
}
if (this._customHeaders && Object.keys(this._customHeaders).length > 0) {
configLines.push(
` Custom Headers: ${
Object.keys(this._customHeaders).length
} header(s)`,
);
}
this._logger.debug(configLines.join('\n'));
}
/**
* Extracts the value from a Param object or returns the value directly
*/
private extractParamValue(val: any): any {
// Handle Param objects
if (val instanceof Param) {
return val.value;
}
// Handle legacy Param-like objects
if (val && typeof val === 'object' && 'value' in val && 'type' in val) {
return val.value;
}
return val;
}
/**
* Converts parameters for HTTP endpoint format
*/
private convertParametersForHttp(
parameters?: QueryParameters,
): any[] | Record<string, any> {
if (!parameters) {
return [];
}
if (Array.isArray(parameters)) {
// Positional parameters - convert to simple array
return parameters.map((val) => {
const extractedVal = this.extractParamValue(val);
if (extractedVal === null) return null;
if (extractedVal instanceof Date) return extractedVal.toISOString();
if (typeof extractedVal === 'bigint') return extractedVal.toString();
// Check if it's a Buffer-like object (has toString method and type property)
if (
extractedVal &&
typeof (extractedVal as any).toString === 'function' &&
(extractedVal as any).type === 'Buffer'
) {
return (extractedVal as any).toString('base64');
}
return extractedVal;
});
} else {
// Named parameters - the runtime expects a plain JSON object map
// ({"name": value}); nested objects such as [{name, value}] are rejected
const converted: Record<string, any> = {};
for (const [name, value] of Object.entries(parameters)) {
const extractedValue = this.extractParamValue(value);
let serializedValue: any = extractedValue;
if (extractedValue instanceof Date)
serializedValue = extractedValue.toISOString();
else if (typeof extractedValue === 'bigint')
serializedValue = extractedValue.toString();
else if (
extractedValue &&
typeof (extractedValue as any).toString === 'function' &&
(extractedValue as any).type === 'Buffer'
) {
serializedValue = (extractedValue as any).toString('base64');
}
converted[name] = serializedValue;
}
return converted;
}
}
private async doQueryRequest(
queryText: string,
parameters?: QueryParameters,
onData?: (data: Table) => void,
headers?: { [key: string]: string },
): Promise<Table> {
// Transport hierarchy:
// 1. Try gRPC Flight SQL (custom proto with parameter substitution)
// 2. Fallback to HTTP
// Try gRPC Flight SQL if available
if (this._grpcClient) {
const useGrpc = await this._grpcClient.ensureInitialized();
if (useGrpc) {
// Track whether any chunk has reached the caller's callback — once it
// has, falling back to HTTP would deliver duplicate data
let dataSent = false;
const trackingOnData = onData
? (table: Table) => {
dataSent = true;
onData(table);
}
: undefined;
try {
return await this.doGrpcQueryRequest(
queryText,
parameters,
trackingOnData,
headers,
);
} catch (error) {
if (this._flightOnly || dataSent) {
throw error;
}
this._logger.warn(
`[spice.js] Arrow Flight query failed, falling back to HTTP: ${
error instanceof Error ? error.message : String(error)
}`,
);
return this.doHttpQueryRequest(
queryText,
parameters,
onData,
headers,
);
}
}
// If flightOnly mode is enabled and gRPC failed, throw error
if (this._flightOnly) {
throw new Error(
'Arrow Flight connection failed and flightOnly mode is enabled. Cannot fallback to HTTP.',
);
}
}
// If flightOnly mode is enabled but no Flight client available, throw error
if (this._flightOnly) {
throw new Error(
'flightOnly mode is enabled but Arrow Flight client is not available on this platform',
);
}
// Fallback to HTTP
return this.doHttpQueryRequest(queryText, parameters, onData, headers);
}
private async doGrpcQueryRequest(
queryText: string,
parameters?: QueryParameters,
onData?: (data: Table) => void,
headers?: { [key: string]: string },
): Promise<Table> {
if (!this._grpcClient) {
throw new Error('gRPC client not initialized');
}
try {
const resultStream = await this._grpcClient.executeQuery(
queryText,
parameters,
headers,
);
// indicates that data has been partially or fully sent
let isDataAlreadySent = false;
let schema: Buffer | undefined;
const chunks: Buffer[] = [];
resultStream.on('data', (response: FlightData) => {
const ipcMessage = getIpcMessage(response);
chunks.push(ipcMessage);
if (!schema) {
schema = ipcMessage;
} else if (onData) {
isDataAlreadySent = true;
const chunkTable = wrapTableForDecimalConversion(
tableFromIPC([schema, ipcMessage]),
);
onData(chunkTable);
}
});
return new Promise((resolve, reject) => {
resultStream.on('status', (_response: FlightStatus) => {
const table = wrapTableForDecimalConversion(tableFromIPC(chunks));
resolve(table);
});
resultStream.on('error', (err: any) => {
if (isDataAlreadySent) {
this._retry.dontRetry(err);
}
reject(err);
});
});
} catch (error) {
throw error;
}
}
private async doHttpQueryRequest(
queryText: string,
parameters?: QueryParameters,
onData?: (data: Table) => void,
headers?: { [key: string]: string },
): Promise<Table> {
// Use appropriate Accept header based on endpoint (use cached value)
const acceptHeader = this._isSpiceCloud
? 'application/vnd.spiceai.sql.v1+json' // data.spiceai.io returns schema with 'data' field
: 'application/json'; // OSS returns plain JSON array
const httpParameters = this.convertParametersForHttp(parameters);
// The JSON envelope ({sql, parameters}) is only understood by the OSS
// runtime, and only when Content-Type is exactly application/json.
// Spice Cloud parses every request body as raw SQL, so queries without
// parameters are sent as plain text — the format every endpoint accepts.
const hasHttpParameters = Array.isArray(httpParameters)
? httpParameters.length > 0
: Object.keys(httpParameters).length > 0;
let requestBody: string;
let contentType: string;
if (!hasHttpParameters) {
requestBody = queryText;
contentType = 'text/plain';
} else if (this._isSpiceCloud) {
throw new Error(
'Parameterized queries over HTTP are not supported by Spice Cloud. Use Arrow Flight (gRPC) for parameterized queries.',
);
} else {
requestBody = JSON.stringify({
sql: queryText,
parameters: httpParameters,
});
contentType = 'application/json';
}
// Custom headers merge first — the computed Content-Type/Accept always
// win, because the SDK picks the body format (raw SQL vs JSON envelope)
// and parses the response according to these values; a caller override
// would desync the headers from the body.
const requestHeaders: { [key: string]: string } = {
...headers,
'Content-Type': contentType,
Accept: acceptHeader,
};
const response = await this.fetchInternal(
'POST',
'/v1/sql',
undefined,
requestBody,
requestHeaders,
);
if (!response.ok) {
const errorText = await response.text();
throw new Error(
`HTTP query failed with status ${response.status}: ${errorText}`,
);
}
const body = await response.text();
// Try to parse as newline-delimited JSON (streaming)
const lines = body
.trim()
.split('\n')
.filter((line: string) => line.trim());
// Handle streaming responses (multiple JSON objects)
if (lines.length > 1) {
return this.parseStreamingResponse(lines, onData, this._isSpiceCloud);
}
// Handle single response
return this.parseSingleResponse(body, onData, this._isSpiceCloud);
}
private parseStreamingResponse(
lines: string[],
onData: ((data: Table) => void) | undefined,
isSpiceAI: boolean,
): Table {
const allRows: any[] = [];
let schema: any[] = [];
for (const line of lines) {
try {
const jsonData = JSON.parse(line);
const sqlV1 = convertToSqlV1Format(jsonData, isSpiceAI);
// Extract schema from first response
if (schema.length === 0) {
schema = normalizeSchema(sqlV1.schema);
}
// Accumulate rows
if (sqlV1.data.length > 0) {
allRows.push(...sqlV1.data);
// Send partial results if callback provided
if (onData) {
const partialTable = wrapTableForDecimalConversion(
jsonToArrowTable(schema, sqlV1.data),
);
onData(partialTable);
}
}
} catch (parseError) {
this._logger.warn(
`[spice.js] Failed to parse JSON line: ${parseError}`,
);
}
}
return wrapTableForDecimalConversion(jsonToArrowTable(schema, allRows));
}
private parseSingleResponse(
body: string,
onData: ((data: Table) => void) | undefined,
isSpiceAI: boolean,
): Table {
try {
const jsonData = JSON.parse(body);
const sqlV1 = convertToSqlV1Format(jsonData, isSpiceAI);
const schema = normalizeSchema(sqlV1.schema);
const rows = sqlV1.data;
// Send results via callback if provided
if (onData && rows.length > 0) {
const table = jsonToArrowTable(schema, rows);
onData(table);
}
return wrapTableForDecimalConversion(jsonToArrowTable(schema, rows));
} catch (error) {
throw new Error(
`Failed to parse query response: ${
error instanceof Error ? error.message : 'Unknown error'
}`,
);
}
}
/**
* Executes a SQL query and returns results as Arrow Tables.
* Supports parameterized queries when options.parameters is provided.
*
* @param queryText - The SQL query to execute. Use $1, $2 for positional parameters or $param_name for named parameters.
* @param optionsOrCallback - Either SqlQueryOptions with parameters, or a callback function for streaming results
* @param onData - Optional callback for streaming results (used when second parameter is SqlQueryOptions)
* @param headers - Optional headers to pass with the request (HTTP headers for HTTP, Flight metadata for gRPC)
* @returns Promise resolving to the final Arrow Table
*
* @example
* // Simple query
* await client.sql('SELECT * FROM table LIMIT 10');
*
* @example
* // Parameterized query with positional parameters
* await client.sql('SELECT * FROM table WHERE id = $1 AND status = $2', { parameters: [123, 'active'] });
*
* @example