-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathStatementExecutionStatement.cs
More file actions
1257 lines (1114 loc) · 60 KB
/
StatementExecutionStatement.cs
File metadata and controls
1257 lines (1114 loc) · 60 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
/*
* Copyright (c) 2025 ADBC Drivers Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using AdbcDrivers.Databricks;
using AdbcDrivers.Databricks.Reader.CloudFetch;
using AdbcDrivers.Databricks.StatementExecution.MetadataCommands;
using AdbcDrivers.Databricks.Result;
using AdbcDrivers.HiveServer2;
using AdbcDrivers.HiveServer2.Hive2;
using Apache.Arrow;
using Apache.Arrow.Adbc;
using Apache.Arrow.Adbc.Tracing;
using Apache.Arrow.Ipc;
using Apache.Arrow.Types;
namespace AdbcDrivers.Databricks.StatementExecution
{
/// <summary>
/// Statement implementation using the Databricks Statement Execution REST API.
/// Handles query execution, polling, and result retrieval.
/// Extends TracingStatement for consistent tracing support with Thrift protocol.
/// </summary>
internal class StatementExecutionStatement : TracingStatement
{
private readonly IStatementExecutionClient _client;
private readonly string? _sessionId;
private readonly string _warehouseId;
private readonly string? _catalog;
private readonly string? _schema;
// Result configuration
private readonly string _resultDisposition;
private readonly string _resultFormat;
private readonly string? _resultCompression;
private readonly int _waitTimeoutSeconds;
private readonly int _pollingIntervalMs;
private readonly int _queryTimeoutSeconds; // 0 = no timeout
// Connection properties for CloudFetch configuration
private readonly IReadOnlyDictionary<string, string> _properties;
// Memory pooling
private readonly Microsoft.IO.RecyclableMemoryStreamManager _recyclableMemoryStreamManager;
private readonly System.Buffers.ArrayPool<byte> _lz4BufferPool;
// HTTP client for CloudFetch downloads
private readonly HttpClient _httpClient;
// Complex type configuration
private readonly bool _enableComplexDatatypeSupport;
// Connection reference for metadata queries
private readonly StatementExecutionConnection _connection;
// Statement state
private string? _currentStatementId;
private string? _sqlQuery;
// Metadata command support
private bool _isMetadataCommand;
private bool _escapePatternWildcards;
private string? _metadataCatalogName;
private string? _metadataSchemaName;
private string? _metadataTableName;
private string? _metadataColumnName;
private string? _metadataTableTypes;
private string? _metadataForeignCatalogName;
private string? _metadataForeignSchemaName;
private string? _metadataForeignTableName;
public StatementExecutionStatement(
IStatementExecutionClient client,
string? sessionId,
string warehouseId,
string? catalog,
string? schema,
string resultDisposition,
string resultFormat,
string? resultCompression,
int waitTimeoutSeconds,
int pollingIntervalMs,
IReadOnlyDictionary<string, string> properties,
Microsoft.IO.RecyclableMemoryStreamManager recyclableMemoryStreamManager,
System.Buffers.ArrayPool<byte> lz4BufferPool,
HttpClient httpClient,
StatementExecutionConnection connection)
: base(connection)
{
_connection = connection ?? throw new ArgumentNullException(nameof(connection));
_client = client ?? throw new ArgumentNullException(nameof(client));
_sessionId = sessionId;
_warehouseId = warehouseId ?? throw new ArgumentNullException(nameof(warehouseId));
_catalog = catalog;
_schema = schema;
_resultDisposition = resultDisposition ?? throw new ArgumentNullException(nameof(resultDisposition));
_resultFormat = resultFormat ?? throw new ArgumentNullException(nameof(resultFormat));
_resultCompression = resultCompression;
_waitTimeoutSeconds = waitTimeoutSeconds;
_pollingIntervalMs = pollingIntervalMs;
_properties = properties ?? throw new ArgumentNullException(nameof(properties));
_queryTimeoutSeconds = PropertyHelper.GetIntPropertyWithValidation(
properties, ApacheParameters.QueryTimeoutSeconds, 0);
_recyclableMemoryStreamManager = recyclableMemoryStreamManager ?? throw new ArgumentNullException(nameof(recyclableMemoryStreamManager));
_lz4BufferPool = lz4BufferPool ?? throw new ArgumentNullException(nameof(lz4BufferPool));
_httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient));
_enableComplexDatatypeSupport = connection.EnableComplexDatatypeSupport;
}
/// <summary>
/// Gets or sets the SQL query to execute.
/// </summary>
public override string? SqlQuery
{
get => _sqlQuery;
set => _sqlQuery = value;
}
public override void SetOption(string key, string value)
{
switch (key)
{
case ApacheParameters.IsMetadataCommand:
_isMetadataCommand = bool.TryParse(value, out bool b) && b;
break;
case ApacheParameters.CatalogName:
_metadataCatalogName = value;
break;
case ApacheParameters.SchemaName:
_metadataSchemaName = value;
break;
case ApacheParameters.TableName:
_metadataTableName = value;
break;
case ApacheParameters.ColumnName:
_metadataColumnName = value;
break;
case ApacheParameters.ForeignCatalogName:
_metadataForeignCatalogName = value;
break;
case ApacheParameters.ForeignSchemaName:
_metadataForeignSchemaName = value;
break;
case ApacheParameters.ForeignTableName:
_metadataForeignTableName = value;
break;
case ApacheParameters.TableTypes:
_metadataTableTypes = value;
break;
case ApacheParameters.EscapePatternWildcards:
_escapePatternWildcards = bool.TryParse(value, out bool escape) && escape;
break;
// These options are readonly in SEA (set at connection level).
// Accept but ignore them to avoid NotImplemented exceptions for compatibility.
case ApacheParameters.PollTimeMilliseconds:
case ApacheParameters.BatchSize:
case ApacheParameters.BatchSizeStopCondition:
case ApacheParameters.QueryTimeoutSeconds:
break;
// DatabricksStatement-specific options: accept but ignore for now.
// TODO(PECOBLR-2259): Implement query_tags support for SEA. The SEA API uses a
// JSON array of {key, value} objects in the executestatement request body,
// unlike Thrift which sends a string in confOverlay.
case DatabricksParameters.QueryTags:
case DatabricksParameters.UseCloudFetch:
case DatabricksParameters.CanDecompressLz4:
case DatabricksParameters.MaxBytesPerFile:
case DatabricksParameters.MaxBytesPerFetchRequest:
break;
default:
base.SetOption(key, value);
break;
}
}
public override QueryResult ExecuteQuery()
{
return ExecuteQueryAsync(CancellationToken.None).GetAwaiter().GetResult();
}
/// <summary>
/// Executes the query asynchronously.
/// </summary>
/// <param name="cancellationToken">Cancellation token.</param>
/// <param name="isMetadataExecution">When true, adds the x-databricks-sea-can-run-fully-sync
/// header for optimized metadata query execution on the server.</param>
public async Task<QueryResult> ExecuteQueryAsync(
CancellationToken cancellationToken = default,
bool isMetadataExecution = false)
{
if (_isMetadataCommand)
{
return await ExecuteMetadataCommandAsync(cancellationToken).ConfigureAwait(false);
}
if (string.IsNullOrEmpty(_sqlQuery))
{
throw new InvalidOperationException("SQL query is required");
}
// Build the execute statement request
// Note: warehouse_id is always required by the Databricks Statement Execution API
// Note: catalog/schema cannot be set when session_id is provided (session has context)
var request = new ExecuteStatementRequest
{
Statement = _sqlQuery,
WarehouseId = _warehouseId,
SessionId = _sessionId,
Catalog = string.IsNullOrEmpty(_sessionId) ? _catalog : null,
Schema = string.IsNullOrEmpty(_sessionId) ? _schema : null,
Disposition = _resultDisposition,
Format = _resultFormat,
ResultCompression = _resultCompression,
WaitTimeout = $"{_waitTimeoutSeconds}s",
OnWaitTimeout = "CONTINUE",
IsMetadata = isMetadataExecution
};
// Execute the statement
var response = await _client.ExecuteStatementAsync(request, cancellationToken).ConfigureAwait(false);
_currentStatementId = response.StatementId;
// Handle query status according to Databricks API documentation:
// PENDING: waiting for warehouse - continue polling
// RUNNING: running - continue polling
// SUCCEEDED: execution was successful, result data available for fetch
// FAILED: execution failed; reason for failure described in accompanying error message
// CANCELED: user canceled; can come from explicit cancel call, or timeout with on_wait_timeout=CANCEL
// CLOSED: execution successful, and statement closed; result no longer available for fetch
var state = response.Status?.State;
if (state == "PENDING" || state == "RUNNING")
{
response = await PollWithTimeoutAsync(response.StatementId, cancellationToken).ConfigureAwait(false);
state = response.Status?.State;
}
// Check for terminal error states
if (state == "FAILED")
{
var error = response.Status?.Error;
throw new AdbcException($"Statement execution failed: {error?.Message ?? "Unknown error"} (Error Code: {error?.ErrorCode})");
}
if (state == "CANCELED")
{
throw new AdbcException("Statement execution was canceled");
}
if (state == "CLOSED")
{
throw new AdbcException("Statement was closed before results could be retrieved");
}
// Check for truncated results warning
if (response.Manifest?.Truncated == true)
{
Activity.Current?.AddEvent(new ActivityEvent("statement.results_truncated",
tags: new ActivityTagsCollection
{
{ "total_row_count", response.Manifest.TotalRowCount },
{ "total_byte_count", response.Manifest.TotalByteCount }
}));
}
// Create appropriate reader based on result disposition
IArrowArrayStream reader = CreateReader(response, cancellationToken);
// When EnableComplexDatatypeSupport=false (default), serialize complex Arrow types to JSON strings
// so that SEA behavior matches Thrift (which sets ComplexTypesAsArrow=false).
if (!_enableComplexDatatypeSupport)
{
reader = new ComplexTypeSerializingStream(reader);
}
// Get schema from reader
var schema = reader.Schema;
// Return query result - use -1 if row count is not available
long rowCount = response.Manifest?.TotalRowCount ?? -1;
return new QueryResult(rowCount, reader);
}
/// <summary>
/// Wraps PollUntilCompleteAsync with query timeout enforcement.
/// If _queryTimeoutSeconds > 0, cancels the server-side statement and throws on timeout.
/// </summary>
private async Task<ExecuteStatementResponse> PollWithTimeoutAsync(string statementId, CancellationToken cancellationToken)
{
if (_queryTimeoutSeconds <= 0)
{
return await PollUntilCompleteAsync(statementId, cancellationToken).ConfigureAwait(false);
}
using var timeoutCts = new CancellationTokenSource(TimeSpan.FromSeconds(_queryTimeoutSeconds));
using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeoutCts.Token);
try
{
return await PollUntilCompleteAsync(statementId, linkedCts.Token).ConfigureAwait(false);
}
catch (OperationCanceledException) when (timeoutCts.IsCancellationRequested && !cancellationToken.IsCancellationRequested)
{
// Timeout fired (not caller cancellation) — cancel statement on server, best-effort
try
{
await _client.CancelStatementAsync(statementId, CancellationToken.None).ConfigureAwait(false);
}
catch
{
// Best-effort; ignore cancel errors
}
throw new AdbcException(
$"Query timed out after {_queryTimeoutSeconds} seconds (statement {statementId}). " +
$"Increase timeout via '{ApacheParameters.QueryTimeoutSeconds}' or set to 0 for no timeout.");
}
}
/// <summary>
/// Polls the statement until it reaches a terminal state.
/// Terminal states: SUCCEEDED, FAILED, CANCELED, CLOSED
/// Non-terminal states: PENDING, RUNNING
/// </summary>
private async Task<ExecuteStatementResponse> PollUntilCompleteAsync(string statementId, CancellationToken cancellationToken)
{
while (true)
{
// Check for cancellation before each polling iteration
cancellationToken.ThrowIfCancellationRequested();
// Wait for polling interval
await Task.Delay(_pollingIntervalMs, cancellationToken).ConfigureAwait(false);
// Check for cancellation after delay
cancellationToken.ThrowIfCancellationRequested();
// Get statement status
var response = await _client.GetStatementAsync(statementId, cancellationToken).ConfigureAwait(false);
// Convert GetStatementResponse to ExecuteStatementResponse
var executeResponse = new ExecuteStatementResponse
{
StatementId = response.StatementId,
Status = response.Status,
Manifest = response.Manifest,
Result = response.Result
};
// Check if reached a terminal state
var state = response.Status?.State;
if (state == "SUCCEEDED" ||
state == "FAILED" ||
state == "CANCELED" ||
state == "CLOSED")
{
return executeResponse;
}
// Continue polling for PENDING and RUNNING states
}
}
/// <summary>
/// Creates an appropriate reader based on the result disposition.
/// </summary>
private IArrowArrayStream CreateReader(ExecuteStatementResponse response, CancellationToken cancellationToken)
{
if (response.Manifest == null)
{
// No results - return empty reader
return new EmptyArrowArrayStream();
}
// Check for external links in manifest chunks or result
bool hasExternalLinksInChunks = response.Manifest.Chunks != null &&
response.Manifest.Chunks.Count > 0 &&
response.Manifest.Chunks[0].ExternalLinks != null &&
response.Manifest.Chunks[0].ExternalLinks.Count > 0;
bool hasExternalLinksInResult = response.Result != null &&
response.Result.ExternalLinks != null &&
response.Result.ExternalLinks.Count > 0;
bool hasExternalLinks = hasExternalLinksInChunks || hasExternalLinksInResult;
if (hasExternalLinks)
{
// Use CloudFetch for external links
return CreateCloudFetchReader(response);
}
else if (response.Result != null && response.Result.Attachment != null && response.Result.Attachment.Length > 0)
{
// Check if data is LZ4 compressed
bool isLz4Compressed = response.Manifest?.ResultCompression?.ToUpperInvariant() == "LZ4_FRAME";
// Inline results - may be split across multiple chunks
int totalChunks = response.Manifest?.Chunks?.Count ?? 1;
return new InlineArrowStreamReader(_client, _currentStatementId!, response.Result.Attachment,
isLz4Compressed, totalChunks, _lz4BufferPool, cancellationToken);
}
else
{
// No data rows, but the manifest contains schema information.
// Preserve the schema so callers get correct column metadata even
// when the queried table is empty — following the same pattern as
// the JDBC driver where ResultManifest schema is always extracted
// independently of data presence.
Schema schema = TryGetSchemaFromManifest(response.Manifest) ?? new Schema.Builder().Build();
return new EmptyArrowArrayStream(schema);
}
}
/// <summary>
/// Creates a CloudFetch reader for external link results.
/// </summary>
private IArrowArrayStream CreateCloudFetchReader(ExecuteStatementResponse response)
{
var manifest = response.Manifest!;
// Build schema from manifest
var schema = GetSchemaFromManifest(manifest);
// The Statement Execution API response structure:
// - manifest.chunks: Array of ChunkInfo with metadata for ALL chunks (row counts, offsets, etc.)
// - result.external_links: Presigned URL for chunk 0 only (subsequent chunks fetched via GetChunk API)
//
// We pass the initial external links separately to avoid mutating the manifest.
var initialExternalLinks = response.Result?.ExternalLinks;
return CloudFetchReaderFactory.CreateStatementExecutionReader(
_client,
_currentStatementId!,
schema,
manifest,
initialExternalLinks,
_httpClient,
_properties,
_recyclableMemoryStreamManager,
_lz4BufferPool,
this); // Pass statement as ITracingStatement (via TracingStatement base class)
}
/// <summary>
/// Extracts the Arrow schema from the result manifest.
/// Throws <see cref="AdbcException"/> if the manifest contains no column definitions.
/// </summary>
private Schema GetSchemaFromManifest(ResultManifest manifest)
{
return TryGetSchemaFromManifest(manifest)
?? throw new AdbcException("Result manifest does not contain schema information");
}
/// <summary>
/// Tries to extract the Arrow schema from the result manifest.
/// Returns <c>null</c> when the manifest contains no column definitions,
/// allowing callers to decide on a fallback (e.g. empty schema for no-data results).
/// </summary>
private Schema? TryGetSchemaFromManifest(ResultManifest manifest)
{
if (manifest.Schema == null || manifest.Schema.Columns == null || manifest.Schema.Columns.Count == 0)
{
return null;
}
var fields = new List<Field>();
foreach (var column in manifest.Schema.Columns)
{
var typeName = column.TypeName ?? string.Empty;
var arrowType = MapDatabricksTypeToArrowType(typeName);
// Embed the SQL type name as Arrow field metadata so that consumers
// (e.g. the PowerBI connector's AdjustNativeTypes) can read it via
// the "Spark:DataType:SqlName" key — the same metadata the Databricks
// server embeds in the Arrow IPC stream for non-empty results.
//
// Note: the Thrift server also sets "Spark:DataType:JsonType" (the JSON
// representation of the type, e.g. "{\"type\":\"integer\"}") alongside
// SqlName. That key is not read by any known consumer today, so we omit
// it here for now. Add it if a consumer requires it (PECO-2950).
var metadata = new Dictionary<string, string>
{
["Spark:DataType:SqlName"] = ColumnMetadataHelper.GetSparkSqlName(typeName)
};
fields.Add(new Field(column.Name, arrowType, true, metadata));
}
return new Schema(fields, null);
}
/// <summary>
/// Maps Databricks SQL type names to Arrow types.
/// </summary>
private IArrowType MapDatabricksTypeToArrowType(string typeName)
{
// Handle parameterized types (e.g., DECIMAL(10,2), VARCHAR(100))
var baseType = typeName.Split('(')[0].ToUpperInvariant();
return baseType switch
{
"BOOLEAN" => BooleanType.Default,
"BYTE" or "TINYINT" => Int8Type.Default,
"SHORT" or "SMALLINT" => Int16Type.Default,
"INT" or "INTEGER" => Int32Type.Default,
"LONG" or "BIGINT" => Int64Type.Default,
"FLOAT" or "REAL" => FloatType.Default,
"DOUBLE" => DoubleType.Default,
"DECIMAL" or "NUMERIC" => ParseDecimalType(typeName),
"STRING" or "VARCHAR" or "CHAR" => StringType.Default,
"BINARY" or "VARBINARY" => BinaryType.Default,
"DATE" => Date32Type.Default,
"TIMESTAMP" or "TIMESTAMP_NTZ" or "TIMESTAMP_LTZ" => TimestampType.Default,
"INTERVAL" => StringType.Default, // Intervals as strings for now
"ARRAY" => StringType.Default, // Complex types as strings for now
"MAP" => StringType.Default,
"STRUCT" => StringType.Default,
"NULL" or "VOID" => NullType.Default,
_ => StringType.Default // Default to string for unknown types
};
}
/// <summary>
/// Parses a DECIMAL type to determine precision and scale.
/// </summary>
private IArrowType ParseDecimalType(string typeName)
{
// Default precision and scale
int precision = 38;
int scale = 18;
// Try to parse DECIMAL(precision, scale)
var match = System.Text.RegularExpressions.Regex.Match(typeName, @"DECIMAL\((\d+),\s*(\d+)\)", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
if (match.Success)
{
precision = int.Parse(match.Groups[1].Value);
scale = int.Parse(match.Groups[2].Value);
}
return new Decimal128Type(precision, scale);
}
/// <summary>
/// Executes an update query and returns the number of affected rows.
/// </summary>
public override UpdateResult ExecuteUpdate()
{
return ExecuteUpdateAsync(CancellationToken.None).GetAwaiter().GetResult();
}
/// <summary>
/// Executes an update query asynchronously and returns the number of affected rows.
/// </summary>
public async Task<UpdateResult> ExecuteUpdateAsync(CancellationToken cancellationToken = default)
{
if (string.IsNullOrEmpty(_sqlQuery))
{
throw new InvalidOperationException("SQL query is required");
}
// Build the execute statement request
// Note: catalog/schema cannot be set when session_id is provided (session has context)
var request = new ExecuteStatementRequest
{
Statement = _sqlQuery,
WarehouseId = _warehouseId,
SessionId = _sessionId,
Catalog = string.IsNullOrEmpty(_sessionId) ? _catalog : null,
Schema = string.IsNullOrEmpty(_sessionId) ? _schema : null,
Disposition = _resultDisposition,
Format = _resultFormat,
ResultCompression = _resultCompression,
WaitTimeout = $"{_waitTimeoutSeconds}s",
OnWaitTimeout = "CONTINUE",
IsMetadata = false
};
// Execute the statement
var response = await _client.ExecuteStatementAsync(request, cancellationToken).ConfigureAwait(false);
_currentStatementId = response.StatementId;
// Handle query status - poll until complete
var state = response.Status?.State;
if (state == "PENDING" || state == "RUNNING")
{
response = await PollWithTimeoutAsync(response.StatementId, cancellationToken).ConfigureAwait(false);
state = response.Status?.State;
}
// Check for terminal error states
if (state == "FAILED")
{
var error = response.Status?.Error;
throw new AdbcException($"Statement execution failed: {error?.Message ?? "Unknown error"} (Error Code: {error?.ErrorCode})");
}
if (state == "CANCELED")
{
throw new AdbcException("Statement execution was canceled");
}
if (state == "CLOSED")
{
throw new AdbcException("Statement was closed before results could be retrieved");
}
// For updates, we don't need to read the results - just return the row count
long rowCount = response.Manifest?.TotalRowCount ?? 0;
return new UpdateResult(rowCount);
}
/// <summary>
/// Disposes the statement and cancels/closes any active statement.
/// </summary>
public override void Dispose()
{
if (_currentStatementId != null)
{
try
{
// Close statement synchronously during dispose
Activity.Current?.AddEvent(new ActivityEvent("statement.dispose",
tags: new ActivityTagsCollection
{
{ "statement_id", _currentStatementId }
}));
_client.CloseStatementAsync(_currentStatementId, CancellationToken.None).GetAwaiter().GetResult();
}
catch (Exception ex)
{
// Best effort - ignore errors during dispose
Activity.Current?.AddEvent(new ActivityEvent("statement.dispose.error",
tags: new ActivityTagsCollection
{
{ "error", ex.Message }
}));
}
finally
{
_currentStatementId = null;
}
}
}
/// <summary>
/// Empty Arrow array stream for queries with no results.
/// Accepts an optional schema so that column metadata is preserved
/// even when the result contains zero rows (e.g. querying an empty table).
/// </summary>
private class EmptyArrowArrayStream : IArrowArrayStream
{
public EmptyArrowArrayStream(Schema? schema = null)
{
Schema = schema ?? new Schema.Builder().Build();
}
public Schema Schema { get; }
public ValueTask<RecordBatch?> ReadNextRecordBatchAsync(CancellationToken cancellationToken = default)
{
return new ValueTask<RecordBatch?>((RecordBatch?)null);
}
public void Dispose()
{
// Nothing to dispose
}
}
/// <summary>
/// Reader for inline results in Arrow IPC stream format.
/// Handles both single-chunk and multi-chunk inline results by fetching
/// all chunks and concatenating them into a single Arrow stream.
/// Supports LZ4_FRAME compressed data.
/// </summary>
private class InlineArrowStreamReader : IArrowArrayStream
{
private readonly ArrowStreamReader _streamReader;
private readonly System.IO.MemoryStream _memoryStream;
private bool _disposed;
public InlineArrowStreamReader(
IStatementExecutionClient client,
string statementId,
byte[] firstChunkData,
bool isLz4Compressed,
int totalChunks,
System.Buffers.ArrayPool<byte> bufferPool,
CancellationToken cancellationToken)
{
if (firstChunkData == null || firstChunkData.Length == 0)
{
throw new ArgumentException("First chunk data cannot be null or empty", nameof(firstChunkData));
}
// Fetch and concatenate all chunks
var allData = FetchAllChunksAsync(client, statementId, firstChunkData, isLz4Compressed, totalChunks, bufferPool, cancellationToken).GetAwaiter().GetResult();
_memoryStream = new System.IO.MemoryStream(allData);
_streamReader = new ArrowStreamReader(_memoryStream);
}
public Schema Schema => _streamReader.Schema;
public async ValueTask<RecordBatch?> ReadNextRecordBatchAsync(CancellationToken cancellationToken = default)
{
if (_disposed)
{
throw new ObjectDisposedException(nameof(InlineArrowStreamReader));
}
return await _streamReader.ReadNextRecordBatchAsync(cancellationToken).ConfigureAwait(false);
}
public void Dispose()
{
if (!_disposed)
{
_streamReader?.Dispose();
_memoryStream?.Dispose();
_disposed = true;
}
}
private static async Task<byte[]> FetchAllChunksAsync(
IStatementExecutionClient client,
string statementId,
byte[] firstChunkData,
bool isLz4Compressed,
int totalChunks,
System.Buffers.ArrayPool<byte> bufferPool,
CancellationToken cancellationToken)
{
// Start with the first chunk (already have it inline)
var chunks = new List<byte[]>();
// Decompress first chunk if needed
if (isLz4Compressed)
{
var decompressed = Lz4Utilities.DecompressLz4(firstChunkData, bufferPool);
chunks.Add(decompressed.ToArray());
}
else
{
chunks.Add(firstChunkData);
}
// Fetch remaining chunks (chunks are 0-indexed, chunk 0 is already inline)
for (int i = 1; i < totalChunks; i++)
{
var chunkResult = await client.GetResultChunkAsync(statementId, i, cancellationToken).ConfigureAwait(false);
if (chunkResult.Attachment != null && chunkResult.Attachment.Length > 0)
{
if (isLz4Compressed)
{
var decompressed = Lz4Utilities.DecompressLz4(chunkResult.Attachment, bufferPool);
chunks.Add(decompressed.ToArray());
}
else
{
chunks.Add(chunkResult.Attachment);
}
}
}
// Concatenate all chunks
int totalLength = chunks.Sum(c => c.Length);
byte[] result = new byte[totalLength];
int offset = 0;
foreach (var chunk in chunks)
{
Buffer.BlockCopy(chunk, 0, result, offset, chunk.Length);
offset += chunk.Length;
}
return result;
}
}
// Metadata command routing
private string? EffectiveCatalog => _connection.ResolveEffectiveCatalog(_metadataCatalogName);
/// <summary>
/// Escapes wildcard characters (_ and %) in metadata name parameters when
/// EscapePatternWildcards is enabled. This prevents literal underscores or
/// percent signs in identifiers from being treated as pattern wildcards.
/// </summary>
private string? EscapePatternWildcardsInName(string? name)
{
if (!_escapePatternWildcards || name == null)
return name;
return name.Replace("_", "\\_").Replace("%", "\\%");
}
private Task<QueryResult> ExecuteMetadataCommandAsync(CancellationToken cancellationToken)
{
return _sqlQuery?.ToLowerInvariant() switch
{
"getcatalogs" => GetCatalogsAsync(cancellationToken),
"getschemas" => GetSchemasAsync(cancellationToken),
"gettables" => GetTablesAsync(cancellationToken),
"getcolumns" => GetColumnsAsync(cancellationToken),
"getcolumnsextended" => GetColumnsExtendedAsync(cancellationToken),
"getprimarykeys" => GetPrimaryKeysAsync(cancellationToken),
"getcrossreference" => GetCrossReferenceAsync(cancellationToken),
_ => throw new NotSupportedException($"Metadata command '{_sqlQuery}' is not supported"),
};
}
private async Task<QueryResult> GetCatalogsAsync(CancellationToken cancellationToken)
{
return await this.TraceActivityAsync(async activity =>
{
activity?.SetTag("catalog_pattern", _metadataCatalogName ?? "(none)");
activity?.SetTag("enable_multiple_catalog_support", _connection.EnableMultipleCatalogSupport);
// When multiple catalog support is disabled, return a single "SPARK" catalog
if (!_connection.EnableMultipleCatalogSupport)
{
var catalogSchema = MetadataSchemaFactory.CreateCatalogsSchema();
var sparkBuilder = new StringArray.Builder();
sparkBuilder.Append("SPARK");
return new QueryResult(1, new HiveInfoArrowStream(catalogSchema, new IArrowArray[] { sparkBuilder.Build() }));
}
string sql = new ShowCatalogsCommand(EscapePatternWildcardsInName(_metadataCatalogName)).Build();
activity?.SetTag("sql_query", sql);
var batches = await _connection.ExecuteMetadataSqlAsync(sql, cancellationToken).ConfigureAwait(false);
var tableCatBuilder = new StringArray.Builder();
int count = 0;
foreach (var batch in batches)
{
var catalogArray = TryGetColumn<StringArray>(batch, "catalog");
if (catalogArray == null) continue;
for (int i = 0; i < batch.Length; i++)
{
if (!catalogArray.IsNull(i))
{
tableCatBuilder.Append(catalogArray.GetString(i));
count++;
}
}
}
activity?.SetTag("result_count", count);
var schema = MetadataSchemaFactory.CreateCatalogsSchema();
return new QueryResult(count, new HiveInfoArrowStream(schema, new IArrowArray[] { tableCatBuilder.Build() }));
}, "GetCatalogs").ConfigureAwait(false);
}
private async Task<QueryResult> GetSchemasAsync(CancellationToken cancellationToken)
{
return await this.TraceActivityAsync(async activity =>
{
var catalog = EffectiveCatalog;
activity?.SetTag("catalog", catalog ?? "(none)");
activity?.SetTag("schema_pattern", _metadataSchemaName ?? "(none)");
activity?.SetTag("enable_multiple_catalog_support", _connection.EnableMultipleCatalogSupport);
// When flag=false and user specified an explicit non-SPARK catalog, return empty
if (!_connection.EnableMultipleCatalogSupport
&& MetadataUtilities.NormalizeSparkCatalog(_metadataCatalogName) != null)
return MetadataSchemaFactory.CreateEmptySchemasResult();
string sql = new ShowSchemasCommand(
catalog,
EscapePatternWildcardsInName(_metadataSchemaName)).Build();
activity?.SetTag("sql_query", sql);
var batches = await _connection.ExecuteMetadataSqlAsync(sql, cancellationToken).ConfigureAwait(false);
// SHOW SCHEMAS IN ALL CATALOGS returns 2 columns: catalog_name, databaseName
// SHOW SCHEMAS IN `catalog` returns 1 column: databaseName
bool showAllCatalogs = catalog == null;
var tableSchemaBuilder = new StringArray.Builder();
var tableCatalogBuilder = new StringArray.Builder();
int count = 0;
foreach (var batch in batches)
{
StringArray? catalogArray = null;
StringArray? schemaArray = null;
if (showAllCatalogs)
{
catalogArray = batch.Column(0) as StringArray;
schemaArray = batch.Column(1) as StringArray;
}
else
{
schemaArray = batch.Column(0) as StringArray;
}
if (schemaArray == null) continue;
for (int i = 0; i < batch.Length; i++)
{
if (schemaArray.IsNull(i)) continue;
tableSchemaBuilder.Append(schemaArray.GetString(i));
string catalogValue = catalogArray != null && !catalogArray.IsNull(i)
? catalogArray.GetString(i)
: catalog ?? "";
tableCatalogBuilder.Append(catalogValue);
count++;
}
}
activity?.SetTag("result_count", count);
var schema = MetadataSchemaFactory.CreateSchemasSchema();
return new QueryResult(count, new HiveInfoArrowStream(schema, new IArrowArray[]
{
tableSchemaBuilder.Build(), tableCatalogBuilder.Build()
}));
}, "GetSchemas").ConfigureAwait(false);
}
private async Task<QueryResult> GetTablesAsync(CancellationToken cancellationToken)
{
return await this.TraceActivityAsync(async activity =>
{
var catalog = EffectiveCatalog;
activity?.SetTag("catalog", catalog ?? "(none)");
activity?.SetTag("schema_pattern", _metadataSchemaName ?? "(none)");
activity?.SetTag("table_pattern", _metadataTableName ?? "(none)");
activity?.SetTag("enable_multiple_catalog_support", _connection.EnableMultipleCatalogSupport);
if (!_connection.EnableMultipleCatalogSupport
&& MetadataUtilities.NormalizeSparkCatalog(_metadataCatalogName) != null)
return MetadataSchemaFactory.CreateEmptyTablesResult();
string sql = new ShowTablesCommand(
catalog,
EscapePatternWildcardsInName(_metadataSchemaName),
EscapePatternWildcardsInName(_metadataTableName)).Build();
activity?.SetTag("sql_query", sql);
var batches = await _connection.ExecuteMetadataSqlAsync(sql, cancellationToken).ConfigureAwait(false);
var tableCatBuilder = new StringArray.Builder();
var tableSchemaBuilder = new StringArray.Builder();
var tableNameBuilder = new StringArray.Builder();
var tableTypeBuilder = new StringArray.Builder();
var remarksBuilder = new StringArray.Builder();
var typeCatBuilder = new StringArray.Builder();
var typeSchemaBuilder = new StringArray.Builder();
var typeNameBuilder = new StringArray.Builder();
var selfRefColBuilder = new StringArray.Builder();
var refGenBuilder = new StringArray.Builder();
var tableTypeFilter = !string.IsNullOrEmpty(_metadataTableTypes)
? new HashSet<string>(
_metadataTableTypes!.Split(',').Select(t => t.Trim()),
StringComparer.OrdinalIgnoreCase)
: null;
int count = 0;
foreach (var batch in batches)
{
var catalogArray = TryGetColumn<StringArray>(batch, "catalogName");
var schemaArray = TryGetColumn<StringArray>(batch, "namespace");
var tableArray = TryGetColumn<StringArray>(batch, "tableName");
var tableTypeArray = TryGetColumn<StringArray>(batch, "tableType");
var remarksArray = TryGetColumn<StringArray>(batch, "remarks");
if (catalogArray == null || schemaArray == null || tableArray == null) continue;
for (int i = 0; i < batch.Length; i++)
{
if (catalogArray.IsNull(i) || schemaArray.IsNull(i) || tableArray.IsNull(i)) continue;
string tableType = tableTypeArray != null && !tableTypeArray.IsNull(i) ? tableTypeArray.GetString(i) : "TABLE";
if (tableTypeFilter != null && !tableTypeFilter.Contains(tableType)) continue;
tableCatBuilder.Append(catalogArray.GetString(i));
tableSchemaBuilder.Append(schemaArray.GetString(i));
tableNameBuilder.Append(tableArray.GetString(i));
tableTypeBuilder.Append(tableType);
remarksBuilder.Append(remarksArray != null && !remarksArray.IsNull(i) ? remarksArray.GetString(i) : "");
typeCatBuilder.AppendNull();
typeSchemaBuilder.AppendNull();
typeNameBuilder.AppendNull();
selfRefColBuilder.AppendNull();
refGenBuilder.AppendNull();
count++;
}
}
activity?.SetTag("result_count", count);
var schema = MetadataSchemaFactory.CreateTablesSchema();
return new QueryResult(count, new HiveInfoArrowStream(schema, new IArrowArray[]
{
tableCatBuilder.Build(), tableSchemaBuilder.Build(), tableNameBuilder.Build(),