-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
SqliteCommand.cs
548 lines (474 loc) · 23.2 KB
/
SqliteCommand.cs
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Data.Sqlite.Properties;
using Microsoft.Data.Sqlite.Utilities;
using SQLitePCL;
using static SQLitePCL.raw;
namespace Microsoft.Data.Sqlite
{
/// <summary>
/// Represents a SQL statement to be executed against a SQLite database.
/// </summary>
/// <seealso href="https://docs.microsoft.com/dotnet/standard/data/sqlite/batching">Batching</seealso>
/// <seealso href="https://docs.microsoft.com/dotnet/standard/data/sqlite/database-errors">Database Errors</seealso>
/// <seealso href="https://docs.microsoft.com/dotnet/standard/data/sqlite/async">Async Limitations</seealso>
public class SqliteCommand : DbCommand
{
private SqliteParameterCollection? _parameters;
private readonly List<(sqlite3_stmt Statement, int ParamCount)> _preparedStatements = new(1);
private SqliteConnection? _connection;
private string _commandText = string.Empty;
private bool _prepared;
private int? _commandTimeout;
/// <summary>
/// Initializes a new instance of the <see cref="SqliteCommand" /> class.
/// </summary>
public SqliteCommand()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="SqliteCommand" /> class.
/// </summary>
/// <param name="commandText">The SQL to execute against the database.</param>
public SqliteCommand(string? commandText)
=> CommandText = commandText;
/// <summary>
/// Initializes a new instance of the <see cref="SqliteCommand" /> class.
/// </summary>
/// <param name="commandText">The SQL to execute against the database.</param>
/// <param name="connection">The connection used by the command.</param>
public SqliteCommand(string? commandText, SqliteConnection? connection)
: this(commandText)
{
Connection = connection;
}
/// <summary>
/// Initializes a new instance of the <see cref="SqliteCommand" /> class.
/// </summary>
/// <param name="commandText">The SQL to execute against the database.</param>
/// <param name="connection">The connection used by the command.</param>
/// <param name="transaction">The transaction within which the command executes.</param>
public SqliteCommand(string? commandText, SqliteConnection? connection, SqliteTransaction? transaction)
: this(commandText, connection)
=> Transaction = transaction;
/// <summary>
/// Gets or sets a value indicating how <see cref="CommandText" /> is interpreted. Only
/// <see cref="CommandType.Text" /> is supported.
/// </summary>
/// <value>A value indicating how <see cref="CommandText" /> is interpreted.</value>
public override CommandType CommandType
{
get => CommandType.Text;
set
{
if (value != CommandType.Text)
{
throw new ArgumentException(Resources.InvalidCommandType(value));
}
}
}
/// <summary>
/// Gets or sets the SQL to execute against the database.
/// </summary>
/// <value>The SQL to execute against the database.</value>
/// <seealso href="https://docs.microsoft.com/dotnet/standard/data/sqlite/batching">Batching</seealso>
[AllowNull]
public override string CommandText
{
get => _commandText;
set
{
if (DataReader != null)
{
throw new InvalidOperationException(Resources.SetRequiresNoOpenReader(nameof(CommandText)));
}
if (value != _commandText)
{
DisposePreparedStatements();
_commandText = value ?? string.Empty;
}
}
}
/// <summary>
/// Gets or sets the connection used by the command.
/// </summary>
/// <value>The connection used by the command.</value>
public new virtual SqliteConnection? Connection
{
get => _connection;
set
{
if (DataReader != null)
{
throw new InvalidOperationException(Resources.SetRequiresNoOpenReader(nameof(Connection)));
}
if (value != _connection)
{
DisposePreparedStatements();
_connection?.RemoveCommand(this);
_connection = value;
value?.AddCommand(this);
}
}
}
/// <summary>
/// Gets or sets the connection used by the command. Must be a <see cref="SqliteConnection" />.
/// </summary>
/// <value>The connection used by the command.</value>
protected override DbConnection? DbConnection
{
get => Connection;
set => Connection = (SqliteConnection?)value;
}
/// <summary>
/// Gets or sets the transaction within which the command executes.
/// </summary>
/// <value>The transaction within which the command executes.</value>
public new virtual SqliteTransaction? Transaction { get; set; }
/// <summary>
/// Gets or sets the transaction within which the command executes. Must be a <see cref="SqliteTransaction" />.
/// </summary>
/// <value>The transaction within which the command executes.</value>
protected override DbTransaction? DbTransaction
{
get => Transaction;
set => Transaction = (SqliteTransaction?)value;
}
/// <summary>
/// Gets the collection of parameters used by the command.
/// </summary>
/// <value>The collection of parameters used by the command.</value>
/// <seealso href="https://docs.microsoft.com/dotnet/standard/data/sqlite/parameters">Parameters</seealso>
public new virtual SqliteParameterCollection Parameters
=> _parameters ??= [];
/// <summary>
/// Gets the collection of parameters used by the command.
/// </summary>
/// <value>The collection of parameters used by the command.</value>
protected override DbParameterCollection DbParameterCollection
=> Parameters;
/// <summary>
/// Gets or sets the number of seconds to wait before terminating the attempt to execute the command.
/// Defaults to 30. A value of 0 means no timeout.
/// </summary>
/// <value>The number of seconds to wait before terminating the attempt to execute the command.</value>
/// <remarks>
/// The timeout is used when the command is waiting to obtain a lock on the table.
/// </remarks>
/// <seealso href="https://docs.microsoft.com/dotnet/standard/data/sqlite/database-errors">Database Errors</seealso>
public override int CommandTimeout
{
get => _commandTimeout ?? _connection?.DefaultTimeout ?? 30;
set => _commandTimeout = value;
}
/// <summary>
/// Gets or sets a value indicating whether the command should be visible in an interface control.
/// </summary>
/// <value>A value indicating whether the command should be visible in an interface control.</value>
public override bool DesignTimeVisible { get; set; }
/// <summary>
/// Gets or sets a value indicating how the results are applied to the row being updated.
/// </summary>
/// <value>A value indicating how the results are applied to the row being updated.</value>
public override UpdateRowSource UpdatedRowSource { get; set; }
/// <summary>
/// Gets or sets the data reader currently being used by the command, or null if none.
/// </summary>
/// <value>The data reader currently being used by the command.</value>
protected internal virtual SqliteDataReader? DataReader { get; set; }
/// <summary>
/// Releases any resources used by the connection and closes it.
/// </summary>
/// <param name="disposing">
/// <see langword="true" /> to release managed and unmanaged resources;
/// <see langword="false" /> to release only unmanaged resources.
/// </param>
protected override void Dispose(bool disposing)
{
DisposePreparedStatements(disposing);
if (disposing)
{
_connection?.RemoveCommand(this);
}
base.Dispose(disposing);
}
/// <summary>
/// Creates a new parameter.
/// </summary>
/// <returns>The new parameter.</returns>
public new virtual SqliteParameter CreateParameter()
=> new();
/// <summary>
/// Creates a new parameter.
/// </summary>
/// <returns>The new parameter.</returns>
protected override DbParameter CreateDbParameter()
=> CreateParameter();
/// <summary>
/// Creates a prepared version of the command on the database.
/// </summary>
public override void Prepare()
{
if (_connection?.State != ConnectionState.Open)
{
throw new InvalidOperationException(Resources.CallRequiresOpenConnection(nameof(Prepare)));
}
if (_prepared)
{
return;
}
using var enumerator = PrepareAndEnumerateStatements().GetEnumerator();
while (enumerator.MoveNext())
{
}
}
/// <summary>
/// Executes the <see cref="CommandText" /> against the database and returns a data reader.
/// </summary>
/// <returns>The data reader.</returns>
/// <exception cref="SqliteException">A SQLite error occurs during execution.</exception>
/// <seealso href="https://docs.microsoft.com/dotnet/standard/data/sqlite/database-errors">Database Errors</seealso>
/// <seealso href="https://docs.microsoft.com/dotnet/standard/data/sqlite/batching">Batching</seealso>
public new virtual SqliteDataReader ExecuteReader()
=> ExecuteReader(CommandBehavior.Default);
/// <summary>
/// Executes the <see cref="CommandText" /> against the database and returns a data reader.
/// </summary>
/// <param name="behavior">A description of the results of the query and its effect on the database.</param>
/// <returns>The data reader.</returns>
/// <exception cref="SqliteException">A SQLite error occurs during execution.</exception>
/// <seealso href="https://docs.microsoft.com/dotnet/standard/data/sqlite/database-errors">Database Errors</seealso>
/// <seealso href="https://docs.microsoft.com/dotnet/standard/data/sqlite/batching">Batching</seealso>
public new virtual SqliteDataReader ExecuteReader(CommandBehavior behavior)
{
if (DataReader != null)
{
throw new InvalidOperationException(Resources.DataReaderOpen);
}
if (_connection?.State != ConnectionState.Open)
{
throw new InvalidOperationException(Resources.CallRequiresOpenConnection(nameof(ExecuteReader)));
}
if (Transaction != _connection.Transaction)
{
throw new InvalidOperationException(
Transaction == null
? Resources.TransactionRequired
: Resources.TransactionConnectionMismatch);
}
if (_connection.Transaction?.ExternalRollback == true)
{
throw new InvalidOperationException(Resources.TransactionCompleted);
}
var closeConnection = behavior.HasFlag(CommandBehavior.CloseConnection);
var dataReader = new SqliteDataReader(this, GetStatements(), closeConnection);
dataReader.NextResult();
return DataReader = dataReader;
}
private IEnumerable<sqlite3_stmt> GetStatements()
{
foreach ((var stmt, var expectedParams) in !_prepared
? PrepareAndEnumerateStatements()
: _preparedStatements)
{
var boundParams = _parameters?.Bind(stmt, Connection!.Handle!) ?? 0;
if (expectedParams != boundParams)
{
var unboundParams = new List<string>();
for (var i = 1; i <= expectedParams; i++)
{
var name = sqlite3_bind_parameter_name(stmt, i).utf8_to_string();
if (_parameters != null
&& !_parameters.Cast<SqliteParameter>().Any(p => p.ParameterName == name))
{
unboundParams.Add(name);
}
}
if (sqlite3_libversion_number() < 3028000 || sqlite3_stmt_isexplain(stmt) == 0)
{
throw new InvalidOperationException(Resources.MissingParameters(string.Join(", ", unboundParams)));
}
}
yield return stmt;
}
}
/// <summary>
/// Executes the <see cref="CommandText" /> against the database and returns a data reader.
/// </summary>
/// <param name="behavior">A description of query's results and its effect on the database.</param>
/// <returns>The data reader.</returns>
protected override DbDataReader ExecuteDbDataReader(CommandBehavior behavior)
=> ExecuteReader(behavior);
/// <summary>
/// Executes the <see cref="CommandText" /> asynchronously against the database and returns a data reader.
/// </summary>
/// <returns>A task representing the asynchronous operation.</returns>
/// <seealso href="https://docs.microsoft.com/dotnet/standard/data/sqlite/async">Async Limitations</seealso>
/// <seealso href="https://docs.microsoft.com/dotnet/standard/data/sqlite/batching">Batching</seealso>
/// <seealso href="https://docs.microsoft.com/dotnet/standard/data/sqlite/database-errors">Database Errors</seealso>
public new virtual Task<SqliteDataReader> ExecuteReaderAsync()
=> ExecuteReaderAsync(CommandBehavior.Default, CancellationToken.None);
/// <summary>
/// Executes the <see cref="CommandText" /> asynchronously against the database and returns a data reader.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <returns>A task representing the asynchronous operation.</returns>
/// <seealso href="https://docs.microsoft.com/dotnet/standard/data/sqlite/async">Async Limitations</seealso>
/// <seealso href="https://docs.microsoft.com/dotnet/standard/data/sqlite/batching">Batching</seealso>
/// <seealso href="https://docs.microsoft.com/dotnet/standard/data/sqlite/database-errors">Database Errors</seealso>
/// <exception cref="OperationCanceledException">If the <see cref="CancellationToken"/> is canceled.</exception>
public new virtual Task<SqliteDataReader> ExecuteReaderAsync(CancellationToken cancellationToken)
=> ExecuteReaderAsync(CommandBehavior.Default, cancellationToken);
/// <summary>
/// Executes the <see cref="CommandText" /> asynchronously against the database and returns a data reader.
/// </summary>
/// <param name="behavior">A description of query's results and its effect on the database.</param>
/// <returns>A task representing the asynchronous operation.</returns>
/// <seealso href="https://docs.microsoft.com/dotnet/standard/data/sqlite/async">Async Limitations</seealso>
/// <seealso href="https://docs.microsoft.com/dotnet/standard/data/sqlite/batching">Batching</seealso>
/// <seealso href="https://docs.microsoft.com/dotnet/standard/data/sqlite/database-errors">Database Errors</seealso>
public new virtual Task<SqliteDataReader> ExecuteReaderAsync(CommandBehavior behavior)
=> ExecuteReaderAsync(behavior, CancellationToken.None);
/// <summary>
/// Executes the <see cref="CommandText" /> asynchronously against the database and returns a data reader.
/// </summary>
/// <param name="behavior">A description of query's results and its effect on the database.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <returns>A task representing the asynchronous operation.</returns>
/// <seealso href="https://docs.microsoft.com/dotnet/standard/data/sqlite/async">Async Limitations</seealso>
/// <seealso href="https://docs.microsoft.com/dotnet/standard/data/sqlite/batching">Batching</seealso>
/// <seealso href="https://docs.microsoft.com/dotnet/standard/data/sqlite/database-errors">Database Errors</seealso>
/// <exception cref="OperationCanceledException">If the <see cref="CancellationToken"/> is canceled.</exception>
public new virtual Task<SqliteDataReader> ExecuteReaderAsync(
CommandBehavior behavior,
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
return Task.FromResult(ExecuteReader(behavior));
}
/// <summary>
/// Executes the <see cref="CommandText" /> asynchronously against the database and returns a data reader.
/// </summary>
/// <param name="behavior">A description of query's results and its effect on the database.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <returns>A task representing the asynchronous operation.</returns>
/// <seealso href="https://docs.microsoft.com/dotnet/standard/data/sqlite/async">Async Limitations</seealso>
/// <exception cref="OperationCanceledException">If the <see cref="CancellationToken"/> is canceled.</exception>
protected override async Task<DbDataReader> ExecuteDbDataReaderAsync(
CommandBehavior behavior,
CancellationToken cancellationToken)
=> await ExecuteReaderAsync(behavior, cancellationToken).ConfigureAwait(false);
/// <summary>
/// Executes the <see cref="CommandText" /> against the database.
/// </summary>
/// <returns>The number of rows inserted, updated, or deleted. -1 for SELECT statements.</returns>
/// <exception cref="SqliteException">A SQLite error occurs during execution.</exception>
/// <seealso href="https://docs.microsoft.com/dotnet/standard/data/sqlite/database-errors">Database Errors</seealso>
public override int ExecuteNonQuery()
{
if (_connection?.State != ConnectionState.Open)
{
throw new InvalidOperationException(Resources.CallRequiresOpenConnection(nameof(ExecuteNonQuery)));
}
var reader = ExecuteReader();
reader.Dispose();
return reader.RecordsAffected;
}
/// <summary>
/// Executes the <see cref="CommandText" /> against the database and returns the result.
/// </summary>
/// <returns>The first column of the first row of the results, or null if no results.</returns>
/// <exception cref="SqliteException">A SQLite error occurs during execution.</exception>
/// <seealso href="https://docs.microsoft.com/dotnet/standard/data/sqlite/database-errors">Database Errors</seealso>
public override object? ExecuteScalar()
{
if (_connection?.State != ConnectionState.Open)
{
throw new InvalidOperationException(Resources.CallRequiresOpenConnection(nameof(ExecuteScalar)));
}
using var reader = ExecuteReader();
return reader.Read()
? reader.GetValue(0)
: null;
}
/// <summary>
/// Attempts to cancel the execution of the command. Does nothing.
/// </summary>
public override void Cancel()
{
}
private IEnumerable<(sqlite3_stmt Statement, int ParamCount)> PrepareAndEnumerateStatements()
{
DisposePreparedStatements(disposing: false);
var byteCount = Encoding.UTF8.GetByteCount(_commandText);
var sql = new byte[byteCount + 1];
Encoding.UTF8.GetBytes(_commandText, 0, _commandText.Length, sql, 0);
var totalElapsedTime = TimeSpan.Zero;
int rc;
sqlite3_stmt stmt;
var start = 0;
do
{
var timer = SharedStopwatch.StartNew();
ReadOnlySpan<byte> tail;
while (IsBusy(rc = sqlite3_prepare_v2(_connection!.Handle, sql.AsSpan(start), out stmt, out tail)))
{
if (CommandTimeout != 0
&& (totalElapsedTime + timer.Elapsed).TotalMilliseconds >= CommandTimeout * 1000L)
{
break;
}
Thread.Sleep(150);
}
totalElapsedTime += timer.Elapsed;
start = sql.Length - tail.Length;
SqliteException.ThrowExceptionForRC(rc, _connection.Handle);
// Statement was empty, white space, or a comment
if (stmt.IsInvalid)
{
if (start < byteCount)
{
continue;
}
break;
}
var paramsCount = sqlite3_bind_parameter_count(stmt);
var statementWithParams = (stmt, paramsCount);
_preparedStatements.Add(statementWithParams);
yield return statementWithParams;
}
while (start < byteCount);
_prepared = true;
}
private void DisposePreparedStatements(bool disposing = true)
{
if (disposing
&& DataReader != null)
{
DataReader.Dispose();
DataReader = null;
}
if (_preparedStatements != null)
{
foreach ((var stmt, _) in _preparedStatements)
{
stmt.Dispose();
}
_preparedStatements.Clear();
}
_prepared = false;
}
private static bool IsBusy(int rc)
=> rc is SQLITE_LOCKED or SQLITE_BUSY or SQLITE_LOCKED_SHAREDCACHE;
}
}