System.Data.SQLite
Check-in [e7803b3ae7]
Not logged in

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:Add some workarounds to allow the core managed assembly to work on Mono 4.0.
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1: e7803b3ae77e69f9298d1d8fc3ce87c0334b3d07
User & Date: mistachkin 2015-08-12 22:21:25
Context
2015-08-12
22:25
Fix typo in the previous check-in. check-in: ea0c351664 user: mistachkin tags: trunk
22:21
Add some workarounds to allow the core managed assembly to work on Mono 4.0. check-in: e7803b3ae7 user: mistachkin tags: trunk
20:27
Make it easier to build the managed-only binaries for Mono. check-in: eeb5a164be user: mistachkin tags: trunk
Changes
Hide Diffs Unified Diffs Ignore Whitespace Patch

Changes to System.Data.SQLite/LINQ/SQLiteFactory_Linq.cs.

86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
            string typeName = UnsafeNativeMethods.GetSettingValue(
                "TypeName_SQLiteProviderServices", null);

            Version version = this.GetType().Assembly.GetName().Version;

            if (typeName != null)
            {
                typeName = String.Format(
                    CultureInfo.InvariantCulture, typeName, version);
            }
            else
            {
                typeName = String.Format(
                    CultureInfo.InvariantCulture, DefaultTypeName, version);
            }

            Type type = Type.GetType(typeName, false);

            if (type != null)
            {







|




|







86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
            string typeName = UnsafeNativeMethods.GetSettingValue(
                "TypeName_SQLiteProviderServices", null);

            Version version = this.GetType().Assembly.GetName().Version;

            if (typeName != null)
            {
                typeName = UnsafeNativeMethods.StringFormat(
                    CultureInfo.InvariantCulture, typeName, version);
            }
            else
            {
                typeName = UnsafeNativeMethods.StringFormat(
                    CultureInfo.InvariantCulture, DefaultTypeName, version);
            }

            Type type = Type.GetType(typeName, false);

            if (type != null)
            {

Changes to System.Data.SQLite/SQLite3.cs.

244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
...
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
...
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
...
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
....
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
....
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
....
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
....
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462

1463
1464
1465
1466
1467
1468
1469
....
1477
1478
1479
1480
1481
1482
1483
1484

1485
1486
1487
1488
1489
1490
1491
1492
1493

1494
1495
1496
1497
1498
1499
1500
....
1512
1513
1514
1515
1516
1517
1518
1519

1520
1521
1522
1523
1524
1525
1526
....
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
....
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
....
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
....
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
              if (SQLiteBase.ResetConnection(_sql, _sql, canThrow))
              {
                  if (unbindFunctions)
                  {
                      if (SQLiteFunction.UnbindAllFunctions(this, _flags, false))
                      {
#if !NET_COMPACT_20 && TRACE_CONNECTION
                          Trace.WriteLine(String.Format(
                              CultureInfo.CurrentCulture,
                              "UnbindFunctions (Pool) Success: {0}",
                              HandleToString()));
#endif
                      }
                      else
                      {
#if !NET_COMPACT_20 && TRACE_CONNECTION
                          Trace.WriteLine(String.Format(
                              CultureInfo.CurrentCulture,
                              "UnbindFunctions (Pool) Failure: {0}",
                              HandleToString()));
#endif
                      }
                  }

................................................................................

                  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(String.Format(
                      CultureInfo.CurrentCulture,
                      "Close (Pool) Success: {0}",
                      HandleToString()));
#endif
              }
#if !NET_COMPACT_20 && TRACE_CONNECTION
              else
              {
                  Trace.WriteLine(String.Format(
                      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(String.Format(
                          CultureInfo.CurrentCulture,
                          "UnbindFunctions Success: {0}",
                          HandleToString()));
#endif
                  }
                  else
                  {
#if !NET_COMPACT_20 && TRACE_CONNECTION
                      Trace.WriteLine(String.Format(
                          CultureInfo.CurrentCulture,
                          "UnbindFunctions Failure: {0}",
                          HandleToString()));
#endif
                  }
              }

................................................................................
        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(String.Format(
            CultureInfo.CurrentCulture,
            "Open (Pool): {0}", HandleToString()));
#endif
      }

      if (_sql == null)
      {
................................................................................
          else
#endif
          {
            n = UnsafeNativeMethods.sqlite3_open_v2(ToUTF8(strFilename), ref db, openFlags, ToUTF8(vfsName));
          }

#if !NET_COMPACT_20 && TRACE_CONNECTION
          Trace.WriteLine(String.Format(
              CultureInfo.CurrentCulture,
              "Open: {0}", db));
#endif

          if (n != SQLiteErrorCode.Ok) throw new SQLiteException(n, null);
          _sql = new SQLiteConnectionHandle(db, true);
        }
................................................................................
        //       data classes.
        //
        string baseSchemaName = (cnn != null) ? cnn._baseSchemaName : null;

        if (!String.IsNullOrEmpty(baseSchemaName))
        {
          strSql = strSql.Replace(
              String.Format(CultureInfo.InvariantCulture,
              "[{0}].", baseSchemaName), String.Empty);

          strSql = strSql.Replace(
              String.Format(CultureInfo.InvariantCulture,
              "{0}.", baseSchemaName), String.Empty);
        }
      }

      SQLiteConnectionFlags flags =
          (cnn != null) ? cnn.Flags : SQLiteConnectionFlags.Default;

................................................................................
          ForceLogPrepare() ||
#endif
          ((flags & SQLiteConnectionFlags.LogPrepare) == SQLiteConnectionFlags.LogPrepare))
      {
          if ((strSql == null) || (strSql.Length == 0) || (strSql.Trim().Length == 0))
              SQLiteLog.LogMessage("Preparing {<nothing>}...");
          else
              SQLiteLog.LogMessage(String.Format(
                  CultureInfo.CurrentCulture, "Preparing {{{0}}}...", strSql));
      }

      IntPtr stmt = IntPtr.Zero;
      IntPtr ptr = IntPtr.Zero;
      int len = 0;
      SQLiteErrorCode n = SQLiteErrorCode.Schema;
................................................................................
#else
            n = UnsafeNativeMethods.sqlite3_prepare(_sql, psql, b.Length - 1, ref stmt, ref ptr);
#endif
            len = -1;
#endif

#if !NET_COMPACT_20 && TRACE_STATEMENT
            Trace.WriteLine(String.Format(
                CultureInfo.CurrentCulture,
                "Prepare ({0}): {1}", n, stmt));
#endif

            if ((n == SQLiteErrorCode.Ok) && (stmt != IntPtr.Zero))
            {
              if (statementHandle != null) statementHandle.Dispose();
................................................................................
      }
    }

    protected static void LogBind(SQLiteStatementHandle handle, int index)
    {
        IntPtr handleIntPtr = handle;

        SQLiteLog.LogMessage(String.Format(
            CultureInfo.CurrentCulture,
            "Binding statement {0} paramter #{1} as NULL...",
            handleIntPtr, index));
    }

    protected static void LogBind(SQLiteStatementHandle handle, int index, ValueType value)
    {
        IntPtr handleIntPtr = handle;

        SQLiteLog.LogMessage(String.Format(

            "Binding statement {0} paramter #{1} as type {2} with value {{{3}}}...",
            handleIntPtr, index, value.GetType(), value));
    }

    private static string FormatDateTime(DateTime value)
    {
        StringBuilder result = new StringBuilder();
................................................................................
        return result.ToString();
    }

    protected static void LogBind(SQLiteStatementHandle handle, int index, DateTime value)
    {
        IntPtr handleIntPtr = handle;

        SQLiteLog.LogMessage(String.Format(

            "Binding statement {0} paramter #{1} as type {2} with value {{{3}}}...",
            handleIntPtr, index, typeof(DateTime), FormatDateTime(value)));
    }

    protected static void LogBind(SQLiteStatementHandle handle, int index, string value)
    {
        IntPtr handleIntPtr = handle;

        SQLiteLog.LogMessage(String.Format(

            "Binding statement {0} paramter #{1} as type {2} with value {{{3}}}...",
            handleIntPtr, index, typeof(String), (value != null) ? value : "<null>"));
    }

    private static string ToHexadecimalString(
        byte[] array
        )
................................................................................
        return result.ToString();
    }

    protected static void LogBind(SQLiteStatementHandle handle, int index, byte[] value)
    {
        IntPtr handleIntPtr = handle;

        SQLiteLog.LogMessage(String.Format(

            "Binding statement {0} paramter #{1} as type {2} with value {{{3}}}...",
            handleIntPtr, index, typeof(Byte[]), (value != null) ? ToHexadecimalString(value) : "<null>"));
    }

    internal override void Bind_Double(SQLiteStatement stmt, SQLiteConnectionFlags flags, int index, double value)
    {
        SQLiteStatementHandle handle = stmt._sqlite_stmt;
................................................................................
        SQLiteStatementHandle handle = stmt._sqlite_stmt;
        int value = UnsafeNativeMethods.sqlite3_bind_parameter_count(handle);

        if ((flags & SQLiteConnectionFlags.LogBind) == SQLiteConnectionFlags.LogBind)
        {
            IntPtr handleIntPtr = handle;

            SQLiteLog.LogMessage(String.Format(
                CultureInfo.CurrentCulture,
                "Statement {0} paramter count is {1}.",
                handleIntPtr, value));
        }

        return value;
    }
................................................................................
        name = UTF8ToString(UnsafeNativeMethods.sqlite3_bind_parameter_name(handle, index), -1);
#endif

        if ((flags & SQLiteConnectionFlags.LogBind) == SQLiteConnectionFlags.LogBind)
        {
            IntPtr handleIntPtr = handle;

            SQLiteLog.LogMessage(String.Format(
                CultureInfo.CurrentCulture,
                "Statement {0} paramter #{1} name is {{{2}}}.",
                handleIntPtr, index, name));
        }

        return name;
    }
................................................................................
        SQLiteStatementHandle handle = stmt._sqlite_stmt;
        int index = UnsafeNativeMethods.sqlite3_bind_parameter_index(handle, ToUTF8(paramName));

        if ((flags & SQLiteConnectionFlags.LogBind) == SQLiteConnectionFlags.LogBind)
        {
            IntPtr handleIntPtr = handle;

            SQLiteLog.LogMessage(String.Format(
                CultureInfo.CurrentCulture,
                "Statement {0} paramter index of name {{{1}}} is #{2}.",
                handleIntPtr, paramName, index));
        }

        return index;
    }
................................................................................
            _modules.Add(module.Name, module);

            if (_usePool)
            {
                _usePool = false;

#if !NET_COMPACT_20 && TRACE_CONNECTION
                Trace.WriteLine(String.Format(
                    CultureInfo.CurrentCulture,
                    "CreateModule (Pool) Disabled: {0}",
                    HandleToString()));
#endif
            }
        }
        else







|








|







 







|








|













|








|







 







|







 







|







 







|



|







 







|







 







|







 







|









|
>







 







|
>








|
>







 







|
>







 







|







 







|







 







|







 







|







244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
...
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
...
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
...
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
....
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
....
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
....
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
....
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
....
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
....
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
....
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
....
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
....
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
....
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
              if (SQLiteBase.ResetConnection(_sql, _sql, canThrow))
              {
                  if (unbindFunctions)
                  {
                      if (SQLiteFunction.UnbindAllFunctions(this, _flags, false))
                      {
#if !NET_COMPACT_20 && TRACE_CONNECTION
                          Trace.WriteLine(UnsafeNativeMethods.StringFormat(
                              CultureInfo.CurrentCulture,
                              "UnbindFunctions (Pool) Success: {0}",
                              HandleToString()));
#endif
                      }
                      else
                      {
#if !NET_COMPACT_20 && TRACE_CONNECTION
                          Trace.WriteLine(UnsafeNativeMethods.StringFormat(
                              CultureInfo.CurrentCulture,
                              "UnbindFunctions (Pool) Failure: {0}",
                              HandleToString()));
#endif
                      }
                  }

................................................................................

                  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(UnsafeNativeMethods.StringFormat(
                      CultureInfo.CurrentCulture,
                      "Close (Pool) Success: {0}",
                      HandleToString()));
#endif
              }
#if !NET_COMPACT_20 && TRACE_CONNECTION
              else
              {
                  Trace.WriteLine(UnsafeNativeMethods.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(UnsafeNativeMethods.StringFormat(
                          CultureInfo.CurrentCulture,
                          "UnbindFunctions Success: {0}",
                          HandleToString()));
#endif
                  }
                  else
                  {
#if !NET_COMPACT_20 && TRACE_CONNECTION
                      Trace.WriteLine(UnsafeNativeMethods.StringFormat(
                          CultureInfo.CurrentCulture,
                          "UnbindFunctions Failure: {0}",
                          HandleToString()));
#endif
                  }
              }

................................................................................
        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(UnsafeNativeMethods.StringFormat(
            CultureInfo.CurrentCulture,
            "Open (Pool): {0}", HandleToString()));
#endif
      }

      if (_sql == null)
      {
................................................................................
          else
#endif
          {
            n = UnsafeNativeMethods.sqlite3_open_v2(ToUTF8(strFilename), ref db, openFlags, ToUTF8(vfsName));
          }

#if !NET_COMPACT_20 && TRACE_CONNECTION
          Trace.WriteLine(UnsafeNativeMethods.StringFormat(
              CultureInfo.CurrentCulture,
              "Open: {0}", db));
#endif

          if (n != SQLiteErrorCode.Ok) throw new SQLiteException(n, null);
          _sql = new SQLiteConnectionHandle(db, true);
        }
................................................................................
        //       data classes.
        //
        string baseSchemaName = (cnn != null) ? cnn._baseSchemaName : null;

        if (!String.IsNullOrEmpty(baseSchemaName))
        {
          strSql = strSql.Replace(
              UnsafeNativeMethods.StringFormat(CultureInfo.InvariantCulture,
              "[{0}].", baseSchemaName), String.Empty);

          strSql = strSql.Replace(
              UnsafeNativeMethods.StringFormat(CultureInfo.InvariantCulture,
              "{0}.", baseSchemaName), String.Empty);
        }
      }

      SQLiteConnectionFlags flags =
          (cnn != null) ? cnn.Flags : SQLiteConnectionFlags.Default;

................................................................................
          ForceLogPrepare() ||
#endif
          ((flags & SQLiteConnectionFlags.LogPrepare) == SQLiteConnectionFlags.LogPrepare))
      {
          if ((strSql == null) || (strSql.Length == 0) || (strSql.Trim().Length == 0))
              SQLiteLog.LogMessage("Preparing {<nothing>}...");
          else
              SQLiteLog.LogMessage(UnsafeNativeMethods.StringFormat(
                  CultureInfo.CurrentCulture, "Preparing {{{0}}}...", strSql));
      }

      IntPtr stmt = IntPtr.Zero;
      IntPtr ptr = IntPtr.Zero;
      int len = 0;
      SQLiteErrorCode n = SQLiteErrorCode.Schema;
................................................................................
#else
            n = UnsafeNativeMethods.sqlite3_prepare(_sql, psql, b.Length - 1, ref stmt, ref ptr);
#endif
            len = -1;
#endif

#if !NET_COMPACT_20 && TRACE_STATEMENT
            Trace.WriteLine(UnsafeNativeMethods.StringFormat(
                CultureInfo.CurrentCulture,
                "Prepare ({0}): {1}", n, stmt));
#endif

            if ((n == SQLiteErrorCode.Ok) && (stmt != IntPtr.Zero))
            {
              if (statementHandle != null) statementHandle.Dispose();
................................................................................
      }
    }

    protected static void LogBind(SQLiteStatementHandle handle, int index)
    {
        IntPtr handleIntPtr = handle;

        SQLiteLog.LogMessage(UnsafeNativeMethods.StringFormat(
            CultureInfo.CurrentCulture,
            "Binding statement {0} paramter #{1} as NULL...",
            handleIntPtr, index));
    }

    protected static void LogBind(SQLiteStatementHandle handle, int index, ValueType value)
    {
        IntPtr handleIntPtr = handle;

        SQLiteLog.LogMessage(UnsafeNativeMethods.StringFormat(
            CultureInfo.CurrentCulture,
            "Binding statement {0} paramter #{1} as type {2} with value {{{3}}}...",
            handleIntPtr, index, value.GetType(), value));
    }

    private static string FormatDateTime(DateTime value)
    {
        StringBuilder result = new StringBuilder();
................................................................................
        return result.ToString();
    }

    protected static void LogBind(SQLiteStatementHandle handle, int index, DateTime value)
    {
        IntPtr handleIntPtr = handle;

        SQLiteLog.LogMessage(UnsafeNativeMethods.StringFormat(
            CultureInfo.CurrentCulture,
            "Binding statement {0} paramter #{1} as type {2} with value {{{3}}}...",
            handleIntPtr, index, typeof(DateTime), FormatDateTime(value)));
    }

    protected static void LogBind(SQLiteStatementHandle handle, int index, string value)
    {
        IntPtr handleIntPtr = handle;

        SQLiteLog.LogMessage(UnsafeNativeMethods.StringFormat(
            CultureInfo.CurrentCulture,
            "Binding statement {0} paramter #{1} as type {2} with value {{{3}}}...",
            handleIntPtr, index, typeof(String), (value != null) ? value : "<null>"));
    }

    private static string ToHexadecimalString(
        byte[] array
        )
................................................................................
        return result.ToString();
    }

    protected static void LogBind(SQLiteStatementHandle handle, int index, byte[] value)
    {
        IntPtr handleIntPtr = handle;

        SQLiteLog.LogMessage(UnsafeNativeMethods.StringFormat(
            CultureInfo.CurrentCulture,
            "Binding statement {0} paramter #{1} as type {2} with value {{{3}}}...",
            handleIntPtr, index, typeof(Byte[]), (value != null) ? ToHexadecimalString(value) : "<null>"));
    }

    internal override void Bind_Double(SQLiteStatement stmt, SQLiteConnectionFlags flags, int index, double value)
    {
        SQLiteStatementHandle handle = stmt._sqlite_stmt;
................................................................................
        SQLiteStatementHandle handle = stmt._sqlite_stmt;
        int value = UnsafeNativeMethods.sqlite3_bind_parameter_count(handle);

        if ((flags & SQLiteConnectionFlags.LogBind) == SQLiteConnectionFlags.LogBind)
        {
            IntPtr handleIntPtr = handle;

            SQLiteLog.LogMessage(UnsafeNativeMethods.StringFormat(
                CultureInfo.CurrentCulture,
                "Statement {0} paramter count is {1}.",
                handleIntPtr, value));
        }

        return value;
    }
................................................................................
        name = UTF8ToString(UnsafeNativeMethods.sqlite3_bind_parameter_name(handle, index), -1);
#endif

        if ((flags & SQLiteConnectionFlags.LogBind) == SQLiteConnectionFlags.LogBind)
        {
            IntPtr handleIntPtr = handle;

            SQLiteLog.LogMessage(UnsafeNativeMethods.StringFormat(
                CultureInfo.CurrentCulture,
                "Statement {0} paramter #{1} name is {{{2}}}.",
                handleIntPtr, index, name));
        }

        return name;
    }
................................................................................
        SQLiteStatementHandle handle = stmt._sqlite_stmt;
        int index = UnsafeNativeMethods.sqlite3_bind_parameter_index(handle, ToUTF8(paramName));

        if ((flags & SQLiteConnectionFlags.LogBind) == SQLiteConnectionFlags.LogBind)
        {
            IntPtr handleIntPtr = handle;

            SQLiteLog.LogMessage(UnsafeNativeMethods.StringFormat(
                CultureInfo.CurrentCulture,
                "Statement {0} paramter index of name {{{1}}} is #{2}.",
                handleIntPtr, paramName, index));
        }

        return index;
    }
................................................................................
            _modules.Add(module.Name, module);

            if (_usePool)
            {
                _usePool = false;

#if !NET_COMPACT_20 && TRACE_CONNECTION
                Trace.WriteLine(UnsafeNativeMethods.StringFormat(
                    CultureInfo.CurrentCulture,
                    "CreateModule (Pool) Disabled: {0}",
                    HandleToString()));
#endif
            }
        }
        else

Changes to System.Data.SQLite/SQLite3_UTF16.cs.

8
9
10
11
12
13
14
15
16
17

18
19

20
21
22
23
24
25
26
...
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
...
197
198
199
200
201
202
203
204

205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
namespace System.Data.SQLite
{
  using System;
  using System.Collections.Generic;

#if !NET_COMPACT_20 && TRACE_CONNECTION
  using System.Diagnostics;
  using System.Globalization;
#endif


  using System.IO;
  using System.Runtime.InteropServices;


  /// <summary>
  /// Alternate SQLite3 object, overriding many text behaviors to support UTF-16 (Unicode)
  /// </summary>
  internal sealed class SQLite3_UTF16 : SQLite3
  {
    /// <summary>
................................................................................
            SQLiteConnectionEventType.OpenedFromPool, null, null,
            null, null, _sql, strFilename, new object[] {
            typeof(SQLite3_UTF16), strFilename, vfsName,
            connectionFlags, openFlags, maxPoolSize, usePool,
            _poolVersion }));

#if !NET_COMPACT_20 && TRACE_CONNECTION
        Trace.WriteLine(String.Format(
            CultureInfo.CurrentCulture,
            "Open16 (Pool): {0}",
            HandleToString()));
#endif
      }

      if (_sql == null)
................................................................................
            //       a flags parameter.
            //
            if (((openFlags & SQLiteOpenFlagsEnum.Create) != SQLiteOpenFlagsEnum.Create) && !File.Exists(strFilename))
              throw new SQLiteException(SQLiteErrorCode.CantOpen, strFilename);

            if (vfsName != null)
            {
              throw new SQLiteException(SQLiteErrorCode.CantOpen, String.Format(

                "cannot open using UTF-16 and VFS \"{0}\": need interop assembly", vfsName));
            }

            n = UnsafeNativeMethods.sqlite3_open16(strFilename, ref db);
          }

#if !NET_COMPACT_20 && TRACE_CONNECTION
          Trace.WriteLine(String.Format(
              CultureInfo.CurrentCulture,
              "Open16: {0}", db));
#endif

          if (n != SQLiteErrorCode.Ok) throw new SQLiteException(n, null);
          _sql = new SQLiteConnectionHandle(db, true);
        }







<


>


>







 







|







 







|
>







|







8
9
10
11
12
13
14

15
16
17
18
19
20
21
22
23
24
25
26
27
...
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
...
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
namespace System.Data.SQLite
{
  using System;
  using System.Collections.Generic;

#if !NET_COMPACT_20 && TRACE_CONNECTION
  using System.Diagnostics;

#endif

  using System.Globalization;
  using System.IO;
  using System.Runtime.InteropServices;


  /// <summary>
  /// Alternate SQLite3 object, overriding many text behaviors to support UTF-16 (Unicode)
  /// </summary>
  internal sealed class SQLite3_UTF16 : SQLite3
  {
    /// <summary>
................................................................................
            SQLiteConnectionEventType.OpenedFromPool, null, null,
            null, null, _sql, strFilename, new object[] {
            typeof(SQLite3_UTF16), strFilename, vfsName,
            connectionFlags, openFlags, maxPoolSize, usePool,
            _poolVersion }));

#if !NET_COMPACT_20 && TRACE_CONNECTION
        Trace.WriteLine(UnsafeNativeMethods.StringFormat(
            CultureInfo.CurrentCulture,
            "Open16 (Pool): {0}",
            HandleToString()));
#endif
      }

      if (_sql == null)
................................................................................
            //       a flags parameter.
            //
            if (((openFlags & SQLiteOpenFlagsEnum.Create) != SQLiteOpenFlagsEnum.Create) && !File.Exists(strFilename))
              throw new SQLiteException(SQLiteErrorCode.CantOpen, strFilename);

            if (vfsName != null)
            {
              throw new SQLiteException(SQLiteErrorCode.CantOpen, UnsafeNativeMethods.StringFormat(
                CultureInfo.CurrentCulture,
                "cannot open using UTF-16 and VFS \"{0}\": need interop assembly", vfsName));
            }

            n = UnsafeNativeMethods.sqlite3_open16(strFilename, ref db);
          }

#if !NET_COMPACT_20 && TRACE_CONNECTION
          Trace.WriteLine(UnsafeNativeMethods.StringFormat(
              CultureInfo.CurrentCulture,
              "Open16: {0}", db));
#endif

          if (n != SQLiteErrorCode.Ok) throw new SQLiteException(n, null);
          _sql = new SQLiteConnectionHandle(db, true);
        }

Changes to System.Data.SQLite/SQLiteCommandBuilder.cs.

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
    /// <summary>
    /// Returns a valid named parameter
    /// </summary>
    /// <param name="parameterName">The name of the parameter</param>
    /// <returns>Error</returns>
    protected override string GetParameterName(string parameterName)
    {
      return String.Format(CultureInfo.InvariantCulture, "@{0}", parameterName);
    }

    /// <summary>
    /// Returns a named parameter for the given ordinal
    /// </summary>
    /// <param name="parameterOrdinal">The i of the parameter</param>
    /// <returns>Error</returns>
    protected override string GetParameterName(int parameterOrdinal)
    {
      return String.Format(CultureInfo.InvariantCulture, "@param{0}", parameterOrdinal);
    }

    /// <summary>
    /// Returns a placeholder character for the specified parameter i.
    /// </summary>
    /// <param name="parameterOrdinal">The index of the parameter to provide a placeholder for</param>
    /// <returns>Returns a named parameter</returns>







|









|







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
    /// <summary>
    /// Returns a valid named parameter
    /// </summary>
    /// <param name="parameterName">The name of the parameter</param>
    /// <returns>Error</returns>
    protected override string GetParameterName(string parameterName)
    {
      return UnsafeNativeMethods.StringFormat(CultureInfo.InvariantCulture, "@{0}", parameterName);
    }

    /// <summary>
    /// Returns a named parameter for the given ordinal
    /// </summary>
    /// <param name="parameterOrdinal">The i of the parameter</param>
    /// <returns>Error</returns>
    protected override string GetParameterName(int parameterOrdinal)
    {
      return UnsafeNativeMethods.StringFormat(CultureInfo.InvariantCulture, "@param{0}", parameterOrdinal);
    }

    /// <summary>
    /// Returns a placeholder character for the specified parameter i.
    /// </summary>
    /// <param name="parameterOrdinal">The index of the parameter to provide a placeholder for</param>
    /// <returns>Returns a named parameter</returns>

Changes to System.Data.SQLite/SQLiteConnection.cs.

927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
....
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
....
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
....
2034
2035
2036
2037
2038
2039
2040

2041
2042
2043
2044
2045
2046
2047
2048
....
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
....
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
....
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
....
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
....
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
....
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
....
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
....
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
....
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
....
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
....
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
....
3386
3387
3388
3389
3390
3391
3392


3393
3394
3395
3396
3397
3398
3399
3400
....
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
....
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
....
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
....
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
....
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
....
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
....
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
....
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
....
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
....
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
....
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
....
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
....
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
....
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
....
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
....
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
....
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
....
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
....
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
....
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
....
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
          {
            string str = row[0].ToString();
            if (String.Compare(str, "main", StringComparison.OrdinalIgnoreCase) != 0
              && String.Compare(str, "temp", StringComparison.OrdinalIgnoreCase) != 0)
            {
              using (SQLiteCommand cmd = CreateCommand())
              {
                cmd.CommandText = String.Format(CultureInfo.InvariantCulture, "ATTACH DATABASE '{0}' AS [{1}]", row[1], row[0]);
                cmd.ExecuteNonQuery();
              }
            }
          }
        }
      }
    }
................................................................................
                    break;
            }
        }
        catch (Exception e)
        {
            if ((_flags & SQLiteConnectionFlags.LogBackup) == SQLiteConnectionFlags.LogBackup)
            {
                SQLiteLog.LogMessage(String.Format(
                    CultureInfo.CurrentCulture,
                    "Caught exception while backing up database: {0}", e));
            }

            throw;
        }
        finally
................................................................................
    protected override void Dispose(bool disposing)
    {
#if !NET_COMPACT_20 && TRACE_WARNING
        if ((_flags & SQLiteConnectionFlags.TraceWarning) == SQLiteConnectionFlags.TraceWarning)
        {
            if (_noDispose)
            {
                System.Diagnostics.Trace.WriteLine(String.Format(
                    CultureInfo.CurrentCulture,
                    "WARNING: Disposing of connection \"{0}\" with the no-dispose flag set.",
                    _connectionString));
            }
        }
#endif

................................................................................
      if (UnsafeNativeMethods.GetSettingValue("No_SQLiteConnectionNewParser", null) != null)
          arParts = SQLiteConvert.Split(s, ';');
      else
          arParts = SQLiteConvert.NewSplit(s, ';', true, ref error);

      if (arParts == null)
      {

          throw new ArgumentException(String.Format(CultureInfo.CurrentCulture,
              "Invalid ConnectionString format, cannot parse: {0}", (error != null) ?
              error : "could not split connection string into properties"));
      }

      int x = (arParts != null) ? arParts.Length : 0;
      // For each semi-colon piece, split into key and value pairs by the presence of the = sign
      for (n = 0; n < x; n++)
................................................................................
        int indexOf = arParts[n].IndexOf('=');

        if (indexOf != -1)
          ls.Add(UnwrapString(arParts[n].Substring(0, indexOf).Trim()), UnwrapString(arParts[n].Substring(indexOf + 1).Trim()));
        else if (allowNameOnly)
          ls.Add(UnwrapString(arParts[n].Trim()), String.Empty);
        else
          throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, "Invalid ConnectionString format for part \"{0}\", no equal sign found", arParts[n]));
      }
      return ls;
    }

    /// <summary>
    /// Parses a connection string using the built-in (i.e. framework provided)
    /// connection string parser class and returns the key/value pairs.  An
................................................................................
    public void EnableExtensions(
        bool enable
        )
    {
        CheckDisposed();

        if (_sql == null)
            throw new InvalidOperationException(String.Format(
                CultureInfo.CurrentCulture,
                "Database connection not valid for {0} extensions.",
                enable ? "enabling" : "disabling"));

        if ((_flags & SQLiteConnectionFlags.NoLoadExtension) == SQLiteConnectionFlags.NoLoadExtension)
            throw new SQLiteException("Loading extensions is disabled for this database connection.");

................................................................................

        StringBuilder result = new StringBuilder();

        int length = array.Length;

        for (int index = 0; index < length; index++)
#if NET_COMPACT_20
            result.Append(String.Format("{0:x2}", array[index]));
#else
            result.AppendFormat("{0:x2}", array[index]);
#endif

        return result.ToString();
    }

................................................................................
        for (int index = 0; index < text.Length; index += 2)
        {
            string value = text.Substring(index, 2);

            if (!TryParseByte(value,
                    NumberStyles.HexNumber, out result[index / 2]))
            {
                error = String.Format(
                    CultureInfo.CurrentCulture,
                    "string contains \"{0}\", which cannot be converted to a byte value",
                    value);

                return null;
            }
        }
................................................................................
#if !NET_COMPACT_20 && TRACE_WARNING
      bool uri = false;
#endif
      bool fullUri = false;
      string fileName;

      if (Convert.ToInt32(FindKey(opts, "Version", DefaultVersion.ToString()), CultureInfo.InvariantCulture) != DefaultVersion)
        throw new NotSupportedException(String.Format(CultureInfo.CurrentCulture, "Only SQLite Version {0} is supported at this time", DefaultVersion));

#if INTEROP_INCLUDE_ZIPVFS
      bool useZipVfs = false;
      string zipVfsVersion = FindKey(opts, "ZipVfsVersion", DefaultZipVfsVersion);

      if (zipVfsVersion != null)
      {
................................................................................
          else if (String.Compare(zipVfsVersion, ZipVfs_V3) == 0)
          {
              UnsafeNativeMethods.zipvfsInit_v3(0);
              useZipVfs = true;
          }
          else
          {
              throw new NotSupportedException(String.Format(
                  CultureInfo.CurrentCulture, "Only ZipVFS versions {0}, {1}, and {2} are supported at this time",
                  ZipVfs_Automatic, ZipVfs_V2, ZipVfs_V3));
          }
      }
#endif

      fileName = FindKey(opts, "Data Source", DefaultDataSource);
................................................................................
      if (String.IsNullOrEmpty(fileName))
      {
        fileName = FindKey(opts, "Uri", DefaultUri);
        if (String.IsNullOrEmpty(fileName))
        {
          fileName = FindKey(opts, "FullUri", DefaultFullUri);
          if (String.IsNullOrEmpty(fileName))
            throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, "Data Source cannot be empty.  Use {0} to open an in-memory database", MemoryFileName));
          else
            fullUri = true;
        }
        else
        {
          fileName = MapUriPath(fileName);
#if !NET_COMPACT_20 && TRACE_WARNING
................................................................................
#if !NET_COMPACT_20 && TRACE_WARNING
      if ((_flags & SQLiteConnectionFlags.TraceWarning) == SQLiteConnectionFlags.TraceWarning)
      {
          if (!uri && !fullUri && !isMemory && !String.IsNullOrEmpty(fileName) &&
              fileName.StartsWith("\\", StringComparison.OrdinalIgnoreCase) &&
              !fileName.StartsWith("\\\\", StringComparison.OrdinalIgnoreCase))
          {
              System.Diagnostics.Trace.WriteLine(String.Format(
                  CultureInfo.CurrentCulture,
                  "WARNING: Detected a possibly malformed UNC database file name \"{0}\" that " +
                  "may have originally started with two backslashes; however, four leading " +
                  "backslashes may be required, e.g.: \"Data Source=\\\\\\{0};\"",
                  fileName));
          }
      }
................................................................................
        if (hexPassword != null)
        {
            string error = null;
            byte[] hexPasswordBytes = FromHexString(hexPassword, ref error);

            if (hexPasswordBytes == null)
            {
                throw new FormatException(String.Format(
                    CultureInfo.CurrentCulture,
                    "Cannot parse 'HexPassword' property value into byte values: {0}",
                    error));
            }

            _sql.SetPassword(hexPasswordBytes);
        }
................................................................................

          if (boolValue)
          {
              using (SQLiteCommand cmd = CreateCommand())
              {
                  if (_busyTimeout != DefaultBusyTimeout)
                  {
                      cmd.CommandText = String.Format(CultureInfo.InvariantCulture, "PRAGMA busy_timeout={0}", _busyTimeout);
                      cmd.ExecuteNonQuery();
                  }

                  int intValue;

                  if (!fullUri && !isMemory)
                  {
                      strValue = FindKey(opts, "Page Size", DefaultPageSize.ToString());
                      intValue = Convert.ToInt32(strValue, CultureInfo.InvariantCulture);
                      if (intValue != DefaultPageSize)
                      {
                          cmd.CommandText = String.Format(CultureInfo.InvariantCulture, "PRAGMA page_size={0}", intValue);
                          cmd.ExecuteNonQuery();
                      }
                  }

                  strValue = FindKey(opts, "Max Page Count", DefaultMaxPageCount.ToString());
                  intValue = Convert.ToInt32(strValue, CultureInfo.InvariantCulture);
                  if (intValue != DefaultMaxPageCount)
                  {
                      cmd.CommandText = String.Format(CultureInfo.InvariantCulture, "PRAGMA max_page_count={0}", intValue);
                      cmd.ExecuteNonQuery();
                  }

                  strValue = FindKey(opts, "Legacy Format", DefaultLegacyFormat.ToString());
                  boolValue = SQLiteConvert.ToBoolean(strValue);
                  if (boolValue != DefaultLegacyFormat)
                  {
                      cmd.CommandText = String.Format(CultureInfo.InvariantCulture, "PRAGMA legacy_file_format={0}", boolValue ? "ON" : "OFF");
                      cmd.ExecuteNonQuery();
                  }

                  strValue = FindKey(opts, "Synchronous", DefaultSynchronous.ToString());
                  enumValue = TryParseEnum(typeof(SQLiteSynchronousEnum), strValue, true);
                  if (!(enumValue is SQLiteSynchronousEnum) || ((SQLiteSynchronousEnum)enumValue != DefaultSynchronous))
                  {
                      cmd.CommandText = String.Format(CultureInfo.InvariantCulture, "PRAGMA synchronous={0}", strValue);
                      cmd.ExecuteNonQuery();
                  }

                  strValue = FindKey(opts, "Cache Size", DefaultCacheSize.ToString());
                  intValue = Convert.ToInt32(strValue, CultureInfo.InvariantCulture);
                  if (intValue != DefaultCacheSize)
                  {
                      cmd.CommandText = String.Format(CultureInfo.InvariantCulture, "PRAGMA cache_size={0}", intValue);
                      cmd.ExecuteNonQuery();
                  }

                  strValue = FindKey(opts, "Journal Mode", DefaultJournalMode.ToString());
                  enumValue = TryParseEnum(typeof(SQLiteJournalModeEnum), strValue, true);
                  if (!(enumValue is SQLiteJournalModeEnum) || ((SQLiteJournalModeEnum)enumValue != DefaultJournalMode))
                  {
................................................................................
                      string pragmaStr = "PRAGMA journal_mode={0}";

#if INTEROP_INCLUDE_ZIPVFS
                      if (useZipVfs)
                          pragmaStr = "PRAGMA zipvfs_journal_mode={0}";
#endif

                      cmd.CommandText = String.Format(CultureInfo.InvariantCulture, pragmaStr, strValue);
                      cmd.ExecuteNonQuery();
                  }

                  strValue = FindKey(opts, "Foreign Keys", DefaultForeignKeys.ToString());
                  boolValue = SQLiteConvert.ToBoolean(strValue);
                  if (boolValue != DefaultForeignKeys)
                  {
                      cmd.CommandText = String.Format(CultureInfo.InvariantCulture, "PRAGMA foreign_keys={0}", boolValue ? "ON" : "OFF");
                      cmd.ExecuteNonQuery();
                  }

                  strValue = FindKey(opts, "Recursive Triggers", DefaultRecursiveTriggers.ToString());
                  boolValue = SQLiteConvert.ToBoolean(strValue);
                  if (boolValue != DefaultRecursiveTriggers)
                  {
                      cmd.CommandText = String.Format(CultureInfo.InvariantCulture, "PRAGMA recursive_triggers={0}", boolValue ? "ON" : "OFF");
                      cmd.ExecuteNonQuery();
                  }
              }
          }

          if (_progressHandler != null)
              _sql.SetProgressHook(_progressOps, _progressCallback);
................................................................................
            {
                if (sourceId == null)
                    sourceId = "0000000000000000000000000000000000000000";

                if (sourceTimeStamp == null)
                    sourceTimeStamp = "0000-00-00 00:00:00 UTC";



                return String.Format("{0} {1}", sourceId, sourceTimeStamp);
            }
            else
            {
                return null;
            }
        }
    }
................................................................................
            throw new InvalidOperationException("Database connection not valid for shutdown.");

        _sql.Close(true); /* NOTE: MUST be closed before shutdown. */
        SQLiteErrorCode rc = _sql.Shutdown();

#if !NET_COMPACT_20 && TRACE_CONNECTION
        if (rc != SQLiteErrorCode.Ok)
            System.Diagnostics.Trace.WriteLine(String.Format(
                CultureInfo.CurrentCulture,
                "Shutdown (Instance) Failed: {0}", rc));
#endif

        return rc;
    }

................................................................................
        )
    {
        SQLiteErrorCode rc = SQLite3.StaticShutdown(directories);

        if (rc != SQLiteErrorCode.Ok)
        {
#if !NET_COMPACT_20 && TRACE_CONNECTION
            System.Diagnostics.Trace.WriteLine(String.Format(
                CultureInfo.CurrentCulture,
                "Shutdown (Static) Failed: {0}", rc));
#endif

            if (!noThrow)
                throw new SQLiteException(rc, null);
        }
................................................................................

      tbl.BeginLoadData();

      if (String.IsNullOrEmpty(strCatalog)) strCatalog = "main";

      string master = (String.Compare(strCatalog, "temp", StringComparison.OrdinalIgnoreCase) == 0) ? _tempmasterdb : _masterdb;

      using (SQLiteCommand cmdTables = new SQLiteCommand(String.Format(CultureInfo.InvariantCulture, "SELECT * FROM [{0}].[{1}] WHERE [type] LIKE 'table' OR [type] LIKE 'view'", strCatalog, master), this))
      using (SQLiteDataReader rdTables = cmdTables.ExecuteReader())
      {
        while (rdTables.Read())
        {
          if (String.IsNullOrEmpty(strTable) || String.Compare(strTable, rdTables.GetString(2), StringComparison.OrdinalIgnoreCase) == 0)
          {
            try
            {
              using (SQLiteCommand cmd = new SQLiteCommand(String.Format(CultureInfo.InvariantCulture, "SELECT * FROM [{0}].[{1}]", strCatalog, rdTables.GetString(2)), this))
              using (SQLiteDataReader rd = (SQLiteDataReader)cmd.ExecuteReader(CommandBehavior.SchemaOnly))
              using (DataTable tblSchema = rd.GetSchemaTable(true, true))
              {
                foreach (DataRow schemaRow in tblSchema.Rows)
                {
                  if (String.Compare(schemaRow[SchemaTableColumn.ColumnName].ToString(), strColumn, StringComparison.OrdinalIgnoreCase) == 0
                    || strColumn == null)
................................................................................

      tbl.BeginLoadData();

      if (String.IsNullOrEmpty(strCatalog)) strCatalog = "main";

      string master = (String.Compare(strCatalog, "temp", StringComparison.OrdinalIgnoreCase) == 0) ? _tempmasterdb : _masterdb;

      using (SQLiteCommand cmdTables = new SQLiteCommand(String.Format(CultureInfo.InvariantCulture, "SELECT * FROM [{0}].[{1}] WHERE [type] LIKE 'table'", strCatalog, master), this))
      using (SQLiteDataReader rdTables = cmdTables.ExecuteReader())
      {
        while (rdTables.Read())
        {
          maybeRowId = false;
          primaryKeys.Clear();
          if (String.IsNullOrEmpty(strTable) || String.Compare(rdTables.GetString(2), strTable, StringComparison.OrdinalIgnoreCase) == 0)
          {
            // First, look for any rowid indexes -- which sqlite defines are INTEGER PRIMARY KEY columns.
            // Such indexes are not listed in the indexes list but count as indexes just the same.
            try
            {
              using (SQLiteCommand cmdTable = new SQLiteCommand(String.Format(CultureInfo.InvariantCulture, "PRAGMA [{0}].table_info([{1}])", strCatalog, rdTables.GetString(2)), this))
              using (SQLiteDataReader rdTable = cmdTable.ExecuteReader())
              {
                while (rdTable.Read())
                {
                  if (rdTable.GetInt32(5) != 0)
                  {
                    primaryKeys.Add(rdTable.GetInt32(0));
................................................................................
            {
              row = tbl.NewRow();

              row["TABLE_CATALOG"] = strCatalog;
              row["TABLE_NAME"] = rdTables.GetString(2);
              row["INDEX_CATALOG"] = strCatalog;
              row["PRIMARY_KEY"] = true;
              row["INDEX_NAME"] = String.Format(CultureInfo.InvariantCulture, "{1}_PK_{0}", rdTables.GetString(2), master);
              row["UNIQUE"] = true;

              if (String.Compare((string)row["INDEX_NAME"], strIndex, StringComparison.OrdinalIgnoreCase) == 0
              || strIndex == null)
              {
                tbl.Rows.Add(row);
              }
................................................................................

              primaryKeys.Clear();
            }

            // Now fetch all the rest of the indexes.
            try
            {
              using (SQLiteCommand cmd = new SQLiteCommand(String.Format(CultureInfo.InvariantCulture, "PRAGMA [{0}].index_list([{1}])", strCatalog, rdTables.GetString(2)), this))
              using (SQLiteDataReader rd = (SQLiteDataReader)cmd.ExecuteReader())
              {
                while (rd.Read())
                {
                  if (String.Compare(rd.GetString(1), strIndex, StringComparison.OrdinalIgnoreCase) == 0
                  || strIndex == null)
                  {
................................................................................
                    row["TABLE_NAME"] = rdTables.GetString(2);
                    row["INDEX_CATALOG"] = strCatalog;
                    row["INDEX_NAME"] = rd.GetString(1);
                    row["UNIQUE"] = SQLiteConvert.ToBoolean(rd.GetValue(2), CultureInfo.InvariantCulture, false);
                    row["PRIMARY_KEY"] = false;

                    // get the index definition
                    using (SQLiteCommand cmdIndexes = new SQLiteCommand(String.Format(CultureInfo.InvariantCulture, "SELECT * FROM [{0}].[{2}] WHERE [type] LIKE 'index' AND [name] LIKE '{1}'", strCatalog, rd.GetString(1).Replace("'", "''"), master), this))
                    using (SQLiteDataReader rdIndexes = cmdIndexes.ExecuteReader())
                    {
                      while (rdIndexes.Read())
                      {
                        if (rdIndexes.IsDBNull(4) == false)
                          row["INDEX_DEFINITION"] = rdIndexes.GetString(4);
                        break;
................................................................................
                    }

                    // Now for the really hard work.  Figure out which index is the primary key index.
                    // The only way to figure it out is to check if the index was an autoindex and if we have a non-rowid
                    // primary key, and all the columns in the given index match the primary key columns
                    if (primaryKeys.Count > 0 && rd.GetString(1).StartsWith("sqlite_autoindex_" + rdTables.GetString(2), StringComparison.InvariantCultureIgnoreCase) == true)
                    {
                      using (SQLiteCommand cmdDetails = new SQLiteCommand(String.Format(CultureInfo.InvariantCulture, "PRAGMA [{0}].index_info([{1}])", strCatalog, rd.GetString(1)), this))
                      using (SQLiteDataReader rdDetails = cmdDetails.ExecuteReader())
                      {
                        int nMatches = 0;
                        while (rdDetails.Read())
                        {
                          if (primaryKeys.Contains(rdDetails.GetInt32(1)) == false)
                          {
................................................................................

      tbl.BeginLoadData();

      if (String.IsNullOrEmpty(table)) table = null;
      if (String.IsNullOrEmpty(catalog)) catalog = "main";
      string master = (String.Compare(catalog, "temp", StringComparison.OrdinalIgnoreCase) == 0) ? _tempmasterdb : _masterdb;

      using (SQLiteCommand cmd = new SQLiteCommand(String.Format(CultureInfo.InvariantCulture, "SELECT [type], [name], [tbl_name], [rootpage], [sql], [rowid] FROM [{0}].[{1}] WHERE [type] LIKE 'trigger'", catalog, master), this))
      using (SQLiteDataReader rd = (SQLiteDataReader)cmd.ExecuteReader())
      {
        while (rd.Read())
        {
          if (String.Compare(rd.GetString(1), triggerName, StringComparison.OrdinalIgnoreCase) == 0
            || triggerName == null)
          {
................................................................................
      tbl.Columns.Add("TABLE_DEFINITION", typeof(string));
      tbl.BeginLoadData();

      if (String.IsNullOrEmpty(strCatalog)) strCatalog = "main";

      string master = (String.Compare(strCatalog, "temp", StringComparison.OrdinalIgnoreCase) == 0) ? _tempmasterdb : _masterdb;

      using (SQLiteCommand cmd = new SQLiteCommand(String.Format(CultureInfo.InvariantCulture, "SELECT [type], [name], [tbl_name], [rootpage], [sql], [rowid] FROM [{0}].[{1}] WHERE [type] LIKE 'table'", strCatalog, master), this))
      using (SQLiteDataReader rd = (SQLiteDataReader)cmd.ExecuteReader())
      {
        while (rd.Read())
        {
          strItem = rd.GetString(0);
          if (String.Compare(rd.GetString(2), 0, "SQLITE_", 0, 7, StringComparison.OrdinalIgnoreCase) == 0)
            strItem = "SYSTEM_TABLE";
................................................................................

      tbl.BeginLoadData();

      if (String.IsNullOrEmpty(strCatalog)) strCatalog = "main";

      string master = (String.Compare(strCatalog, "temp", StringComparison.OrdinalIgnoreCase) == 0) ? _tempmasterdb : _masterdb;

      using (SQLiteCommand cmd = new SQLiteCommand(String.Format(CultureInfo.InvariantCulture, "SELECT * FROM [{0}].[{1}] WHERE [type] LIKE 'view'", strCatalog, master), this))
      using (SQLiteDataReader rd = (SQLiteDataReader)cmd.ExecuteReader())
      {
        while (rd.Read())
        {
          if (String.Compare(rd.GetString(1), strView, StringComparison.OrdinalIgnoreCase) == 0
            || String.IsNullOrEmpty(strView))
          {
................................................................................

      if (String.IsNullOrEmpty(strCatalog)) strCatalog = "main";

      string master = (String.Compare(strCatalog, "temp", StringComparison.OrdinalIgnoreCase) == 0) ? _tempmasterdb : _masterdb;

      tbl.BeginLoadData();

      using (SQLiteCommand cmdTables = new SQLiteCommand(String.Format(CultureInfo.InvariantCulture, "SELECT * FROM [{0}].[{1}] WHERE [type] LIKE 'table'", strCatalog, master), this))
      using (SQLiteDataReader rdTables = cmdTables.ExecuteReader())
      {
        while (rdTables.Read())
        {
          maybeRowId = false;
          primaryKeys.Clear();
          if (String.IsNullOrEmpty(strTable) || String.Compare(rdTables.GetString(2), strTable, StringComparison.OrdinalIgnoreCase) == 0)
          {
            try
            {
              using (SQLiteCommand cmdTable = new SQLiteCommand(String.Format(CultureInfo.InvariantCulture, "PRAGMA [{0}].table_info([{1}])", strCatalog, rdTables.GetString(2)), this))
              using (SQLiteDataReader rdTable = cmdTable.ExecuteReader())
              {
                while (rdTable.Read())
                {
                  if (rdTable.GetInt32(5) == 1) // is a primary key
                  {
                    primaryKeys.Add(new KeyValuePair<int, string>(rdTable.GetInt32(0), rdTable.GetString(1)));
................................................................................
            {
            }
            // This is a rowid row
            if (primaryKeys.Count == 1 && maybeRowId == true)
            {
              row = tbl.NewRow();
              row["CONSTRAINT_CATALOG"] = strCatalog;
              row["CONSTRAINT_NAME"] = String.Format(CultureInfo.InvariantCulture, "{1}_PK_{0}", rdTables.GetString(2), master);
              row["TABLE_CATALOG"] = strCatalog;
              row["TABLE_NAME"] = rdTables.GetString(2);
              row["COLUMN_NAME"] = primaryKeys[0].Value;
              row["INDEX_NAME"] = row["CONSTRAINT_NAME"];
              row["ORDINAL_POSITION"] = 0; // primaryKeys[0].Key;
              row["COLLATION_NAME"] = "BINARY";
              row["SORT_MODE"] = "ASC";
              row["CONFLICT_OPTION"] = 2;

              if (String.IsNullOrEmpty(strIndex) || String.Compare(strIndex, (string)row["INDEX_NAME"], StringComparison.OrdinalIgnoreCase) == 0)
                tbl.Rows.Add(row);
            }

            using (SQLiteCommand cmdIndexes = new SQLiteCommand(String.Format(CultureInfo.InvariantCulture, "SELECT * FROM [{0}].[{2}] WHERE [type] LIKE 'index' AND [tbl_name] LIKE '{1}'", strCatalog, rdTables.GetString(2).Replace("'", "''"), master), this))
            using (SQLiteDataReader rdIndexes = cmdIndexes.ExecuteReader())
            {
              while (rdIndexes.Read())
              {
                int ordinal = 0;
                if (String.IsNullOrEmpty(strIndex) || String.Compare(strIndex, rdIndexes.GetString(1), StringComparison.OrdinalIgnoreCase) == 0)
                {
                  try
                  {
                    using (SQLiteCommand cmdIndex = new SQLiteCommand(String.Format(CultureInfo.InvariantCulture, "PRAGMA [{0}].index_info([{1}])", strCatalog, rdIndexes.GetString(1)), this))
                    using (SQLiteDataReader rdIndex = cmdIndex.ExecuteReader())
                    {
                      while (rdIndex.Read())
                      {
                        row = tbl.NewRow();
                        row["CONSTRAINT_CATALOG"] = strCatalog;
                        row["CONSTRAINT_NAME"] = rdIndexes.GetString(1);
................................................................................

      if (String.IsNullOrEmpty(strCatalog)) strCatalog = "main";

      string master = (String.Compare(strCatalog, "temp", StringComparison.OrdinalIgnoreCase) == 0) ? _tempmasterdb : _masterdb;

      tbl.BeginLoadData();

      using (SQLiteCommand cmdViews = new SQLiteCommand(String.Format(CultureInfo.InvariantCulture, "SELECT * FROM [{0}].[{1}] WHERE [type] LIKE 'view'", strCatalog, master), this))
      using (SQLiteDataReader rdViews = cmdViews.ExecuteReader())
      {
        while (rdViews.Read())
        {
          if (String.IsNullOrEmpty(strView) || String.Compare(strView, rdViews.GetString(2), StringComparison.OrdinalIgnoreCase) == 0)
          {
            using (SQLiteCommand cmdViewSelect = new SQLiteCommand(String.Format(CultureInfo.InvariantCulture, "SELECT * FROM [{0}].[{1}]", strCatalog, rdViews.GetString(2)), this))
            {
              strSql = rdViews.GetString(4).Replace('\r', ' ').Replace('\n', ' ').Replace('\t', ' ');
              n = CultureInfo.InvariantCulture.CompareInfo.IndexOf(strSql, " AS ", CompareOptions.IgnoreCase);
              if (n < 0)
                continue;

              strSql = strSql.Substring(n + 4);
................................................................................

      if (String.IsNullOrEmpty(strCatalog)) strCatalog = "main";

      string master = (String.Compare(strCatalog, "temp", StringComparison.OrdinalIgnoreCase) == 0) ? _tempmasterdb : _masterdb;

      tbl.BeginLoadData();

      using (SQLiteCommand cmdTables = new SQLiteCommand(String.Format(CultureInfo.InvariantCulture, "SELECT * FROM [{0}].[{1}] WHERE [type] LIKE 'table'", strCatalog, master), this))
      using (SQLiteDataReader rdTables = cmdTables.ExecuteReader())
      {
        while (rdTables.Read())
        {
          if (String.IsNullOrEmpty(strTable) || String.Compare(strTable, rdTables.GetString(2), StringComparison.OrdinalIgnoreCase) == 0)
          {
            try
            {
              using (SQLiteCommandBuilder builder = new SQLiteCommandBuilder())
              using (SQLiteCommand cmdKey = new SQLiteCommand(String.Format(CultureInfo.InvariantCulture, "PRAGMA [{0}].foreign_key_list([{1}])", strCatalog, rdTables.GetString(2)), this))
              using (SQLiteDataReader rdKey = cmdKey.ExecuteReader())
              {
                while (rdKey.Read())
                {
                  row = tbl.NewRow();
                  row["CONSTRAINT_CATALOG"] = strCatalog;
                  row["CONSTRAINT_NAME"] = String.Format(CultureInfo.InvariantCulture, "FK_{0}_{1}_{2}", rdTables[2], rdKey.GetInt32(0), rdKey.GetInt32(1));
                  row["TABLE_CATALOG"] = strCatalog;
                  row["TABLE_NAME"] = builder.UnquoteIdentifier(rdTables.GetString(2));
                  row["CONSTRAINT_TYPE"] = "FOREIGN KEY";
                  row["IS_DEFERRABLE"] = false;
                  row["INITIALLY_DEFERRED"] = false;
                  row["FKEY_ID"] = rdKey[0];
                  row["FKEY_FROM_COLUMN"] = builder.UnquoteIdentifier(rdKey[3].ToString());
................................................................................
        {
            try
            {
                if ((_flags & SQLiteConnectionFlags.LogCallbackException) ==
                        SQLiteConnectionFlags.LogCallbackException)
                {
                    SQLiteLog.LogMessage(SQLiteBase.COR_E_EXCEPTION,
                        String.Format(CultureInfo.CurrentCulture,
                        "Caught exception in \"Progress\" method: {1}",
                        e)); /* throw */
                }
            }
            catch
            {
                // do nothing.
................................................................................
        {
            try
            {
                if ((_flags & SQLiteConnectionFlags.LogCallbackException) ==
                        SQLiteConnectionFlags.LogCallbackException)
                {
                    SQLiteLog.LogMessage(SQLiteBase.COR_E_EXCEPTION,
                        String.Format(CultureInfo.CurrentCulture,
                        "Caught exception in \"Authorize\" method: {1}",
                        e)); /* throw */
                }
            }
            catch
            {
                // do nothing.
................................................................................
        {
            try
            {
                if ((_flags & SQLiteConnectionFlags.LogCallbackException) ==
                        SQLiteConnectionFlags.LogCallbackException)
                {
                    SQLiteLog.LogMessage(SQLiteBase.COR_E_EXCEPTION,
                        String.Format(CultureInfo.CurrentCulture,
                        "Caught exception in \"Update\" method: {1}",
                        e)); /* throw */
                }
            }
            catch
            {
                // do nothing.
................................................................................
        {
            try
            {
                if ((_flags & SQLiteConnectionFlags.LogCallbackException) ==
                        SQLiteConnectionFlags.LogCallbackException)
                {
                    SQLiteLog.LogMessage(SQLiteBase.COR_E_EXCEPTION,
                        String.Format(CultureInfo.CurrentCulture,
                        "Caught exception in \"Trace\" method: {1}",
                        e)); /* throw */
                }
            }
            catch
            {
                // do nothing.
................................................................................
        {
            try
            {
                if ((_flags & SQLiteConnectionFlags.LogCallbackException) ==
                        SQLiteConnectionFlags.LogCallbackException)
                {
                    SQLiteLog.LogMessage(SQLiteBase.COR_E_EXCEPTION,
                        String.Format(CultureInfo.CurrentCulture,
                        "Caught exception in \"Commit\" method: {1}",
                        e)); /* throw */
                }
            }
            catch
            {
                // do nothing.
................................................................................
        {
            try
            {
                if ((_flags & SQLiteConnectionFlags.LogCallbackException) ==
                        SQLiteConnectionFlags.LogCallbackException)
                {
                    SQLiteLog.LogMessage(SQLiteBase.COR_E_EXCEPTION,
                        String.Format(CultureInfo.CurrentCulture,
                        "Caught exception in \"Rollback\" method: {1}",
                        e)); /* throw */
                }
            }
            catch
            {
                // do nothing.







|







 







|







 







|







 







>
|







 







|







 







|







 







|







 







|







 







|







 







|







 







|







 







|







 







|







 







|











|








|







|







|







|







 







|







|







|







 







>
>
|







 







|







 







|







 







|








|







 







|












|







 







|







 







|







 







|







 







|







 







|







 







|







 







|







 







|










|







 







|













|









|







 







|






|







 







|









|






|







 







|







 







|







 







|







 







|







 







|







 







|







927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
....
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
....
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
....
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
....
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
....
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
....
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
....
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
....
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
....
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
....
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
....
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
....
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
....
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
....
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
....
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
....
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
....
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
....
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
....
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
....
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
....
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
....
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
....
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
....
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
....
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
....
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
....
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
....
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
....
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
....
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
....
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
....
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
....
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
....
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
....
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
....
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
          {
            string str = row[0].ToString();
            if (String.Compare(str, "main", StringComparison.OrdinalIgnoreCase) != 0
              && String.Compare(str, "temp", StringComparison.OrdinalIgnoreCase) != 0)
            {
              using (SQLiteCommand cmd = CreateCommand())
              {
                cmd.CommandText = UnsafeNativeMethods.StringFormat(CultureInfo.InvariantCulture, "ATTACH DATABASE '{0}' AS [{1}]", row[1], row[0]);
                cmd.ExecuteNonQuery();
              }
            }
          }
        }
      }
    }
................................................................................
                    break;
            }
        }
        catch (Exception e)
        {
            if ((_flags & SQLiteConnectionFlags.LogBackup) == SQLiteConnectionFlags.LogBackup)
            {
                SQLiteLog.LogMessage(UnsafeNativeMethods.StringFormat(
                    CultureInfo.CurrentCulture,
                    "Caught exception while backing up database: {0}", e));
            }

            throw;
        }
        finally
................................................................................
    protected override void Dispose(bool disposing)
    {
#if !NET_COMPACT_20 && TRACE_WARNING
        if ((_flags & SQLiteConnectionFlags.TraceWarning) == SQLiteConnectionFlags.TraceWarning)
        {
            if (_noDispose)
            {
                System.Diagnostics.Trace.WriteLine(UnsafeNativeMethods.StringFormat(
                    CultureInfo.CurrentCulture,
                    "WARNING: Disposing of connection \"{0}\" with the no-dispose flag set.",
                    _connectionString));
            }
        }
#endif

................................................................................
      if (UnsafeNativeMethods.GetSettingValue("No_SQLiteConnectionNewParser", null) != null)
          arParts = SQLiteConvert.Split(s, ';');
      else
          arParts = SQLiteConvert.NewSplit(s, ';', true, ref error);

      if (arParts == null)
      {
          throw new ArgumentException(UnsafeNativeMethods.StringFormat(
              CultureInfo.CurrentCulture,
              "Invalid ConnectionString format, cannot parse: {0}", (error != null) ?
              error : "could not split connection string into properties"));
      }

      int x = (arParts != null) ? arParts.Length : 0;
      // For each semi-colon piece, split into key and value pairs by the presence of the = sign
      for (n = 0; n < x; n++)
................................................................................
        int indexOf = arParts[n].IndexOf('=');

        if (indexOf != -1)
          ls.Add(UnwrapString(arParts[n].Substring(0, indexOf).Trim()), UnwrapString(arParts[n].Substring(indexOf + 1).Trim()));
        else if (allowNameOnly)
          ls.Add(UnwrapString(arParts[n].Trim()), String.Empty);
        else
          throw new ArgumentException(UnsafeNativeMethods.StringFormat(CultureInfo.CurrentCulture, "Invalid ConnectionString format for part \"{0}\", no equal sign found", arParts[n]));
      }
      return ls;
    }

    /// <summary>
    /// Parses a connection string using the built-in (i.e. framework provided)
    /// connection string parser class and returns the key/value pairs.  An
................................................................................
    public void EnableExtensions(
        bool enable
        )
    {
        CheckDisposed();

        if (_sql == null)
            throw new InvalidOperationException(UnsafeNativeMethods.StringFormat(
                CultureInfo.CurrentCulture,
                "Database connection not valid for {0} extensions.",
                enable ? "enabling" : "disabling"));

        if ((_flags & SQLiteConnectionFlags.NoLoadExtension) == SQLiteConnectionFlags.NoLoadExtension)
            throw new SQLiteException("Loading extensions is disabled for this database connection.");

................................................................................

        StringBuilder result = new StringBuilder();

        int length = array.Length;

        for (int index = 0; index < length; index++)
#if NET_COMPACT_20
            result.Append(UnsafeNativeMethods.StringFormat("{0:x2}", array[index]));
#else
            result.AppendFormat("{0:x2}", array[index]);
#endif

        return result.ToString();
    }

................................................................................
        for (int index = 0; index < text.Length; index += 2)
        {
            string value = text.Substring(index, 2);

            if (!TryParseByte(value,
                    NumberStyles.HexNumber, out result[index / 2]))
            {
                error = UnsafeNativeMethods.StringFormat(
                    CultureInfo.CurrentCulture,
                    "string contains \"{0}\", which cannot be converted to a byte value",
                    value);

                return null;
            }
        }
................................................................................
#if !NET_COMPACT_20 && TRACE_WARNING
      bool uri = false;
#endif
      bool fullUri = false;
      string fileName;

      if (Convert.ToInt32(FindKey(opts, "Version", DefaultVersion.ToString()), CultureInfo.InvariantCulture) != DefaultVersion)
        throw new NotSupportedException(UnsafeNativeMethods.StringFormat(CultureInfo.CurrentCulture, "Only SQLite Version {0} is supported at this time", DefaultVersion));

#if INTEROP_INCLUDE_ZIPVFS
      bool useZipVfs = false;
      string zipVfsVersion = FindKey(opts, "ZipVfsVersion", DefaultZipVfsVersion);

      if (zipVfsVersion != null)
      {
................................................................................
          else if (String.Compare(zipVfsVersion, ZipVfs_V3) == 0)
          {
              UnsafeNativeMethods.zipvfsInit_v3(0);
              useZipVfs = true;
          }
          else
          {
              throw new NotSupportedException(UnsafeNativeMethods.StringFormat(
                  CultureInfo.CurrentCulture, "Only ZipVFS versions {0}, {1}, and {2} are supported at this time",
                  ZipVfs_Automatic, ZipVfs_V2, ZipVfs_V3));
          }
      }
#endif

      fileName = FindKey(opts, "Data Source", DefaultDataSource);
................................................................................
      if (String.IsNullOrEmpty(fileName))
      {
        fileName = FindKey(opts, "Uri", DefaultUri);
        if (String.IsNullOrEmpty(fileName))
        {
          fileName = FindKey(opts, "FullUri", DefaultFullUri);
          if (String.IsNullOrEmpty(fileName))
            throw new ArgumentException(UnsafeNativeMethods.StringFormat(CultureInfo.CurrentCulture, "Data Source cannot be empty.  Use {0} to open an in-memory database", MemoryFileName));
          else
            fullUri = true;
        }
        else
        {
          fileName = MapUriPath(fileName);
#if !NET_COMPACT_20 && TRACE_WARNING
................................................................................
#if !NET_COMPACT_20 && TRACE_WARNING
      if ((_flags & SQLiteConnectionFlags.TraceWarning) == SQLiteConnectionFlags.TraceWarning)
      {
          if (!uri && !fullUri && !isMemory && !String.IsNullOrEmpty(fileName) &&
              fileName.StartsWith("\\", StringComparison.OrdinalIgnoreCase) &&
              !fileName.StartsWith("\\\\", StringComparison.OrdinalIgnoreCase))
          {
              System.Diagnostics.Trace.WriteLine(UnsafeNativeMethods.StringFormat(
                  CultureInfo.CurrentCulture,
                  "WARNING: Detected a possibly malformed UNC database file name \"{0}\" that " +
                  "may have originally started with two backslashes; however, four leading " +
                  "backslashes may be required, e.g.: \"Data Source=\\\\\\{0};\"",
                  fileName));
          }
      }
................................................................................
        if (hexPassword != null)
        {
            string error = null;
            byte[] hexPasswordBytes = FromHexString(hexPassword, ref error);

            if (hexPasswordBytes == null)
            {
                throw new FormatException(UnsafeNativeMethods.StringFormat(
                    CultureInfo.CurrentCulture,
                    "Cannot parse 'HexPassword' property value into byte values: {0}",
                    error));
            }

            _sql.SetPassword(hexPasswordBytes);
        }
................................................................................

          if (boolValue)
          {
              using (SQLiteCommand cmd = CreateCommand())
              {
                  if (_busyTimeout != DefaultBusyTimeout)
                  {
                      cmd.CommandText = UnsafeNativeMethods.StringFormat(CultureInfo.InvariantCulture, "PRAGMA busy_timeout={0}", _busyTimeout);
                      cmd.ExecuteNonQuery();
                  }

                  int intValue;

                  if (!fullUri && !isMemory)
                  {
                      strValue = FindKey(opts, "Page Size", DefaultPageSize.ToString());
                      intValue = Convert.ToInt32(strValue, CultureInfo.InvariantCulture);
                      if (intValue != DefaultPageSize)
                      {
                          cmd.CommandText = UnsafeNativeMethods.StringFormat(CultureInfo.InvariantCulture, "PRAGMA page_size={0}", intValue);
                          cmd.ExecuteNonQuery();
                      }
                  }

                  strValue = FindKey(opts, "Max Page Count", DefaultMaxPageCount.ToString());
                  intValue = Convert.ToInt32(strValue, CultureInfo.InvariantCulture);
                  if (intValue != DefaultMaxPageCount)
                  {
                      cmd.CommandText = UnsafeNativeMethods.StringFormat(CultureInfo.InvariantCulture, "PRAGMA max_page_count={0}", intValue);
                      cmd.ExecuteNonQuery();
                  }

                  strValue = FindKey(opts, "Legacy Format", DefaultLegacyFormat.ToString());
                  boolValue = SQLiteConvert.ToBoolean(strValue);
                  if (boolValue != DefaultLegacyFormat)
                  {
                      cmd.CommandText = UnsafeNativeMethods.StringFormat(CultureInfo.InvariantCulture, "PRAGMA legacy_file_format={0}", boolValue ? "ON" : "OFF");
                      cmd.ExecuteNonQuery();
                  }

                  strValue = FindKey(opts, "Synchronous", DefaultSynchronous.ToString());
                  enumValue = TryParseEnum(typeof(SQLiteSynchronousEnum), strValue, true);
                  if (!(enumValue is SQLiteSynchronousEnum) || ((SQLiteSynchronousEnum)enumValue != DefaultSynchronous))
                  {
                      cmd.CommandText = UnsafeNativeMethods.StringFormat(CultureInfo.InvariantCulture, "PRAGMA synchronous={0}", strValue);
                      cmd.ExecuteNonQuery();
                  }

                  strValue = FindKey(opts, "Cache Size", DefaultCacheSize.ToString());
                  intValue = Convert.ToInt32(strValue, CultureInfo.InvariantCulture);
                  if (intValue != DefaultCacheSize)
                  {
                      cmd.CommandText = UnsafeNativeMethods.StringFormat(CultureInfo.InvariantCulture, "PRAGMA cache_size={0}", intValue);
                      cmd.ExecuteNonQuery();
                  }

                  strValue = FindKey(opts, "Journal Mode", DefaultJournalMode.ToString());
                  enumValue = TryParseEnum(typeof(SQLiteJournalModeEnum), strValue, true);
                  if (!(enumValue is SQLiteJournalModeEnum) || ((SQLiteJournalModeEnum)enumValue != DefaultJournalMode))
                  {
................................................................................
                      string pragmaStr = "PRAGMA journal_mode={0}";

#if INTEROP_INCLUDE_ZIPVFS
                      if (useZipVfs)
                          pragmaStr = "PRAGMA zipvfs_journal_mode={0}";
#endif

                      cmd.CommandText = UnsafeNativeMethods.StringFormat(CultureInfo.InvariantCulture, pragmaStr, strValue);
                      cmd.ExecuteNonQuery();
                  }

                  strValue = FindKey(opts, "Foreign Keys", DefaultForeignKeys.ToString());
                  boolValue = SQLiteConvert.ToBoolean(strValue);
                  if (boolValue != DefaultForeignKeys)
                  {
                      cmd.CommandText = UnsafeNativeMethods.StringFormat(CultureInfo.InvariantCulture, "PRAGMA foreign_keys={0}", boolValue ? "ON" : "OFF");
                      cmd.ExecuteNonQuery();
                  }

                  strValue = FindKey(opts, "Recursive Triggers", DefaultRecursiveTriggers.ToString());
                  boolValue = SQLiteConvert.ToBoolean(strValue);
                  if (boolValue != DefaultRecursiveTriggers)
                  {
                      cmd.CommandText = UnsafeNativeMethods.StringFormat(CultureInfo.InvariantCulture, "PRAGMA recursive_triggers={0}", boolValue ? "ON" : "OFF");
                      cmd.ExecuteNonQuery();
                  }
              }
          }

          if (_progressHandler != null)
              _sql.SetProgressHook(_progressOps, _progressCallback);
................................................................................
            {
                if (sourceId == null)
                    sourceId = "0000000000000000000000000000000000000000";

                if (sourceTimeStamp == null)
                    sourceTimeStamp = "0000-00-00 00:00:00 UTC";

                return UnsafeNativeMethods.StringFormat(
                    CultureInfo.InvariantCulture,
                    "{0} {1}", sourceId, sourceTimeStamp);
            }
            else
            {
                return null;
            }
        }
    }
................................................................................
            throw new InvalidOperationException("Database connection not valid for shutdown.");

        _sql.Close(true); /* NOTE: MUST be closed before shutdown. */
        SQLiteErrorCode rc = _sql.Shutdown();

#if !NET_COMPACT_20 && TRACE_CONNECTION
        if (rc != SQLiteErrorCode.Ok)
            System.Diagnostics.Trace.WriteLine(UnsafeNativeMethods.StringFormat(
                CultureInfo.CurrentCulture,
                "Shutdown (Instance) Failed: {0}", rc));
#endif

        return rc;
    }

................................................................................
        )
    {
        SQLiteErrorCode rc = SQLite3.StaticShutdown(directories);

        if (rc != SQLiteErrorCode.Ok)
        {
#if !NET_COMPACT_20 && TRACE_CONNECTION
            System.Diagnostics.Trace.WriteLine(UnsafeNativeMethods.StringFormat(
                CultureInfo.CurrentCulture,
                "Shutdown (Static) Failed: {0}", rc));
#endif

            if (!noThrow)
                throw new SQLiteException(rc, null);
        }
................................................................................

      tbl.BeginLoadData();

      if (String.IsNullOrEmpty(strCatalog)) strCatalog = "main";

      string master = (String.Compare(strCatalog, "temp", StringComparison.OrdinalIgnoreCase) == 0) ? _tempmasterdb : _masterdb;

      using (SQLiteCommand cmdTables = new SQLiteCommand(UnsafeNativeMethods.StringFormat(CultureInfo.InvariantCulture, "SELECT * FROM [{0}].[{1}] WHERE [type] LIKE 'table' OR [type] LIKE 'view'", strCatalog, master), this))
      using (SQLiteDataReader rdTables = cmdTables.ExecuteReader())
      {
        while (rdTables.Read())
        {
          if (String.IsNullOrEmpty(strTable) || String.Compare(strTable, rdTables.GetString(2), StringComparison.OrdinalIgnoreCase) == 0)
          {
            try
            {
              using (SQLiteCommand cmd = new SQLiteCommand(UnsafeNativeMethods.StringFormat(CultureInfo.InvariantCulture, "SELECT * FROM [{0}].[{1}]", strCatalog, rdTables.GetString(2)), this))
              using (SQLiteDataReader rd = (SQLiteDataReader)cmd.ExecuteReader(CommandBehavior.SchemaOnly))
              using (DataTable tblSchema = rd.GetSchemaTable(true, true))
              {
                foreach (DataRow schemaRow in tblSchema.Rows)
                {
                  if (String.Compare(schemaRow[SchemaTableColumn.ColumnName].ToString(), strColumn, StringComparison.OrdinalIgnoreCase) == 0
                    || strColumn == null)
................................................................................

      tbl.BeginLoadData();

      if (String.IsNullOrEmpty(strCatalog)) strCatalog = "main";

      string master = (String.Compare(strCatalog, "temp", StringComparison.OrdinalIgnoreCase) == 0) ? _tempmasterdb : _masterdb;

      using (SQLiteCommand cmdTables = new SQLiteCommand(UnsafeNativeMethods.StringFormat(CultureInfo.InvariantCulture, "SELECT * FROM [{0}].[{1}] WHERE [type] LIKE 'table'", strCatalog, master), this))
      using (SQLiteDataReader rdTables = cmdTables.ExecuteReader())
      {
        while (rdTables.Read())
        {
          maybeRowId = false;
          primaryKeys.Clear();
          if (String.IsNullOrEmpty(strTable) || String.Compare(rdTables.GetString(2), strTable, StringComparison.OrdinalIgnoreCase) == 0)
          {
            // First, look for any rowid indexes -- which sqlite defines are INTEGER PRIMARY KEY columns.
            // Such indexes are not listed in the indexes list but count as indexes just the same.
            try
            {
              using (SQLiteCommand cmdTable = new SQLiteCommand(UnsafeNativeMethods.StringFormat(CultureInfo.InvariantCulture, "PRAGMA [{0}].table_info([{1}])", strCatalog, rdTables.GetString(2)), this))
              using (SQLiteDataReader rdTable = cmdTable.ExecuteReader())
              {
                while (rdTable.Read())
                {
                  if (rdTable.GetInt32(5) != 0)
                  {
                    primaryKeys.Add(rdTable.GetInt32(0));
................................................................................
            {
              row = tbl.NewRow();

              row["TABLE_CATALOG"] = strCatalog;
              row["TABLE_NAME"] = rdTables.GetString(2);
              row["INDEX_CATALOG"] = strCatalog;
              row["PRIMARY_KEY"] = true;
              row["INDEX_NAME"] = UnsafeNativeMethods.StringFormat(CultureInfo.InvariantCulture, "{1}_PK_{0}", rdTables.GetString(2), master);
              row["UNIQUE"] = true;

              if (String.Compare((string)row["INDEX_NAME"], strIndex, StringComparison.OrdinalIgnoreCase) == 0
              || strIndex == null)
              {
                tbl.Rows.Add(row);
              }
................................................................................

              primaryKeys.Clear();
            }

            // Now fetch all the rest of the indexes.
            try
            {
              using (SQLiteCommand cmd = new SQLiteCommand(UnsafeNativeMethods.StringFormat(CultureInfo.InvariantCulture, "PRAGMA [{0}].index_list([{1}])", strCatalog, rdTables.GetString(2)), this))
              using (SQLiteDataReader rd = (SQLiteDataReader)cmd.ExecuteReader())
              {
                while (rd.Read())
                {
                  if (String.Compare(rd.GetString(1), strIndex, StringComparison.OrdinalIgnoreCase) == 0
                  || strIndex == null)
                  {
................................................................................
                    row["TABLE_NAME"] = rdTables.GetString(2);
                    row["INDEX_CATALOG"] = strCatalog;
                    row["INDEX_NAME"] = rd.GetString(1);
                    row["UNIQUE"] = SQLiteConvert.ToBoolean(rd.GetValue(2), CultureInfo.InvariantCulture, false);
                    row["PRIMARY_KEY"] = false;

                    // get the index definition
                    using (SQLiteCommand cmdIndexes = new SQLiteCommand(UnsafeNativeMethods.StringFormat(CultureInfo.InvariantCulture, "SELECT * FROM [{0}].[{2}] WHERE [type] LIKE 'index' AND [name] LIKE '{1}'", strCatalog, rd.GetString(1).Replace("'", "''"), master), this))
                    using (SQLiteDataReader rdIndexes = cmdIndexes.ExecuteReader())
                    {
                      while (rdIndexes.Read())
                      {
                        if (rdIndexes.IsDBNull(4) == false)
                          row["INDEX_DEFINITION"] = rdIndexes.GetString(4);
                        break;
................................................................................
                    }

                    // Now for the really hard work.  Figure out which index is the primary key index.
                    // The only way to figure it out is to check if the index was an autoindex and if we have a non-rowid
                    // primary key, and all the columns in the given index match the primary key columns
                    if (primaryKeys.Count > 0 && rd.GetString(1).StartsWith("sqlite_autoindex_" + rdTables.GetString(2), StringComparison.InvariantCultureIgnoreCase) == true)
                    {
                      using (SQLiteCommand cmdDetails = new SQLiteCommand(UnsafeNativeMethods.StringFormat(CultureInfo.InvariantCulture, "PRAGMA [{0}].index_info([{1}])", strCatalog, rd.GetString(1)), this))
                      using (SQLiteDataReader rdDetails = cmdDetails.ExecuteReader())
                      {
                        int nMatches = 0;
                        while (rdDetails.Read())
                        {
                          if (primaryKeys.Contains(rdDetails.GetInt32(1)) == false)
                          {
................................................................................

      tbl.BeginLoadData();

      if (String.IsNullOrEmpty(table)) table = null;
      if (String.IsNullOrEmpty(catalog)) catalog = "main";
      string master = (String.Compare(catalog, "temp", StringComparison.OrdinalIgnoreCase) == 0) ? _tempmasterdb : _masterdb;

      using (SQLiteCommand cmd = new SQLiteCommand(UnsafeNativeMethods.StringFormat(CultureInfo.InvariantCulture, "SELECT [type], [name], [tbl_name], [rootpage], [sql], [rowid] FROM [{0}].[{1}] WHERE [type] LIKE 'trigger'", catalog, master), this))
      using (SQLiteDataReader rd = (SQLiteDataReader)cmd.ExecuteReader())
      {
        while (rd.Read())
        {
          if (String.Compare(rd.GetString(1), triggerName, StringComparison.OrdinalIgnoreCase) == 0
            || triggerName == null)
          {
................................................................................
      tbl.Columns.Add("TABLE_DEFINITION", typeof(string));
      tbl.BeginLoadData();

      if (String.IsNullOrEmpty(strCatalog)) strCatalog = "main";

      string master = (String.Compare(strCatalog, "temp", StringComparison.OrdinalIgnoreCase) == 0) ? _tempmasterdb : _masterdb;

      using (SQLiteCommand cmd = new SQLiteCommand(UnsafeNativeMethods.StringFormat(CultureInfo.InvariantCulture, "SELECT [type], [name], [tbl_name], [rootpage], [sql], [rowid] FROM [{0}].[{1}] WHERE [type] LIKE 'table'", strCatalog, master), this))
      using (SQLiteDataReader rd = (SQLiteDataReader)cmd.ExecuteReader())
      {
        while (rd.Read())
        {
          strItem = rd.GetString(0);
          if (String.Compare(rd.GetString(2), 0, "SQLITE_", 0, 7, StringComparison.OrdinalIgnoreCase) == 0)
            strItem = "SYSTEM_TABLE";
................................................................................

      tbl.BeginLoadData();

      if (String.IsNullOrEmpty(strCatalog)) strCatalog = "main";

      string master = (String.Compare(strCatalog, "temp", StringComparison.OrdinalIgnoreCase) == 0) ? _tempmasterdb : _masterdb;

      using (SQLiteCommand cmd = new SQLiteCommand(UnsafeNativeMethods.StringFormat(CultureInfo.InvariantCulture, "SELECT * FROM [{0}].[{1}] WHERE [type] LIKE 'view'", strCatalog, master), this))
      using (SQLiteDataReader rd = (SQLiteDataReader)cmd.ExecuteReader())
      {
        while (rd.Read())
        {
          if (String.Compare(rd.GetString(1), strView, StringComparison.OrdinalIgnoreCase) == 0
            || String.IsNullOrEmpty(strView))
          {
................................................................................

      if (String.IsNullOrEmpty(strCatalog)) strCatalog = "main";

      string master = (String.Compare(strCatalog, "temp", StringComparison.OrdinalIgnoreCase) == 0) ? _tempmasterdb : _masterdb;

      tbl.BeginLoadData();

      using (SQLiteCommand cmdTables = new SQLiteCommand(UnsafeNativeMethods.StringFormat(CultureInfo.InvariantCulture, "SELECT * FROM [{0}].[{1}] WHERE [type] LIKE 'table'", strCatalog, master), this))
      using (SQLiteDataReader rdTables = cmdTables.ExecuteReader())
      {
        while (rdTables.Read())
        {
          maybeRowId = false;
          primaryKeys.Clear();
          if (String.IsNullOrEmpty(strTable) || String.Compare(rdTables.GetString(2), strTable, StringComparison.OrdinalIgnoreCase) == 0)
          {
            try
            {
              using (SQLiteCommand cmdTable = new SQLiteCommand(UnsafeNativeMethods.StringFormat(CultureInfo.InvariantCulture, "PRAGMA [{0}].table_info([{1}])", strCatalog, rdTables.GetString(2)), this))
              using (SQLiteDataReader rdTable = cmdTable.ExecuteReader())
              {
                while (rdTable.Read())
                {
                  if (rdTable.GetInt32(5) == 1) // is a primary key
                  {
                    primaryKeys.Add(new KeyValuePair<int, string>(rdTable.GetInt32(0), rdTable.GetString(1)));
................................................................................
            {
            }
            // This is a rowid row
            if (primaryKeys.Count == 1 && maybeRowId == true)
            {
              row = tbl.NewRow();
              row["CONSTRAINT_CATALOG"] = strCatalog;
              row["CONSTRAINT_NAME"] = UnsafeNativeMethods.StringFormat(CultureInfo.InvariantCulture, "{1}_PK_{0}", rdTables.GetString(2), master);
              row["TABLE_CATALOG"] = strCatalog;
              row["TABLE_NAME"] = rdTables.GetString(2);
              row["COLUMN_NAME"] = primaryKeys[0].Value;
              row["INDEX_NAME"] = row["CONSTRAINT_NAME"];
              row["ORDINAL_POSITION"] = 0; // primaryKeys[0].Key;
              row["COLLATION_NAME"] = "BINARY";
              row["SORT_MODE"] = "ASC";
              row["CONFLICT_OPTION"] = 2;

              if (String.IsNullOrEmpty(strIndex) || String.Compare(strIndex, (string)row["INDEX_NAME"], StringComparison.OrdinalIgnoreCase) == 0)
                tbl.Rows.Add(row);
            }

            using (SQLiteCommand cmdIndexes = new SQLiteCommand(UnsafeNativeMethods.StringFormat(CultureInfo.InvariantCulture, "SELECT * FROM [{0}].[{2}] WHERE [type] LIKE 'index' AND [tbl_name] LIKE '{1}'", strCatalog, rdTables.GetString(2).Replace("'", "''"), master), this))
            using (SQLiteDataReader rdIndexes = cmdIndexes.ExecuteReader())
            {
              while (rdIndexes.Read())
              {
                int ordinal = 0;
                if (String.IsNullOrEmpty(strIndex) || String.Compare(strIndex, rdIndexes.GetString(1), StringComparison.OrdinalIgnoreCase) == 0)
                {
                  try
                  {
                    using (SQLiteCommand cmdIndex = new SQLiteCommand(UnsafeNativeMethods.StringFormat(CultureInfo.InvariantCulture, "PRAGMA [{0}].index_info([{1}])", strCatalog, rdIndexes.GetString(1)), this))
                    using (SQLiteDataReader rdIndex = cmdIndex.ExecuteReader())
                    {
                      while (rdIndex.Read())
                      {
                        row = tbl.NewRow();
                        row["CONSTRAINT_CATALOG"] = strCatalog;
                        row["CONSTRAINT_NAME"] = rdIndexes.GetString(1);
................................................................................

      if (String.IsNullOrEmpty(strCatalog)) strCatalog = "main";

      string master = (String.Compare(strCatalog, "temp", StringComparison.OrdinalIgnoreCase) == 0) ? _tempmasterdb : _masterdb;

      tbl.BeginLoadData();

      using (SQLiteCommand cmdViews = new SQLiteCommand(UnsafeNativeMethods.StringFormat(CultureInfo.InvariantCulture, "SELECT * FROM [{0}].[{1}] WHERE [type] LIKE 'view'", strCatalog, master), this))
      using (SQLiteDataReader rdViews = cmdViews.ExecuteReader())
      {
        while (rdViews.Read())
        {
          if (String.IsNullOrEmpty(strView) || String.Compare(strView, rdViews.GetString(2), StringComparison.OrdinalIgnoreCase) == 0)
          {
            using (SQLiteCommand cmdViewSelect = new SQLiteCommand(UnsafeNativeMethods.StringFormat(CultureInfo.InvariantCulture, "SELECT * FROM [{0}].[{1}]", strCatalog, rdViews.GetString(2)), this))
            {
              strSql = rdViews.GetString(4).Replace('\r', ' ').Replace('\n', ' ').Replace('\t', ' ');
              n = CultureInfo.InvariantCulture.CompareInfo.IndexOf(strSql, " AS ", CompareOptions.IgnoreCase);
              if (n < 0)
                continue;

              strSql = strSql.Substring(n + 4);
................................................................................

      if (String.IsNullOrEmpty(strCatalog)) strCatalog = "main";

      string master = (String.Compare(strCatalog, "temp", StringComparison.OrdinalIgnoreCase) == 0) ? _tempmasterdb : _masterdb;

      tbl.BeginLoadData();

      using (SQLiteCommand cmdTables = new SQLiteCommand(UnsafeNativeMethods.StringFormat(CultureInfo.InvariantCulture, "SELECT * FROM [{0}].[{1}] WHERE [type] LIKE 'table'", strCatalog, master), this))
      using (SQLiteDataReader rdTables = cmdTables.ExecuteReader())
      {
        while (rdTables.Read())
        {
          if (String.IsNullOrEmpty(strTable) || String.Compare(strTable, rdTables.GetString(2), StringComparison.OrdinalIgnoreCase) == 0)
          {
            try
            {
              using (SQLiteCommandBuilder builder = new SQLiteCommandBuilder())
              using (SQLiteCommand cmdKey = new SQLiteCommand(UnsafeNativeMethods.StringFormat(CultureInfo.InvariantCulture, "PRAGMA [{0}].foreign_key_list([{1}])", strCatalog, rdTables.GetString(2)), this))
              using (SQLiteDataReader rdKey = cmdKey.ExecuteReader())
              {
                while (rdKey.Read())
                {
                  row = tbl.NewRow();
                  row["CONSTRAINT_CATALOG"] = strCatalog;
                  row["CONSTRAINT_NAME"] = UnsafeNativeMethods.StringFormat(CultureInfo.InvariantCulture, "FK_{0}_{1}_{2}", rdTables[2], rdKey.GetInt32(0), rdKey.GetInt32(1));
                  row["TABLE_CATALOG"] = strCatalog;
                  row["TABLE_NAME"] = builder.UnquoteIdentifier(rdTables.GetString(2));
                  row["CONSTRAINT_TYPE"] = "FOREIGN KEY";
                  row["IS_DEFERRABLE"] = false;
                  row["INITIALLY_DEFERRED"] = false;
                  row["FKEY_ID"] = rdKey[0];
                  row["FKEY_FROM_COLUMN"] = builder.UnquoteIdentifier(rdKey[3].ToString());
................................................................................
        {
            try
            {
                if ((_flags & SQLiteConnectionFlags.LogCallbackException) ==
                        SQLiteConnectionFlags.LogCallbackException)
                {
                    SQLiteLog.LogMessage(SQLiteBase.COR_E_EXCEPTION,
                        UnsafeNativeMethods.StringFormat(CultureInfo.CurrentCulture,
                        "Caught exception in \"Progress\" method: {1}",
                        e)); /* throw */
                }
            }
            catch
            {
                // do nothing.
................................................................................
        {
            try
            {
                if ((_flags & SQLiteConnectionFlags.LogCallbackException) ==
                        SQLiteConnectionFlags.LogCallbackException)
                {
                    SQLiteLog.LogMessage(SQLiteBase.COR_E_EXCEPTION,
                        UnsafeNativeMethods.StringFormat(CultureInfo.CurrentCulture,
                        "Caught exception in \"Authorize\" method: {1}",
                        e)); /* throw */
                }
            }
            catch
            {
                // do nothing.
................................................................................
        {
            try
            {
                if ((_flags & SQLiteConnectionFlags.LogCallbackException) ==
                        SQLiteConnectionFlags.LogCallbackException)
                {
                    SQLiteLog.LogMessage(SQLiteBase.COR_E_EXCEPTION,
                        UnsafeNativeMethods.StringFormat(CultureInfo.CurrentCulture,
                        "Caught exception in \"Update\" method: {1}",
                        e)); /* throw */
                }
            }
            catch
            {
                // do nothing.
................................................................................
        {
            try
            {
                if ((_flags & SQLiteConnectionFlags.LogCallbackException) ==
                        SQLiteConnectionFlags.LogCallbackException)
                {
                    SQLiteLog.LogMessage(SQLiteBase.COR_E_EXCEPTION,
                        UnsafeNativeMethods.StringFormat(CultureInfo.CurrentCulture,
                        "Caught exception in \"Trace\" method: {1}",
                        e)); /* throw */
                }
            }
            catch
            {
                // do nothing.
................................................................................
        {
            try
            {
                if ((_flags & SQLiteConnectionFlags.LogCallbackException) ==
                        SQLiteConnectionFlags.LogCallbackException)
                {
                    SQLiteLog.LogMessage(SQLiteBase.COR_E_EXCEPTION,
                        UnsafeNativeMethods.StringFormat(CultureInfo.CurrentCulture,
                        "Caught exception in \"Commit\" method: {1}",
                        e)); /* throw */
                }
            }
            catch
            {
                // do nothing.
................................................................................
        {
            try
            {
                if ((_flags & SQLiteConnectionFlags.LogCallbackException) ==
                        SQLiteConnectionFlags.LogCallbackException)
                {
                    SQLiteLog.LogMessage(SQLiteBase.COR_E_EXCEPTION,
                        UnsafeNativeMethods.StringFormat(CultureInfo.CurrentCulture,
                        "Caught exception in \"Rollback\" method: {1}",
                        e)); /* throw */
                }
            }
            catch
            {
                // do nothing.

Changes to System.Data.SQLite/SQLiteConvert.cs.

1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
....
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
....
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
            case TypeCode.Decimal:
                return ((decimal)obj) != Decimal.Zero ? true : false;
            case TypeCode.String:
                return viaFramework ?
                    Convert.ToBoolean(obj, provider) :
                    ToBoolean(ToStringWithProvider(obj, provider));
            default:
                throw new SQLiteException(String.Format(
                    CultureInfo.CurrentCulture,
                    "Cannot convert type {0} to boolean",
                    typeCode));
        }
    }

    /// <summary>
................................................................................
        DbType dbType,
        SQLiteConnectionFlags flags,
        string typeName
        )
    {
        if ((flags & SQLiteConnectionFlags.TraceWarning) == SQLiteConnectionFlags.TraceWarning)
        {
            Trace.WriteLine(String.Format(
                CultureInfo.CurrentCulture,
                "WARNING: Type mapping failed, returning default name \"{0}\" for type {1}.",
                typeName, dbType));
        }
    }

    /// <summary>
................................................................................
        SQLiteConnectionFlags flags,
        DbType? dbType
        )
    {
        if (!String.IsNullOrEmpty(typeName) &&
            ((flags & SQLiteConnectionFlags.TraceWarning) == SQLiteConnectionFlags.TraceWarning))
        {
            Trace.WriteLine(String.Format(
                CultureInfo.CurrentCulture,
                "WARNING: Type mapping failed, returning default type {0} for name \"{1}\".",
                dbType, typeName));
        }
    }
#endif








|







 







|







 







|







1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
....
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
....
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
            case TypeCode.Decimal:
                return ((decimal)obj) != Decimal.Zero ? true : false;
            case TypeCode.String:
                return viaFramework ?
                    Convert.ToBoolean(obj, provider) :
                    ToBoolean(ToStringWithProvider(obj, provider));
            default:
                throw new SQLiteException(UnsafeNativeMethods.StringFormat(
                    CultureInfo.CurrentCulture,
                    "Cannot convert type {0} to boolean",
                    typeCode));
        }
    }

    /// <summary>
................................................................................
        DbType dbType,
        SQLiteConnectionFlags flags,
        string typeName
        )
    {
        if ((flags & SQLiteConnectionFlags.TraceWarning) == SQLiteConnectionFlags.TraceWarning)
        {
            Trace.WriteLine(UnsafeNativeMethods.StringFormat(
                CultureInfo.CurrentCulture,
                "WARNING: Type mapping failed, returning default name \"{0}\" for type {1}.",
                typeName, dbType));
        }
    }

    /// <summary>
................................................................................
        SQLiteConnectionFlags flags,
        DbType? dbType
        )
    {
        if (!String.IsNullOrEmpty(typeName) &&
            ((flags & SQLiteConnectionFlags.TraceWarning) == SQLiteConnectionFlags.TraceWarning))
        {
            Trace.WriteLine(UnsafeNativeMethods.StringFormat(
                CultureInfo.CurrentCulture,
                "WARNING: Type mapping failed, returning default type {0} for name \"{1}\".",
                dbType, typeName));
        }
    }
#endif

Changes to System.Data.SQLite/SQLiteDataReader.cs.

1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
              }
            }
          }

          if (wantDefaultValue)
          {
            // Determine the default value for the column, which sucks because we have to query the schema for each column
            using (SQLiteCommand cmdTable = new SQLiteCommand(String.Format(CultureInfo.InvariantCulture, "PRAGMA [{0}].TABLE_INFO([{1}])",
              row[SchemaTableOptionalColumn.BaseCatalogName],
              row[SchemaTableColumn.BaseTableName]
              ), _command.Connection))
            using (DbDataReader rdTable = cmdTable.ExecuteReader())
            {
              // Find the matching column
              while (rdTable.Read())







|







1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
              }
            }
          }

          if (wantDefaultValue)
          {
            // Determine the default value for the column, which sucks because we have to query the schema for each column
            using (SQLiteCommand cmdTable = new SQLiteCommand(UnsafeNativeMethods.StringFormat(CultureInfo.InvariantCulture, "PRAGMA [{0}].TABLE_INFO([{1}])",
              row[SchemaTableOptionalColumn.BaseCatalogName],
              row[SchemaTableColumn.BaseTableName]
              ), _command.Connection))
            using (DbDataReader rdTable = cmdTable.ExecuteReader())
            {
              // Find the matching column
              while (rdTable.Read())

Changes to System.Data.SQLite/SQLiteEnlistment.cs.

92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
        // NOTE: When in "strict" mode, throw an exception if the isolation
        //       level is not recognized; otherwise, fallback to the default
        //       isolation level specified by the caller.
        //
        if (throwOnUnsupported)
        {
            throw new InvalidOperationException(
                String.Format(CultureInfo.InvariantCulture,
                "unsupported isolation level {0}", isolationLevel));
        }

        return defaultIsolationLevel;
    }

    ///////////////////////////////////////////////////////////////////////////







|







92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
        // NOTE: When in "strict" mode, throw an exception if the isolation
        //       level is not recognized; otherwise, fallback to the default
        //       isolation level specified by the caller.
        //
        if (throwOnUnsupported)
        {
            throw new InvalidOperationException(
                UnsafeNativeMethods.StringFormat(CultureInfo.InvariantCulture,
                "unsupported isolation level {0}", isolationLevel));
        }

        return defaultIsolationLevel;
    }

    ///////////////////////////////////////////////////////////////////////////

Changes to System.Data.SQLite/SQLiteException.cs.

5
6
7
8
9
10
11

12
13
14
15
16
17
18
...
178
179
180
181
182
183
184


185
186
187
188
189
190
191
192
 * Released to the public domain, use at your own risk!
 ********************************************************/

namespace System.Data.SQLite
{
  using System;
  using System.Data.Common;


#if !PLATFORM_COMPACTFRAMEWORK
  using System.Reflection;
  using System.Runtime.Serialization;
  using System.Security.Permissions;
#endif

................................................................................
    /// <param name="message">Optional detailed error message.</param>
    /// <returns>Error message text for the return code.</returns>
    private static string GetStockErrorMessage(
        SQLiteErrorCode errorCode,
        string message
        )
    {


        return String.Format("{0}{1}{2}",
            GetErrorString(errorCode),
#if !NET_COMPACT_20
            Environment.NewLine, message).Trim();
#else
            "\r\n", message).Trim();
#endif
    }







>







 







>
>
|







5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
...
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
 * Released to the public domain, use at your own risk!
 ********************************************************/

namespace System.Data.SQLite
{
  using System;
  using System.Data.Common;
  using System.Globalization;

#if !PLATFORM_COMPACTFRAMEWORK
  using System.Reflection;
  using System.Runtime.Serialization;
  using System.Security.Permissions;
#endif

................................................................................
    /// <param name="message">Optional detailed error message.</param>
    /// <returns>Error message text for the return code.</returns>
    private static string GetStockErrorMessage(
        SQLiteErrorCode errorCode,
        string message
        )
    {
        return UnsafeNativeMethods.StringFormat(
            CultureInfo.InvariantCulture,
            "{0}{1}{2}",
            GetErrorString(errorCode),
#if !NET_COMPACT_20
            Environment.NewLine, message).Trim();
#else
            "\r\n", message).Trim();
#endif
    }

Changes to System.Data.SQLite/SQLiteFunction.cs.

413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
...
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
...
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
...
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
...
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
        {
            try
            {
                if ((_flags & SQLiteConnectionFlags.LogCallbackException) ==
                        SQLiteConnectionFlags.LogCallbackException)
                {
                    SQLiteLog.LogMessage(SQLiteBase.COR_E_EXCEPTION,
                        String.Format(CultureInfo.CurrentCulture,
                        "Caught exception in \"Invoke\" method: {0}",
                        e)); /* throw */
                }
            }
            catch
            {
                // do nothing.
................................................................................
        {
            try
            {
                if ((_flags & SQLiteConnectionFlags.LogCallbackException) ==
                        SQLiteConnectionFlags.LogCallbackException)
                {
                    SQLiteLog.LogMessage(SQLiteBase.COR_E_EXCEPTION,
                        String.Format(CultureInfo.CurrentCulture,
                        "Caught exception in \"Compare\" (UTF8) method: {0}",
                        e)); /* throw */
                }
            }
            catch
            {
                // do nothing.
................................................................................
        {
            try
            {
                if ((_flags & SQLiteConnectionFlags.LogCallbackException) ==
                        SQLiteConnectionFlags.LogCallbackException)
                {
                    SQLiteLog.LogMessage(SQLiteBase.COR_E_EXCEPTION,
                        String.Format(CultureInfo.CurrentCulture,
                        "Caught exception in \"Compare\" (UTF16) method: {0}",
                        e)); /* throw */
                }
            }
            catch
            {
                // do nothing.
................................................................................
        {
            try
            {
                if ((_flags & SQLiteConnectionFlags.LogCallbackException) ==
                        SQLiteConnectionFlags.LogCallbackException)
                {
                    SQLiteLog.LogMessage(SQLiteBase.COR_E_EXCEPTION,
                        String.Format(CultureInfo.CurrentCulture,
                        "Caught exception in \"Step\" method: {1}",
                        e)); /* throw */
                }
            }
            catch
            {
                // do nothing.
................................................................................
        {
            try
            {
                if ((_flags & SQLiteConnectionFlags.LogCallbackException) ==
                        SQLiteConnectionFlags.LogCallbackException)
                {
                    SQLiteLog.LogMessage(SQLiteBase.COR_E_EXCEPTION,
                        String.Format(CultureInfo.CurrentCulture,
                        "Caught exception in \"Final\" method: {1}",
                        e)); /* throw */
                }
            }
            catch
            {
                // do nothing.







|







 







|







 







|







 







|







 







|







413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
...
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
...
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
...
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
...
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
        {
            try
            {
                if ((_flags & SQLiteConnectionFlags.LogCallbackException) ==
                        SQLiteConnectionFlags.LogCallbackException)
                {
                    SQLiteLog.LogMessage(SQLiteBase.COR_E_EXCEPTION,
                        UnsafeNativeMethods.StringFormat(CultureInfo.CurrentCulture,
                        "Caught exception in \"Invoke\" method: {0}",
                        e)); /* throw */
                }
            }
            catch
            {
                // do nothing.
................................................................................
        {
            try
            {
                if ((_flags & SQLiteConnectionFlags.LogCallbackException) ==
                        SQLiteConnectionFlags.LogCallbackException)
                {
                    SQLiteLog.LogMessage(SQLiteBase.COR_E_EXCEPTION,
                        UnsafeNativeMethods.StringFormat(CultureInfo.CurrentCulture,
                        "Caught exception in \"Compare\" (UTF8) method: {0}",
                        e)); /* throw */
                }
            }
            catch
            {
                // do nothing.
................................................................................
        {
            try
            {
                if ((_flags & SQLiteConnectionFlags.LogCallbackException) ==
                        SQLiteConnectionFlags.LogCallbackException)
                {
                    SQLiteLog.LogMessage(SQLiteBase.COR_E_EXCEPTION,
                        UnsafeNativeMethods.StringFormat(CultureInfo.CurrentCulture,
                        "Caught exception in \"Compare\" (UTF16) method: {0}",
                        e)); /* throw */
                }
            }
            catch
            {
                // do nothing.
................................................................................
        {
            try
            {
                if ((_flags & SQLiteConnectionFlags.LogCallbackException) ==
                        SQLiteConnectionFlags.LogCallbackException)
                {
                    SQLiteLog.LogMessage(SQLiteBase.COR_E_EXCEPTION,
                        UnsafeNativeMethods.StringFormat(CultureInfo.CurrentCulture,
                        "Caught exception in \"Step\" method: {1}",
                        e)); /* throw */
                }
            }
            catch
            {
                // do nothing.
................................................................................
        {
            try
            {
                if ((_flags & SQLiteConnectionFlags.LogCallbackException) ==
                        SQLiteConnectionFlags.LogCallbackException)
                {
                    SQLiteLog.LogMessage(SQLiteBase.COR_E_EXCEPTION,
                        UnsafeNativeMethods.StringFormat(CultureInfo.CurrentCulture,
                        "Caught exception in \"Final\" method: {1}",
                        e)); /* throw */
                }
            }
            catch
            {
                // do nothing.

Changes to System.Data.SQLite/SQLiteKeyReader.cs.

54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
            {
                _command = cnn.CreateCommand();
                for (int n = 0; n < columns.Length; n++)
                {
                    columns[n] = builder.QuoteIdentifier(columns[n]);
                }
            }
            _command.CommandText = String.Format(CultureInfo.InvariantCulture, "SELECT {0} FROM [{1}].[{2}] WHERE ROWID = ?", String.Join(",", columns), database, table);
            _command.Parameters.AddWithValue(null, (long)0);
        }

        internal bool IsValid
        {
            set
            {







|







54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
            {
                _command = cnn.CreateCommand();
                for (int n = 0; n < columns.Length; n++)
                {
                    columns[n] = builder.QuoteIdentifier(columns[n]);
                }
            }
            _command.CommandText = UnsafeNativeMethods.StringFormat(CultureInfo.InvariantCulture, "SELECT {0} FROM [{1}].[{2}] WHERE ROWID = ?", String.Join(",", columns), database, table);
            _command.Parameters.AddWithValue(null, (long)0);
        }

        internal bool IsValid
        {
            set
            {

Changes to System.Data.SQLite/SQLiteLog.cs.

555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
            {
                type = "trace";
            }

            if ((errorCode != null) &&
                !Object.ReferenceEquals(errorCode, String.Empty))
            {
                Trace.WriteLine(String.Format(
                    CultureInfo.CurrentCulture, "SQLite {0} ({1}): {2}",
                    type, errorCode, message));
            }
            else
            {
                Trace.WriteLine(String.Format(
                    CultureInfo.CurrentCulture, "SQLite {0}: {1}",
                    type, message));
            }
#endif
        }
    }
}







|





|







555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
            {
                type = "trace";
            }

            if ((errorCode != null) &&
                !Object.ReferenceEquals(errorCode, String.Empty))
            {
                Trace.WriteLine(UnsafeNativeMethods.StringFormat(
                    CultureInfo.CurrentCulture, "SQLite {0} ({1}): {2}",
                    type, errorCode, message));
            }
            else
            {
                Trace.WriteLine(UnsafeNativeMethods.StringFormat(
                    CultureInfo.CurrentCulture, "SQLite {0}: {1}",
                    type, message));
            }
#endif
        }
    }
}

Changes to System.Data.SQLite/SQLiteModule.cs.

6163
6164
6165
6166
6167
6168
6169

6170
6171
6172
6173
6174
6175
6176
6177
....
6222
6223
6224
6225
6226
6227
6228

6229
6230
6231
6232
6233
6234
6235
6236
....
6269
6270
6271
6272
6273
6274
6275

6276
6277
6278
6279
6280
6281
6282
6283
....
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
....
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
....
6850
6851
6852
6853
6854
6855
6856


6857
6858
6859
6860
6861
6862
6863
6864
....
8675
8676
8677
8678
8679
8680
8681

8682
8683
8684
8685
8686
8687
8688
8689
                //
                try
                {
                    if (LogExceptionsNoThrow)
                    {
                        /* throw */
                        SQLiteLog.LogMessage(SQLiteBase.COR_E_EXCEPTION,

                            String.Format(CultureInfo.CurrentCulture,
                            "Caught exception in \"{0}\" method: {1}",
                            destroy ? "xDestroy" : "xDisconnect", e));
                    }
                }
                catch
                {
                    // do nothing.
................................................................................
            )
        {
            try
            {
                if (logErrors)
                {
                    SQLiteLog.LogMessage(SQLiteErrorCode.Error,

                        String.Format(CultureInfo.CurrentCulture,
                        "Virtual table error: {0}", error)); /* throw */
                }
            }
            catch
            {
                // do nothing.
            }
................................................................................
            catch (Exception e) /* NOTE: Must catch ALL. */
            {
                try
                {
                    if (logExceptions)
                    {
                        SQLiteLog.LogMessage(SQLiteBase.COR_E_EXCEPTION,

                            String.Format(CultureInfo.CurrentCulture,
                            "Caught exception in \"SetTableError\" method: {0}",
                            e)); /* throw */
                    }
                }
                catch
                {
                    // do nothing.
................................................................................

            if ((tables != null) &&
                tables.TryGetValue(pVtab, out table))
            {
                return table;
            }

            SetTableError(pVtab, String.Format(
                CultureInfo.CurrentCulture,
                "managed table for {0} not found", pVtab));

            return null;
        }

        ///////////////////////////////////////////////////////////////////////
................................................................................

            if ((cursors != null) &&
                cursors.TryGetValue(pCursor, out cursor))
            {
                return cursor;
            }

            SetTableError(pVtab, String.Format(
                CultureInfo.CurrentCulture,
                "managed cursor for {0} not found", pCursor));

            return null;
        }

        ///////////////////////////////////////////////////////////////////////
................................................................................
        /// </returns>
        protected virtual string GetFunctionKey(
            int argumentCount,
            string name,
            SQLiteFunction function
            )
        {


            return String.Format("{0}:{1}", argumentCount, name);
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region Table Declaration Helper Methods
        /// <summary>
................................................................................
                catch (Exception e)
                {
                    try
                    {
                        if (LogExceptionsNoThrow)
                        {
                            SQLiteLog.LogMessage(SQLiteBase.COR_E_EXCEPTION,

                                String.Format(CultureInfo.CurrentCulture,
                                "Caught exception in \"Dispose\" method: {0}",
                                e)); /* throw */
                        }
                    }
                    catch
                    {
                        // do nothing.







>
|







 







>
|







 







>
|







 







|







 







|







 







>
>
|







 







>
|







6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
....
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
....
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
....
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
....
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
....
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
....
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
                //
                try
                {
                    if (LogExceptionsNoThrow)
                    {
                        /* throw */
                        SQLiteLog.LogMessage(SQLiteBase.COR_E_EXCEPTION,
                            UnsafeNativeMethods.StringFormat(
                            CultureInfo.CurrentCulture,
                            "Caught exception in \"{0}\" method: {1}",
                            destroy ? "xDestroy" : "xDisconnect", e));
                    }
                }
                catch
                {
                    // do nothing.
................................................................................
            )
        {
            try
            {
                if (logErrors)
                {
                    SQLiteLog.LogMessage(SQLiteErrorCode.Error,
                        UnsafeNativeMethods.StringFormat(
                        CultureInfo.CurrentCulture,
                        "Virtual table error: {0}", error)); /* throw */
                }
            }
            catch
            {
                // do nothing.
            }
................................................................................
            catch (Exception e) /* NOTE: Must catch ALL. */
            {
                try
                {
                    if (logExceptions)
                    {
                        SQLiteLog.LogMessage(SQLiteBase.COR_E_EXCEPTION,
                            UnsafeNativeMethods.StringFormat(
                            CultureInfo.CurrentCulture,
                            "Caught exception in \"SetTableError\" method: {0}",
                            e)); /* throw */
                    }
                }
                catch
                {
                    // do nothing.
................................................................................

            if ((tables != null) &&
                tables.TryGetValue(pVtab, out table))
            {
                return table;
            }

            SetTableError(pVtab, UnsafeNativeMethods.StringFormat(
                CultureInfo.CurrentCulture,
                "managed table for {0} not found", pVtab));

            return null;
        }

        ///////////////////////////////////////////////////////////////////////
................................................................................

            if ((cursors != null) &&
                cursors.TryGetValue(pCursor, out cursor))
            {
                return cursor;
            }

            SetTableError(pVtab, UnsafeNativeMethods.StringFormat(
                CultureInfo.CurrentCulture,
                "managed cursor for {0} not found", pCursor));

            return null;
        }

        ///////////////////////////////////////////////////////////////////////
................................................................................
        /// </returns>
        protected virtual string GetFunctionKey(
            int argumentCount,
            string name,
            SQLiteFunction function
            )
        {
            return UnsafeNativeMethods.StringFormat(
                CultureInfo.CurrentCulture,
                "{0}:{1}", argumentCount, name);
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region Table Declaration Helper Methods
        /// <summary>
................................................................................
                catch (Exception e)
                {
                    try
                    {
                        if (LogExceptionsNoThrow)
                        {
                            SQLiteLog.LogMessage(SQLiteBase.COR_E_EXCEPTION,
                                UnsafeNativeMethods.StringFormat(
                                CultureInfo.CurrentCulture,
                                "Caught exception in \"Dispose\" method: {0}",
                                e)); /* throw */
                        }
                    }
                    catch
                    {
                        // do nothing.

Changes to System.Data.SQLite/SQLiteModuleCommon.cs.

19
20
21
22
23
24
25
26

27
28
29
30
31
32
33
34
35
...
114
115
116
117
118
119
120
121
122

123
124
125
126
127
128
129
    public class SQLiteModuleCommon : SQLiteModuleNoop /* NOT SEALED */
    {
        #region Private Constants
        /// <summary>
        /// The CREATE TABLE statement used to declare the schema for the
        /// virtual table.
        /// </summary>
        private static readonly string declareSql = String.Format(

            CultureInfo.CurrentCulture, "CREATE TABLE {0}(x);",
            typeof(SQLiteModuleCommon).Name);
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region Private Data
        /// <summary>
        /// Non-zero if different object instances with the same value should
................................................................................
        protected virtual SQLiteErrorCode CursorTypeMismatchError(
            SQLiteVirtualTableCursor cursor,
            Type type
            )
        {
            if (type != null)
            {
                SetCursorError(cursor,
                    String.Format("not a \"{0}\" cursor", type));

            }
            else
            {
                SetCursorError(cursor, "cursor type mismatch");
            }

            return SQLiteErrorCode.Error;







|
>
|
|







 







|
|
>







19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
...
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
    public class SQLiteModuleCommon : SQLiteModuleNoop /* NOT SEALED */
    {
        #region Private Constants
        /// <summary>
        /// The CREATE TABLE statement used to declare the schema for the
        /// virtual table.
        /// </summary>
        private static readonly string declareSql =
            UnsafeNativeMethods.StringFormat(
                CultureInfo.CurrentCulture, "CREATE TABLE {0}(x);",
                typeof(SQLiteModuleCommon).Name);
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region Private Data
        /// <summary>
        /// Non-zero if different object instances with the same value should
................................................................................
        protected virtual SQLiteErrorCode CursorTypeMismatchError(
            SQLiteVirtualTableCursor cursor,
            Type type
            )
        {
            if (type != null)
            {
                SetCursorError(cursor, UnsafeNativeMethods.StringFormat(
                    CultureInfo.CurrentCulture, "not a \"{0}\" cursor",
                    type));
            }
            else
            {
                SetCursorError(cursor, "cursor type mismatch");
            }

            return SQLiteErrorCode.Error;

Changes to System.Data.SQLite/SQLiteModuleEnumerable.cs.

499
500
501
502
503
504
505

506
507
508
509
510
511
512
513
...
826
827
828
829
830
831
832

833
834
835
836
837
838
839
840
...
855
856
857
858
859
860
861

862
863
864
865
866
867
868
869
            SQLiteIndex index
            )
        {
            CheckDisposed();

            if (!table.BestIndex(index))
            {

                SetTableError(table, String.Format(CultureInfo.CurrentCulture,
                    "failed to select best index for virtual table \"{0}\"",
                    table.TableName));

                return SQLiteErrorCode.Error;
            }

            return SQLiteErrorCode.Ok;
................................................................................
            SQLiteVirtualTable table,
            SQLiteValue[] values,
            ref long rowId
            )
        {
            CheckDisposed();


            SetTableError(table, String.Format(CultureInfo.CurrentCulture,
                "virtual table \"{0}\" is read-only", table.TableName));

            return SQLiteErrorCode.Error;
        }

        ///////////////////////////////////////////////////////////////////////

................................................................................
            string newName
            )
        {
            CheckDisposed();

            if (!table.Rename(newName))
            {

                SetTableError(table, String.Format(CultureInfo.CurrentCulture,
                    "failed to rename virtual table from \"{0}\" to \"{1}\"",
                    table.TableName, newName));

                return SQLiteErrorCode.Error;
            }

            return SQLiteErrorCode.Ok;







>
|







 







>
|







 







>
|







499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
...
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
...
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
            SQLiteIndex index
            )
        {
            CheckDisposed();

            if (!table.BestIndex(index))
            {
                SetTableError(table, UnsafeNativeMethods.StringFormat(
                    CultureInfo.CurrentCulture,
                    "failed to select best index for virtual table \"{0}\"",
                    table.TableName));

                return SQLiteErrorCode.Error;
            }

            return SQLiteErrorCode.Ok;
................................................................................
            SQLiteVirtualTable table,
            SQLiteValue[] values,
            ref long rowId
            )
        {
            CheckDisposed();

            SetTableError(table, UnsafeNativeMethods.StringFormat(
                CultureInfo.CurrentCulture,
                "virtual table \"{0}\" is read-only", table.TableName));

            return SQLiteErrorCode.Error;
        }

        ///////////////////////////////////////////////////////////////////////

................................................................................
            string newName
            )
        {
            CheckDisposed();

            if (!table.Rename(newName))
            {
                SetTableError(table, UnsafeNativeMethods.StringFormat(
                    CultureInfo.CurrentCulture,
                    "failed to rename virtual table from \"{0}\" to \"{1}\"",
                    table.TableName, newName));

                return SQLiteErrorCode.Error;
            }

            return SQLiteErrorCode.Ok;

Changes to System.Data.SQLite/SQLiteParameterCollection.cs.

423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
...
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466

      foreach(SQLiteParameter p in _parameterList)
      {
        y ++;
        s = p.ParameterName;
        if (s == null)
        {
          s = String.Format(CultureInfo.InvariantCulture, ";{0}", nUnnamed);
          nUnnamed++;
        }

        int x;
        bool isMapped = false;

        if (activeStatement == null)
................................................................................
          stmt = null;
        }

        // If the parameter has a name, but the SQL statement uses unnamed references, this can happen -- attempt to map
        // the parameter by its index in the collection
        if (isMapped == false)
        {
          s = String.Format(CultureInfo.InvariantCulture, ";{0}", y);

          stmt = activeStatement;
          for (n = 0; n < x; n++)
          {
            if (stmt == null) stmt = _command._statementList[n];
            if (stmt._paramNames != null)
            {







|







 







|







423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
...
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466

      foreach(SQLiteParameter p in _parameterList)
      {
        y ++;
        s = p.ParameterName;
        if (s == null)
        {
          s = UnsafeNativeMethods.StringFormat(CultureInfo.InvariantCulture, ";{0}", nUnnamed);
          nUnnamed++;
        }

        int x;
        bool isMapped = false;

        if (activeStatement == null)
................................................................................
          stmt = null;
        }

        // If the parameter has a name, but the SQL statement uses unnamed references, this can happen -- attempt to map
        // the parameter by its index in the collection
        if (isMapped == false)
        {
          s = UnsafeNativeMethods.StringFormat(CultureInfo.InvariantCulture, ";{0}", y);

          stmt = activeStatement;
          for (n = 0; n < x; n++)
          {
            if (stmt == null) stmt = _command._statementList[n];
            if (stmt._paramNames != null)
            {

Changes to System.Data.SQLite/SQLiteStatement.cs.

1
2
3
4
5
6
7
8
9
10
11
..
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
...
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
...
254
255
256
257
258
259
260
261

262
263
264
265
266
267
268
/********************************************************
 * ADO.NET 2.0 Data Provider for SQLite Version 3.X
 * Written by Robert Simpson (robert@blackcastlesoft.com)
 * 
 * Released to the public domain, use at your own risk!
 ********************************************************/

namespace System.Data.SQLite
{
  using System;
  using System.Globalization;
................................................................................
        _paramValues = new SQLiteParameter[n];

        for (x = 0; x < n; x++)
        {
          s = _sql.Bind_ParamName(this, _flags, x + 1);
          if (String.IsNullOrEmpty(s))
          {
            s = String.Format(CultureInfo.InvariantCulture, ";{0}", nCmdStart);
            nCmdStart++;
            _unnamedParameters++;
          }
          _paramNames[x] = s;
          _paramValues[x] = null;
        }
      }
................................................................................
    /// this statement, and if so, keeps a reference to the parameter so it can be bound later.
    /// </summary>
    /// <param name="s">The parameter name to map</param>
    /// <param name="p">The parameter to assign it</param>
    internal bool MapParameter(string s, SQLiteParameter p)
    {
      if (_paramNames == null) return false;
      
      int startAt = 0;
      if (s.Length > 0)
      {
        if (":$@;".IndexOf(s[0]) == -1)
          startAt = 1;
      }

................................................................................
      if ((obj != null) && (objType == DbType.Object))
          objType = SQLiteConvert.TypeToDbType(obj.GetType());

      if ((_flags & SQLiteConnectionFlags.LogPreBind) == SQLiteConnectionFlags.LogPreBind)
      {
          IntPtr handle = _sqlite_stmt;

          SQLiteLog.LogMessage(String.Format(

              "Binding statement {0} paramter #{1} with database type {2} and raw value {{{3}}}...",
              handle, index, objType, obj));
      }

      if ((obj == null) || Convert.IsDBNull(obj))
      {
          _sql.Bind_Null(this, _flags, index);



|







 







|







 







|







 







|
>







1
2
3
4
5
6
7
8
9
10
11
..
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
...
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
...
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
/********************************************************
 * ADO.NET 2.0 Data Provider for SQLite Version 3.X
 * Written by Robert Simpson (robert@blackcastlesoft.com)
 *
 * Released to the public domain, use at your own risk!
 ********************************************************/

namespace System.Data.SQLite
{
  using System;
  using System.Globalization;
................................................................................
        _paramValues = new SQLiteParameter[n];

        for (x = 0; x < n; x++)
        {
          s = _sql.Bind_ParamName(this, _flags, x + 1);
          if (String.IsNullOrEmpty(s))
          {
            s = UnsafeNativeMethods.StringFormat(CultureInfo.InvariantCulture, ";{0}", nCmdStart);
            nCmdStart++;
            _unnamedParameters++;
          }
          _paramNames[x] = s;
          _paramValues[x] = null;
        }
      }
................................................................................
    /// this statement, and if so, keeps a reference to the parameter so it can be bound later.
    /// </summary>
    /// <param name="s">The parameter name to map</param>
    /// <param name="p">The parameter to assign it</param>
    internal bool MapParameter(string s, SQLiteParameter p)
    {
      if (_paramNames == null) return false;

      int startAt = 0;
      if (s.Length > 0)
      {
        if (":$@;".IndexOf(s[0]) == -1)
          startAt = 1;
      }

................................................................................
      if ((obj != null) && (objType == DbType.Object))
          objType = SQLiteConvert.TypeToDbType(obj.GetType());

      if ((_flags & SQLiteConnectionFlags.LogPreBind) == SQLiteConnectionFlags.LogPreBind)
      {
          IntPtr handle = _sqlite_stmt;

          SQLiteLog.LogMessage(UnsafeNativeMethods.StringFormat(
              CultureInfo.CurrentCulture,
              "Binding statement {0} paramter #{1} with database type {2} and raw value {{{3}}}...",
              handle, index, objType, obj));
      }

      if ((obj == null) || Convert.IsDBNull(obj))
      {
          _sql.Bind_Null(this, _flags, index);

Changes to System.Data.SQLite/UnsafeNativeMethods.cs.

117
118
119
120
121
122
123








































































124
125
126
127
128
129
130
...
297
298
299
300
301
302
303
304

305
306
307
308
309
310
311
312
...
323
324
325
326
327
328
329
330

331
332
333
334
335
336
337
...
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
...
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
...
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
...
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
...
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
...
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
....
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
....
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
....
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
....
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
....
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
....
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
....
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
....
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
      /// <summary>
      /// For now, this method simply calls the Initialize method.
      /// </summary>
      static UnsafeNativeMethods()
      {
          Initialize();
      }









































































      /////////////////////////////////////////////////////////////////////////
      /// <summary>
      /// Attempts to initialize this class by pre-loading the native SQLite
      /// library for the processor architecture of the current process.
      /// </summary>
      internal static void Initialize()
................................................................................
#if !PLATFORM_COMPACTFRAMEWORK
          bool expand = true;

          if (Environment.GetEnvironmentVariable("No_Expand") != null)
          {
              expand = false;
          }
          else if (Environment.GetEnvironmentVariable(String.Format(

                  "No_Expand_{0}", name)) != null)
          {
              expand = false;
          }

          value = Environment.GetEnvironmentVariable(name);

          if (expand && !String.IsNullOrEmpty(value))
................................................................................
              if (fileName == null)
                  return @default;

              XmlDocument document = new XmlDocument();

              document.Load(fileName);

              XmlElement element = document.SelectSingleNode(String.Format(

                  "/configuration/appSettings/add[@key='{0}']", name)) as
                  XmlElement;

              if (element != null)
              {
                  if (element.HasAttribute("value"))
                      value = element.GetAttribute("value");
................................................................................
#else
          catch (Exception)
#endif
          {
#if !NET_COMPACT_20 && TRACE_SHARED
              try
              {
                  Trace.WriteLine(String.Format(
                      CultureInfo.CurrentCulture,
                      "Native library pre-loader failed to get setting " +
                      "\"{0}\" value: {1}", name, e)); /* throw */
              }
              catch
              {
                  // do nothing.
................................................................................
                  directory, XmlConfigFileName);

              if (File.Exists(xmlConfigFileName))
              {
#if !NET_COMPACT_20 && TRACE_DETECTION
                  try
                  {
                      Trace.WriteLine(String.Format(
                          CultureInfo.CurrentCulture,
                          "Native library pre-loader found XML configuration file " +
                          "via code base for currently executing assembly: \"{0}\"",
                          xmlConfigFileName)); /* throw */
                  }
                  catch
                  {
................................................................................
              List<string> matches = null;

              if (CheckForArchitecturesAndPlatforms(directory, ref matches) > 0)
              {
#if !NET_COMPACT_20 && TRACE_DETECTION
                  try
                  {
                      Trace.WriteLine(String.Format(
                          CultureInfo.CurrentCulture,
                          "Native library pre-loader found native sub-directories " +
                          "via code base for currently executing assembly: \"{0}\"",
                          ListToString(matches))); /* throw */
                  }
                  catch
                  {
................................................................................
#else
          catch (Exception)
#endif
          {
#if !NET_COMPACT_20 && TRACE_SHARED
              try
              {
                  Trace.WriteLine(String.Format(
                      CultureInfo.CurrentCulture,
                      "Native library pre-loader failed to check code base " +
                      "for currently executing assembly: {0}", e)); /* throw */
              }
              catch
              {
                  // do nothing.
................................................................................
#else
          catch (Exception)
#endif
          {
#if !NET_COMPACT_20 && TRACE_SHARED
              try
              {
                  Trace.WriteLine(String.Format(
                      CultureInfo.CurrentCulture,
                      "Native library pre-loader failed to get directory " +
                      "for currently executing assembly: {0}", e)); /* throw */
              }
              catch
              {
                  // do nothing.
................................................................................
#if !NET_COMPACT_20 && TRACE_DETECTION
              try
              {
                  //
                  // NOTE: Show that we hit a fairly unusual situation (i.e.
                  //       the "wrong" processor architecture was detected).
                  //
                  Trace.WriteLine(String.Format(
                      CultureInfo.CurrentCulture,
                      "Native library pre-loader detected {0}-bit pointer " +
                      "size with processor architecture \"{1}\", using " +
                      "processor architecture \"{2}\" instead...",
                      IntPtr.Size * 8 /* bits */, savedProcessorArchitecture,
                      processorArchitecture)); /* throw */
              }
................................................................................
#if !NET_COMPACT_20 && TRACE_PRELOAD
              try
              {
                  //
                  // NOTE: Show exactly where we are trying to load the native
                  //       SQLite library from.
                  //
                  Trace.WriteLine(String.Format(
                      CultureInfo.CurrentCulture,
                      "Native library pre-loader is trying to load native " +
                      "SQLite library \"{0}\"...", fileName)); /* throw */
              }
              catch
              {
                  // do nothing.
................................................................................
                  int lastError = Marshal.GetLastWin32Error(); /* throw */

                  //
                  // NOTE: Show where we failed to load the native SQLite
                  //       library from along with the Win32 error code and
                  //       exception information.
                  //
                  Trace.WriteLine(String.Format(
                      CultureInfo.CurrentCulture,
                      "Native library pre-loader failed to load native " +
                      "SQLite library \"{0}\" (getLastError = {1}): {2}",
                      fileName, lastError, e)); /* throw */
              }
              catch
              {
................................................................................
                if (localHandle != IntPtr.Zero)
                    SQLiteBase.CloseConnection(this, localHandle);
#endif

#if !NET_COMPACT_20 && TRACE_HANDLE
                try
                {
                    Trace.WriteLine(String.Format(
                        CultureInfo.CurrentCulture,
                        "CloseConnection: {0}", localHandle)); /* throw */
                }
                catch
                {
                }
#endif
................................................................................
#else
            catch (SQLiteException)
#endif
            {
#if !NET_COMPACT_20 && TRACE_HANDLE
                try
                {
                    Trace.WriteLine(String.Format(
                        CultureInfo.CurrentCulture,
                        "CloseConnection: {0}, exception: {1}",
                        handle, e)); /* throw */
                }
                catch
                {
                }
................................................................................

                if (localHandle != IntPtr.Zero)
                    SQLiteBase.FinalizeStatement(cnn, localHandle);

#if !NET_COMPACT_20 && TRACE_HANDLE
                try
                {
                    Trace.WriteLine(String.Format(
                        CultureInfo.CurrentCulture,
                        "FinalizeStatement: {0}", localHandle)); /* throw */
                }
                catch
                {
                }
#endif
................................................................................
#else
            catch (SQLiteException)
#endif
            {
#if !NET_COMPACT_20 && TRACE_HANDLE
                try
                {
                    Trace.WriteLine(String.Format(
                        CultureInfo.CurrentCulture,
                        "FinalizeStatement: {0}, exception: {1}",
                        handle, e)); /* throw */
                }
                catch
                {
                }
................................................................................

                if (localHandle != IntPtr.Zero)
                    SQLiteBase.FinishBackup(cnn, localHandle);

#if !NET_COMPACT_20 && TRACE_HANDLE
                try
                {
                    Trace.WriteLine(String.Format(
                        CultureInfo.CurrentCulture,
                        "FinishBackup: {0}", localHandle)); /* throw */
                }
                catch
                {
                }
#endif
................................................................................
#else
            catch (SQLiteException)
#endif
            {
#if !NET_COMPACT_20 && TRACE_HANDLE
                try
                {
                    Trace.WriteLine(String.Format(
                        CultureInfo.CurrentCulture,
                        "FinishBackup: {0}, exception: {1}",
                        handle, e)); /* throw */
                }
                catch
                {
                }







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







|
>
|







 







|
>







 







|







 







|







 







|







 







|







 







|







 







|







 







|







 







|







 







|







 







|







 







|







 







|







 







|







 







|







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
...
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
...
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
...
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
...
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
...
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
...
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
...
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
....
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
....
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
....
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
....
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
....
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
....
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
....
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
....
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
....
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
      /// <summary>
      /// For now, this method simply calls the Initialize method.
      /// </summary>
      static UnsafeNativeMethods()
      {
          Initialize();
      }

      /////////////////////////////////////////////////////////////////////////

      /// <summary>
      /// This type is only present when running on Mono.
      /// </summary>
      private static readonly string MonoRuntimeType = "Mono.Runtime";

      /// <summary>
      /// Keeps track of whether we are running on Mono.  Initially null, it is
      /// set by the <see cref="IsMono" /> method on its first call.  Later, it
      /// is returned verbatim.
      /// </summary>
      private static bool? isMono = null;

      /// <summary>
      /// Determines whether or not this assembly is running on Mono.
      /// </summary>
      /// <returns>
      /// Non-zero if this assembly is running on Mono.
      /// </returns>
      private static bool IsMono()
      {
          try
          {
              lock (staticSyncRoot)
              {
                  if (isMono == null)
                      isMono = (Type.GetType(MonoRuntimeType) != null);

                  return (bool)isMono;
              }
          }
          catch
          {
              // do nothing.
          }

          return false;
      }

      /////////////////////////////////////////////////////////////////////////

      /// <summary>
      /// This is a wrapper around the
      /// <see cref="String.Format(IFormatProvider,String,Object[])" /> method.
      /// On Mono, it has to call the method overload without the
      /// <see cref="IFormatProvider" /> parameter, due to a bug in Mono.
      /// </summary>
      /// <param name="provider">
      /// This is used for culture-specific formatting.
      /// </param>
      /// <param name="format">
      /// The format string.
      /// </param>
      /// <param name="args">
      /// An array the objects to format.
      /// </param>
      /// <returns>
      /// The resulting string.
      /// </returns>
      internal static string StringFormat(
          IFormatProvider provider,
          string format,
          params object[] args
          )
      {
          if (IsMono())
              return String.Format(format, args);
          else
              return String.Format(provider, format, args);
      }

      /////////////////////////////////////////////////////////////////////////
      /// <summary>
      /// Attempts to initialize this class by pre-loading the native SQLite
      /// library for the processor architecture of the current process.
      /// </summary>
      internal static void Initialize()
................................................................................
#if !PLATFORM_COMPACTFRAMEWORK
          bool expand = true;

          if (Environment.GetEnvironmentVariable("No_Expand") != null)
          {
              expand = false;
          }
          else if (Environment.GetEnvironmentVariable(StringFormat(
                  CultureInfo.InvariantCulture, "No_Expand_{0}",
                  name)) != null)
          {
              expand = false;
          }

          value = Environment.GetEnvironmentVariable(name);

          if (expand && !String.IsNullOrEmpty(value))
................................................................................
              if (fileName == null)
                  return @default;

              XmlDocument document = new XmlDocument();

              document.Load(fileName);

              XmlElement element = document.SelectSingleNode(StringFormat(
                  CultureInfo.InvariantCulture,
                  "/configuration/appSettings/add[@key='{0}']", name)) as
                  XmlElement;

              if (element != null)
              {
                  if (element.HasAttribute("value"))
                      value = element.GetAttribute("value");
................................................................................
#else
          catch (Exception)
#endif
          {
#if !NET_COMPACT_20 && TRACE_SHARED
              try
              {
                  Trace.WriteLine(StringFormat(
                      CultureInfo.CurrentCulture,
                      "Native library pre-loader failed to get setting " +
                      "\"{0}\" value: {1}", name, e)); /* throw */
              }
              catch
              {
                  // do nothing.
................................................................................
                  directory, XmlConfigFileName);

              if (File.Exists(xmlConfigFileName))
              {
#if !NET_COMPACT_20 && TRACE_DETECTION
                  try
                  {
                      Trace.WriteLine(StringFormat(
                          CultureInfo.CurrentCulture,
                          "Native library pre-loader found XML configuration file " +
                          "via code base for currently executing assembly: \"{0}\"",
                          xmlConfigFileName)); /* throw */
                  }
                  catch
                  {
................................................................................
              List<string> matches = null;

              if (CheckForArchitecturesAndPlatforms(directory, ref matches) > 0)
              {
#if !NET_COMPACT_20 && TRACE_DETECTION
                  try
                  {
                      Trace.WriteLine(StringFormat(
                          CultureInfo.CurrentCulture,
                          "Native library pre-loader found native sub-directories " +
                          "via code base for currently executing assembly: \"{0}\"",
                          ListToString(matches))); /* throw */
                  }
                  catch
                  {
................................................................................
#else
          catch (Exception)
#endif
          {
#if !NET_COMPACT_20 && TRACE_SHARED
              try
              {
                  Trace.WriteLine(StringFormat(
                      CultureInfo.CurrentCulture,
                      "Native library pre-loader failed to check code base " +
                      "for currently executing assembly: {0}", e)); /* throw */
              }
              catch
              {
                  // do nothing.
................................................................................
#else
          catch (Exception)
#endif
          {
#if !NET_COMPACT_20 && TRACE_SHARED
              try
              {
                  Trace.WriteLine(StringFormat(
                      CultureInfo.CurrentCulture,
                      "Native library pre-loader failed to get directory " +
                      "for currently executing assembly: {0}", e)); /* throw */
              }
              catch
              {
                  // do nothing.
................................................................................
#if !NET_COMPACT_20 && TRACE_DETECTION
              try
              {
                  //
                  // NOTE: Show that we hit a fairly unusual situation (i.e.
                  //       the "wrong" processor architecture was detected).
                  //
                  Trace.WriteLine(StringFormat(
                      CultureInfo.CurrentCulture,
                      "Native library pre-loader detected {0}-bit pointer " +
                      "size with processor architecture \"{1}\", using " +
                      "processor architecture \"{2}\" instead...",
                      IntPtr.Size * 8 /* bits */, savedProcessorArchitecture,
                      processorArchitecture)); /* throw */
              }
................................................................................
#if !NET_COMPACT_20 && TRACE_PRELOAD
              try
              {
                  //
                  // NOTE: Show exactly where we are trying to load the native
                  //       SQLite library from.
                  //
                  Trace.WriteLine(StringFormat(
                      CultureInfo.CurrentCulture,
                      "Native library pre-loader is trying to load native " +
                      "SQLite library \"{0}\"...", fileName)); /* throw */
              }
              catch
              {
                  // do nothing.
................................................................................
                  int lastError = Marshal.GetLastWin32Error(); /* throw */

                  //
                  // NOTE: Show where we failed to load the native SQLite
                  //       library from along with the Win32 error code and
                  //       exception information.
                  //
                  Trace.WriteLine(StringFormat(
                      CultureInfo.CurrentCulture,
                      "Native library pre-loader failed to load native " +
                      "SQLite library \"{0}\" (getLastError = {1}): {2}",
                      fileName, lastError, e)); /* throw */
              }
              catch
              {
................................................................................
                if (localHandle != IntPtr.Zero)
                    SQLiteBase.CloseConnection(this, localHandle);
#endif

#if !NET_COMPACT_20 && TRACE_HANDLE
                try
                {
                    Trace.WriteLine(StringFormat(
                        CultureInfo.CurrentCulture,
                        "CloseConnection: {0}", localHandle)); /* throw */
                }
                catch
                {
                }
#endif
................................................................................
#else
            catch (SQLiteException)
#endif
            {
#if !NET_COMPACT_20 && TRACE_HANDLE
                try
                {
                    Trace.WriteLine(StringFormat(
                        CultureInfo.CurrentCulture,
                        "CloseConnection: {0}, exception: {1}",
                        handle, e)); /* throw */
                }
                catch
                {
                }
................................................................................

                if (localHandle != IntPtr.Zero)
                    SQLiteBase.FinalizeStatement(cnn, localHandle);

#if !NET_COMPACT_20 && TRACE_HANDLE
                try
                {
                    Trace.WriteLine(StringFormat(
                        CultureInfo.CurrentCulture,
                        "FinalizeStatement: {0}", localHandle)); /* throw */
                }
                catch
                {
                }
#endif
................................................................................
#else
            catch (SQLiteException)
#endif
            {
#if !NET_COMPACT_20 && TRACE_HANDLE
                try
                {
                    Trace.WriteLine(StringFormat(
                        CultureInfo.CurrentCulture,
                        "FinalizeStatement: {0}, exception: {1}",
                        handle, e)); /* throw */
                }
                catch
                {
                }
................................................................................

                if (localHandle != IntPtr.Zero)
                    SQLiteBase.FinishBackup(cnn, localHandle);

#if !NET_COMPACT_20 && TRACE_HANDLE
                try
                {
                    Trace.WriteLine(StringFormat(
                        CultureInfo.CurrentCulture,
                        "FinishBackup: {0}", localHandle)); /* throw */
                }
                catch
                {
                }
#endif
................................................................................
#else
            catch (SQLiteException)
#endif
            {
#if !NET_COMPACT_20 && TRACE_HANDLE
                try
                {
                    Trace.WriteLine(StringFormat(
                        CultureInfo.CurrentCulture,
                        "FinishBackup: {0}, exception: {1}",
                        handle, e)); /* throw */
                }
                catch
                {
                }