-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathSqlHelper.cs
More file actions
274 lines (228 loc) · 9.66 KB
/
SqlHelper.cs
File metadata and controls
274 lines (228 loc) · 9.66 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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using SQLite;
namespace SqlUsage.Helpers
{
/// <summary>
/// A collection of helper methods for working with SQLite databases.
/// </summary>
public static class SqlHelper
{
public static Task<List<TResult>> ExecuteCancellableQueryAsync<TResult>(SQLiteAsyncConnection connection,
string sql,
Dictionary<string, object> parameters,
Func<SQLitePCL.sqlite3_stmt, TResult> mapper,
CancellationToken cancellationToken) where TResult : class
{
if (connection is null)
{
throw new ArgumentNullException(nameof(connection));
}
if (string.IsNullOrEmpty(sql))
{
throw new ArgumentException($"'{nameof(sql)}' cannot be null or empty.", nameof(sql));
}
if (mapper is null)
{
throw new ArgumentNullException(nameof(mapper));
}
return Task.Factory.StartNew(() => {
var conn = connection.GetConnection();
using (conn.Lock())
{
return ExecuteCancellableQuery(conn, sql, parameters, mapper, cancellationToken);
}
}, cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
public static Task<List<TResult>> ExecuteCancellableQueryAsync<TResult>(SQLiteConnection connection,
string sql,
Dictionary<string, object> parameters,
Func<SQLitePCL.sqlite3_stmt, TResult> mapper,
CancellationToken cancellationToken)
{
if (connection is null)
{
throw new ArgumentNullException(nameof(connection));
}
if (string.IsNullOrEmpty(sql))
{
throw new ArgumentException($"'{nameof(sql)}' cannot be null or empty.", nameof(sql));
}
if (mapper is null)
{
throw new ArgumentNullException(nameof(mapper));
}
return Task.Factory.StartNew(() =>
{
return ExecuteCancellableQuery(connection, sql, parameters, mapper, cancellationToken);
}, cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
public static List<TResult> ExecuteCancellableQuery<TResult>(SQLiteConnection connection,
string sql,
Dictionary<string, object> parameters,
Func<SQLitePCL.sqlite3_stmt, TResult> mapper,
CancellationToken cancellationToken)
{
if (connection is null)
{
throw new ArgumentNullException(nameof(connection));
}
if (string.IsNullOrEmpty(sql))
{
throw new ArgumentException($"'{nameof(sql)}' cannot be null or empty.", nameof(sql));
}
if (mapper is null)
{
throw new ArgumentNullException(nameof(mapper));
}
var results = new List<TResult>();
var statement = CreateStatement(connection, sql, parameters);
try
{
while (SQLite3.Step(statement) == SQLite3.Result.Row)
{
cancellationToken.ThrowIfCancellationRequested();
var element = mapper(statement);
if (element != null)
{
results.Add(element);
}
}
}
catch (TaskCanceledException tce)
{
throw tce;
}
catch (OperationCanceledException oex)
{
throw oex;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
throw;
}
finally
{
SQLite3.Finalize(statement);
}
return results;
}
private static readonly Lazy<MethodInfo> prepareMethod = new Lazy<MethodInfo>(() => typeof(SQLiteCommand).GetMethod("Prepare", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic));
private static readonly Dictionary<string, object> emptyParameters = new Dictionary<string, object>();
public static SQLitePCL.sqlite3_stmt CreateStatement(SQLiteConnection connection, string sql, Dictionary<string, object> parameters)
{
if (connection is null)
{
throw new ArgumentNullException(nameof(connection));
}
if (string.IsNullOrEmpty(sql))
{
throw new ArgumentException($"'{nameof(sql)}' cannot be null or empty.", nameof(sql));
}
parameters = parameters ?? emptyParameters;
var command = connection.CreateCommand(sql, parameters);
var result = prepareMethod.Value.Invoke(command, null);
return (SQLitePCL.sqlite3_stmt)result;
}
public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
var knownKeys = new HashSet<TKey>();
foreach (var element in source)
{
if (knownKeys.Add(keySelector(element)))
{
yield return element;
}
}
}
/// <summary>
/// Checks if a table with the given <paramref name="tableName"/> exists in the database <paramref name="connection"/>.
/// </summary>
public static bool TableExists(SQLiteConnection connection, string tableName)
{
const string cmdText = "SELECT name FROM sqlite_master WHERE type='table' AND name=?";
var cmd = connection.CreateCommand(cmdText, tableName);
return cmd.ExecuteScalar<string>() != null;
}
/// <summary>
/// Gets all the tables in the provided <paramref name="connection"/>.
/// </summary>
public static List<string> Tables(this SQLiteConnection connection)
{
const string GET_TABLES_QUERY = "SELECT NAME from sqlite_master";
var tables = new List<string>();
var statement = SQLite3.Prepare2(connection.Handle, GET_TABLES_QUERY);
try
{
var done = false;
while (!done)
{
var result = SQLite3.Step(statement);
if (result == SQLite3.Result.Row)
{
var tableName = SQLite3.ColumnString(statement, 0);
tables.Add(tableName);
}
else if (result == SQLite3.Result.Done)
{
done = true;
}
else
{
throw SQLiteException.New(result, SQLite3.GetErrmsg(connection.Handle));
}
}
}
finally
{
SQLite3.Finalize(statement);
}
return tables;
}
/// <summary>
/// Gets all the columns for the <paramref name="tableName"/> in the provided <paramref name="connection"/>.
/// </summary>
/// <returns>The for table.</returns>
/// <param name="connection">Connection.</param>
/// <param name="tableName">Table name.</param>
public static List<string> ColumnsForTable(this SQLiteConnection connection, string tableName)
{
const string GET_COLUMNS_QUERY = "PRAGMA table_info({0})";
var query = string.Format(GET_COLUMNS_QUERY, tableName);
var columns = new List<string>();
var statement = SQLite3.Prepare2(connection.Handle, query);
try
{
var done = false;
while (!done)
{
var result = SQLite3.Step(statement);
if (result == SQLite3.Result.Row)
{
var columnName = SQLite3.ColumnString(statement, 1);
columns.Add(columnName);
}
else if (result == SQLite3.Result.Done)
{
done = true;
}
else
{
throw SQLiteException.New(result, SQLite3.GetErrmsg(connection.Handle));
}
}
}
finally
{
SQLite3.Finalize(statement);
}
return columns;
}
}
}