This repository has been archived by the owner on Jan 2, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
SQLite.cs
1484 lines (1323 loc) · 43.9 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-2010 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.
//
using System;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
namespace SQLite
{
public class SQLiteException : System.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);
}
}
/// <summary>
/// Represents an open connection to a SQLite database.
/// </summary>
public class SQLiteConnection : IDisposable
{
private bool _open;
private TimeSpan _busyTimeout;
private Dictionary<string, TableMapping> _mappings = null;
private Dictionary<string, TableMapping> _tables = null;
private System.Diagnostics.Stopwatch _sw;
private long _elapsedMilliseconds = 0;
public IntPtr Handle { get; private set; }
public string DatabasePath { get; private set; }
public bool TimeExecution { get; set; }
public bool Trace { get; set; }
/// <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>
public SQLiteConnection (string databasePath)
{
DatabasePath = databasePath;
IntPtr handle;
var r = SQLite3.Open (DatabasePath, out handle);
Handle = handle;
if (r != SQLite3.Result.OK) {
throw SQLiteException.New (r, "Could not open database file: " + DatabasePath);
}
_open = true;
BusyTimeout = TimeSpan.FromSeconds (0.1);
}
/// <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 != IntPtr.Zero) {
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 {
if (_tables == null) {
return Enumerable.Empty<TableMapping> ();
} else {
return _tables.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>
/// <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)
{
if (_mappings == null) {
_mappings = new Dictionary<string, TableMapping> ();
}
TableMapping map;
if (!_mappings.TryGetValue (type.FullName, out map)) {
map = new TableMapping (type);
_mappings[type.FullName] = map;
}
return map;
}
/// <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>
/// The number of entries added to the database schema.
/// </returns>
public int CreateTable<T> ()
{
var ty = typeof(T);
if (_tables == null) {
_tables = new Dictionary<string, TableMapping> ();
}
TableMapping map;
if (!_tables.TryGetValue (ty.FullName, out map)) {
map = GetMapping (ty);
_tables.Add (ty.FullName, map);
}
var query = "create table if not exists \"" + map.TableName + "\"(\n";
var decls = map.Columns.Select (p => Orm.SqlDecl (p));
var decl = string.Join (",\n", decls.ToArray ());
query += decl;
query += ")";
var count = Execute (query);
foreach (var p in map.Columns.Where (x => x.IsIndexed)) {
var indexName = map.TableName + "_" + p.Name;
var q = string.Format ("create index if not exists \"{0}\" on \"{1}\"(\"{2}\")", indexName, map.TableName, p.Name);
count += Execute (q);
}
return count;
}
/// <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="args">
/// 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");
} else {
var cmd = new SQLiteCommand (this);
cmd.CommandText = cmdText;
foreach (var o in ps) {
cmd.Bind (o);
}
return cmd;
}
}
/// <summary>
/// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?'
/// in the command text for each of the arguments and then executes that command.
/// Use this method instead of Query when you don't expect rows back. Such cases include
/// INSERTs, UPDATEs, and DELETEs.
/// You can set the Trace or TimeExecution properties of the connection
/// to profile execution.
/// </summary>
/// <param name="query">
/// The fully escaped SQL.
/// </param>
/// <param name="args">
/// Arguments to substitute for the occurences of '?' in the query.
/// </param>
/// <returns>
/// The number of rows modified in the database as a result of this execution.
/// </returns>
public int Execute (string query, params object[] args)
{
var cmd = CreateCommand (query, args);
if (TimeExecution) {
if (_sw == null) {
_sw = new System.Diagnostics.Stopwatch ();
}
_sw.Reset ();
_sw.Start ();
}
int r = cmd.ExecuteNonQuery ();
if (TimeExecution) {
_sw.Stop ();
_elapsedMilliseconds += _sw.ElapsedMilliseconds;
Console.WriteLine ("Finished in {0} ms ({1:0.0} s total)", _sw.ElapsedMilliseconds, _elapsedMilliseconds / 1000.0);
}
return r;
}
/// <summary>
/// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?'
/// in the command text for each of the arguments and then executes that command.
/// It returns each row of the result using the mapping automatically generated for
/// the given type.
/// </summary>
/// <param name="query">
/// The fully escaped SQL.
/// </param>
/// <param name="args">
/// Arguments to substitute for the occurences of '?' in the query.
/// </param>
/// <returns>
/// An enumerable with one result for each row returned by the query.
/// </returns>
public List<T> Query<T> (string query, params object[] args) where T : new()
{
var cmd = CreateCommand (query, args);
return cmd.ExecuteQuery<T> ();
}
/// <summary>
/// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?'
/// in the command text for each of the arguments and then executes that command.
/// It returns each row of the result using the specified mapping. This function is
/// only used by libraries in order to query the database via introspection. It is
/// normally not used.
/// </summary>
/// <param name="map">
/// A <see cref="TableMapping"/> to use to convert the resulting rows
/// into objects.
/// </param>
/// <param name="query">
/// The fully escaped SQL.
/// </param>
/// <param name="args">
/// Arguments to substitute for the occurences of '?' in the query.
/// </param>
/// <returns>
/// An enumerable with one result for each row returned by the query.
/// </returns>
public List<object> Query (TableMapping map, string query, params object[] args)
{
var cmd = CreateCommand (query, args);
return cmd.ExecuteQuery<object> (map);
}
/// <summary>
/// Returns a queryable interface to the table represented by the given type.
/// </summary>
/// <returns>
/// A queryable object that is able to translate Where, OrderBy, and Take
/// queries into native SQL.
/// </returns>
public TableQuery<T> Table<T> () where T : new()
{
return new TableQuery<T> (this);
}
/// <summary>
/// Attempts to retrieve an object with the given primary key from the table
/// associated with the specified type. Use of this method requires that
/// the given type have a designated PrimaryKey (using the PrimaryKeyAttribute).
/// </summary>
/// <param name="pk">
/// The primary key.
/// </param>
/// <returns>
/// The object with the given primary key. Throws a not found exception
/// if the object is not found.
/// </returns>
public T Get<T> (object pk) where T : new()
{
var map = GetMapping (typeof(T));
string query = string.Format ("select * from \"{0}\" where \"{1}\" = ?", map.TableName, map.PK.Name);
return Query<T> (query, pk).First ();
}
/// <summary>
/// Whether <see cref="BeginTransaction"/> has been called and the database is waiting for a <see cref="Commit"/>.
/// </summary>
public bool IsInTransaction { get; private set; }
/// <summary>
/// Begins a new transaction. Call <see cref="Commit"/> to end the transaction.
/// </summary>
public void BeginTransaction ()
{
if (!IsInTransaction) {
Execute ("begin transaction");
IsInTransaction = true;
}
}
/// <summary>
/// Rolls back the transaction that was begun by <see cref="BeginTransaction"/>.
/// </summary>
public void Rollback ()
{
if (IsInTransaction) {
Execute ("rollback");
IsInTransaction = false;
}
}
/// <summary>
/// Commits the transaction that was begun by <see cref="BeginTransaction"/>.
/// </summary>
public void Commit ()
{
if (IsInTransaction) {
Execute ("commit");
IsInTransaction = false;
}
}
/// <summary>
/// Executes <param name="action"> within a transaction and automatically rollsback the transaction
/// if an exception occurs. The exception is rethrown.
/// </summary>
/// <param name="action">
/// The <see cref="Action"/> to perform within a transaction. <param name="action"> can contain any number
/// of operations on the connection but should never call <see cref="BeginTransaction"/>,
/// <see cref="Rollback"/>, or <see cref="Commit"/>.
/// </param>
public void RunInTransaction (Action action)
{
if (IsInTransaction) {
throw new InvalidOperationException ("The connection must not already be in a transaction when RunInTransaction is called");
}
try {
BeginTransaction ();
action ();
Commit ();
} catch (Exception) {
Rollback ();
throw;
}
}
/// <summary>
/// Inserts all specified objects.
/// </summary>
/// <param name="objects">
/// An <see cref="IEnumerable"/> of the objects to insert.
/// </param>
/// <returns>
/// The number of rows added to the table.
/// </returns>
public int InsertAll (System.Collections.IEnumerable objects)
{
BeginTransaction ();
var c = 0;
foreach (var r in objects) {
c += Insert (r);
}
Commit ();
return c;
}
/// <summary>
/// Inserts the given object and retrieves its
/// auto incremented primary key if it has one.
/// </summary>
/// <param name="obj">
/// The object to insert.
/// </param>
/// <returns>
/// The number of rows added to the table.
/// </returns>
public int Insert (object obj)
{
if (obj == null) {
return 0;
}
return Insert (obj, "", obj.GetType ());
}
public int Insert (object obj, Type objType)
{
return Insert (obj, "", objType);
}
public int Insert (object obj, string extra)
{
if (obj == null) {
return 0;
}
return Insert (obj, extra, obj.GetType ());
}
/// <summary>
/// Inserts the given object and retrieves its
/// auto incremented primary key if it has one.
/// </summary>
/// <param name="obj">
/// The object to insert.
/// </param>
/// <param name="extra">
/// Literal SQL code that gets placed into the command. INSERT {extra} INTO ...
/// </param>
/// <returns>
/// The number of rows added to the table.
/// </returns>
public int Insert (object obj, string extra, Type objType)
{
if (obj == null || objType == null) {
return 0;
}
var map = GetMapping (objType);
var cols = map.InsertColumns;
var vals = new object[cols.Length];
for (var i = 0; i < vals.Length; i++) {
vals[i] = cols[i].GetValue (obj);
}
var count = Execute (map.InsertSql (extra), vals);
var id = SQLite3.LastInsertRowid (Handle);
map.SetAutoIncPK (obj, id);
return count;
}
/// <summary>
/// Updates all of the columns of a table using the specified object
/// except for its primary key.
/// The object is required to have a primary key.
/// </summary>
/// <param name="obj">
/// The object to update. It must have a primary key designated using the PrimaryKeyAttribute.
/// </param>
/// <returns>
/// The number of rows updated.
/// </returns>
public int Update (object obj)
{
if (obj == null) {
return 0;
}
return Update (obj, obj.GetType ());
}
public int Update (object obj, Type objType)
{
if (obj == null || objType == null) {
return 0;
}
var map = GetMapping (objType);
var pk = map.PK;
if (pk == null) {
throw new NotSupportedException ("Cannot update " + map.TableName + ": it has no PK");
}
var cols = from p in map.Columns
where p != pk
select p;
var vals = from c in cols
select c.GetValue (obj);
var ps = new List<object> (vals);
ps.Add (pk.GetValue (obj));
var q = string.Format ("update \"{0}\" set {1} where {2} = ? ", map.TableName, string.Join (",", (from c in cols
select "\"" + c.Name + "\" = ? ").ToArray ()), pk.Name);
return Execute (q, ps.ToArray ());
}
/// <summary>
/// Deletes the given object from the database using its primary key.
/// </summary>
/// <param name="obj">
/// The object to delete. It must have a primary key designated using the PrimaryKeyAttribute.
/// </param>
/// <returns>
/// The number of rows deleted.
/// </returns>
public int Delete<T> (T obj)
{
var map = GetMapping (obj.GetType ());
var pk = map.PK;
if (pk == null) {
throw new NotSupportedException ("Cannot delete " + map.TableName + ": it has no PK");
}
var q = string.Format ("delete from \"{0}\" where \"{1}\" = ?", map.TableName, pk.Name);
return Execute (q, pk.GetValue (obj));
}
public void Dispose ()
{
Close ();
}
public void Close ()
{
if (_open && Handle != IntPtr.Zero) {
SQLite3.Close (Handle);
Handle = IntPtr.Zero;
_open = false;
}
}
}
public class PrimaryKeyAttribute : Attribute
{
}
public class AutoIncrementAttribute : Attribute
{
}
public class IndexedAttribute : Attribute
{
}
public class IgnoreAttribute : Attribute
{
}
public class MaxLengthAttribute : Attribute
{
public int Value { get; private set; }
public MaxLengthAttribute (int length)
{
Value = length;
}
}
public class TableMapping
{
public Type MappedType { get; private set; }
public string TableName { get; private set; }
public Column[] Columns { get; private set; }
public Column PK { get; private set; }
Column _autoPk = null;
Column[] _insertColumns = null;
string _insertSql = null;
public TableMapping (Type type)
{
MappedType = type;
TableName = MappedType.Name;
var props = MappedType.GetProperties (BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty);
var cols = new List<Column> ();
foreach (var p in props) {
var ignore = p.GetCustomAttributes (typeof(IgnoreAttribute), true).Length > 0;
if (p.CanWrite && !ignore) {
cols.Add (new PropColumn (p));
}
}
Columns = cols.ToArray ();
foreach (var c in Columns) {
if (c.IsAutoInc && c.IsPK) {
_autoPk = c;
}
if (c.IsPK) {
PK = c;
}
}
}
public void SetAutoIncPK (object obj, long id)
{
if (_autoPk != null) {
_autoPk.SetValue (obj, Convert.ChangeType (id, _autoPk.ColumnType,null));
}
}
public Column[] InsertColumns {
get {
if (_insertColumns == null) {
_insertColumns = Columns.Where (c => !c.IsAutoInc).ToArray ();
}
return _insertColumns;
}
}
public Column FindColumn (string name)
{
var exact = Columns.Where (c => c.Name == name).FirstOrDefault ();
return exact;
}
public string InsertSql (string extra)
{
if (_insertSql == null) {
var cols = InsertColumns;
_insertSql = string.Format ("insert {3} into \"{0}\"({1}) values ({2})", TableName, string.Join (",", (from c in cols
select "\"" + c.Name + "\"").ToArray ()), string.Join (",", (from c in cols
select "?").ToArray ()), extra);
}
return _insertSql;
}
public abstract class Column
{
public string Name { get; protected set; }
public Type ColumnType { get; protected set; }
public bool IsAutoInc { get; protected set; }
public bool IsPK { get; protected set; }
public bool IsIndexed { get; protected set; }
public bool IsNullable { get; protected set; }
public int MaxStringLength { get; protected set; }
public abstract void SetValue (object obj, object val);
public abstract object GetValue (object obj);
}
public class PropColumn : Column
{
PropertyInfo _prop;
public PropColumn (PropertyInfo prop)
{
_prop = prop;
Name = prop.Name;
ColumnType = prop.PropertyType;
IsAutoInc = Orm.IsAutoInc (prop);
IsPK = Orm.IsPK (prop);
IsIndexed = Orm.IsIndexed (prop);
IsNullable = !IsPK;
MaxStringLength = Orm.MaxStringLength (prop);
}
public override void SetValue (object obj, object val)
{
_prop.SetValue (obj, val, null);
}
public override object GetValue (object obj)
{
return _prop.GetValue (obj, null);
}
}
}
public static class Orm
{
public const int DefaultMaxStringLength = 140;
public static string SqlDecl (TableMapping.Column p)
{
string decl = "\"" + p.Name + "\" " + SqlType (p) + " ";
if (p.IsPK) {
decl += "primary key ";
}
if (p.IsAutoInc) {
decl += "autoincrement ";
}
if (!p.IsNullable) {
decl += "not null ";
}
return decl;
}
public static string SqlType (TableMapping.Column p)
{
var clrType = p.ColumnType;
if (clrType == typeof(Boolean) || clrType == typeof(Byte) || clrType == typeof(UInt16) || clrType == typeof(SByte) || clrType == typeof(Int16) || clrType == typeof(Int32)) {
return "integer";
} else if (clrType == typeof(UInt32) || clrType == typeof(Int64)) {
return "bigint";
} else if (clrType == typeof(Single) || clrType == typeof(Double) || clrType == typeof(Decimal)) {
return "float";
} else if (clrType == typeof(String)) {
int len = p.MaxStringLength;
return "varchar(" + len + ")";
} else if (clrType == typeof(DateTime)) {
return "datetime";
} else if (clrType.IsEnum) {
return "integer";
} else {
throw new NotSupportedException ("Don't know about " + clrType);
}
}
public static bool IsPK (MemberInfo p)
{
var attrs = p.GetCustomAttributes (typeof(PrimaryKeyAttribute), true);
return attrs.Length > 0;
}
public static bool IsAutoInc (MemberInfo p)
{
var attrs = p.GetCustomAttributes (typeof(AutoIncrementAttribute), true);
return attrs.Length > 0;
}
public static bool IsIndexed (MemberInfo p)
{
var attrs = p.GetCustomAttributes (typeof(IndexedAttribute), true);
return attrs.Length > 0;
}
public static int MaxStringLength (PropertyInfo p)
{
var attrs = p.GetCustomAttributes (typeof(MaxLengthAttribute), true);
if (attrs.Length > 0) {
return ((MaxLengthAttribute)attrs[0]).Value;
} else {
return DefaultMaxStringLength;
}
}
}
public class SQLiteCommand
{
SQLiteConnection _conn;
private List<Binding> _bindings;
public string CommandText { get; set; }
internal SQLiteCommand (SQLiteConnection conn)
{
_conn = conn;
_bindings = new List<Binding> ();
CommandText = "";
}
public int ExecuteNonQuery ()
{
if (_conn.Trace) {
Console.WriteLine ("Executing: " + this);
}
var r = SQLite3.Result.OK;
var stmt = Prepare ();
r = SQLite3.Step (stmt);
Finalize (stmt);
if (r == SQLite3.Result.Done) {
int rowsAffected = SQLite3.Changes (_conn.Handle);
return rowsAffected;
} else if (r == SQLite3.Result.Error) {
string msg = SQLite3.GetErrmsg (_conn.Handle);
throw SQLiteException.New (r, msg);
} else {
throw SQLiteException.New (r, r.ToString ());
}
}
public List<T> ExecuteQuery<T> () where T : new()
{
return ExecuteQuery<T> (_conn.GetMapping (typeof(T)));
}
class ColRef
{
public SQLite3.ColType ColType;
public TableMapping.Column MappingColumn;
}
public List<T> ExecuteQuery<T> (TableMapping map)
{
if (_conn.Trace) {
Console.WriteLine ("Executing Query: " + this);
}
var r = new List<T> ();
var stmt = Prepare ();
var cols = new ColRef[SQLite3.ColumnCount (stmt)];
for (int i = 0; i < cols.Length; i++) {
var name = Marshal.PtrToStringUni (SQLite3.ColumnName16 (stmt, i));
cols[i] = new ColRef ();
cols[i].MappingColumn = map.FindColumn (name);
}
var first = true;
while (SQLite3.Step (stmt) == SQLite3.Result.Row) {
var obj = Activator.CreateInstance (map.MappedType);
for (int i = 0; i < cols.Length; i++) {
if (cols[i].MappingColumn == null)
continue;
if (first) {
cols[i].ColType = SQLite3.ColumnType (stmt, i);
}
var val = ReadCol (stmt, i, cols[i].ColType, cols[i].MappingColumn.ColumnType);
cols[i].MappingColumn.SetValue (obj, val);
}
first = false;
r.Add ((T)obj);
}
Finalize (stmt);
return r;
}
public T ExecuteScalar<T> ()
{
T val = default(T);
var stmt = Prepare ();
if (SQLite3.Step (stmt) == SQLite3.Result.Row) {
var colType = SQLite3.ColumnType (stmt, 0);
val = (T)ReadCol (stmt, 0, colType, typeof(T));
}
Finalize (stmt);
return val;
}
public void Bind (string name, object val)
{
_bindings.Add (new Binding {
Name = name,
Value = val
});
}
public void Bind (object val)
{
Bind (null, val);
}
public override string ToString ()
{
var parts = new string[1 + _bindings.Count];
parts[0] = CommandText;
var i = 1;
foreach (var b in _bindings) {
parts[i] = string.Format (" {0}: {1}", i - 1, b.Value);
i++;
}
return string.Join (Environment.NewLine, parts);
}
IntPtr Prepare ()
{
var stmt = SQLite3.Prepare2 (_conn.Handle, CommandText);
BindAll (stmt);
return stmt;
}
void Finalize (IntPtr stmt)
{
SQLite3.Finalize (stmt);
}
void BindAll (IntPtr stmt)
{
int nextIdx = 1;
foreach (var b in _bindings) {
if (b.Name != null) {
b.Index = SQLite3.BindParameterIndex (stmt, b.Name);
} else {
b.Index = nextIdx++;
}
}
foreach (var b in _bindings) {
if (b.Value == null) {
SQLite3.BindNull (stmt, b.Index);
} else {
var bty = b.Value.GetType ();
if (b.Value is Int32) {
SQLite3.BindInt (stmt, b.Index, (int)b.Value);
} else if (b.Value is String) {
SQLite3.BindText (stmt, b.Index, (string)b.Value, -1, new IntPtr (-1));
} else if (b.Value is Byte || b.Value is UInt16 || b.Value is SByte || b.Value is Int16) {
SQLite3.BindInt (stmt, b.Index, Convert.ToInt32 (b.Value));
} else if (b.Value is Boolean) {
SQLite3.BindInt (stmt, b.Index, (bool)b.Value ? 1 : 0);
} else if (b.Value is UInt32 || b.Value is Int64) {
SQLite3.BindInt64 (stmt, b.Index, Convert.ToInt64 (b.Value));
} else if (b.Value is Single || b.Value is Double || b.Value is Decimal) {
SQLite3.BindDouble (stmt, b.Index, Convert.ToDouble (b.Value));
} else if (b.Value is DateTime) {
SQLite3.BindText (stmt, b.Index, ((DateTime)b.Value).ToString ("yyyy-MM-dd HH:mm:ss"), -1, new IntPtr (-1));
} else if (bty.IsEnum) {
SQLite3.BindInt (stmt, b.Index, Convert.ToInt32 (b.Value));
}
}
}
}
class Binding
{
public string Name { get; set; }
public object Value { get; set; }
public int Index { get; set; }
}
object ReadCol (IntPtr stmt, int index, SQLite3.ColType type, Type clrType)
{
if (type == SQLite3.ColType.Null) {
return null;
} else {
if (clrType == typeof(String)) {
return SQLite3.ColumnString (stmt, index);
} else if (clrType == typeof(Int32)) {
return (int)SQLite3.ColumnInt (stmt, index);
} else if (clrType == typeof(Boolean)) {
return SQLite3.ColumnInt (stmt, index) == 1;
} else if (clrType == typeof(double)) {
return SQLite3.ColumnDouble (stmt, index);
} else if (clrType == typeof(float)) {
return (float)SQLite3.ColumnDouble (stmt, index);
} else if (clrType == typeof(DateTime)) {
var text = SQLite3.ColumnString (stmt, index);
return DateTime.Parse (text);
} else if (clrType.IsEnum) {
return SQLite3.ColumnInt (stmt, index);
} else if (clrType == typeof(Int64)) {
return SQLite3.ColumnInt64 (stmt, index);
} else if (clrType == typeof(UInt32)) {
return (uint)SQLite3.ColumnInt64 (stmt, index);
} else if (clrType == typeof(decimal)) {
return (decimal)SQLite3.ColumnDouble (stmt, index);
} else if (clrType == typeof(Byte)) {
return (byte)SQLite3.ColumnInt (stmt, index);
} else if (clrType == typeof(UInt16)) {
return (ushort)SQLite3.ColumnInt (stmt, index);
} else if (clrType == typeof(Int16)) {
return (short)SQLite3.ColumnInt (stmt, index);
} else if (clrType == typeof(sbyte)) {
return (sbyte)SQLite3.ColumnInt (stmt, index);
} else {
throw new NotSupportedException ("Don't know how to read " + clrType);
}
}
}
}
public class TableQuery<T> : IEnumerable<T> where T : new()
{
public SQLiteConnection Connection { get; private set; }
public TableMapping Table { get; private set; }
Expression _where;
List<Ordering> _orderBys;
int? _limit;
int? _offset;
class Ordering
{
public string ColumnName { get; set; }
public bool Ascending { get; set; }
}
TableQuery (SQLiteConnection conn, TableMapping table)
{
Connection = conn;
Table = table;
}
public TableQuery (SQLiteConnection conn)
{
Connection = conn;
Table = Connection.GetMapping (typeof(T));
}
public TableQuery<T> Clone ()
{
var q = new TableQuery<T> (Connection, Table);
q._where = _where;
if (_orderBys != null) {
q._orderBys = new List<Ordering> (_orderBys);
}
q._limit = _limit;
q._offset = _offset;
return q;
}
public TableQuery<T> Where (Expression<Func<T, bool>> predExpr)
{
if (predExpr.NodeType == ExpressionType.Lambda) {