• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

Giorgi / DuckDB.NET / 45665699352

25 Nov 2026 11:40AM UTC coverage: 93.942%. Remained the same
45665699352

push

github

web-flow
Merge pull request #396 from Giorgi/ccr-a946efa5-2d13qn

Register functions in Functions/, without the ADO.NET classes

3121 of 3368 branches covered (92.67%)

Branch coverage included in aggregate %.

662 of 705 new or added lines in 10 files covered. (93.9%)

8 existing lines in 2 files now uncovered.

4834 of 5100 relevant lines covered (94.78%)

916145.94 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

90.32
/DuckDB.NET.Data/Functions/TableFunctionRegistration.cs
1
using DuckDB.NET.Data.Common;
2
using DuckDB.NET.Data.Connection;
3
using DuckDB.NET.Data.DataChunk.Writer;
4
using System.Runtime.CompilerServices;
5
using System.Runtime.InteropServices;
6

7
namespace DuckDB.NET.Data.Functions;
8

9
// Every table function is registered here, by the public methods of DuckDBConnection and of
10
// DuckDBConnectionTableFunctionExtensions. DuckDB.ExtensionKit compiles this folder too (see AGENTS.md here), so
11
// nothing in it depends on the ADO.NET classes: it takes the native connection, and what only DuckDB.NET does with
12
// the exception of a function goes through UdfErrors.
13
internal static class TableFunctionRegistration
14
{
15
    // The low-level registration: the rows are an IEnumerable, and the mapper writes a row as an object.
16
    public static void Register(DuckDBNativeConnection connection, string name, Func<IReadOnlyList<IDuckDBValueReader>, IReadOnlyDictionary<string, IDuckDBValueReader>, TableFunction> resultCallback, Action<object?, IDuckDBDataWriter[], ulong> mapperCallback, DuckDBLogicalType[] positionalLogicalTypes, NamedParameterDefinition[] namedParameters)
17
    {
18
        Register(connection, name, resultCallback, (data, projected, columnCount) => new ObjectTableFunctionScan(data.GetEnumerator(), mapperCallback, projected, columnCount), positionalLogicalTypes, namedParameters);
291 ✔
19
    }
156 ✔
20

21
    public static unsafe void Register(DuckDBNativeConnection connection, string name, Func<IReadOnlyList<IDuckDBValueReader>, IReadOnlyDictionary<string, IDuckDBValueReader>, TableFunction> resultCallback, TableFunctionScanFactory createScan, DuckDBLogicalType[] positionalLogicalTypes, NamedParameterDefinition[] namedParameters)
22
    {
23
        var function = NativeMethods.TableFunction.DuckDBCreateTableFunction();
396 ✔
24
        NativeMethods.TableFunction.DuckDBTableFunctionSetName(function, name);
396 ✔
25

26
        foreach (var logicalType in positionalLogicalTypes)
1,278 ✔
27
        {
28
            NativeMethods.TableFunction.DuckDBTableFunctionAddParameter(function, logicalType);
243 ✔
29
            logicalType.Dispose();
243 ✔
30
        }
31

32
        foreach (var param in namedParameters)
828 ✔
33
        {
34
            using var logicalType = param.Type.GetLogicalType();
18 ✔
35
            NativeMethods.TableFunction.DuckDBTableFunctionAddNamedParameter(function, param.Name, logicalType);
18 ✔
36
        }
37

38
        var tableFunctionInfo = new TableFunctionInfo(resultCallback, createScan, Array.ConvertAll(namedParameters, p => p.Name));
414 ✔
39

40
        NativeMethods.TableFunction.DuckDBTableFunctionSetBind(function, &Bind);
396 ✔
41
        NativeMethods.TableFunction.DuckDBTableFunctionSetInit(function, &Init);
396 ✔
42
        NativeMethods.TableFunction.DuckDBTableFunctionSetFunction(function, &TableFunction);
396 ✔
43
        NativeMethods.TableFunction.DuckDBTableFunctionSetExtraInfo(function, tableFunctionInfo.ToHandle(), &DestroyExtraInfo);
396 ✔
44
        NativeMethods.TableFunction.DuckDBTableFunctionSupportsProjectionPushdown(function, true);
396 ✔
45

46
        var state = NativeMethods.TableFunction.DuckDBRegisterTableFunction(connection, function);
396 ✔
47

48
        NativeMethods.TableFunction.DuckDBDestroyTableFunction(ref function);
396 ✔
49

50
        if (!state.IsSuccess())
396 !
51
        {
NEW
52
            throw new InvalidOperationException($"Error registering user defined table function: {name}");
×
53
        }
54
    }
396 ✔
55

56
    [UnmanagedCallersOnly(CallConvs = [typeof(CallConvCdecl)])]
57
    private static unsafe void Bind(IntPtr info)
58
    {
59
        IDuckDBValueReader[] parameters = [];
1,056 ✔
60
        Dictionary<string, IDuckDBValueReader> named = [];
1,056 ✔
61
        try
62
        {
63
            var handle = GCHandle.FromIntPtr(NativeMethods.TableFunction.DuckDBBindGetExtraInfo(info));
1,056 ✔
64

65
            if (handle.Target is not TableFunctionInfo functionInfo)
1,056 !
66
            {
NEW
67
                throw new InvalidOperationException("User defined table function bind failed. Bind extra info is null");
×
68
            }
69

70
            parameters = new IDuckDBValueReader[NativeMethods.TableFunction.DuckDBBindGetParameterCount(info)];
1,056 ✔
71

72
            for (var i = 0; i < parameters.Length; i++)
3,156 ✔
73
            {
74
                var value = NativeMethods.TableFunction.DuckDBBindGetParameter(info, (ulong)i);
522 ✔
75
                parameters[i] = value;
522 ✔
76
            }
77

78
            // When a named parameter is omitted in SQL, duckdb_bind_get_named_parameter returns a null pointer.
79
            // We substitute it with NullValueReader so CompileValueReader's IsNull() check
80
            // correctly handles it (returns default for nullable, throws for non-nullable).
81
            foreach (var paramName in functionInfo.NamedParameterNames)
2,226 ✔
82
            {
83
                var value = NativeMethods.TableFunction.DuckDBBindGetNamedParameter(info, paramName);
57 ✔
84
                named[paramName] = value.IsInvalid ? NullValueReader.Instance : value;
57 ✔
85
            }
86

87
            var tableFunctionData = functionInfo.Bind(parameters, named);
1,056 ✔
88

89
            foreach (var columnInfo in tableFunctionData.Columns)
5,496 ✔
90
            {
91
                using var logicalType = columnInfo.Type.GetLogicalType();
1,704 ✔
92
                NativeMethods.TableFunction.DuckDBBindAddResultColumn(info, columnInfo.Name, logicalType);
1,704 ✔
93
            }
94

95
            // When the function gives no number of its own and its data is a collection, DuckDB is told the
96
            // collection's count. The length of an array cannot change before the scan reads it, so it is exact,
97
            // which DuckDB also takes as the most rows there are. Any other collection can be longer when it is
98
            // read than now, so its count is only an estimate, which DuckDB uses for planning only.
99
            var cardinality = tableFunctionData.Cardinality ?? tableFunctionData.Data switch
1,044 ✔
100
            {
1,044 ✔
101
                Array array => new CardinalityHint((ulong)array.LongLength, IsExact: true),
300 ✔
102
                ICollection collection => new CardinalityHint((ulong)collection.Count),
72 ✔
103
                IReadOnlyCollection<object> collection => new CardinalityHint((ulong)collection.Count),
6 ✔
104
                _ => null
300 ✔
105
            };
1,044 ✔
106

107
            if (cardinality is not null)
1,044 ✔
108
            {
109
                NativeMethods.TableFunction.DuckDBBindSetCardinality(info, cardinality.Value, isExact: cardinality.IsExact);
744 ✔
110
            }
111

112
            var connectionId = UdfErrors.TableFunctionBound(info);
1,044 ✔
113
            var bindData = new TableFunctionBindData(tableFunctionData.Columns, tableFunctionData.Data, tableFunctionData.DataFactory, connectionId);
1,044 ✔
114

115
            NativeMethods.TableFunction.DuckDBBindSetBindData(info, bindData.ToHandle(), &DestroyExtraInfo);
1,044 ✔
116
        }
1,044 ✔
117
        catch (Exception ex)
12 ✔
118
        {
119
            UdfErrors.TableFunctionBindFailed(info, ex);
12 ✔
120

121
            NativeMethods.TableFunction.DuckDBBindSetError(info, ex.Message);
12 ✔
122
        }
12 ✔
123
        finally
124
        {
125
            foreach (var parameter in parameters)
3,156 ✔
126
            {
127
                (parameter as IDisposable)?.Dispose();
522 !
128
            }
129

130
            foreach (var namedParam in named.Values)
2,226 ✔
131
            {
132
                (namedParam as IDisposable)?.Dispose();
57 ✔
133
            }
134
        }
1,056 ✔
135
    }
1,056 ✔
136

137
    [UnmanagedCallersOnly(CallConvs = [typeof(CallConvCdecl)])]
138
    private static unsafe void Init(IntPtr info)
139
    {
140
        TableFunctionBindData? bindData = null;
495 ✔
141
        try
142
        {
143
            var bindHandle = GCHandle.FromIntPtr(NativeMethods.TableFunction.DuckDBInitGetBindData(info));
495 ✔
144
            if (bindHandle.Target is not TableFunctionBindData data)
495 !
145
            {
NEW
146
                throw new InvalidOperationException("User defined table function init failed. Bind data is null");
×
147
            }
148
            bindData = data;
495 ✔
149

150
            var count = (int)NativeMethods.TableFunction.DuckDBInitGetColumnCount(info);
495 ✔
151
            var projected = new int[count];
495 ✔
152
            for (var i = 0; i < count; i++)
2,322 ✔
153
            {
154
                projected[i] = (int)NativeMethods.TableFunction.DuckDBInitGetColumnIndex(info, (ulong)i);
666 ✔
155
            }
156

157
            if (GCHandle.FromIntPtr(NativeMethods.TableFunction.DuckDBInitGetExtraInfo(info)).Target is not TableFunctionInfo functionInfo)
495 !
158
            {
NEW
159
                throw new InvalidOperationException("User defined table function init failed. Function extra info is null");
×
160
            }
161

162
            // The scan must be created per init, not per bind: DuckDB re-initializes a scan
163
            // without re-binding when it re-executes a pipeline (e.g. on every iteration of a
164
            // recursive CTE), and each scan must read the data from the beginning.
165
            IEnumerable? rows;
166
            if (bindData.DataFactory is { } factory)
495 ✔
167
            {
168
                var projectedColumns = new ProjectedColumn[count];
54 ✔
169
                for (var i = 0; i < count; i++)
300 ✔
170
                {
171
                    var column = bindData.Columns[projected[i]];
96 ✔
172
                    projectedColumns[i] = new ProjectedColumn(projected[i], column.Name, column.Type);
96 ✔
173
                }
174

175
                rows = factory(projectedColumns);
54 ✔
176
            }
177
            else
178
            {
179
                rows = bindData.Data;
441 ✔
180
            }
181

182
            // The scan is disposed in TableFunctionInitData.Dispose.
183
            var scan = rows is null ? null : functionInfo.CreateScan(rows, projected, bindData.Columns.Count);
489 !
184

185
            var logicalTypes = new DuckDBLogicalType[count];
489 ✔
186
            for (var i = 0; i < count; i++)
2,298 ✔
187
            {
188
                logicalTypes[i] = bindData.Columns[projected[i]].Type.GetLogicalType();
660 ✔
189
            }
190

191
            var initData = new TableFunctionInitData(scan, logicalTypes);
489 ✔
192
            NativeMethods.TableFunction.DuckDBInitSetInitData(info, initData.ToHandle(), &DestroyExtraInfo);
489 ✔
193
        }
489 ✔
194
        catch (Exception ex)
6 ✔
195
        {
196
            if (bindData is not null)
6 ✔
197
            {
198
                UdfErrors.TableFunctionFailed(bindData.ConnectionId, ex);
6 ✔
199
            }
200
            NativeMethods.TableFunction.DuckDBInitSetError(info, ex.Message);
6 ✔
201
        }
6 ✔
202
    }
495 ✔
203

204
    [UnmanagedCallersOnly(CallConvs = [typeof(CallConvCdecl)])]
205
    private static void TableFunction(IntPtr info, IntPtr chunk)
206
    {
207
        VectorDataWriterBase?[] writers = [];
1,185 ✔
208
        try
209
        {
210
            var initHandle = GCHandle.FromIntPtr(NativeMethods.TableFunction.DuckDBFunctionGetInitData(info));
1,185 ✔
211

212
            if (initHandle.Target is not TableFunctionInitData tableFunctionInitData)
1,185 !
213
            {
NEW
214
                throw new InvalidOperationException("User defined table function failed. Function init data is null");
×
215
            }
216

217
            var dataChunk = new DuckDBDataChunk(chunk);
1,185 ✔
218
            var logicalTypes = tableFunctionInitData.LogicalTypes;
1,185 ✔
219

220
            writers = tableFunctionInitData.Writers;
1,185 ✔
221

222
            for (var columnIndex = 0; columnIndex < logicalTypes.Length; columnIndex++)
5,562 ✔
223
            {
224
                var vector = NativeMethods.DataChunks.DuckDBDataChunkGetVector(dataChunk, columnIndex);
1,596 ✔
225

226
                writers[columnIndex] = VectorDataWriterFactory.CreateWriter(vector, logicalTypes[columnIndex]);
1,596 ✔
227
            }
228

229
            if (tableFunctionInitData.Scan is not { } scan)
1,185 !
230
            {
NEW
231
                throw new InvalidOperationException("User defined table function failed. No data source available");
×
232
            }
233

234
            var size = scan.Fill(tableFunctionInitData.Writers, DuckDBGlobalData.VectorSize);
1,185 ✔
235

236
            NativeMethods.DataChunks.DuckDBDataChunkSetSize(dataChunk, size);
1,152 ✔
237
        }
1,152 ✔
238
        catch (Exception ex)
33 ✔
239
        {
240
            try
241
            {
242
                var bindData = GCHandle.FromIntPtr(NativeMethods.TableFunction.DuckDBFunctionGetBindData(info));
33 ✔
243
                if (bindData.Target is TableFunctionBindData tableFunctionBindData)
33 ✔
244
                {
245
                    UdfErrors.TableFunctionFailed(tableFunctionBindData.ConnectionId, ex);
33 ✔
246
                }
247
            }
33 ✔
NEW
248
            catch
×
249
            {
250
                // If we can't get the connection ID, we still report the error message
NEW
251
            }
×
252

253
            NativeMethods.TableFunction.DuckDBFunctionSetError(info, ex.Message);
33 ✔
254
        }
33 ✔
255
        finally
256
        {
257
            // The writers of a chunk are not used for the next one. A slot is cleared, so that a chunk that fails
258
            // before it has made all its writers does not dispose one of the chunk before again.
259
            for (var index = 0; index < writers.Length; index++)
5,562 ✔
260
            {
261
                writers[index]?.Dispose();
1,596 !
262
                writers[index] = null;
1,596 ✔
263
            }
264
        }
1,185 ✔
265
    }
1,185 ✔
266

267
    private class NullValueReader : IDuckDBValueReader
268
    {
269
        public static readonly NullValueReader Instance = new();
3 ✔
270
        public bool IsNull() => true;
15 ✔
NEW
271
        public T GetValue<T>() => throw new InvalidOperationException("Cannot read value from a null parameter.");
×
272
    }
273

274
    [UnmanagedCallersOnly(CallConvs = [typeof(CallConvCdecl)])]
275
    private static void DestroyExtraInfo(IntPtr pointer) => pointer.FreeHandle();
1,929 ✔
276
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc