-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathSQLite.cs
4992 lines (4449 loc) · 161 KB
/
SQLite.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
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
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// Copyright (c) 2009-2024 Krueger Systems, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#if WINDOWS_PHONE && !USE_WP8_NATIVE_SQLITE
#define USE_CSHARP_SQLITE
#endif
using System;
using System.Collections;
using System.Diagnostics;
#if !USE_SQLITEPCL_RAW
using System.Runtime.InteropServices;
#endif
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading;
#if USE_CSHARP_SQLITE
using Sqlite3 = Community.CsharpSqlite.Sqlite3;
using Sqlite3DatabaseHandle = Community.CsharpSqlite.Sqlite3.sqlite3;
using Sqlite3Statement = Community.CsharpSqlite.Sqlite3.Vdbe;
#elif USE_WP8_NATIVE_SQLITE
using Sqlite3 = Sqlite.Sqlite3;
using Sqlite3DatabaseHandle = Sqlite.Database;
using Sqlite3Statement = Sqlite.Statement;
#elif USE_SQLITEPCL_RAW
using Sqlite3DatabaseHandle = SQLitePCL.sqlite3;
using Sqlite3BackupHandle = SQLitePCL.sqlite3_backup;
using Sqlite3Statement = SQLitePCL.sqlite3_stmt;
using Sqlite3 = SQLitePCL.raw;
#else
using Sqlite3DatabaseHandle = System.IntPtr;
using Sqlite3BackupHandle = System.IntPtr;
using Sqlite3Statement = System.IntPtr;
#endif
#pragma warning disable 1591 // XML Doc Comments
namespace SQLite
{
public class SQLiteException : Exception
{
public SQLite3.Result Result { get; private set; }
protected SQLiteException (SQLite3.Result r, string message) : base (message)
{
Result = r;
}
public static SQLiteException New (SQLite3.Result r, string message)
{
return new SQLiteException (r, message);
}
}
public class NotNullConstraintViolationException : SQLiteException
{
public IEnumerable<TableMapping.Column> Columns { get; protected set; }
protected NotNullConstraintViolationException (SQLite3.Result r, string message)
: this (r, message, null, null)
{
}
protected NotNullConstraintViolationException (SQLite3.Result r, string message, TableMapping mapping, object obj)
: base (r, message)
{
if (mapping != null && obj != null) {
this.Columns = from c in mapping.Columns
where c.IsNullable == false && c.GetValue (obj) == null
select c;
}
}
public static new NotNullConstraintViolationException New (SQLite3.Result r, string message)
{
return new NotNullConstraintViolationException (r, message);
}
public static NotNullConstraintViolationException New (SQLite3.Result r, string message, TableMapping mapping, object obj)
{
return new NotNullConstraintViolationException (r, message, mapping, obj);
}
public static NotNullConstraintViolationException New (SQLiteException exception, TableMapping mapping, object obj)
{
return new NotNullConstraintViolationException (exception.Result, exception.Message, mapping, obj);
}
}
[Flags]
public enum SQLiteOpenFlags
{
ReadOnly = 1, ReadWrite = 2, Create = 4,
Uri = 0x40, Memory = 0x80,
NoMutex = 0x8000, FullMutex = 0x10000,
SharedCache = 0x20000, PrivateCache = 0x40000,
ProtectionComplete = 0x00100000,
ProtectionCompleteUnlessOpen = 0x00200000,
ProtectionCompleteUntilFirstUserAuthentication = 0x00300000,
ProtectionNone = 0x00400000
}
[Flags]
public enum CreateFlags
{
/// <summary>
/// Use the default creation options
/// </summary>
None = 0x000,
/// <summary>
/// Create a primary key index for a property called 'Id' (case-insensitive).
/// This avoids the need for the [PrimaryKey] attribute.
/// </summary>
ImplicitPK = 0x001,
/// <summary>
/// Create indices for properties ending in 'Id' (case-insensitive).
/// </summary>
ImplicitIndex = 0x002,
/// <summary>
/// Create a primary key for a property called 'Id' and
/// create an indices for properties ending in 'Id' (case-insensitive).
/// </summary>
AllImplicit = 0x003,
/// <summary>
/// Force the primary key property to be auto incrementing.
/// This avoids the need for the [AutoIncrement] attribute.
/// The primary key property on the class should have type int or long.
/// </summary>
AutoIncPK = 0x004,
/// <summary>
/// Create virtual table using FTS3
/// </summary>
FullTextSearch3 = 0x100,
/// <summary>
/// Create virtual table using FTS4
/// </summary>
FullTextSearch4 = 0x200
}
public interface ISQLiteConnection : IDisposable
{
Sqlite3DatabaseHandle Handle { get; }
string DatabasePath { get; }
int LibVersionNumber { get; }
bool TimeExecution { get; set; }
bool Trace { get; set; }
Action<string> Tracer { get; set; }
bool StoreDateTimeAsTicks { get; }
bool StoreTimeSpanAsTicks { get; }
string DateTimeStringFormat { get; }
TimeSpan BusyTimeout { get; set; }
IEnumerable<TableMapping> TableMappings { get; }
bool IsInTransaction { get; }
event EventHandler<NotifyTableChangedEventArgs> TableChanged;
void Backup (string destinationDatabasePath, string databaseName = "main");
void BeginTransaction ();
void Close ();
void Commit ();
SQLiteCommand CreateCommand (string cmdText, params object[] ps);
SQLiteCommand CreateCommand (string cmdText, Dictionary<string, object> args);
int CreateIndex (string indexName, string tableName, string[] columnNames, bool unique = false);
int CreateIndex (string indexName, string tableName, string columnName, bool unique = false);
int CreateIndex (string tableName, string columnName, bool unique = false);
int CreateIndex (string tableName, string[] columnNames, bool unique = false);
int CreateIndex<T> (Expression<Func<T, object>> property, bool unique = false);
CreateTableResult CreateTable<T> (CreateFlags createFlags = CreateFlags.None);
CreateTableResult CreateTable (Type ty, CreateFlags createFlags = CreateFlags.None);
CreateTablesResult CreateTables<T, T2> (CreateFlags createFlags = CreateFlags.None)
where T : new()
where T2 : new();
CreateTablesResult CreateTables<T, T2, T3> (CreateFlags createFlags = CreateFlags.None)
where T : new()
where T2 : new()
where T3 : new();
CreateTablesResult CreateTables<T, T2, T3, T4> (CreateFlags createFlags = CreateFlags.None)
where T : new()
where T2 : new()
where T3 : new()
where T4 : new();
CreateTablesResult CreateTables<T, T2, T3, T4, T5> (CreateFlags createFlags = CreateFlags.None)
where T : new()
where T2 : new()
where T3 : new()
where T4 : new()
where T5 : new();
CreateTablesResult CreateTables (CreateFlags createFlags = CreateFlags.None, params Type[] types);
IEnumerable<T> DeferredQuery<T> (string query, params object[] args) where T : new();
IEnumerable<object> DeferredQuery (TableMapping map, string query, params object[] args);
int Delete (object objectToDelete);
int Delete<T> (object primaryKey);
int Delete (object primaryKey, TableMapping map);
int DeleteAll<T> ();
int DeleteAll (TableMapping map);
int DropTable<T> ();
int DropTable (TableMapping map);
void EnableLoadExtension (bool enabled);
void EnableWriteAheadLogging ();
int Execute (string query, params object[] args);
T ExecuteScalar<T> (string query, params object[] args);
T Find<T> (object pk) where T : new();
object Find (object pk, TableMapping map);
T Find<T> (Expression<Func<T, bool>> predicate) where T : new();
T FindWithQuery<T> (string query, params object[] args) where T : new();
object FindWithQuery (TableMapping map, string query, params object[] args);
T Get<T> (object pk) where T : new();
object Get (object pk, TableMapping map);
T Get<T> (Expression<Func<T, bool>> predicate) where T : new();
TableMapping GetMapping (Type type, CreateFlags createFlags = CreateFlags.None);
TableMapping GetMapping<T> (CreateFlags createFlags = CreateFlags.None);
List<SQLiteConnection.ColumnInfo> GetTableInfo (string tableName);
int Insert (object obj);
int Insert (object obj, Type objType);
int Insert (object obj, string extra);
int Insert (object obj, string extra, Type objType);
int InsertAll (IEnumerable objects, bool runInTransaction = true);
int InsertAll (IEnumerable objects, string extra, bool runInTransaction = true);
int InsertAll (IEnumerable objects, Type objType, bool runInTransaction = true);
int InsertOrReplace (object obj);
int InsertOrReplace (object obj, Type objType);
List<T> Query<T> (string query, params object[] args) where T : new();
List<object> Query (TableMapping map, string query, params object[] args);
List<T> QueryScalars<T> (string query, params object[] args);
void ReKey (string key);
void ReKey (byte[] key);
void Release (string savepoint);
void Rollback ();
void RollbackTo (string savepoint);
void RunInTransaction (Action action);
string SaveTransactionPoint ();
TableQuery<T> Table<T> () where T : new();
int Update (object obj);
int Update (object obj, Type objType);
int UpdateAll (IEnumerable objects, bool runInTransaction = true);
}
/// <summary>
/// An open connection to a SQLite database.
/// </summary>
[Preserve (AllMembers = true)]
public partial class SQLiteConnection : ISQLiteConnection
{
private bool _open;
private TimeSpan _busyTimeout;
readonly static Dictionary<string, TableMapping> _mappings = new Dictionary<string, TableMapping> ();
private System.Diagnostics.Stopwatch _sw;
private long _elapsedMilliseconds = 0;
private int _transactionDepth = 0;
private Random _rand = new Random ();
public Sqlite3DatabaseHandle Handle { get; private set; }
static readonly Sqlite3DatabaseHandle NullHandle = default (Sqlite3DatabaseHandle);
static readonly Sqlite3BackupHandle NullBackupHandle = default (Sqlite3BackupHandle);
/// <summary>
/// Gets the database path used by this connection.
/// </summary>
public string DatabasePath { get; private set; }
/// <summary>
/// Gets the SQLite library version number. 3007014 would be v3.7.14
/// </summary>
public int LibVersionNumber { get; private set; }
/// <summary>
/// Whether Trace lines should be written that show the execution time of queries.
/// </summary>
public bool TimeExecution { get; set; }
/// <summary>
/// Whether to write queries to <see cref="Tracer"/> during execution.
/// </summary>
public bool Trace { get; set; }
/// <summary>
/// The delegate responsible for writing trace lines.
/// </summary>
/// <value>The tracer.</value>
public Action<string> Tracer { get; set; }
/// <summary>
/// Whether to store DateTime properties as ticks (true) or strings (false).
/// </summary>
public bool StoreDateTimeAsTicks { get; private set; }
/// <summary>
/// Whether to store TimeSpan properties as ticks (true) or strings (false).
/// </summary>
public bool StoreTimeSpanAsTicks { get; private set; }
/// <summary>
/// The format to use when storing DateTime properties as strings. Ignored if StoreDateTimeAsTicks is true.
/// </summary>
/// <value>The date time string format.</value>
public string DateTimeStringFormat { get; private set; }
/// <summary>
/// The DateTimeStyles value to use when parsing a DateTime property string.
/// </summary>
/// <value>The date time style.</value>
internal System.Globalization.DateTimeStyles DateTimeStyle { get; private set; }
#if USE_SQLITEPCL_RAW && !NO_SQLITEPCL_RAW_BATTERIES
static SQLiteConnection ()
{
SQLitePCL.Batteries_V2.Init ();
}
#endif
/// <summary>
/// Constructs a new SQLiteConnection and opens a SQLite database specified by databasePath.
/// </summary>
/// <param name="databasePath">
/// Specifies the path to the database file.
/// </param>
/// <param name="storeDateTimeAsTicks">
/// Specifies whether to store DateTime properties as ticks (true) or strings (false). You
/// absolutely do want to store them as Ticks in all new projects. The value of false is
/// only here for backwards compatibility. There is a *significant* speed advantage, with no
/// down sides, when setting storeDateTimeAsTicks = true.
/// If you use DateTimeOffset properties, it will be always stored as ticks regardingless
/// the storeDateTimeAsTicks parameter.
/// </param>
public SQLiteConnection (string databasePath, bool storeDateTimeAsTicks = true)
: this (new SQLiteConnectionString (databasePath, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create, storeDateTimeAsTicks))
{
}
/// <summary>
/// Constructs a new SQLiteConnection and opens a SQLite database specified by databasePath.
/// </summary>
/// <param name="databasePath">
/// Specifies the path to the database file.
/// </param>
/// <param name="openFlags">
/// Flags controlling how the connection should be opened.
/// </param>
/// <param name="storeDateTimeAsTicks">
/// Specifies whether to store DateTime properties as ticks (true) or strings (false). You
/// absolutely do want to store them as Ticks in all new projects. The value of false is
/// only here for backwards compatibility. There is a *significant* speed advantage, with no
/// down sides, when setting storeDateTimeAsTicks = true.
/// If you use DateTimeOffset properties, it will be always stored as ticks regardingless
/// the storeDateTimeAsTicks parameter.
/// </param>
public SQLiteConnection (string databasePath, SQLiteOpenFlags openFlags, bool storeDateTimeAsTicks = true)
: this (new SQLiteConnectionString (databasePath, openFlags, storeDateTimeAsTicks))
{
}
/// <summary>
/// Constructs a new SQLiteConnection and opens a SQLite database specified by databasePath.
/// </summary>
/// <param name="connectionString">
/// Details on how to find and open the database.
/// </param>
public SQLiteConnection (SQLiteConnectionString connectionString)
{
if (connectionString == null)
throw new ArgumentNullException (nameof (connectionString));
if (connectionString.DatabasePath == null)
throw new InvalidOperationException ("DatabasePath must be specified");
DatabasePath = connectionString.DatabasePath;
LibVersionNumber = SQLite3.LibVersionNumber ();
#if NETFX_CORE
SQLite3.SetDirectory(/*temp directory type*/2, Windows.Storage.ApplicationData.Current.TemporaryFolder.Path);
#endif
Sqlite3DatabaseHandle handle;
#if SILVERLIGHT || USE_CSHARP_SQLITE || USE_SQLITEPCL_RAW
var r = SQLite3.Open (connectionString.DatabasePath, out handle, (int)connectionString.OpenFlags, connectionString.VfsName);
#else
// open using the byte[]
// in the case where the path may include Unicode
// force open to using UTF-8 using sqlite3_open_v2
var databasePathAsBytes = GetNullTerminatedUtf8 (connectionString.DatabasePath);
var r = SQLite3.Open (databasePathAsBytes, out handle, (int)connectionString.OpenFlags, connectionString.VfsName);
#endif
Handle = handle;
if (r != SQLite3.Result.OK) {
throw SQLiteException.New (r, String.Format ("Could not open database file: {0} ({1})", DatabasePath, r));
}
_open = true;
StoreDateTimeAsTicks = connectionString.StoreDateTimeAsTicks;
StoreTimeSpanAsTicks = connectionString.StoreTimeSpanAsTicks;
DateTimeStringFormat = connectionString.DateTimeStringFormat;
DateTimeStyle = connectionString.DateTimeStyle;
BusyTimeout = TimeSpan.FromSeconds (1.0);
Tracer = line => Debug.WriteLine (line);
connectionString.PreKeyAction?.Invoke (this);
if (connectionString.Key is string stringKey) {
SetKey (stringKey);
}
else if (connectionString.Key is byte[] bytesKey) {
SetKey (bytesKey);
}
else if (connectionString.Key != null) {
throw new InvalidOperationException ("Encryption keys must be strings or byte arrays");
}
connectionString.PostKeyAction?.Invoke (this);
}
/// <summary>
/// Enables the write ahead logging. WAL is significantly faster in most scenarios
/// by providing better concurrency and better disk IO performance than the normal
/// journal mode. You only need to call this function once in the lifetime of the database.
/// </summary>
public void EnableWriteAheadLogging ()
{
ExecuteScalar<string> ("PRAGMA journal_mode=WAL");
}
/// <summary>
/// Convert an input string to a quoted SQL string that can be safely used in queries.
/// </summary>
/// <returns>The quoted string.</returns>
/// <param name="unsafeString">The unsafe string to quote.</param>
static string Quote (string unsafeString)
{
// TODO: Doesn't call sqlite3_mprintf("%Q", u) because we're waiting on https://github.com/ericsink/SQLitePCL.raw/issues/153
if (unsafeString == null)
return "NULL";
var safe = unsafeString.Replace ("'", "''");
return "'" + safe + "'";
}
/// <summary>
/// Sets the key used to encrypt/decrypt the database with "pragma key = ...".
/// This must be the first thing you call before doing anything else with this connection
/// if your database is encrypted.
/// This only has an effect if you are using the SQLCipher nuget package.
/// </summary>
/// <param name="key">Encryption key plain text that is converted to the real encryption key using PBKDF2 key derivation</param>
void SetKey (string key)
{
if (key == null)
throw new ArgumentNullException (nameof (key));
var q = Quote (key);
ExecuteScalar<string> ("pragma key = " + q);
}
/// <summary>
/// Sets the key used to encrypt/decrypt the database.
/// This must be the first thing you call before doing anything else with this connection
/// if your database is encrypted.
/// This only has an effect if you are using the SQLCipher nuget package.
/// </summary>
/// <param name="key">256-bit (32 byte) encryption key data</param>
void SetKey (byte[] key)
{
if (key == null)
throw new ArgumentNullException (nameof (key));
if (key.Length != 32 && key.Length != 48)
throw new ArgumentException ("Key must be 32 bytes (256-bit) or 48 bytes (384-bit)", nameof (key));
var s = String.Join ("", key.Select (x => x.ToString ("X2")));
ExecuteScalar<string> ("pragma key = \"x'" + s + "'\"");
}
/// <summary>
/// Change the encryption key for a SQLCipher database with "pragma rekey = ...".
/// </summary>
/// <param name="key">Encryption key plain text that is converted to the real encryption key using PBKDF2 key derivation</param>
public void ReKey (string key)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
var q = Quote(key);
ExecuteScalar<string>("pragma rekey = " + q);
}
/// <summary>
/// Change the encryption key for a SQLCipher database.
/// </summary>
/// <param name="key">256-bit (32 byte) or 384-bit (48 bytes) encryption key data</param>
public void ReKey (byte[] key)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
if (key.Length != 32 && key.Length != 48)
throw new ArgumentException ("Key must be 32 bytes (256-bit) or 48 bytes (384-bit)", nameof (key));
var s = String.Join("", key.Select(x => x.ToString("X2")));
ExecuteScalar<string>("pragma rekey = \"x'" + s + "'\"");
}
/// <summary>
/// Enable or disable extension loading.
/// </summary>
public void EnableLoadExtension (bool enabled)
{
SQLite3.Result r = SQLite3.EnableLoadExtension (Handle, enabled ? 1 : 0);
if (r != SQLite3.Result.OK) {
string msg = SQLite3.GetErrmsg (Handle);
throw SQLiteException.New (r, msg);
}
}
#if !USE_SQLITEPCL_RAW
static byte[] GetNullTerminatedUtf8 (string s)
{
var utf8Length = System.Text.Encoding.UTF8.GetByteCount (s);
var bytes = new byte [utf8Length + 1];
utf8Length = System.Text.Encoding.UTF8.GetBytes(s, 0, s.Length, bytes, 0);
return bytes;
}
#endif
/// <summary>
/// Sets a busy handler to sleep the specified amount of time when a table is locked.
/// The handler will sleep multiple times until a total time of <see cref="BusyTimeout"/> has accumulated.
/// </summary>
public TimeSpan BusyTimeout {
get { return _busyTimeout; }
set {
_busyTimeout = value;
if (Handle != NullHandle) {
SQLite3.BusyTimeout (Handle, (int)_busyTimeout.TotalMilliseconds);
}
}
}
/// <summary>
/// Returns the mappings from types to tables that the connection
/// currently understands.
/// </summary>
public IEnumerable<TableMapping> TableMappings {
get {
lock (_mappings) {
return new List<TableMapping> (_mappings.Values);
}
}
}
/// <summary>
/// Retrieves the mapping that is automatically generated for the given type.
/// </summary>
/// <param name="type">
/// The type whose mapping to the database is returned.
/// </param>
/// <param name="createFlags">
/// Optional flags allowing implicit PK and indexes based on naming conventions
/// </param>
/// <returns>
/// The mapping represents the schema of the columns of the database and contains
/// methods to set and get properties of objects.
/// </returns>
public TableMapping GetMapping (Type type, CreateFlags createFlags = CreateFlags.None)
{
TableMapping map;
var key = type.FullName;
lock (_mappings) {
if (_mappings.TryGetValue (key, out map)) {
if (createFlags != CreateFlags.None && createFlags != map.CreateFlags) {
map = new TableMapping (type, createFlags);
_mappings[key] = map;
}
}
else {
map = new TableMapping (type, createFlags);
_mappings.Add (key, map);
}
}
return map;
}
/// <summary>
/// Retrieves the mapping that is automatically generated for the given type.
/// </summary>
/// <param name="createFlags">
/// Optional flags allowing implicit PK and indexes based on naming conventions
/// </param>
/// <returns>
/// The mapping represents the schema of the columns of the database and contains
/// methods to set and get properties of objects.
/// </returns>
public TableMapping GetMapping<T> (CreateFlags createFlags = CreateFlags.None)
{
return GetMapping (typeof (T), createFlags);
}
private struct IndexedColumn
{
public int Order;
public string ColumnName;
}
private struct IndexInfo
{
public string IndexName;
public string TableName;
public bool Unique;
public List<IndexedColumn> Columns;
}
/// <summary>
/// Executes a "drop table" on the database. This is non-recoverable.
/// </summary>
public int DropTable<T> ()
{
return DropTable (GetMapping (typeof (T)));
}
/// <summary>
/// Executes a "drop table" on the database. This is non-recoverable.
/// </summary>
/// <param name="map">
/// The TableMapping used to identify the table.
/// </param>
public int DropTable (TableMapping map)
{
var query = string.Format ("drop table if exists \"{0}\"", map.TableName);
return Execute (query);
}
/// <summary>
/// Executes a "create table if not exists" on the database. It also
/// creates any specified indexes on the columns of the table. It uses
/// a schema automatically generated from the specified type. You can
/// later access this schema by calling GetMapping.
/// </summary>
/// <returns>
/// Whether the table was created or migrated.
/// </returns>
public CreateTableResult CreateTable<T> (CreateFlags createFlags = CreateFlags.None)
{
return CreateTable (typeof (T), createFlags);
}
/// <summary>
/// Executes a "create table if not exists" on the database. It also
/// creates any specified indexes on the columns of the table. It uses
/// a schema automatically generated from the specified type. You can
/// later access this schema by calling GetMapping.
/// </summary>
/// <param name="ty">Type to reflect to a database table.</param>
/// <param name="createFlags">Optional flags allowing implicit PK and indexes based on naming conventions.</param>
/// <returns>
/// Whether the table was created or migrated.
/// </returns>
public CreateTableResult CreateTable (Type ty, CreateFlags createFlags = CreateFlags.None)
{
var map = GetMapping (ty, createFlags);
// Present a nice error if no columns specified
if (map.Columns.Length == 0) {
throw new Exception (string.Format ("Cannot create a table without columns (does '{0}' have public properties?)", ty.FullName));
}
// Check if the table exists
var result = CreateTableResult.Created;
var existingCols = GetTableInfo (map.TableName);
// Create or migrate it
if (existingCols.Count == 0) {
// Facilitate virtual tables a.k.a. full-text search.
bool fts3 = (createFlags & CreateFlags.FullTextSearch3) != 0;
bool fts4 = (createFlags & CreateFlags.FullTextSearch4) != 0;
bool fts = fts3 || fts4;
var @virtual = fts ? "virtual " : string.Empty;
var @using = fts3 ? "using fts3 " : fts4 ? "using fts4 " : string.Empty;
// Build query.
var query = "create " + @virtual + "table if not exists \"" + map.TableName + "\" " + @using + "(\n";
var decls = map.Columns.Select (p => Orm.SqlDecl (p, StoreDateTimeAsTicks, StoreTimeSpanAsTicks));
var decl = string.Join (",\n", decls.ToArray ());
query += decl;
query += ")";
if (map.WithoutRowId) {
query += " without rowid";
}
Execute (query);
}
else {
result = CreateTableResult.Migrated;
MigrateTable (map, existingCols);
}
var indexes = new Dictionary<string, IndexInfo> ();
foreach (var c in map.Columns) {
foreach (var i in c.Indices) {
var iname = i.Name ?? map.TableName + "_" + c.Name;
IndexInfo iinfo;
if (!indexes.TryGetValue (iname, out iinfo)) {
iinfo = new IndexInfo {
IndexName = iname,
TableName = map.TableName,
Unique = i.Unique,
Columns = new List<IndexedColumn> ()
};
indexes.Add (iname, iinfo);
}
if (i.Unique != iinfo.Unique)
throw new Exception ("All the columns in an index must have the same value for their Unique property");
iinfo.Columns.Add (new IndexedColumn {
Order = i.Order,
ColumnName = c.Name
});
}
}
foreach (var indexName in indexes.Keys) {
var index = indexes[indexName];
var columns = index.Columns.OrderBy (i => i.Order).Select (i => i.ColumnName).ToArray ();
CreateIndex (indexName, index.TableName, columns, index.Unique);
}
return result;
}
/// <summary>
/// Executes a "create table if not exists" on the database for each type. It also
/// creates any specified indexes on the columns of the table. It uses
/// a schema automatically generated from the specified type. You can
/// later access this schema by calling GetMapping.
/// </summary>
/// <returns>
/// Whether the table was created or migrated for each type.
/// </returns>
public CreateTablesResult CreateTables<T, T2> (CreateFlags createFlags = CreateFlags.None)
where T : new()
where T2 : new()
{
return CreateTables (createFlags, typeof (T), typeof (T2));
}
/// <summary>
/// Executes a "create table if not exists" on the database for each type. It also
/// creates any specified indexes on the columns of the table. It uses
/// a schema automatically generated from the specified type. You can
/// later access this schema by calling GetMapping.
/// </summary>
/// <returns>
/// Whether the table was created or migrated for each type.
/// </returns>
public CreateTablesResult CreateTables<T, T2, T3> (CreateFlags createFlags = CreateFlags.None)
where T : new()
where T2 : new()
where T3 : new()
{
return CreateTables (createFlags, typeof (T), typeof (T2), typeof (T3));
}
/// <summary>
/// Executes a "create table if not exists" on the database for each type. It also
/// creates any specified indexes on the columns of the table. It uses
/// a schema automatically generated from the specified type. You can
/// later access this schema by calling GetMapping.
/// </summary>
/// <returns>
/// Whether the table was created or migrated for each type.
/// </returns>
public CreateTablesResult CreateTables<T, T2, T3, T4> (CreateFlags createFlags = CreateFlags.None)
where T : new()
where T2 : new()
where T3 : new()
where T4 : new()
{
return CreateTables (createFlags, typeof (T), typeof (T2), typeof (T3), typeof (T4));
}
/// <summary>
/// Executes a "create table if not exists" on the database for each type. It also
/// creates any specified indexes on the columns of the table. It uses
/// a schema automatically generated from the specified type. You can
/// later access this schema by calling GetMapping.
/// </summary>
/// <returns>
/// Whether the table was created or migrated for each type.
/// </returns>
public CreateTablesResult CreateTables<T, T2, T3, T4, T5> (CreateFlags createFlags = CreateFlags.None)
where T : new()
where T2 : new()
where T3 : new()
where T4 : new()
where T5 : new()
{
return CreateTables (createFlags, typeof (T), typeof (T2), typeof (T3), typeof (T4), typeof (T5));
}
/// <summary>
/// Executes a "create table if not exists" on the database for each type. It also
/// creates any specified indexes on the columns of the table. It uses
/// a schema automatically generated from the specified type. You can
/// later access this schema by calling GetMapping.
/// </summary>
/// <returns>
/// Whether the table was created or migrated for each type.
/// </returns>
public CreateTablesResult CreateTables (CreateFlags createFlags = CreateFlags.None, params Type[] types)
{
var result = new CreateTablesResult ();
foreach (Type type in types) {
var aResult = CreateTable (type, createFlags);
result.Results[type] = aResult;
}
return result;
}
/// <summary>
/// Creates an index for the specified table and columns.
/// </summary>
/// <param name="indexName">Name of the index to create</param>
/// <param name="tableName">Name of the database table</param>
/// <param name="columnNames">An array of column names to index</param>
/// <param name="unique">Whether the index should be unique</param>
/// <returns>Zero on success.</returns>
public int CreateIndex (string indexName, string tableName, string[] columnNames, bool unique = false)
{
const string sqlFormat = "create {2} index if not exists \"{3}\" on \"{0}\"(\"{1}\")";
var sql = String.Format (sqlFormat, tableName, string.Join ("\", \"", columnNames), unique ? "unique" : "", indexName);
return Execute (sql);
}
/// <summary>
/// Creates an index for the specified table and column.
/// </summary>
/// <param name="indexName">Name of the index to create</param>
/// <param name="tableName">Name of the database table</param>
/// <param name="columnName">Name of the column to index</param>
/// <param name="unique">Whether the index should be unique</param>
/// <returns>Zero on success.</returns>
public int CreateIndex (string indexName, string tableName, string columnName, bool unique = false)
{
return CreateIndex (indexName, tableName, new string[] { columnName }, unique);
}
/// <summary>
/// Creates an index for the specified table and column.
/// </summary>
/// <param name="tableName">Name of the database table</param>
/// <param name="columnName">Name of the column to index</param>
/// <param name="unique">Whether the index should be unique</param>
/// <returns>Zero on success.</returns>
public int CreateIndex (string tableName, string columnName, bool unique = false)
{
return CreateIndex (tableName + "_" + columnName, tableName, columnName, unique);
}
/// <summary>
/// Creates an index for the specified table and columns.
/// </summary>
/// <param name="tableName">Name of the database table</param>
/// <param name="columnNames">An array of column names to index</param>
/// <param name="unique">Whether the index should be unique</param>
/// <returns>Zero on success.</returns>
public int CreateIndex (string tableName, string[] columnNames, bool unique = false)
{
return CreateIndex (tableName + "_" + string.Join ("_", columnNames), tableName, columnNames, unique);
}
/// <summary>
/// Creates an index for the specified object property.
/// e.g. CreateIndex<Client>(c => c.Name);
/// </summary>
/// <typeparam name="T">Type to reflect to a database table.</typeparam>
/// <param name="property">Property to index</param>
/// <param name="unique">Whether the index should be unique</param>
/// <returns>Zero on success.</returns>
public int CreateIndex<T> (Expression<Func<T, object>> property, bool unique = false)
{
MemberExpression mx;
if (property.Body.NodeType == ExpressionType.Convert) {
mx = ((UnaryExpression)property.Body).Operand as MemberExpression;
}
else {
mx = (property.Body as MemberExpression);
}
var propertyInfo = mx.Member as PropertyInfo;
if (propertyInfo == null) {
throw new ArgumentException ("The lambda expression 'property' should point to a valid Property");
}
var propName = propertyInfo.Name;
var map = GetMapping<T> ();
var colName = map.FindColumnWithPropertyName (propName).Name;
return CreateIndex (map.TableName, colName, unique);
}
[Preserve (AllMembers = true)]
public class ColumnInfo
{
// public int cid { get; set; }
[Column ("name")]
public string Name { get; set; }
// [Column ("type")]
// public string ColumnType { get; set; }
public int notnull { get; set; }
// public string dflt_value { get; set; }
// public int pk { get; set; }
public override string ToString ()
{
return Name;
}
}
/// <summary>
/// Query the built-in sqlite table_info table for a specific tables columns.
/// </summary>
/// <returns>The columns contains in the table.</returns>
/// <param name="tableName">Table name.</param>
public List<ColumnInfo> GetTableInfo (string tableName)
{
var query = "pragma table_info(\"" + tableName + "\")";
return Query<ColumnInfo> (query);
}
void MigrateTable (TableMapping map, List<ColumnInfo> existingCols)
{
var toBeAdded = new List<TableMapping.Column> ();
foreach (var p in map.Columns) {
var found = false;
foreach (var c in existingCols) {
found = (string.Compare (p.Name, c.Name, StringComparison.OrdinalIgnoreCase) == 0);
if (found)
break;
}
if (!found) {
toBeAdded.Add (p);
}
}
foreach (var p in toBeAdded) {
var addCol = "alter table \"" + map.TableName + "\" add column " + Orm.SqlDecl (p, StoreDateTimeAsTicks, StoreTimeSpanAsTicks);
Execute (addCol);
}
}
/// <summary>
/// Creates a new SQLiteCommand. Can be overridden to provide a sub-class.
/// </summary>
/// <seealso cref="SQLiteCommand.OnInstanceCreated"/>
protected virtual SQLiteCommand NewCommand ()
{
return new SQLiteCommand (this);
}
/// <summary>
/// Creates a new SQLiteCommand given the command text with arguments. Place a '?'
/// in the command text for each of the arguments.
/// </summary>
/// <param name="cmdText">
/// The fully escaped SQL.
/// </param>
/// <param name="ps">
/// Arguments to substitute for the occurences of '?' in the command text.
/// </param>
/// <returns>
/// A <see cref="SQLiteCommand"/>
/// </returns>
public SQLiteCommand CreateCommand (string cmdText, params object[] ps)
{
if (!_open)
throw SQLiteException.New (SQLite3.Result.Error, "Cannot create commands from unopened database");
var cmd = NewCommand ();