-
-
Notifications
You must be signed in to change notification settings - Fork 92
Expand file tree
/
Copy pathDuckDBDataReader.cs
More file actions
468 lines (376 loc) · 13.8 KB
/
Copy pathDuckDBDataReader.cs
File metadata and controls
468 lines (376 loc) · 13.8 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
using DuckDB.NET.Data.DataChunk.Reader;
using DuckDB.NET.Native;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.IO;
namespace DuckDB.NET.Data;
public class DuckDBDataReader : DbDataReader
{
private readonly DuckDBCommand command;
private readonly CommandBehavior behavior;
private DuckDBResult currentResult;
private DuckDBDataChunk? currentChunk;
private int fieldCount;
private ulong currentChunkRowCount;
private ulong rowsReadFromCurrentChunk;
private bool closed;
private bool hasRows;
private bool streamingResult;
private long currentChunkIndex;
private readonly IEnumerator<DuckDBResult> resultEnumerator;
private VectorDataReaderBase[] vectorReaders = [];
private Dictionary<string, int> columnMapping = [];
internal DuckDBDataReader(DuckDBCommand command, IEnumerable<DuckDBResult> queryResults, CommandBehavior behavior)
{
this.command = command;
this.behavior = behavior;
resultEnumerator = queryResults.GetEnumerator();
InitNextReader();
}
private bool InitNextReader()
{
while (resultEnumerator.MoveNext())
{
var result = resultEnumerator.Current;
if (NativeMethods.Query.DuckDBResultReturnType(result) == DuckDBResultType.QueryResult)
{
currentChunkIndex = 0;
currentResult = result;
columnMapping = [];
fieldCount = (int)NativeMethods.Query.DuckDBColumnCount(ref currentResult);
streamingResult = NativeMethods.Types.DuckDBResultIsStreaming(currentResult) > 0;
hasRows = InitChunkData();
return true;
}
result.Close();
}
return false;
}
private bool InitChunkData()
{
foreach (var reader in vectorReaders)
{
reader.Dispose();
}
currentChunk?.Dispose();
currentChunk = streamingResult ? NativeMethods.StreamingResult.DuckDBStreamFetchChunk(currentResult) : NativeMethods.Types.DuckDBResultGetChunk(currentResult, currentChunkIndex);
rowsReadFromCurrentChunk = 0;
currentChunkRowCount = NativeMethods.DataChunks.DuckDBDataChunkGetSize(currentChunk);
if (vectorReaders.Length != fieldCount)
{
vectorReaders = new VectorDataReaderBase[fieldCount];
}
for (int index = 0; index < fieldCount; index++)
{
var vector = NativeMethods.DataChunks.DuckDBDataChunkGetVector(currentChunk, index);
using var logicalType = NativeMethods.Query.DuckDBColumnLogicalType(ref currentResult, index);
var columnName = vectorReaders[index]?.ColumnName ?? NativeMethods.Query.DuckDBColumnName(ref currentResult, index).ToManagedString(false);
vectorReaders[index] = VectorDataReaderFactory.CreateReader(vector, logicalType, columnName);
}
if (columnMapping.Count == 0)
{
for (var i = 0; i < vectorReaders.Length; i++)
{
if (!columnMapping.ContainsKey(vectorReaders[i].ColumnName))
{
columnMapping.Add(vectorReaders[i].ColumnName, i);
}
}
}
return currentChunkRowCount > 0;
}
public override bool GetBoolean(int ordinal)
{
return GetFieldValue<bool>(ordinal);
}
public override byte GetByte(int ordinal)
{
return GetFieldValue<byte>(ordinal);
}
public override long GetBytes(int ordinal, long dataOffset, byte[]? buffer, int bufferOffset, int length)
{
throw new NotImplementedException();
}
public override char GetChar(int ordinal)
{
throw new NotSupportedException();
}
public override long GetChars(int ordinal, long dataOffset, char[]? buffer, int bufferOffset, int length)
{
throw new NotSupportedException();
}
public override string GetDataTypeName(int ordinal)
{
return vectorReaders[ordinal].DuckDBType.ToString();
}
public override DateTime GetDateTime(int ordinal)
{
return GetFieldValue<DateTime>(ordinal);
}
public override decimal GetDecimal(int ordinal)
{
return GetFieldValue<decimal>(ordinal);
}
public override double GetDouble(int ordinal)
{
return GetFieldValue<double>(ordinal);
}
public override Type GetFieldType(int ordinal)
{
return vectorReaders[ordinal].ClrType;
}
public override Type GetProviderSpecificFieldType(int ordinal)
{
return vectorReaders[ordinal].ProviderSpecificClrType;
}
public override float GetFloat(int ordinal)
{
return GetFieldValue<float>(ordinal);
}
public override Guid GetGuid(int ordinal)
{
return GetFieldValue<Guid>(ordinal);
}
public override short GetInt16(int ordinal)
{
return GetFieldValue<short>(ordinal);
}
public override int GetInt32(int ordinal)
{
return GetFieldValue<int>(ordinal);
}
public override long GetInt64(int ordinal)
{
return GetFieldValue<long>(ordinal);
}
public override string GetName(int ordinal)
{
return vectorReaders[ordinal].ColumnName;
}
public override int GetOrdinal(string name)
{
if (columnMapping.TryGetValue(name, out var index))
{
return index;
}
throw new DuckDBException($"Column with name {name} was not found.");
}
public override string GetString(int ordinal)
{
return GetFieldValue<string>(ordinal);
}
public override T GetFieldValue<T>(int ordinal)
{
CheckRowRead();
return vectorReaders[ordinal].GetValue<T>(rowsReadFromCurrentChunk - 1);
}
public override object GetValue(int ordinal)
{
CheckRowRead();
return IsDBNull(ordinal) ? DBNull.Value : vectorReaders[ordinal].GetValue(rowsReadFromCurrentChunk - 1);
}
public override object GetProviderSpecificValue(int ordinal)
{
CheckRowRead();
return IsDBNull(ordinal) ? DBNull.Value : vectorReaders[ordinal].GetProviderSpecificValue(rowsReadFromCurrentChunk - 1);
}
public override int GetValues(object[] values)
{
for (var i = 0; i < FieldCount; i++)
{
values[i] = GetValue(i);
}
return FieldCount;
}
public override Stream GetStream(int ordinal)
{
return GetFieldValue<Stream>(ordinal);
}
public override bool IsDBNull(int ordinal)
{
CheckRowRead();
return !vectorReaders[ordinal].IsValid(rowsReadFromCurrentChunk - 1);
}
public override int FieldCount => fieldCount;
public override object this[int ordinal] => GetValue(ordinal);
public override object this[string name] => GetValue(GetOrdinal(name));
public override int RecordsAffected => -1;
public override bool HasRows => hasRows;
public override bool IsClosed => closed;
public override bool NextResult()
{
return InitNextReader();
}
public override bool Read()
{
if (rowsReadFromCurrentChunk == currentChunkRowCount)
{
currentChunkIndex++;
var hasData = InitChunkData();
if (hasData)
{
rowsReadFromCurrentChunk++;
}
return hasData;
}
else
{
rowsReadFromCurrentChunk++;
return true;
}
}
public override int Depth { get; }
public override IEnumerator GetEnumerator()
{
return new DbEnumerator(this, behavior == CommandBehavior.CloseConnection);
}
public override DataTable GetSchemaTable()
{
var table = new DataTable
{
Columns =
{
{ SchemaTableColumn.ColumnName, typeof(string) },
{ SchemaTableColumn.ColumnOrdinal, typeof(int) },
{ SchemaTableColumn.ColumnSize, typeof(int) },
{ SchemaTableColumn.NumericPrecision, typeof(byte)},
{ SchemaTableColumn.NumericScale, typeof(byte) },
{ SchemaTableColumn.DataType, typeof(Type) },
{ SchemaTableColumn.AllowDBNull, typeof(bool) },
{ SchemaTableColumn.BaseSchemaName, typeof(string) },
{ SchemaTableColumn.BaseTableName, typeof(string) },
{ SchemaTableColumn.BaseColumnName, typeof(string) }
}
};
// Get table names from the query
// Note: DuckDB's duckdb_get_table_names returns unique table names referenced in the query,
// not per-column mappings. For single-table queries, we can populate BaseTableName.
// For multi-table queries (joins), the mapping is not directly available from the C API.
var tableNames = GetTableNamesFromQuery();
var singleTableName = tableNames != null && tableNames.Length == 1 ? tableNames[0] : null;
var rowData = new object[10];
for (var i = 0; i < FieldCount; i++)
{
var columnName = GetName(i);
rowData[0] = columnName;
rowData[1] = i;
rowData[2] = -1;
rowData[5] = GetFieldType(i);
rowData[6] = true;
if (vectorReaders[i] is DecimalVectorDataReader decimalVectorDataReader)
{
rowData[4] = decimalVectorDataReader.Scale;
rowData[3] = decimalVectorDataReader.Precision;
}
else
{
rowData[3] = rowData[4] = DBNull.Value;
}
// Set table name information
// For single-table queries, populate the table name
// For multi-table queries, BaseTableName will be DBNull since we cannot determine
// which table each column comes from without additional API support
if (!string.IsNullOrEmpty(singleTableName))
{
// The table name from duckdb_get_table_names with qualified=true should be in the format "schema.table"
// Split by the last dot to handle schema names or table names that might contain dots
var lastDotIndex = singleTableName.LastIndexOf('.');
if (lastDotIndex > 0 && lastDotIndex < singleTableName.Length - 1)
{
rowData[7] = singleTableName.Substring(0, lastDotIndex); // BaseSchemaName
rowData[8] = singleTableName.Substring(lastDotIndex + 1); // BaseTableName
}
else
{
// No schema qualifier found, just use the table name
rowData[7] = DBNull.Value; // BaseSchemaName
rowData[8] = singleTableName; // BaseTableName
}
}
else
{
rowData[7] = DBNull.Value;
rowData[8] = DBNull.Value;
}
rowData[9] = columnName; // BaseColumnName
table.Rows.Add(rowData);
}
return table;
}
private string[]? GetTableNamesFromQuery()
{
try
{
var duckDBConnection = command?.Connection as DuckDBConnection;
if (duckDBConnection?.NativeConnection == null || command?.CommandText == null || string.IsNullOrEmpty(command.CommandText))
{
return null;
}
// Call duckdb_get_table_names with qualified=true to get schema-qualified names
using var tableNamesValue = NativeMethods.Query.DuckDBGetTableNames(
duckDBConnection.NativeConnection,
command.CommandText,
true);
if (tableNamesValue.IsNull())
{
return null;
}
// Get the size of the list
var listSize = NativeMethods.Value.DuckDBGetListSize(tableNamesValue);
// If the list is empty, return null
if (listSize == 0)
{
return null;
}
var tableNames = new string[listSize];
// Extract each table name from the list
for (ulong i = 0; i < listSize; i++)
{
using var childValue = NativeMethods.Value.DuckDBGetListChild(tableNamesValue, i);
if (!childValue.IsNull())
{
tableNames[i] = NativeMethods.Value.DuckDBGetVarchar(childValue);
}
else
{
tableNames[i] = string.Empty;
}
}
return tableNames;
}
catch (Exception ex) when (ex is DllNotFoundException or EntryPointNotFoundException or InvalidOperationException)
{
// If we fail to get table names due to missing DLL, missing entry point, or operation errors,
// just return null. This ensures backward compatibility - if the feature isn't available or fails,
// we just don't populate the table names.
// We don't log here to avoid noise in normal operation when the feature might not be available.
return null;
}
}
public override void Close()
{
if (closed) return;
foreach (var reader in vectorReaders)
{
reader.Dispose();
}
currentChunk?.Dispose();
currentResult.Close();
if (behavior == CommandBehavior.CloseConnection)
{
command.CloseConnection();
}
closed = true;
resultEnumerator.Dispose();
}
private void CheckRowRead()
{
if (rowsReadFromCurrentChunk <= 0)
{
throw new InvalidOperationException("No row has been read");
}
}
}