-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSQLite3.cs
executable file
·3357 lines (2871 loc) · 108 KB
/
SQLite3.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
/********************************************************
* ADO.NET 2.0 Data Provider for SQLite Version 3.X
* Written by Robert Simpson ([email protected])
*
* Released to the public domain, use at your own risk!
********************************************************/
namespace System.Data.SQLite
{
using System;
using System.Collections.Generic;
#if !NET_COMPACT_20 && (TRACE_CONNECTION || TRACE_STATEMENT)
using System.Diagnostics;
#endif
using System.Globalization;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
/// <summary>
/// This is the method signature for the SQLite core library logging callback
/// function for use with sqlite3_log() and the SQLITE_CONFIG_LOG.
///
/// WARNING: This delegate is used more-or-less directly by native code, do
/// not modify its type signature.
/// </summary>
/// <param name="pUserData">
/// The extra data associated with this message, if any.
/// </param>
/// <param name="errorCode">
/// The error code associated with this message.
/// </param>
/// <param name="pMessage">
/// The message string to be logged.
/// </param>
#if !PLATFORM_COMPACTFRAMEWORK
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
#endif
internal delegate void SQLiteLogCallback(IntPtr pUserData, int errorCode, IntPtr pMessage);
/// <summary>
/// This class implements SQLiteBase completely, and is the guts of the code that interop's SQLite with .NET
/// </summary>
internal class SQLite3 : SQLiteBase
{
private static object syncRoot = new object();
//
// NOTE: This is the public key for the System.Data.SQLite assembly. If you change the
// SNK file, you will need to change this as well.
//
internal const string PublicKey =
"002400000480000094000000060200000024000052534131000400000100010005a288de5687c4e1" +
"b621ddff5d844727418956997f475eb829429e411aff3e93f97b70de698b972640925bdd44280df0" +
"a25a843266973704137cbb0e7441c1fe7cae4e2440ae91ab8cde3933febcb1ac48dd33b40e13c421" +
"d8215c18a4349a436dd499e3c385cc683015f886f6c10bd90115eb2bd61b67750839e3a19941dc9c";
#if !PLATFORM_COMPACTFRAMEWORK
internal const string DesignerVersion = "1.0.104.0";
#endif
/// <summary>
/// The opaque pointer returned to us by the sqlite provider
/// </summary>
protected internal SQLiteConnectionHandle _sql;
protected string _fileName;
protected SQLiteConnectionFlags _flags;
protected bool _usePool;
protected int _poolVersion;
private int _cancelCount;
#if (NET_35 || NET_40 || NET_45 || NET_451 || NET_452 || NET_46 || NET_461 || NET_462) && !PLATFORM_COMPACTFRAMEWORK
private bool _buildingSchema;
#endif
/// <summary>
/// The user-defined functions registered on this connection
/// </summary>
protected Dictionary<SQLiteFunctionAttribute, SQLiteFunction> _functions;
#if INTEROP_VIRTUAL_TABLE
/// <summary>
/// This is the name of the native library file that contains the
/// "vtshim" extension [wrapper].
/// </summary>
protected string _shimExtensionFileName = null;
/// <summary>
/// This is the flag indicate whether the native library file that
/// contains the "vtshim" extension must be dynamically loaded by
/// this class prior to use.
/// </summary>
protected bool? _shimIsLoadNeeded = null;
/// <summary>
/// This is the name of the native entry point for the "vtshim"
/// extension [wrapper].
/// </summary>
protected string _shimExtensionProcName = "sqlite3_vtshim_init";
/// <summary>
/// The modules created using this connection.
/// </summary>
protected Dictionary<string, SQLiteModule> _modules;
#endif
///////////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Constructs the object used to interact with the SQLite core library
/// using the UTF-8 text encoding.
/// </summary>
/// <param name="fmt">
/// The DateTime format to be used when converting string values to a
/// DateTime and binding DateTime parameters.
/// </param>
/// <param name="kind">
/// The <see cref="DateTimeKind" /> to be used when creating DateTime
/// values.
/// </param>
/// <param name="fmtString">
/// The format string to be used when parsing and formatting DateTime
/// values.
/// </param>
/// <param name="db">
/// The native handle to be associated with the database connection.
/// </param>
/// <param name="fileName">
/// The fully qualified file name associated with <paramref name="db "/>.
/// </param>
/// <param name="ownHandle">
/// Non-zero if the newly created object instance will need to dispose
/// of <paramref name="db" /> when it is no longer needed.
/// </param>
internal SQLite3(
SQLiteDateFormats fmt,
DateTimeKind kind,
string fmtString,
IntPtr db,
string fileName,
bool ownHandle
)
: base(fmt, kind, fmtString)
{
if (db != IntPtr.Zero)
{
_sql = new SQLiteConnectionHandle(db, ownHandle);
_fileName = fileName;
SQLiteConnection.OnChanged(null, new ConnectionEventArgs(
SQLiteConnectionEventType.NewCriticalHandle, null,
null, null, null, _sql, fileName, new object[] {
typeof(SQLite3), fmt, kind, fmtString, db, fileName,
ownHandle }));
}
}
///////////////////////////////////////////////////////////////////////////////////////////////
#region IDisposable "Pattern" Members
private bool disposed;
private void CheckDisposed() /* throw */
{
#if THROW_ON_DISPOSED
if (disposed)
throw new ObjectDisposedException(typeof(SQLite3).Name);
#endif
}
///////////////////////////////////////////////////////////////////////////////////////////////
protected override void Dispose(bool disposing)
{
try
{
if (!disposed)
{
//if (disposing)
//{
// ////////////////////////////////////
// // dispose managed resources here...
// ////////////////////////////////////
//}
//////////////////////////////////////
// release unmanaged resources here...
//////////////////////////////////////
#if INTEROP_VIRTUAL_TABLE
DisposeModules();
#endif
Close(false); /* Disposing, cannot throw. */
}
}
finally
{
base.Dispose(disposing);
//
// NOTE: Everything should be fully disposed at this point.
//
disposed = true;
}
}
#endregion
///////////////////////////////////////////////////////////////////////////////////////////////
#if INTEROP_VIRTUAL_TABLE
/// <summary>
/// This method attempts to dispose of all the <see cref="SQLiteModule" /> derived
/// object instances currently associated with the native database connection.
/// </summary>
private void DisposeModules()
{
//
// NOTE: If any modules were created, attempt to dispose of
// them now. This code is designed to avoid throwing
// exceptions unless the Dispose method of the module
// itself throws an exception.
//
if (_modules != null)
{
foreach (KeyValuePair<string, SQLiteModule> pair in _modules)
{
SQLiteModule module = pair.Value;
if (module == null)
continue;
module.Dispose();
}
_modules.Clear();
}
}
#endif
///////////////////////////////////////////////////////////////////////////////////////////////
// It isn't necessary to cleanup any functions we've registered. If the connection
// goes to the pool and is resurrected later, re-registered functions will overwrite the
// previous functions. The SQLiteFunctionCookieHandle will take care of freeing unmanaged
// resources belonging to the previously-registered functions.
internal override void Close(bool canThrow)
{
if (_sql != null)
{
if (!_sql.OwnHandle)
{
_sql = null;
return;
}
bool unbindFunctions = ((_flags & SQLiteConnectionFlags.UnbindFunctionsOnClose)
== SQLiteConnectionFlags.UnbindFunctionsOnClose);
if (_usePool)
{
if (SQLiteBase.ResetConnection(_sql, _sql, canThrow))
{
if (unbindFunctions)
{
if (SQLiteFunction.UnbindAllFunctions(this, _flags, false))
{
#if !NET_COMPACT_20 && TRACE_CONNECTION
Trace.WriteLine(HelperMethods.StringFormat(
CultureInfo.CurrentCulture,
"UnbindFunctions (Pool) Success: {0}",
HandleToString()));
#endif
}
else
{
#if !NET_COMPACT_20 && TRACE_CONNECTION
Trace.WriteLine(HelperMethods.StringFormat(
CultureInfo.CurrentCulture,
"UnbindFunctions (Pool) Failure: {0}",
HandleToString()));
#endif
}
}
#if INTEROP_VIRTUAL_TABLE
DisposeModules();
#endif
SQLiteConnectionPool.Add(_fileName, _sql, _poolVersion);
SQLiteConnection.OnChanged(null, new ConnectionEventArgs(
SQLiteConnectionEventType.ClosedToPool, null, null,
null, null, _sql, _fileName, new object[] {
typeof(SQLite3), canThrow, _fileName, _poolVersion }));
#if !NET_COMPACT_20 && TRACE_CONNECTION
Trace.WriteLine(HelperMethods.StringFormat(
CultureInfo.CurrentCulture,
"Close (Pool) Success: {0}",
HandleToString()));
#endif
}
#if !NET_COMPACT_20 && TRACE_CONNECTION
else
{
Trace.WriteLine(HelperMethods.StringFormat(
CultureInfo.CurrentCulture,
"Close (Pool) Failure: {0}",
HandleToString()));
}
#endif
}
else
{
if (unbindFunctions)
{
if (SQLiteFunction.UnbindAllFunctions(this, _flags, false))
{
#if !NET_COMPACT_20 && TRACE_CONNECTION
Trace.WriteLine(HelperMethods.StringFormat(
CultureInfo.CurrentCulture,
"UnbindFunctions Success: {0}",
HandleToString()));
#endif
}
else
{
#if !NET_COMPACT_20 && TRACE_CONNECTION
Trace.WriteLine(HelperMethods.StringFormat(
CultureInfo.CurrentCulture,
"UnbindFunctions Failure: {0}",
HandleToString()));
#endif
}
}
_sql.Dispose();
}
_sql = null;
}
}
///////////////////////////////////////////////////////////////////////////////////////////////
#if !NET_COMPACT_20 && TRACE_CONNECTION
protected string HandleToString()
{
if (_sql == null)
return "<null>";
return _sql.ToString();
}
#endif
///////////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Returns the number of times the <see cref="Cancel" /> method has been
/// called.
/// </summary>
private int GetCancelCount()
{
return Interlocked.CompareExchange(ref _cancelCount, 0, 0);
}
///////////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// This method determines whether or not a <see cref="SQLiteException" />
/// with a return code of <see cref="SQLiteErrorCode.Interrupt" /> should
/// be thrown after making a call into the SQLite core library.
/// </summary>
/// <returns>
/// Non-zero if a <see cref="SQLiteException" /> to be thrown. This method
/// will only return non-zero if the <see cref="Cancel" /> method was called
/// one or more times during a call into the SQLite core library (e.g. when
/// the sqlite3_prepare*() or sqlite3_step() APIs are used).
/// </returns>
private bool ShouldThrowForCancel()
{
return GetCancelCount() > 0;
}
///////////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Resets the value of the <see cref="_cancelCount" /> field.
/// </summary>
private int ResetCancelCount()
{
return Interlocked.CompareExchange(ref _cancelCount, 0, _cancelCount);
}
///////////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Attempts to interrupt the query currently executing on the associated
/// native database connection.
/// </summary>
internal override void Cancel()
{
try
{
// do nothing.
}
finally /* NOTE: Thread.Abort() protection. */
{
Interlocked.Increment(ref _cancelCount);
UnsafeNativeMethods.sqlite3_interrupt(_sql);
}
}
/// <summary>
/// This function binds a user-defined function to the connection.
/// </summary>
/// <param name="functionAttribute">
/// The <see cref="SQLiteFunctionAttribute"/> object instance containing
/// the metadata for the function to be bound.
/// </param>
/// <param name="function">
/// The <see cref="SQLiteFunction"/> object instance that implements the
/// function to be bound.
/// </param>
/// <param name="flags">
/// The flags associated with the parent connection object.
/// </param>
internal override void BindFunction(
SQLiteFunctionAttribute functionAttribute,
SQLiteFunction function,
SQLiteConnectionFlags flags
)
{
if (functionAttribute == null)
throw new ArgumentNullException("functionAttribute");
if (function == null)
throw new ArgumentNullException("function");
SQLiteFunction.BindFunction(this, functionAttribute, function, flags);
if (_functions == null)
_functions = new Dictionary<SQLiteFunctionAttribute, SQLiteFunction>();
_functions[functionAttribute] = function;
}
/// <summary>
/// This function binds a user-defined function to the connection.
/// </summary>
/// <param name="functionAttribute">
/// The <see cref="SQLiteFunctionAttribute"/> object instance containing
/// the metadata for the function to be unbound.
/// </param>
/// <param name="flags">
/// The flags associated with the parent connection object.
/// </param>
/// <returns>Non-zero if the function was unbound and removed.</returns>
internal override bool UnbindFunction(
SQLiteFunctionAttribute functionAttribute,
SQLiteConnectionFlags flags
)
{
if (functionAttribute == null)
throw new ArgumentNullException("functionAttribute");
if (_functions == null)
return false;
SQLiteFunction function;
if (_functions.TryGetValue(functionAttribute, out function))
{
if (SQLiteFunction.UnbindFunction(
this, functionAttribute, function, flags) &&
_functions.Remove(functionAttribute))
{
return true;
}
}
return false;
}
internal override string Version
{
get
{
return SQLiteVersion;
}
}
internal override int VersionNumber
{
get
{
return SQLiteVersionNumber;
}
}
internal static string DefineConstants
{
get
{
StringBuilder result = new StringBuilder();
IList<string> list = SQLiteDefineConstants.OptionList;
if (list != null)
{
foreach (string element in list)
{
if (element == null)
continue;
if (result.Length > 0)
result.Append(' ');
result.Append(element);
}
}
return result.ToString();
}
}
internal static string SQLiteVersion
{
get
{
return UTF8ToString(UnsafeNativeMethods.sqlite3_libversion(), -1);
}
}
internal static int SQLiteVersionNumber
{
get
{
return UnsafeNativeMethods.sqlite3_libversion_number();
}
}
internal static string SQLiteSourceId
{
get
{
return UTF8ToString(UnsafeNativeMethods.sqlite3_sourceid(), -1);
}
}
internal static string SQLiteCompileOptions
{
get
{
StringBuilder result = new StringBuilder();
int index = 0;
IntPtr zValue = UnsafeNativeMethods.sqlite3_compileoption_get(index++);
while (zValue != IntPtr.Zero)
{
if (result.Length > 0)
result.Append(' ');
result.Append(UTF8ToString(zValue, -1));
zValue = UnsafeNativeMethods.sqlite3_compileoption_get(index++);
}
return result.ToString();
}
}
internal static string InteropVersion
{
get
{
#if !SQLITE_STANDARD
return UTF8ToString(UnsafeNativeMethods.interop_libversion(), -1);
#else
return null;
#endif
}
}
internal static string InteropSourceId
{
get
{
#if !SQLITE_STANDARD
return UTF8ToString(UnsafeNativeMethods.interop_sourceid(), -1);
#else
return null;
#endif
}
}
internal static string InteropCompileOptions
{
get
{
#if !SQLITE_STANDARD
StringBuilder result = new StringBuilder();
int index = 0;
IntPtr zValue = UnsafeNativeMethods.interop_compileoption_get(index++);
while (zValue != IntPtr.Zero)
{
if (result.Length > 0)
result.Append(' ');
result.Append(UTF8ToString(zValue, -1));
zValue = UnsafeNativeMethods.interop_compileoption_get(index++);
}
return result.ToString();
#else
return null;
#endif
}
}
internal override bool AutoCommit
{
get
{
return IsAutocommit(_sql, _sql);
}
}
internal override bool IsReadOnly(
string name
)
{
IntPtr pDbName = IntPtr.Zero;
try
{
if (name != null)
pDbName = SQLiteString.Utf8IntPtrFromString(name);
int result = UnsafeNativeMethods.sqlite3_db_readonly(
_sql, pDbName);
if (result == -1) /* database not found */
{
throw new SQLiteException(HelperMethods.StringFormat(
CultureInfo.CurrentCulture,
"database \"{0}\" not found", name));
}
return result == 0 ? false : true;
}
finally
{
if (pDbName != IntPtr.Zero)
{
SQLiteMemory.Free(pDbName);
pDbName = IntPtr.Zero;
}
}
}
internal override long LastInsertRowId
{
get
{
#if !PLATFORM_COMPACTFRAMEWORK
return UnsafeNativeMethods.sqlite3_last_insert_rowid(_sql);
#elif !SQLITE_STANDARD
long rowId = 0;
UnsafeNativeMethods.sqlite3_last_insert_rowid_interop(_sql, ref rowId);
return rowId;
#else
throw new NotImplementedException();
#endif
}
}
internal override int Changes
{
get
{
#if !SQLITE_STANDARD
return UnsafeNativeMethods.sqlite3_changes_interop(_sql);
#else
return UnsafeNativeMethods.sqlite3_changes(_sql);
#endif
}
}
internal override long MemoryUsed
{
get
{
return StaticMemoryUsed;
}
}
internal static long StaticMemoryUsed
{
get
{
#if !PLATFORM_COMPACTFRAMEWORK
return UnsafeNativeMethods.sqlite3_memory_used();
#elif !SQLITE_STANDARD
long bytes = 0;
UnsafeNativeMethods.sqlite3_memory_used_interop(ref bytes);
return bytes;
#else
throw new NotImplementedException();
#endif
}
}
internal override long MemoryHighwater
{
get
{
return StaticMemoryHighwater;
}
}
internal static long StaticMemoryHighwater
{
get
{
#if !PLATFORM_COMPACTFRAMEWORK
return UnsafeNativeMethods.sqlite3_memory_highwater(0);
#elif !SQLITE_STANDARD
long bytes = 0;
UnsafeNativeMethods.sqlite3_memory_highwater_interop(0, ref bytes);
return bytes;
#else
throw new NotImplementedException();
#endif
}
}
/// <summary>
/// Returns non-zero if the underlying native connection handle is owned
/// by this instance.
/// </summary>
internal override bool OwnHandle
{
get
{
if (_sql == null)
throw new SQLiteException("no connection handle available");
return _sql.OwnHandle;
}
}
/// <summary>
/// Returns the logical list of functions associated with this connection.
/// </summary>
internal override IDictionary<SQLiteFunctionAttribute, SQLiteFunction> Functions
{
get { return _functions; }
}
internal override SQLiteErrorCode SetMemoryStatus(bool value)
{
return StaticSetMemoryStatus(value);
}
internal static SQLiteErrorCode StaticSetMemoryStatus(bool value)
{
SQLiteErrorCode rc = UnsafeNativeMethods.sqlite3_config_int(
SQLiteConfigOpsEnum.SQLITE_CONFIG_MEMSTATUS, value ? 1 : 0);
return rc;
}
/// <summary>
/// Attempts to free as much heap memory as possible for the database connection.
/// </summary>
/// <returns>A standard SQLite return code (i.e. zero for success and non-zero for failure).</returns>
internal override SQLiteErrorCode ReleaseMemory()
{
SQLiteErrorCode rc = UnsafeNativeMethods.sqlite3_db_release_memory(_sql);
return rc;
}
/// <summary>
/// Attempts to free N bytes of heap memory by deallocating non-essential memory
/// allocations held by the database library. Memory used to cache database pages
/// to improve performance is an example of non-essential memory. This is a no-op
/// returning zero if the SQLite core library was not compiled with the compile-time
/// option SQLITE_ENABLE_MEMORY_MANAGEMENT. Optionally, attempts to reset and/or
/// compact the Win32 native heap, if applicable.
/// </summary>
/// <param name="nBytes">
/// The requested number of bytes to free.
/// </param>
/// <param name="reset">
/// Non-zero to attempt a heap reset.
/// </param>
/// <param name="compact">
/// Non-zero to attempt heap compaction.
/// </param>
/// <param name="nFree">
/// The number of bytes actually freed. This value may be zero.
/// </param>
/// <param name="resetOk">
/// This value will be non-zero if the heap reset was successful.
/// </param>
/// <param name="nLargest">
/// The size of the largest committed free block in the heap, in bytes.
/// This value will be zero unless heap compaction is enabled.
/// </param>
/// <returns>
/// A standard SQLite return code (i.e. zero for success and non-zero
/// for failure).
/// </returns>
internal static SQLiteErrorCode StaticReleaseMemory(
int nBytes,
bool reset,
bool compact,
ref int nFree,
ref bool resetOk,
ref uint nLargest
)
{
SQLiteErrorCode rc = SQLiteErrorCode.Ok;
int nFreeLocal = UnsafeNativeMethods.sqlite3_release_memory(nBytes);
uint nLargestLocal = 0;
bool resetOkLocal = false;
#if !DEBUG && WINDOWS // NOTE: Should be "WIN32HEAP && !MEMDEBUG && WINDOWS"
if (HelperMethods.IsWindows())
{
if ((rc == SQLiteErrorCode.Ok) && reset)
{
rc = UnsafeNativeMethods.sqlite3_win32_reset_heap();
if (rc == SQLiteErrorCode.Ok)
resetOkLocal = true;
}
if ((rc == SQLiteErrorCode.Ok) && compact)
rc = UnsafeNativeMethods.sqlite3_win32_compact_heap(ref nLargestLocal);
}
else
#endif
if (reset || compact)
{
rc = SQLiteErrorCode.NotFound;
}
nFree = nFreeLocal;
nLargest = nLargestLocal;
resetOk = resetOkLocal;
return rc;
}
/// <summary>
/// Shutdown the SQLite engine so that it can be restarted with different
/// configuration options. We depend on auto initialization to recover.
/// </summary>
/// <returns>Returns a standard SQLite result code.</returns>
internal override SQLiteErrorCode Shutdown()
{
return StaticShutdown(false);
}
/// <summary>
/// Shutdown the SQLite engine so that it can be restarted with different
/// configuration options. We depend on auto initialization to recover.
/// </summary>
/// <param name="directories">
/// Non-zero to reset the database and temporary directories to their
/// default values, which should be null for both. This parameter has no
/// effect on non-Windows operating systems.
/// </param>
/// <returns>Returns a standard SQLite result code.</returns>
internal static SQLiteErrorCode StaticShutdown(
bool directories
)
{
SQLiteErrorCode rc = SQLiteErrorCode.Ok;
if (directories)
{
#if WINDOWS
if (HelperMethods.IsWindows())
{
if (rc == SQLiteErrorCode.Ok)
rc = UnsafeNativeMethods.sqlite3_win32_set_directory(1, null);
if (rc == SQLiteErrorCode.Ok)
rc = UnsafeNativeMethods.sqlite3_win32_set_directory(2, null);
}
else
#endif
{
#if !NET_COMPACT_20 && TRACE_CONNECTION
Trace.WriteLine(
"Shutdown: Cannot reset directories on this platform.");
#endif
}
}
if (rc == SQLiteErrorCode.Ok)
rc = UnsafeNativeMethods.sqlite3_shutdown();
return rc;
}
/// <summary>
/// Determines if the associated native connection handle is open.
/// </summary>
/// <returns>
/// Non-zero if the associated native connection handle is open.
/// </returns>
internal override bool IsOpen()
{
return (_sql != null) && !_sql.IsInvalid && !_sql.IsClosed;
}
/// <summary>
/// Returns the fully qualified path and file name for the currently open
/// database, if any.
/// </summary>
/// <param name="dbName">
/// The name of the attached database to query.
/// </param>
/// <returns>
/// The fully qualified path and file name for the currently open database,
/// if any.
/// </returns>
internal override string GetFileName(string dbName)
{
if (_sql == null)
return null;
return UTF8ToString(UnsafeNativeMethods.sqlite3_db_filename_bytes(
_sql, ToUTF8(dbName)), -1);
}
internal override void Open(string strFilename, string vfsName, SQLiteConnectionFlags connectionFlags, SQLiteOpenFlagsEnum openFlags, int maxPoolSize, bool usePool)
{
//
// NOTE: If the database connection is currently open, attempt to
// close it now. This must be done because the file name or
// other parameters that may impact the underlying database
// connection may have changed.
//
if (_sql != null) Close(true);
//
// NOTE: If the connection was not closed successfully, throw an
// exception now.
//
if (_sql != null)
throw new SQLiteException("connection handle is still active");
_usePool = usePool;
_fileName = strFilename;
_flags = connectionFlags;
if (usePool)
{
_sql = SQLiteConnectionPool.Remove(strFilename, maxPoolSize, out _poolVersion);
SQLiteConnection.OnChanged(null, new ConnectionEventArgs(
SQLiteConnectionEventType.OpenedFromPool, null, null,
null, null, _sql, strFilename, new object[] {
typeof(SQLite3), strFilename, vfsName, connectionFlags,
openFlags, maxPoolSize, usePool, _poolVersion }));
#if !NET_COMPACT_20 && TRACE_CONNECTION
Trace.WriteLine(HelperMethods.StringFormat(
CultureInfo.CurrentCulture,
"Open (Pool): {0}", HandleToString()));
#endif
}
if (_sql == null)
{
try
{
// do nothing.
}
finally /* NOTE: Thread.Abort() protection. */
{
IntPtr db = IntPtr.Zero;
SQLiteErrorCode n;
#if !SQLITE_STANDARD
int extFuncs = ((connectionFlags & SQLiteConnectionFlags.NoExtensionFunctions) != SQLiteConnectionFlags.NoExtensionFunctions) ? 1 : 0;
if (extFuncs != 0)
{
n = UnsafeNativeMethods.sqlite3_open_interop(ToUTF8(strFilename), ToUTF8(vfsName), openFlags, extFuncs, ref db);
}
else
#endif
{