@@ -33,13 +33,14 @@ public class DuckDBDataReader : DbDataReader
33
33
34
34
internal DuckDBDataReader ( DuckDBCommand command , IEnumerable < PreparedStatement . PreparedStatement > statements , CommandBehavior behavior )
35
35
{
36
- command . DataReader = this ;
37
-
38
36
this . command = command ;
39
37
this . behavior = behavior ;
40
38
statementEnumerator = statements . GetEnumerator ( ) ;
41
39
42
40
InitNextReader ( ) ;
41
+
42
+ // Do not modify the command's state if an exception was thrown in InitNextReader().
43
+ command . DataReader = this ;
43
44
}
44
45
45
46
private bool InitNextReader ( )
@@ -49,20 +50,28 @@ private bool InitNextReader()
49
50
currentResult ? . Dispose ( ) ;
50
51
currentResult = null ; // Prevent double disposal.
51
52
52
- var current = statementEnumerator . Current . Execute ( ) ;
53
- currentResult = current ;
54
-
55
- if ( NativeMethods . Query . DuckDBResultReturnType ( current ) == DuckDBResultType . QueryResult )
53
+ try
56
54
{
57
- currentChunkIndex = 0 ;
55
+ var current = statementEnumerator . Current . Execute ( ) ;
56
+ currentResult = current ;
57
+
58
+ if ( NativeMethods . Query . DuckDBResultReturnType ( current ) == DuckDBResultType . QueryResult )
59
+ {
60
+ currentChunkIndex = 0 ;
58
61
59
- columnMapping = [ ] ;
60
- fieldCount = ( int ) NativeMethods . Query . DuckDBColumnCount ( ref current ) ;
61
- streamingResult = NativeMethods . Types . DuckDBResultIsStreaming ( current ) > 0 ;
62
+ columnMapping = [ ] ;
63
+ fieldCount = ( int ) NativeMethods . Query . DuckDBColumnCount ( ref current ) ;
64
+ streamingResult = NativeMethods . Types . DuckDBResultIsStreaming ( current ) > 0 ;
62
65
63
- hasRows = InitChunkData ( ) ;
66
+ hasRows = InitChunkData ( ) ;
64
67
65
- return true ;
68
+ return true ;
69
+ }
70
+ }
71
+ catch
72
+ {
73
+ Dispose ( ) ;
74
+ throw ;
66
75
}
67
76
}
68
77
@@ -349,6 +358,8 @@ public override void Close()
349
358
{
350
359
if ( closed ) return ;
351
360
361
+ command . DataReader = null ;
362
+
352
363
foreach ( var reader in vectorReaders )
353
364
{
354
365
reader . Dispose ( ) ;
@@ -359,15 +370,26 @@ public override void Close()
359
370
360
371
currentChunk ? . Dispose ( ) ;
361
372
362
- if ( behavior == CommandBehavior . CloseConnection )
373
+ try
363
374
{
364
- command . CloseConnection ( ) ;
375
+ // Try to consume the enumerator to ensure that all statements are prepared.
376
+ while ( statementEnumerator . MoveNext ( ) )
377
+ {
378
+ }
379
+ }
380
+ catch
381
+ {
382
+ // Dispose() must not throw exceptions.
365
383
}
366
384
367
- closed = true ;
368
385
statementEnumerator . Dispose ( ) ;
369
386
370
- command . DataReader = null ;
387
+ closed = true ;
388
+
389
+ if ( behavior == CommandBehavior . CloseConnection )
390
+ {
391
+ command . CloseConnection ( ) ;
392
+ }
371
393
}
372
394
373
395
private void CheckRowRead ( )
0 commit comments