forked from softlion/SQLite.Net-PCL2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSQLiteCommand.cs
More file actions
677 lines (623 loc) · 25.1 KB
/
SQLiteCommand.cs
File metadata and controls
677 lines (623 loc) · 25.1 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
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
//
// Copyright (c) 2012 Krueger Systems, Inc.
// Copyright (c) 2013 Oystein Krog (oystein.krog@gmail.com)
// Copyright (c) 2014 Benjamin Mayrargue
// - support for new types: XElement, TimeSpan
// - ExecuteSimpleQuery
// - ExecuteDeferredQuery: support primitive types in T
//
// 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.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Xml.Linq;
namespace SQLite.Net2
{
public class SQLiteCommand
{
private static readonly IntPtr NegativePointer = new IntPtr(-1);
private readonly List<Binding> _bindings;
private readonly SQLiteConnection _conn;
private const string DateTimeFormat = "yyyy-MM-ddTHH:mm:ss.fffffffZ";
readonly SqliteApi sqlite = SqliteApi.Instance;
internal SQLiteCommand(SQLiteConnection conn)
{
_conn = conn;
_bindings = new List<Binding>();
CommandText = "";
}
public string CommandText { get; set; }
public int ExecuteNonQuery()
{
_conn.TraceListener.WriteLine("Executing: {0}", this);
var stmt = Prepare();
try
{
var r = sqlite.Step(stmt);
switch (r)
{
case Result.Done or Result.Row:
{
var rowsAffected = sqlite.Changes(_conn.Handle);
return rowsAffected;
}
case Result.Error:
{
var msg = sqlite.Errmsg16(_conn.Handle);
throw new SQLiteException(r, msg);
}
case Result.Constraint when sqlite.ExtendedErrCode(_conn.Handle) == ExtendedResult.ConstraintNotNull:
throw new NotNullConstraintViolationException(r, sqlite.Errmsg16(_conn.Handle));
default:
throw new SQLiteException(r, r.ToString());
}
}
finally
{
Finalize(stmt);
}
}
public IEnumerable<T> ExecuteDeferredQuery<T>()
{
return ExecuteDeferredQuery<T>(_conn.GetMapping(typeof (T)));
}
public List<T> ExecuteQuery<T>()
{
return ExecuteDeferredQuery<T>(_conn.GetMapping(typeof (T))).ToList();
}
public List<T> ExecuteQuery<T>(TableMapping map)
{
return ExecuteDeferredQuery<T>(map).ToList();
}
/// <summary>
/// Invoked every time an instance is loaded from the database.
/// </summary>
/// <param name='obj'>
/// The newly created object.
/// </param>
/// <remarks>
/// This can be overridden in combination with the <see cref="SQLiteConnection.NewCommand" />
/// method to hook into the life-cycle of objects.
/// Type safety is not possible because MonoTouch does not support virtual generic methods.
/// </remarks>
protected virtual void OnInstanceCreated(object obj)
{
// Can be overridden.
}
public IEnumerable<T> ExecuteSimpleQuery<T>()
{
_conn.TraceListener.WriteLine("Executing simple query: {0}", this);
var stmt = Prepare();
try
{
while (sqlite.Step(stmt) == Result.Row)
{
var colType = sqlite.ColumnType(stmt, 0);
var val = ReadCol(stmt, 0, colType, typeof(T));
yield return (T)val;
}
}
finally
{
sqlite.Finalize(stmt);
}
}
public IEnumerable<T> ExecuteDeferredQuery<T>(TableMapping map)
{
_conn.TraceListener.WriteLine("Executing Query: {0}", this);
var stmt = Prepare();
try
{
var cols = new TableMapping.Column[sqlite.ColumnCount(stmt)];
var type = typeof (T);
var isPrimitiveType = type.GetTypeInfo().IsPrimitive || type == typeof (string);
for (var i = 0; i < cols.Length; i++)
{
if (!isPrimitiveType)
{
var name = sqlite.ColumnName16(stmt, i);
cols[i] = map.FindColumn(name);
}
else
{
cols[i] = map.CreateColumn(type);
}
}
while (sqlite.Step(stmt) == Result.Row)
{
var obj = isPrimitiveType
? null
: _conn.ColumnInformationProvider.TryReadObject(map, sqlite, stmt);
if (obj != null)
{
yield return (T)obj;
}
else
{
obj = isPrimitiveType ? null : _conn.Resolver.CreateObject(map.MappedType);
for (var i = 0; i < cols.Length; i++)
{
ColType colType;
object val;
//Support of primitive types
if (isPrimitiveType)
{
//Assert(cols.Length == 1)
colType = sqlite.ColumnType(stmt, i);
val = ReadCol(stmt, i, colType, cols[i].ColumnType);
yield return (T)Convert.ChangeType(val, type, CultureInfo.CurrentCulture);
break;
}
if (cols[i] == null)
{
continue;
}
colType = sqlite.ColumnType(stmt, i);
val = ReadCol(stmt, i, colType, cols[i].ColumnType);
cols[i].SetValue(obj, val);
}
if (!isPrimitiveType)
{
OnInstanceCreated(obj);
yield return (T)obj;
}
}
}
}
finally
{
sqlite.Finalize(stmt);
}
}
public T ExecuteScalar<T>()
{
_conn.TraceListener.WriteLine("Executing Query: {0}", this);
var val = default(T);
var stmt = Prepare();
try
{
var r = sqlite.Step(stmt);
if (r == Result.Row)
{
var colType = sqlite.ColumnType(stmt, 0);
if (colType != ColType.Null)
{
var clrType = Nullable.GetUnderlyingType(typeof (T)) ?? typeof (T);
val = (T) ReadCol(stmt, 0, colType, clrType);
}
}
else if (r == Result.Done)
{
}
else
{
throw new SQLiteException(r, sqlite.Errmsg16(_conn.Handle));
}
}
finally
{
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);
}
private IDbStatement Prepare()
{
try
{
var stmt = sqlite.Prepare2(_conn.Handle, CommandText);
BindAll(stmt);
return stmt;
}
catch (Exception e)
{
throw new SQLiteException(Result.Error, $"Sqlite prepare failed for sql: {CommandText}", e);
}
}
private void Finalize(IDbStatement stmt)
{
sqlite.Finalize(stmt);
}
private void BindAll(IDbStatement stmt)
{
var nextIdx = 1;
foreach (var b in _bindings)
{
if (b.Name != null)
{
b.Index = sqlite.BindParameterIndex(stmt, b.Name);
}
else
{
b.Index = nextIdx++;
}
BindParameter(sqlite, stmt, b.Index, b.Value, _conn.StoreDateTimeAsTicks, _conn.Serializer);
}
}
internal static void BindParameter(ISQLiteApi isqLite3Api, IDbStatement stmt, int index, object value, bool storeDateTimeAsTicks, IBlobSerializer serializer)
{
if (value == null)
{
isqLite3Api.BindNull(stmt, index);
}
else
{
if (value is int)
{
isqLite3Api.BindInt(stmt, index, (int) value);
}
else if (value is ISerializable<int>)
{
isqLite3Api.BindInt(stmt, index, ((ISerializable<int>) value).Serialize());
}
else if (value is string)
{
isqLite3Api.BindText16(stmt, index, (string) value, -1, NegativePointer);
}
else if (value is ISerializable<string>)
{
isqLite3Api.BindText16(stmt, index, ((ISerializable<string>) value).Serialize(), -1, NegativePointer);
}
else if (value is XElement)
{
isqLite3Api.BindText16(stmt, index, (value as XElement).ToString(SaveOptions.DisableFormatting), -1, NegativePointer);
}
else if (value is byte || value is ushort || value is sbyte || value is short)
{
isqLite3Api.BindInt(stmt, index, Convert.ToInt32(value));
}
else if (value is ISerializable<byte>)
{
isqLite3Api.BindInt(stmt, index, Convert.ToInt32(((ISerializable<byte>) value).Serialize()));
}
else if (value is ISerializable<ushort>)
{
isqLite3Api.BindInt(stmt, index, Convert.ToInt32(((ISerializable<ushort>) value).Serialize()));
}
else if (value is ISerializable<sbyte>)
{
isqLite3Api.BindInt(stmt, index, Convert.ToInt32(((ISerializable<sbyte>) value).Serialize()));
}
else if (value is ISerializable<short>)
{
isqLite3Api.BindInt(stmt, index, Convert.ToInt32(((ISerializable<short>) value).Serialize()));
}
else if (value is bool)
{
isqLite3Api.BindInt(stmt, index, (bool) value ? 1 : 0);
}
else if (value is ISerializable<bool>)
{
isqLite3Api.BindInt(stmt, index, ((ISerializable<bool>) value).Serialize() ? 1 : 0);
}
else if (value is uint || value is long)
{
isqLite3Api.BindInt64(stmt, index, Convert.ToInt64(value));
}
else if (value is ISerializable<uint>)
{
isqLite3Api.BindInt64(stmt, index, Convert.ToInt64(((ISerializable<uint>) value).Serialize()));
}
else if (value is ISerializable<long>)
{
isqLite3Api.BindInt64(stmt, index, Convert.ToInt64(((ISerializable<long>) value).Serialize()));
}
else if (value is float || value is double || value is decimal)
{
isqLite3Api.BindDouble(stmt, index, Convert.ToDouble(value));
}
else if (value is ISerializable<float>)
{
isqLite3Api.BindDouble(stmt, index, Convert.ToDouble(((ISerializable<float>) value).Serialize()));
}
else if (value is ISerializable<double>)
{
isqLite3Api.BindDouble(stmt, index, Convert.ToDouble(((ISerializable<double>) value).Serialize()));
}
else if (value is ISerializable<decimal>)
{
isqLite3Api.BindDouble(stmt, index, Convert.ToDouble(((ISerializable<decimal>) value).Serialize()));
}
else if (value is TimeSpan)
{
isqLite3Api.BindInt64(stmt, index, ((TimeSpan) value).Ticks);
}
else if (value is ISerializable<TimeSpan>)
{
isqLite3Api.BindInt64(stmt, index, ((ISerializable<TimeSpan>) value).Serialize().Ticks);
}
else if (value is DateTime)
{
if (storeDateTimeAsTicks)
{
long ticks = ((DateTime) value).ToUniversalTime().Ticks;
isqLite3Api.BindInt64(stmt, index, ticks);
}
else
{
string val = ((DateTime) value).ToUniversalTime().ToString(DateTimeFormat, CultureInfo.InvariantCulture);
isqLite3Api.BindText16(stmt, index, val, -1, NegativePointer);
}
}
else if (value is DateTimeOffset)
{
isqLite3Api.BindInt64(stmt, index, ((DateTimeOffset) value).UtcTicks);
}
else if (value is ISerializable<DateTime>)
{
if (storeDateTimeAsTicks)
{
long ticks = ((ISerializable<DateTime>) value).Serialize().ToUniversalTime().Ticks;
isqLite3Api.BindInt64(stmt, index, ticks);
}
else
{
string val = ((ISerializable<DateTime>) value).Serialize().ToUniversalTime().ToString(DateTimeFormat, CultureInfo.InvariantCulture);
isqLite3Api.BindText16(stmt, index, val, -1, NegativePointer);
}
}
else if (value.GetType().GetTypeInfo().IsEnum)
{
isqLite3Api.BindInt(stmt, index, Convert.ToInt32(value));
}
else if (value is byte[])
{
isqLite3Api.BindBlob(stmt, index, (byte[]) value, ((byte[]) value).Length, NegativePointer);
}
else if (value is ISerializable<byte[]>)
{
isqLite3Api.BindBlob(stmt, index, ((ISerializable<byte[]>) value).Serialize(), ((ISerializable<byte[]>) value).Serialize().Length,
NegativePointer);
}
else if (value is Guid)
{
isqLite3Api.BindText16(stmt, index, ((Guid) value).ToString(), 72, NegativePointer);
}
else if (value is ISerializable<Guid>)
{
isqLite3Api.BindText16(stmt, index, ((ISerializable<Guid>) value).Serialize().ToString(), 72, NegativePointer);
}
else if (serializer != null && serializer.CanDeserialize(value.GetType()))
{
var bytes = serializer.Serialize(value);
isqLite3Api.BindBlob(stmt, index, bytes, bytes.Length, NegativePointer);
}
else
{
throw new NotSupportedException("Cannot store type: " + value.GetType());
}
}
}
private object ReadCol(IDbStatement stmt, int index, ColType type, Type clrType)
{
var interfaces = clrType.GetTypeInfo().ImplementedInterfaces.ToHashSet();
if (type == ColType.Null)
{
return null;
}
if (clrType == typeof (string))
{
return sqlite.ColumnText16(stmt, index);
}
if (interfaces.Contains(typeof (ISerializable<string>)))
{
var value = sqlite.ColumnText16(stmt, index);
return _conn.Resolver.CreateObject(clrType, new object[] {value});
}
if (clrType == typeof (int))
{
return sqlite.ColumnInt(stmt, index);
}
if (interfaces.Contains(typeof (ISerializable<int>)))
{
var value = sqlite.ColumnInt(stmt, index);
return _conn.Resolver.CreateObject(clrType, new object[] {value});
}
if (clrType == typeof (bool))
{
return sqlite.ColumnInt(stmt, index) == 1;
}
if (interfaces.Contains(typeof (ISerializable<bool>)))
{
var value = sqlite.ColumnInt(stmt, index) == 1;
return _conn.Resolver.CreateObject(clrType, new object[] {value});
}
if (clrType == typeof (double))
{
return sqlite.ColumnDouble(stmt, index);
}
if (interfaces.Contains(typeof (ISerializable<double>)))
{
var value = sqlite.ColumnDouble(stmt, index);
return _conn.Resolver.CreateObject(clrType, new object[] {value});
}
if (clrType == typeof (float))
{
return (float) sqlite.ColumnDouble(stmt, index);
}
if (interfaces.Contains(typeof (ISerializable<float>)))
{
var value = (float) sqlite.ColumnDouble(stmt, index);
return _conn.Resolver.CreateObject(clrType, new object[] {value});
}
if (clrType == typeof (TimeSpan))
{
return new TimeSpan(sqlite.ColumnInt64(stmt, index));
}
if (interfaces.Contains(typeof (ISerializable<TimeSpan>)))
{
var value = new TimeSpan(sqlite.ColumnInt64(stmt, index));
return _conn.Resolver.CreateObject(clrType, new object[] {value});
}
if (clrType == typeof (DateTime))
{
if (_conn.StoreDateTimeAsTicks)
{
return new DateTime(sqlite.ColumnInt64(stmt, index), DateTimeKind.Utc);
}
return DateTime.Parse(sqlite.ColumnText16(stmt, index), CultureInfo.InvariantCulture);
}
if (clrType == typeof (DateTimeOffset))
{
return new DateTimeOffset(sqlite.ColumnInt64(stmt, index), TimeSpan.Zero);
}
if (interfaces.Contains(typeof (ISerializable<DateTime>)))
{
DateTime value;
if (_conn.StoreDateTimeAsTicks)
{
value = new DateTime(sqlite.ColumnInt64(stmt, index), DateTimeKind.Utc);
}
else
{
value = DateTime.Parse(sqlite.ColumnText16(stmt, index), CultureInfo.InvariantCulture);
}
return Activator.CreateInstance(clrType, value);
}
if (clrType.GetTypeInfo().IsEnum)
{
return sqlite.ColumnInt(stmt, index);
}
if (clrType == typeof (long))
{
return sqlite.ColumnInt64(stmt, index);
}
if (interfaces.Contains(typeof (ISerializable<long>)))
{
var value = sqlite.ColumnInt64(stmt, index);
return _conn.Resolver.CreateObject(clrType, new object[] {value});
}
if (clrType == typeof (uint))
{
return (uint) sqlite.ColumnInt64(stmt, index);
}
if (interfaces.Contains(typeof (ISerializable<long>)))
{
var value = (uint) sqlite.ColumnInt64(stmt, index);
return _conn.Resolver.CreateObject(clrType, new object[] {value});
}
if (clrType == typeof (decimal))
{
return (decimal) sqlite.ColumnDouble(stmt, index);
}
if (interfaces.Contains(typeof (ISerializable<decimal>)))
{
var value = (decimal) sqlite.ColumnDouble(stmt, index);
return _conn.Resolver.CreateObject(clrType, new object[] {value});
}
if (clrType == typeof (byte))
{
return (byte) sqlite.ColumnInt(stmt, index);
}
if (interfaces.Contains(typeof (ISerializable<byte>)))
{
var value = (byte) sqlite.ColumnInt(stmt, index);
return _conn.Resolver.CreateObject(clrType, new object[] {value});
}
if (clrType == typeof (ushort))
{
return (ushort) sqlite.ColumnInt(stmt, index);
}
if (interfaces.Contains(typeof (ISerializable<ushort>)))
{
var value = (ushort) sqlite.ColumnInt(stmt, index);
return _conn.Resolver.CreateObject(clrType, new object[] {value});
}
if (clrType == typeof (short))
{
return (short) sqlite.ColumnInt(stmt, index);
}
if (interfaces.Contains(typeof (ISerializable<short>)))
{
var value = (short) sqlite.ColumnInt(stmt, index);
return _conn.Resolver.CreateObject(clrType, new object[] {value});
}
if (clrType == typeof (sbyte))
{
return (sbyte) sqlite.ColumnInt(stmt, index);
}
if (interfaces.Contains(typeof (ISerializable<sbyte>)))
{
var value = (sbyte) sqlite.ColumnInt(stmt, index);
return _conn.Resolver.CreateObject(clrType, new object[] {value});
}
if (clrType == typeof (byte[]))
{
return sqlite.ColumnByteArray(stmt, index).ToArray();
}
if (interfaces.Contains(typeof (ISerializable<byte[]>)))
{
var value = sqlite.ColumnByteArray(stmt, index);
return _conn.Resolver.CreateObject(clrType, new object[] {value.ToArray()});
}
if (clrType == typeof (Guid))
{
return new Guid(sqlite.ColumnText16(stmt, index));
}
if (interfaces.Contains(typeof (ISerializable<Guid>)))
{
var value = new Guid(sqlite.ColumnText16(stmt, index));
return _conn.Resolver.CreateObject(clrType, new object[] {value});
}
if (clrType == typeof(XElement))
{
var text = sqlite.ColumnText16(stmt, index);
return text==null ? null : XElement.Parse(text);
}
if (_conn.Serializer != null && _conn.Serializer.CanDeserialize(clrType))
{
var bytes = sqlite.ColumnByteArray(stmt, index);
return _conn.Serializer.Deserialize(bytes, clrType);
}
throw new NotSupportedException("Don't know how to read " + clrType);
}
private class Binding
{
public string Name { get; set; }
public object Value { get; set; }
public int Index { get; set; }
}
}
}