-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSQLite.cs
More file actions
389 lines (342 loc) · 14 KB
/
Copy pathSQLite.cs
File metadata and controls
389 lines (342 loc) · 14 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
using System;
using System.Data.Common;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Data.Sqlite;
namespace DBAClientX;
/// <summary>
/// Provides the SQLite-specific implementation of <see cref="DatabaseClientBase"/> exposing
/// convenience helpers for executing commands, queries, and bulk operations against a local
/// or remote SQLite database file.
/// </summary>
public partial class SQLite : DatabaseClientBase
{
private static readonly HashSet<string> ConnectionStringSourceKeys = new(StringComparer.OrdinalIgnoreCase)
{
"Data Source",
"DataSource",
"Filename",
"FullUri"
};
/// <summary>
/// Default busy timeout used for operational commands when a per-instance value is not overridden.
/// </summary>
public const int DefaultBusyTimeoutMs = 5000;
/// <summary>
/// Default upper bound for concurrent query execution in <see cref="RunQueriesInParallel"/>.
/// </summary>
public const int DefaultMaxParallelQueries = 8;
private readonly object _syncRoot = new();
private SqliteConnection? _transactionConnection;
private SqliteTransaction? _transaction;
private string? _transactionConnectionString;
private bool _transactionInitializing;
private volatile int _busyTimeoutMs = DefaultBusyTimeoutMs;
/// <summary>
/// Gets a value indicating whether an explicit transaction scope is currently active.
/// </summary>
/// <remarks>
/// The flag is toggled by the <see cref="BeginTransaction(string)"/>,
/// <see cref="BeginTransactionAsync(string, CancellationToken)"/> and related overloads
/// and resets after invoking <see cref="Commit"/>, <see cref="Rollback"/> or their asynchronous counterparts.
/// </remarks>
public bool IsInTransaction => _transaction != null;
/// <summary>
/// Gets or sets the busy timeout (in milliseconds) applied to operational SQLite connections.
/// </summary>
/// <remarks>
/// Set to <c>0</c> to use provider defaults and disable explicit timeout injection.
/// </remarks>
public int BusyTimeoutMs
{
get => _busyTimeoutMs;
set
{
if (value < 0)
{
throw new ArgumentOutOfRangeException(nameof(value), "BusyTimeoutMs cannot be negative.");
}
_busyTimeoutMs = value;
}
}
/// <summary>
/// Builds a connection string suitable for <see cref="SqliteConnection"/> instances using a database file path.
/// </summary>
/// <param name="database">Absolute or relative path of the SQLite database file.</param>
/// <returns>A connection string that targets <paramref name="database"/>.</returns>
/// <remarks>
/// Pooling is disabled by default so short-lived file workflows and <c>:memory:</c> databases do not outlive
/// the logical connection boundary. Callers that need pooling can still append it explicitly to the returned
/// connection string.
/// </remarks>
public static string BuildConnectionString(string database)
=> BuildConnectionString(database, readOnly: false, busyTimeoutMs: null);
/// <summary>
/// Builds a connection string suitable for <see cref="SqliteConnection"/> instances using a database file path.
/// </summary>
/// <param name="database">Absolute or relative path of the SQLite database file.</param>
/// <param name="readOnly">When true, opens the connection in read-only mode.</param>
/// <param name="busyTimeoutMs">Optional busy timeout applied via the connection string (milliseconds).</param>
/// <returns>A connection string that targets <paramref name="database"/>.</returns>
public static string BuildConnectionString(string database, bool readOnly, int? busyTimeoutMs)
{
ValidateDatabasePath(database);
if (busyTimeoutMs.HasValue && busyTimeoutMs.Value < 0)
{
throw new ArgumentOutOfRangeException(nameof(busyTimeoutMs), "Busy timeout cannot be negative.");
}
var builder = new SqliteConnectionStringBuilder
{
DataSource = database,
Pooling = false
};
if (readOnly)
{
builder.Mode = SqliteOpenMode.ReadOnly;
}
if (busyTimeoutMs.HasValue && busyTimeoutMs.Value > 0)
{
builder.DefaultTimeout = Math.Max(1, (int)Math.Ceiling(busyTimeoutMs.Value / 1000d));
}
return builder.ConnectionString;
}
/// <summary>
/// Builds a read-only connection string for the supplied SQLite database.
/// </summary>
/// <param name="database">Absolute or relative path of the SQLite database file.</param>
/// <param name="busyTimeoutMs">Optional busy timeout applied via the connection string (milliseconds).</param>
/// <returns>A read-only connection string.</returns>
public static string BuildReadOnlyConnectionString(string database, int? busyTimeoutMs = null)
=> BuildConnectionString(database, readOnly: true, busyTimeoutMs: busyTimeoutMs);
private static string BuildOperationalConnectionString(string database, bool readOnly = false) =>
BuildConnectionString(database, readOnly, busyTimeoutMs: null);
private static string NormalizeConnectionString(string connectionString, bool readOnly = false)
{
var builder = new SqliteConnectionStringBuilder(TranslateSQLiteFullUri(connectionString));
if (readOnly &&
builder.Mode != SqliteOpenMode.Memory &&
!string.Equals(builder.DataSource, ":memory:", StringComparison.OrdinalIgnoreCase))
{
builder.Mode = SqliteOpenMode.ReadOnly;
builder.Pooling = false;
}
return builder.ToString();
}
internal static bool IsConnectionString(string connectionStringOrPath)
{
foreach (var segment in connectionStringOrPath.Split(';'))
{
var separator = segment.IndexOf('=');
if (separator > 0 && ConnectionStringSourceKeys.Contains(segment.Substring(0, separator).Trim()))
{
return true;
}
}
return false;
}
internal static string TranslateSQLiteFullUri(string connectionString)
{
var builder = new DbConnectionStringBuilder
{
ConnectionString = connectionString
};
if (TryTranslateSQLiteSourceUri(builder, "FullUri", removeSourceKey: true))
{
return builder.ConnectionString;
}
foreach (var sourceKey in new[] { "Data Source", "DataSource", "Filename" })
{
if (TryTranslateSQLiteSourceUri(builder, sourceKey, removeSourceKey: false))
{
return builder.ConnectionString;
}
}
return connectionString;
}
private static bool TryTranslateSQLiteSourceUri(DbConnectionStringBuilder builder, string sourceKey, bool removeSourceKey)
{
if (!builder.TryGetValue(sourceKey, out var value) || value == null)
{
return false;
}
var uriText = value.ToString();
if (Uri.TryCreate(uriText, UriKind.Absolute, out var uri) && uri.IsFile)
{
if (removeSourceKey)
{
builder.Remove(sourceKey);
}
builder["Data Source"] = uri.LocalPath;
ApplySQLiteFullUriQueryOptions(builder, uri);
return true;
}
if (removeSourceKey)
{
builder.Remove(sourceKey);
builder["Data Source"] = uriText;
return true;
}
return false;
}
private static void ApplySQLiteFullUriQueryOptions(DbConnectionStringBuilder builder, Uri uri)
{
if (string.IsNullOrEmpty(uri.Query) || uri.Query.Length <= 1)
{
return;
}
var query = uri.Query.Substring(1).Split(new[] { '&' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var part in query)
{
var separator = part.IndexOf('=');
var key = separator < 0 ? part : part.Substring(0, separator);
var value = separator < 0 ? string.Empty : part.Substring(separator + 1);
ApplySQLiteFullUriOption(
builder,
Uri.UnescapeDataString(key),
Uri.UnescapeDataString(value));
}
}
private static void ApplySQLiteFullUriOption(DbConnectionStringBuilder builder, string key, string value)
{
if (string.Equals(key, "mode", StringComparison.OrdinalIgnoreCase))
{
if (builder.ContainsKey("Mode"))
{
return;
}
if (string.Equals(value, "ro", StringComparison.OrdinalIgnoreCase))
{
builder["Mode"] = SqliteOpenMode.ReadOnly;
}
else if (string.Equals(value, "rw", StringComparison.OrdinalIgnoreCase))
{
builder["Mode"] = SqliteOpenMode.ReadWrite;
}
else if (string.Equals(value, "rwc", StringComparison.OrdinalIgnoreCase))
{
builder["Mode"] = SqliteOpenMode.ReadWriteCreate;
}
else if (string.Equals(value, "memory", StringComparison.OrdinalIgnoreCase))
{
builder["Mode"] = SqliteOpenMode.Memory;
}
return;
}
if (!string.Equals(key, "cache", StringComparison.OrdinalIgnoreCase) || builder.ContainsKey("Cache"))
{
return;
}
if (string.Equals(value, "shared", StringComparison.OrdinalIgnoreCase))
{
builder["Cache"] = SqliteCacheMode.Shared;
}
else if (string.Equals(value, "private", StringComparison.OrdinalIgnoreCase))
{
builder["Cache"] = SqliteCacheMode.Private;
}
}
private int ResolveBusyTimeoutMs(int? busyTimeoutMs)
{
var effectiveTimeout = busyTimeoutMs ?? BusyTimeoutMs;
if (effectiveTimeout < 0)
{
throw new ArgumentOutOfRangeException(nameof(busyTimeoutMs), "Busy timeout cannot be negative.");
}
return effectiveTimeout;
}
private static int? ResolveConnectionBusyTimeout(string connectionString, int? busyTimeoutMs)
{
if (busyTimeoutMs.HasValue)
{
return busyTimeoutMs;
}
var builder = new DbConnectionStringBuilder
{
ConnectionString = connectionString
};
return builder.ContainsKey("Default Timeout") ||
builder.ContainsKey("Command Timeout")
? 0
: null;
}
private void ApplyBusyTimeout(SqliteConnection connection, int? busyTimeoutMs = null)
{
var effectiveTimeout = ResolveBusyTimeoutMs(busyTimeoutMs);
if (effectiveTimeout <= 0)
{
return;
}
using var command = connection.CreateCommand();
command.CommandText = $"PRAGMA busy_timeout = {effectiveTimeout};";
command.ExecuteNonQuery();
}
private async Task ApplyBusyTimeoutAsync(SqliteConnection connection, int? busyTimeoutMs, CancellationToken cancellationToken)
{
var effectiveTimeout = ResolveBusyTimeoutMs(busyTimeoutMs);
if (effectiveTimeout <= 0)
{
return;
}
using var command = connection.CreateCommand();
command.CommandText = $"PRAGMA busy_timeout = {effectiveTimeout};";
#if NETSTANDARD2_1_OR_GREATER || NETCOREAPP3_0_OR_GREATER || NET5_0_OR_GREATER
await AwaitWithCallerCancellationAsync(
() => command.ExecuteNonQueryAsync(cancellationToken),
cancellationToken).ConfigureAwait(false);
#else
await Task.Yield();
command.ExecuteNonQuery();
#endif
}
/// <summary>
/// Performs a lightweight connectivity test against the supplied SQLite database file.
/// </summary>
/// <param name="database">Absolute or relative path of the SQLite database file.</param>
/// <returns><see langword="true"/> when executing <c>SELECT 1</c> succeeds; otherwise <see langword="false"/>.</returns>
/// <remarks>
/// Exceptions are intentionally swallowed so the probe can be used in health-check scenarios. When detailed
/// error information is required, invoke <see cref="ExecuteScalar(string, string, System.Collections.Generic.IDictionary{string, object?}?, bool, System.Collections.Generic.IDictionary{string, SqliteType}?, System.Collections.Generic.IDictionary{string, System.Data.ParameterDirection}?)"/>
/// to receive the specific <see cref="Exception"/> that occurred.
/// </remarks>
public virtual bool Ping(string database)
{
try
{
ExecuteScalar(database, "SELECT 1");
return true;
}
catch
{
return false;
}
}
/// <summary>
/// Asynchronously performs a connectivity test against the supplied SQLite database file.
/// </summary>
/// <param name="database">Absolute or relative path of the SQLite database file.</param>
/// <param name="cancellationToken">Token used to cancel the underlying command execution.</param>
/// <returns><see langword="true"/> when executing <c>SELECT 1</c> succeeds; otherwise <see langword="false"/>.</returns>
/// <remarks>
/// Mirrors the synchronous <see cref="Ping(string)"/> implementation while relying on asynchronous I/O to avoid
/// blocking the caller's thread. Recommended for UI or ASP.NET workloads.
/// </remarks>
public virtual async Task<bool> PingAsync(string database, CancellationToken cancellationToken = default)
{
try
{
await ExecuteScalarAsync(database, "SELECT 1", cancellationToken: cancellationToken).ConfigureAwait(false);
return true;
}
catch
{
return false;
}
}
private static void ValidateDatabasePath(string database)
{
if (string.IsNullOrWhiteSpace(database))
{
throw new ArgumentException("Database path cannot be null or whitespace.", nameof(database));
}
}
}