System.Data.SQLite

Login
This project makes use of Eagle, provided by Mistachkin Systems.
Eagle: Secure Software Automation

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:Follow-up to experimental (and broken) check-in [73602c161a], further changes to statement disposal, pursuant to connection pool stress issues.
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1: 0ed2dd7eddd084ba5feb7e3d1adbae6264a515a8
User & Date: mistachkin 2024-07-01 21:42:23
Context
2024-07-02
03:02
More test enhancments. check-in: 943172a587 user: mistachkin tags: trunk
2024-07-01
21:42
Follow-up to experimental (and broken) check-in [73602c161a], further changes to statement disposal, pursuant to connection pool stress issues. check-in: 0ed2dd7edd user: mistachkin tags: trunk
2024-06-30
22:10
Update zlib import libraries to resolve multiple compilation issues with mismatched runtimes. check-in: 0600a193b3 user: mistachkin tags: trunk
Changes
Hide Diffs Unified Diffs Ignore Whitespace Patch

Changes to System.Data.SQLite/SQLiteCommand.cs.

251
252
253
254
255
256
257
258

259
260








261



262

263
264
265
266
267
268
269
                    }

                    if (reader != null)
                    {
                        reader._disposeCommand = true;

                        //
                        // HACK: Transfer the statement list to

                        //       our active reader.
                        //








                        reader._statementList = _statementList;



                        _statementList = null;


                        _activeReader = null;
                        skippedDispose = true;
                        return;
                    }

                    Connection = null;







|
>
|

>
>
>
>
>
>
>
>
|
>
>
>
|
>







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
                    }

                    if (reader != null)
                    {
                        reader._disposeCommand = true;

                        //
                        // HACK: Copy the statement list to our active reader,
                        //       after adding a reference to each one of the
                        //       valid statements.
                        //
                        if (_statementList != null)
                        {
                            foreach (SQLiteStatement statement in _statementList)
                            {
                                if (statement == null) continue;
                                statement.AddReference();
                            }

                            reader._statementList = _statementList;
                        }
                        else
                        {
                            reader._statementList = null;
                        }

                        _activeReader = null;
                        skippedDispose = true;
                        return;
                    }

                    Connection = null;
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
        }
    }

    ///////////////////////////////////////////////////////////////////////////////////////////////

    private void DisposeStatements()
    {
        DisposeStatements(ref _statementList);
    }

    ///////////////////////////////////////////////////////////////////////////////////////////////

    internal static void DisposeStatements(

        ref List<SQLiteStatement> statements
        )
    {
        if (statements == null) return;

        int x = statements.Count;

        for (int n = 0; n < x; n++)
        {
            SQLiteStatement stmt = statements[n];

            if (stmt == null) continue;


            stmt.Dispose();
        }

        statements = null;
    }

    ///////////////////////////////////////////////////////////////////////////////////////////////








|





>










>

>
>
|







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
        }
    }

    ///////////////////////////////////////////////////////////////////////////////////////////////

    private void DisposeStatements()
    {
        DisposeStatements(true, ref _statementList);
    }

    ///////////////////////////////////////////////////////////////////////////////////////////////

    internal static void DisposeStatements(
        bool force,
        ref List<SQLiteStatement> statements
        )
    {
        if (statements == null) return;

        int x = statements.Count;

        for (int n = 0; n < x; n++)
        {
            SQLiteStatement stmt = statements[n];

            if (stmt == null) continue;

            if ((stmt.RemoveReference() <= 0) || force)
                stmt.Dispose();
        }

        statements = null;
    }

    ///////////////////////////////////////////////////////////////////////////////////////////////

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
          if (_statementList == null)
            _remainingText = _commandText;

          stmt = _cnn._sql.Prepare(_cnn, this, _remainingText, (_statementList == null) ? null : _statementList[_statementList.Count - 1], (uint)(_commandTimeout * 1000), ref _remainingText);

          if (stmt != null)
          {

            stmt._command = this;

            if (_statementList == null)
              _statementList = new List<SQLiteStatement>();

            _statementList.Add(stmt);

            _parameterCollection.MapParameters(stmt);
            stmt.BindParameters();
          }
        }
        return stmt;
      }
      catch (Exception)
      {
        if (stmt != null)
        {
          if ((_statementList != null) && _statementList.Contains(stmt))
            _statementList.Remove(stmt);


          stmt.Dispose();
        }

        // If we threw an error compiling the statement, we cannot continue on so set the remaining text to null.
        _remainingText = null;

        throw;
      }
    }

    internal SQLiteStatement GetStatement(int index)
    {
      // Haven't built any statements yet
      if (_statementList == null) return BuildNextCommand();

      // If we're at the last built statement and want the next unbuilt statement, then build it
      if (index == _statementList.Count)
      {
        if (String.IsNullOrEmpty(_remainingText) == false) return BuildNextCommand();
        else return null; // No more commands
      }

      SQLiteStatement stmt = _statementList[index];
      stmt.BindParameters();







>




















>
|















|







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
          if (_statementList == null)
            _remainingText = _commandText;

          stmt = _cnn._sql.Prepare(_cnn, this, _remainingText, (_statementList == null) ? null : _statementList[_statementList.Count - 1], (uint)(_commandTimeout * 1000), ref _remainingText);

          if (stmt != null)
          {
            stmt.AddReference();
            stmt._command = this;

            if (_statementList == null)
              _statementList = new List<SQLiteStatement>();

            _statementList.Add(stmt);

            _parameterCollection.MapParameters(stmt);
            stmt.BindParameters();
          }
        }
        return stmt;
      }
      catch (Exception)
      {
        if (stmt != null)
        {
          if ((_statementList != null) && _statementList.Contains(stmt))
            _statementList.Remove(stmt);

          if (stmt.RemoveReference() <= 0)
            stmt.Dispose();
        }

        // If we threw an error compiling the statement, we cannot continue on so set the remaining text to null.
        _remainingText = null;

        throw;
      }
    }

    internal SQLiteStatement GetStatement(int index)
    {
      // Haven't built any statements yet
      if (_statementList == null) return BuildNextCommand();

      // If we're at the last built statement and want the next unbuilt statement, then build it
      if (index >= _statementList.Count)
      {
        if (String.IsNullOrEmpty(_remainingText) == false) return BuildNextCommand();
        else return null; // No more commands
      }

      SQLiteStatement stmt = _statementList[index];
      stmt.BindParameters();
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
            string text = _commandText;
            uint timeout = (uint)(_commandTimeout * 1000);
            SQLiteStatement previousStatement = null;

            while ((text != null) && (text.Length > 0))
            {
                currentStatement = sqlBase.Prepare(
                    connection, this, text, previousStatement, timeout,
                    ref text); /* throw */

                previousStatement = currentStatement;

                if (currentStatement != null)
                {
                    if (statements == null)
                        statements = new List<SQLiteStatement>();







|
|







865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
            string text = _commandText;
            uint timeout = (uint)(_commandTimeout * 1000);
            SQLiteStatement previousStatement = null;

            while ((text != null) && (text.Length > 0))
            {
                currentStatement = sqlBase.Prepare(
                    connection, this, text, previousStatement,
                    timeout, ref text); /* throw */

                previousStatement = currentStatement;

                if (currentStatement != null)
                {
                    if (statements == null)
                        statements = new List<SQLiteStatement>();

Changes to System.Data.SQLite/SQLiteDataReader.cs.

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
    /// <summary>
    /// Internal constructor, initializes the datareader and sets up to begin executing statements
    /// </summary>
    /// <param name="cmd">The SQLiteCommand this data reader is for</param>
    /// <param name="behave">The expected behavior of the data reader</param>
    internal SQLiteDataReader(SQLiteCommand cmd, CommandBehavior behave)
    {


      _throwOnDisposed = true;
      _command = cmd;
      _version = _command.Connection._version;
      _baseSchemaName = _command.Connection._baseSchemaName;

      _commandBehavior = behave;
      _activeStatementIndex = -1;
      _rowsAffected = -1;

      RefreshFlags();

      SQLiteConnection connection = GetConnection(this);

      if (SQLiteConnection.CanOnChanged(connection, false))
      {
          SQLiteConnection.OnChanged(connection,
              new ConnectionEventArgs(SQLiteConnectionEventType.NewDataReader,
              null, null, _command, this, null, null, new object[] { behave }));
      }

      if (_command != null)
          NextResult();
    }































    ///////////////////////////////////////////////////////////////////////////////////////////////

    #region IDisposable "Pattern" Members
    private bool disposed;
    private void CheckDisposed() /* throw */
    {







>
>






<
<















>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







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
    /// <summary>
    /// Internal constructor, initializes the datareader and sets up to begin executing statements
    /// </summary>
    /// <param name="cmd">The SQLiteCommand this data reader is for</param>
    /// <param name="behave">The expected behavior of the data reader</param>
    internal SQLiteDataReader(SQLiteCommand cmd, CommandBehavior behave)
    {
      ResetIterationState();

      _throwOnDisposed = true;
      _command = cmd;
      _version = _command.Connection._version;
      _baseSchemaName = _command.Connection._baseSchemaName;

      _commandBehavior = behave;



      RefreshFlags();

      SQLiteConnection connection = GetConnection(this);

      if (SQLiteConnection.CanOnChanged(connection, false))
      {
          SQLiteConnection.OnChanged(connection,
              new ConnectionEventArgs(SQLiteConnectionEventType.NewDataReader,
              null, null, _command, this, null, null, new object[] { behave }));
      }

      if (_command != null)
          NextResult();
    }

    ///////////////////////////////////////////////////////////////////////////////////////////////

    #region Private Methods
    private void ResetIterationState()
    {
        _activeStatementIndex = -1;
        _activeStatement = null;

        _readingState = 0;
        _rowsAffected = -1;
        _fieldCount = 0;
        _stepCount = 0;

        _fieldIndexes = null;
        _fieldTypeArray = null;

        if (_keyInfo != null)
        {
            _keyInfo.Dispose();
            _keyInfo = null;
        }

        if (_command != null)
        {
            _command.ResetDataReader();
            _command = null;
        }
    }
    #endregion

    ///////////////////////////////////////////////////////////////////////////////////////////////

    #region IDisposable "Pattern" Members
    private bool disposed;
    private void CheckDisposed() /* throw */
    {
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186

187
188
189
190
191
192
193
194
                if (disposing)
                {
                    ////////////////////////////////////
                    // dispose managed resources here...
                    ////////////////////////////////////

                    SQLiteCommand.DisposeStatements(
                        ref _statementList);
                }

                //////////////////////////////////////
                // release unmanaged resources here...
                //////////////////////////////////////

                //
                // NOTE: Fix for ticket [e1b2e0f769], do NOT throw

                //       exceptions while we are being disposed.
                //
                _throwOnDisposed = false;
            }
        }
        finally
        {
            base.Dispose(disposing);







|







|
>
|







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
                if (disposing)
                {
                    ////////////////////////////////////
                    // dispose managed resources here...
                    ////////////////////////////////////

                    SQLiteCommand.DisposeStatements(
                        false, ref _statementList);
                }

                //////////////////////////////////////
                // release unmanaged resources here...
                //////////////////////////////////////

                //
                // NOTE: Fix for ticket [e1b2e0f769],
                //       do NOT throw exceptions while
                //       we are being disposed.
                //
                _throwOnDisposed = false;
            }
        }
        finally
        {
            base.Dispose(disposing);

Changes to System.Data.SQLite/SQLiteStatement.cs.

1
2
3
4
5
6
7
8
9
10
11

12
13
14
15
16
17
18
/********************************************************
 * ADO.NET 2.0 Data Provider for SQLite Version 3.X
 * Written by Robert Simpson (robert@blackcastlesoft.com)
 *
 * Released to the public domain, use at your own risk!
 ********************************************************/

namespace System.Data.SQLite
{
  using System;
  using System.Globalization;


  /// <summary>
  /// Represents a single SQL statement in SQLite.
  /// </summary>
  internal sealed class SQLiteStatement : IDisposable
  {
    /// <summary>











>







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/********************************************************
 * ADO.NET 2.0 Data Provider for SQLite Version 3.X
 * Written by Robert Simpson (robert@blackcastlesoft.com)
 *
 * Released to the public domain, use at your own risk!
 ********************************************************/

namespace System.Data.SQLite
{
  using System;
  using System.Globalization;
  using System.Threading;

  /// <summary>
  /// Represents a single SQL statement in SQLite.
  /// </summary>
  internal sealed class SQLiteStatement : IDisposable
  {
    /// <summary>
64
65
66
67
68
69
70






71
72
73
74
75
76
77
    /// <summary>
    /// The flags associated with the parent connection object.
    /// </summary>
    private SQLiteConnectionFlags _flags;

    private string[] _types;







    /// <summary>
    /// Initializes the statement and attempts to get all information about parameters in the statement
    /// </summary>
    /// <param name="sqlbase">The base SQLite object</param>
    /// <param name="flags">The flags associated with the parent connection object</param>
    /// <param name="stmt">The statement</param>
    /// <param name="strCommand">The command text for this statement</param>







>
>
>
>
>
>







65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
    /// <summary>
    /// The flags associated with the parent connection object.
    /// </summary>
    private SQLiteConnectionFlags _flags;

    private string[] _types;

    /// <summary>
    /// The reference count for this statement, which may be shared between
    /// a <see cref="SQLiteCommand" /> and a <see cref="SQLiteDataReader" />.
    /// </summary>
    private int _referenceCount;

    /// <summary>
    /// Initializes the statement and attempts to get all information about parameters in the statement
    /// </summary>
    /// <param name="sqlbase">The base SQLite object</param>
    /// <param name="flags">The flags associated with the parent connection object</param>
    /// <param name="stmt">The statement</param>
    /// <param name="strCommand">The command text for this statement</param>
111
112
113
114
115
116
117
















118
119
120
121
122
123
124
            _unnamedParameters++;
          }
          _paramNames[x] = s;
          _paramValues[x] = null;
        }
      }
    }

















    ///////////////////////////////////////////////////////////////////////////////////////////////

    #region IDisposable Members
    /// <summary>
    /// Disposes and finalizes the statement
    /// </summary>







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







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
            _unnamedParameters++;
          }
          _paramNames[x] = s;
          _paramValues[x] = null;
        }
      }
    }

    ///////////////////////////////////////////////////////////////////////////////////////////////

    #region Reference Count Members
    internal int AddReference()
    {
        return Interlocked.Increment(ref _referenceCount);
    }

    ///////////////////////////////////////////////////////////////////////////////////////////////

    internal int RemoveReference()
    {
        return Interlocked.Decrement(ref _referenceCount);
    }
    #endregion

    ///////////////////////////////////////////////////////////////////////////////////////////////

    #region IDisposable Members
    /// <summary>
    /// Disposes and finalizes the statement
    /// </summary>

Changes to Tests/pool.eagle.

480
481
482
483
484
485
486


































































487
488
489
490
491

  cleanupDb $fileName

  unset -nocomplain result db fileName
} -constraints {eagle command.object monoBug28 command.sql compile.DATA SQLite\
System.Data.SQLite} -result \
{1 {unknown error -- no pooled connection available}}}



































































###############################################################################

runSQLiteTestEpilogue
runTestEpilogue







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>





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

  cleanupDb $fileName

  unset -nocomplain result db fileName
} -constraints {eagle command.object monoBug28 command.sql compile.DATA SQLite\
System.Data.SQLite} -result \
{1 {unknown error -- no pooled connection available}}}

###############################################################################

runTest {test pool-2.1 {connection pool stress} -setup {
  set fileName pool-2.1.db
} -body {
  set fileName [file join [getTemporaryDirectory] $fileName]

  foreach usePooling [list True False] {
    foreach useDataReader [list True False] {
      object invoke -flags +NonPublic \
          System.Data.SQLite.SQLiteConnectionPool ClearAllPools

      for {set i 0} {$i < 100} {incr i} {
        setupDb $fileName "" "" "" "" \
            [appendArgs Pooling= $usePooling \;] false false

        sql execute $db {CREATE TABLE IF NOT EXISTS t1(x);}
        set transaction [sql transaction begin $db]

        for {set j 0} {$j < 10} {incr j} {
          sql execute $db {
            INSERT INTO t1(x) VALUES(RANDOMBLOB(1024));
          }
        }

        sql transaction commit $transaction

        if {$useDataReader} then {
          set dataReader [sql execute -execute reader -format \
              dataReader -alias $db {SELECT x FROM t1 ORDER BY x;}]

          for {set k 0} {$k < $i % 10} {incr k} {
            $dataReader Read
          }

          unset dataReader
        } else {
          sql execute -execute reader -format list $db \
              {SELECT hex(x) FROM t1 ORDER BY x;}
        }

        cleanupDb $fileName db true false false false false
      }
    }
  }

  list success
} -cleanup {
  catch {
    object invoke -flags +NonPublic \
        System.Data.SQLite.SQLiteConnectionPool ClearAllPools
  }

  catch {
    object invoke -flags +NonPublic \
        System.Data.SQLite.SQLiteConnectionPool TerminateAndReset \
        null
  }

  cleanupDb $fileName

  unset -nocomplain i j k usePooling useDataReader transaction dataReader
  unset -nocomplain db fileName
} -constraints {eagle command.object monoBug28 command.sql compile.DATA SQLite\
System.Data.SQLite} -match regexp -result {success}}

###############################################################################

runSQLiteTestEpilogue
runTestEpilogue