[aa38ec]: test / TestCases.cs Maximize Restore History

Download this file

TestCases.cs    2058 lines (1800 with data), 70.4 kB

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
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
1471
1472
1473
1474
1475
1476
1477
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
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
using System;
using System.Data.Common;
using System.Data;
using System.Data.SQLite;
using System.Transactions;
using System.Collections.Generic;
using System.Text;
namespace test
{
internal class TestCases : TestCaseBase
{
private List<string> droptables = new List<string>();
private List<string> maydroptable = new List<string>();
internal TestCases()
{
}
internal TestCases(DbProviderFactory factory, string connectionString)
: base(factory, connectionString)
{
}
/// <summary>
/// Inserts binary data into the database using a named parameter
/// </summary>
internal void BinaryInsert()
{
using (DbCommand cmd = _cnn.CreateCommand())
{
cmd.CommandText = "INSERT INTO TestCase(Field6) VALUES(@bin)";
DbParameter Field6 = cmd.CreateParameter();
byte[] b = new byte[4000];
b[0] = 1;
b[100] = 2;
b[1000] = 3;
b[2000] = 4;
b[3000] = 5;
Field6.ParameterName = "@bin";
Field6.Value = b;
cmd.Parameters.Add(Field6);
cmd.ExecuteNonQuery();
}
}
internal void CheckLocked()
{
// Lets make sure the database isn't locked. If it is, we've failed.
using (DbConnection newcnn = ((ICloneable)_cnn).Clone() as DbConnection)
using (DbCommand cmd = newcnn.CreateCommand())
{
if (newcnn.State != ConnectionState.Open) newcnn.Open();
cmd.CommandText = "INSERT INTO TestCase (Field1) SELECT 1 WHERE 1 = 2";
cmd.ExecuteNonQuery();
}
}
internal void CheckSQLite()
{
if (_fact.GetType().Name.IndexOf("SQLite", StringComparison.OrdinalIgnoreCase) == -1)
throw new InconclusiveException("Not a SQLite database");
}
[Test(Sequence=1)]
internal string VersionTest()
{
CheckSQLite();
string[] version = _cnn.ServerVersion.Split('.');
if (Convert.ToInt32(version[0]) < 3
|| (Convert.ToInt32(version[0]) == 3 && Convert.ToInt32(version[1]) < 6)
|| (Convert.ToInt32(version[1]) == 6 && Convert.ToInt32(version[2]) < 1)
) throw new Exception(String.Format("SQLite Engine is {0}. Minimum supported version is 3.6.1", _cnn.ServerVersion));
return String.Format("SQLite Engine is {0}", _cnn.ServerVersion);
}
//[Test(Sequence = 1)]
internal void ParseTest()
{
DataTable tbl = _cnn.GetSchema("ViewColumns");
DataTable tbl2 = _cnn.GetSchema("Views");
using (DbCommand cmd = _cnn.CreateCommand())
{
cmd.Parameters.Add(cmd.CreateParameter());
cmd.Parameters[0].Value = 1;
cmd.Parameters.Add(cmd.CreateParameter());
cmd.Parameters[1].Value = 1;
cmd.CommandText = "select * from sqlite_master limit ? offset ?";
object obj = cmd.ExecuteScalar();
cmd.CommandText = @"
CREATE TEMP TABLE A(ID INTEGER, BID INTEGER);CREATE TEMP TABLE B(ID INTEGER, MYVAL VARCHAR);
INSERT INTO A (ID, BID) VALUES(2, 1);
INSERT INTO B (ID, MYVAL) VALUES(1,'TEST');
";
cmd.ExecuteNonQuery();
cmd.CommandText = "select *, (select 1 as c from b where b.id = a.bid) from a;";
using (DbDataReader reader = cmd.ExecuteReader())
{
reader.Read();
}
cmd.CommandText = "select a.id as aa from a where (select 1 from (select 1 where 1 = aa));";
using (DbDataReader reader = cmd.ExecuteReader())
{
reader.Read();
}
cmd.CommandText = "select *, (select count(c) from (select 1 as c from b where b.id = a.bid)) from a;";
using (DbDataReader reader = cmd.ExecuteReader())
{
reader.Read();
}
}
}
[Test(Sequence = 39)]
internal void MultipleFunctions()
{
CheckSQLite();
using (DbCommand cmd = _cnn.CreateCommand())
{
cmd.CommandText = "SELECT MYCOUNT(Field1), MYCOUNT(Field2) FROM TestCase";
using (DbDataReader reader = cmd.ExecuteReader())
{
reader.Read();
}
}
}
[Test(Sequence = 8)]
internal void FunctionWithCollation()
{
CheckSQLite();
using (DbCommand cmd = _cnn.CreateCommand())
{
cmd.CommandText = "SELECT CHARINDEX('pat', 'thepat'), CHARINDEX('pat', 'THEPAT'), CHARINDEX('pat' COLLATE NOCASE, 'THEPAT' COLLATE NOCASE)";
using (DbDataReader reader = cmd.ExecuteReader())
{
reader.Read();
if (reader.GetInt64(0) != reader.GetInt64(2) || reader.GetInt64(1) != 0 || reader.GetInt64(0) != 4)
throw new Exception("CharIndex returned wrong results!");
}
}
}
[Test(Sequence = 9)]
internal void FunctionWithCollation2()
{
CheckSQLite();
using (DbCommand cmd = _cnn.CreateCommand())
{
cmd.CommandText = "SELECT CASETEST('pat', 'pat'), CASETEST('pat', 'PAT'), CASETEST('pat' COLLATE NOCASE, 'PAT' COLLATE NOCASE), CASETEST('pat' COLLATE MYSEQUENCE, 'PAT' COLLATE MYSEQUENCE), CASETEST('tap', 'TAP' COLLATE NOCASE)";
using (DbDataReader reader = cmd.ExecuteReader())
{
reader.Read();
if (reader.GetInt64(0) != reader.GetInt64(2) || reader.GetInt64(1) != 1 || reader.GetInt64(0) != 0)
throw new Exception("CharIndex returned wrong results!");
}
}
}
[Test]
internal void DataTypesSchema()
{
using (DataTable tbl = _cnn.GetSchema("DataTypes"))
{
}
}
/// <summary>
/// Make sure our implementation of ClearPool() behaves exactly as the SqlClient version is documented to behave.
/// </summary>
[Test(Sequence=90)]
internal void ClearPoolTest()
{
string table = "clearpool";
string temp = "TEMP";
if (_fact.GetType().Name.IndexOf("SQLite", StringComparison.OrdinalIgnoreCase) == -1)
{
temp = String.Empty;
table = "#clearpool";
}
object value;
if (_cnnstring.TryGetValue("Pooling", out value) == false) throw new Exception("Pooling not present in connection string");
if ((bool)value == false) throw new InconclusiveException("Pooling not enabled in the connection string");
string sql = String.Format("CREATE {0} TABLE {1}(id int primary key);", temp, table);
using (DbCommand cmd = _cnn.CreateCommand())
{
// Create a temp table in the main connection so we can confirm our new connections are using true new connections
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
}
for (int n = 0; n < 10; n++)
{
using (DbConnection newcnn = ((ICloneable)_cnn).Clone() as DbConnection)
{
if (newcnn.State != ConnectionState.Open) newcnn.Open();
using (DbCommand cmd = newcnn.CreateCommand())
{
// If the pool is properly implemented and the pooled connection properly destroyed, this command will succeed.
// If the new connection was obtained from the pool even after we cleared it, then this table will already exist
// and the test fails.
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
}
// Try and clear the pool associated with this file
newcnn.GetType().InvokeMember("ClearPool", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.InvokeMethod | System.Reflection.BindingFlags.Public, null, null, new object[] { newcnn });
// At this point when the connection is destroyed, it should not be returned to the pool, but instead disposed.
}
}
}
/// <summary>
/// This tests ClearAllPools() functionality. Makes sure that the pool is working properly and clearing properly.
/// </summary>
[Test(Sequence = 100)]
internal void ClearAllPoolsTest()
{
string table = "clearpool";
string temp = "TEMP";
string exists = " IF NOT EXISTS ";
if (_fact.GetType().Name.IndexOf("SQLite", StringComparison.OrdinalIgnoreCase) == -1)
{
temp = String.Empty;
exists = String.Empty;
table = "#clearpool";
}
object value;
if (_cnnstring.TryGetValue("Pooling", out value) == false) throw new Exception("Pooling not present in connection string");
if ((bool)value == false) throw new InconclusiveException("Pooling not enabled in the connection string");
string sql = String.Format("CREATE {0} TABLE {2}{1}(id int primary key);", temp, table, exists);
_cnn.GetType().InvokeMember("ClearAllPools", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.InvokeMethod | System.Reflection.BindingFlags.Public, null, null, null);
DbConnection[] arr = new DbConnection[10];
try
{
// Create 10 connections and create temporary tables on them
for (int n = 0; n < 10; n++)
{
arr[n] = ((ICloneable)_cnn).Clone() as DbConnection;
if (arr[n].State != ConnectionState.Open) arr[n].Open();
using (DbCommand cmd = arr[n].CreateCommand())
{
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
cmd.CommandText = String.Format("INSERT INTO {1} (id) VALUES({0})", n, table);
cmd.ExecuteNonQuery();
}
switch (n)
{
case 2: // Put this one back into the pool
arr[n].Dispose();
arr[n] = null;
break;
case 4:
// Clear all the pools
_cnn.GetType().InvokeMember("ClearAllPools", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.InvokeMethod | System.Reflection.BindingFlags.Public, null, null, null);
break;
}
}
// Now close all the connections. Only the last 5 should go into the pool
for (int n = 0; n < 10; n++)
{
if (arr[n] != null)
{
arr[n].Dispose();
arr[n] = null;
}
}
// Open 10 connections. They should either have a clearpool containing an id of 5 or greater,
// or should have no clearpool table at all.
for (int n = 0; n < 10; n++)
{
arr[n] = ((ICloneable)_cnn).Clone() as DbConnection;
if (arr[n].State != ConnectionState.Open) arr[n].Open();
using (DbCommand cmd = arr[n].CreateCommand())
{
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
cmd.CommandText = String.Format("SELECT [id] FROM {0}", table);
object o = cmd.ExecuteScalar();
if (o == null || o == DBNull.Value)
continue; // No data in the table at all, which means we must've just created it -- connection wasn't part of the pool
if (Convert.ToInt32(o) < 5)
throw new Exception("Unexpected data returned from table!");
}
}
// Clear all the pools
_cnn.GetType().InvokeMember("ClearAllPools", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.InvokeMethod | System.Reflection.BindingFlags.Public, null, null, null);
}
finally
{
// Close all the connections
for (int n = 0; n < 10; n++)
{
if (arr[n] != null)
{
arr[n].Dispose();
arr[n] = null;
}
}
// Clear all the pools
_cnn.GetType().InvokeMember("ClearAllPools", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.InvokeMethod | System.Reflection.BindingFlags.Public, null, null, null);
}
}
[Test(Sequence = 50)]
internal void CoersionTest()
{
using (DbCommand cmd = _cnn.CreateCommand())
{
cmd.CommandText = "SELECT Field1, Field2, [Fiëld3], [Fiæld4], Field5, 'A', 1, 1 + 1, 3.14159 FROM TestCase";
using (DbDataReader rd = cmd.ExecuteReader())
{
if (rd.Read())
{
object Field1 = rd.GetInt32(0);
object Field2 = rd.GetDouble(1);
object Field3 = rd.GetString(2);
object Field4 = rd.GetString(3).TrimEnd();
object Field5 = rd.GetDateTime(4);
// The next statement should cause an exception
try
{
Field1 = rd.GetString(0);
throw new Exception("Should have failed type checking!");
}
catch (InvalidCastException)
{
}
try
{
Field2 = rd.GetString(1);
throw new Exception("Should have failed type checking!");
}
catch (InvalidCastException)
{
}
Field3 = rd.GetString(2);
Field4 = rd.GetString(3);
Field1 = rd.GetInt32(0);
try
{
Field2 = rd.GetInt32(1);
throw new Exception("Should have failed type checking!");
}
catch (InvalidCastException)
{
}
try
{
Field3 = rd.GetInt32(2);
throw new Exception("Should have failed type checking!");
}
catch (InvalidCastException)
{
}
try
{
Field4 = rd.GetInt32(3);
throw new Exception("Should have failed type checking!");
}
catch (InvalidCastException)
{
}
try
{
Field5 = rd.GetInt32(4);
throw new Exception("Should have failed type checking!");
}
catch (InvalidCastException)
{
}
try
{
Field3 = rd.GetDecimal(2);
throw new Exception("Should have failed type checking!");
}
catch (InvalidCastException)
{
}
catch (FormatException)
{
}
try
{
Field4 = rd.GetDecimal(3);
throw new Exception("Should have failed type checking!");
}
catch (InvalidCastException)
{
}
catch (FormatException)
{
}
try
{
Field5 = rd.GetDecimal(4);
throw new Exception("Should have failed type checking!");
}
catch (InvalidCastException)
{
}
catch (FormatException)
{
}
}
else throw new Exception("No data in table");
}
}
}
[Test(Sequence = 10)]
internal void CreateTable()
{
droptables.Add("TestCase");
using (DbCommand cmd = _cnn.CreateCommand())
{
if (_fact.GetType().Name.IndexOf("SQLite", StringComparison.OrdinalIgnoreCase) == -1)
cmd.CommandText = "CREATE TABLE TestCase (ID bigint primary key identity, Field1 integer, Field2 Float, [Fiëld3] VARCHAR(50), [Fiæld4] CHAR(10), Field5 DateTime, Field6 Image)";
else
cmd.CommandText = "CREATE TABLE TestCase (ID integer primary key autoincrement, Field1 int, Field2 Float, [Fiëld3] VARCHAR(50), [Fiæld4] CHAR(10), Field5 DateTime, Field6 Image)";
cmd.ExecuteNonQuery();
}
}
[Test(Sequence = 1100)]
internal string DataAdapterTest()
{
return DataAdapter(false);
}
[Test(Sequence = 1200)]
internal string DataAdapterWithIdentityFetch()
{
return DataAdapter(true);
}
/// <summary>
/// Utilizes the SQLiteCommandBuilder,
/// which in turn utilizes SQLiteDataReader's GetSchemaTable() functionality
/// This insert is slow because it must raise callbacks before and after every update.
/// For a fast update, see the FastInsertMany function beneath this one
/// </summary>
internal string DataAdapter(bool bWithIdentity)
{
StringBuilder builder = new StringBuilder();
using (DbTransaction dbTrans = _cnn.BeginTransaction())
{
using (DbDataAdapter adp = _fact.CreateDataAdapter())
{
using (DbCommand cmd = _cnn.CreateCommand())
{
cmd.Transaction = dbTrans;
cmd.CommandText = "SELECT * FROM TestCase WHERE 1 = 2";
adp.SelectCommand = cmd;
using (DbCommandBuilder bld = _fact.CreateCommandBuilder())
{
bld.DataAdapter = adp;
using (adp.InsertCommand = (DbCommand)((ICloneable)bld.GetInsertCommand()).Clone())
{
if (bWithIdentity)
{
if (_fact.GetType().Name.IndexOf("SQLite", StringComparison.OrdinalIgnoreCase) == -1)
adp.InsertCommand.CommandText += ";SELECT SCOPE_IDENTITY() AS [ID]";
else
adp.InsertCommand.CommandText += ";SELECT last_insert_rowid() AS [ID]";
adp.InsertCommand.UpdatedRowSource = UpdateRowSource.FirstReturnedRecord;
}
bld.DataAdapter = null;
using (DataTable tbl = new DataTable())
{
adp.Fill(tbl);
for (int n = 0; n < 10000; n++)
{
DataRow row = tbl.NewRow();
row[1] = n + (50000 * ((bWithIdentity == true) ? 2 : 1));
tbl.Rows.Add(row);
}
//Console.WriteLine(String.Format(" Inserting using CommandBuilder and DataAdapter\r\n ->{0} (10,000 rows) ...", (bWithIdentity == true) ? "(with identity fetch)" : ""));
int dtStart = Environment.TickCount;
adp.Update(tbl);
int dtEnd = Environment.TickCount;
dtEnd -= dtStart;
builder.AppendFormat("Insert Ends in {0} ms ... ", (dtEnd));
dtStart = Environment.TickCount;
dbTrans.Commit();
dtEnd = Environment.TickCount;
dtEnd -= dtStart;
builder.AppendFormat("Commits in {0} ms", (dtEnd));
if (bWithIdentity)
{
using (DataTable tbl2 = new DataTable())
{
adp.SelectCommand.CommandText = "SELECT * FROM TestCase WHERE Field1 BETWEEN 100000 AND 199999 ORDER BY Field1";
adp.Fill(tbl2);
if (tbl2.Rows.Count != tbl.Rows.Count) throw new Exception("Selected data doesn't match updated data!");
for (int n = 0; n < tbl.Rows.Count; n++)
{
if (tbl.Rows[n][0].Equals(tbl2.Rows[n][0]) == false)
throw new Exception("Fetched identity doesn't match selected identity!");
}
}
}
}
}
}
}
}
}
return builder.ToString();
}
/// <summary>
/// Make sure a datareader can run even if the parent command is disposed, and that the connection is closed
/// by the datareader when it is finished.
/// </summary>
[Test]
internal void DataReaderCleanup()
{
DbConnection newcnn = ((ICloneable)_cnn).Clone() as DbConnection;
DbCommand cmd = newcnn.CreateCommand();
try
{
if (newcnn.State != ConnectionState.Open)
newcnn.Open();
cmd.CommandText = "SELECT 1, 2, 3";
using (DbDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection))
{
cmd.Dispose(); // Dispose of the command while an open reader is active ... should still be able to read
try
{
reader.Read();
}
catch
{
throw new Exception("Unable to read from a DataReader!");
}
if (reader.GetInt32(0) != 1 || reader.GetInt32(1) != 2 || reader.GetInt32(2) != 3)
throw new Exception("Unexpected return values from reader!");
reader.Close(); // Close the reader, and check if the connection is closed
if (newcnn.State != ConnectionState.Closed)
throw new Exception("DataReader failed to cleanup!");
}
}
finally
{
cmd.Dispose();
newcnn.Dispose();
}
}
[Test]
internal void DataTypeTest()
{
DateTime now = DateTime.Now;
using (DbCommand cmd = _cnn.CreateCommand())
{
droptables.Add("datatypetest");
if (_fact.GetType().Name.IndexOf("SQLite", StringComparison.OrdinalIgnoreCase) == -1)
cmd.CommandText = "create table datatypetest(id bigint identity primary key, myvalue sql_variant, datetimevalue datetime, decimalvalue decimal(38,18))";
else
cmd.CommandText = "create table datatypetest(id integer primary key, myvalue sql_variant, datetimevalue datetime, decimalvalue decimal(38,18))";
cmd.ExecuteNonQuery();
System.Globalization.CultureInfo oldculture = System.Threading.Thread.CurrentThread.CurrentCulture;
System.Globalization.CultureInfo olduiculture = System.Threading.Thread.CurrentThread.CurrentUICulture;
// Insert using a different current culture
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("es-ES");
System.Threading.Thread.CurrentThread.CurrentUICulture = System.Threading.Thread.CurrentThread.CurrentCulture;
try
{
cmd.CommandText = "insert into datatypetest(myvalue, datetimevalue, decimalvalue) values(@p1,@p2,@p3)";
DbParameter p1 = cmd.CreateParameter();
DbParameter p2 = cmd.CreateParameter();
DbParameter p3 = cmd.CreateParameter();
cmd.Parameters.Add(p1);
cmd.Parameters.Add(p2);
cmd.Parameters.Add(p3);
p1.ParameterName = "@p1";
p2.ParameterName = "@p2";
p3.ParameterName = "@p3";
p1.Value = (long)1;
p2.Value = new DateTime(1753, 1, 1);
p3.Value = (Decimal)1.05;
cmd.ExecuteNonQuery();
p1.ResetDbType();
p2.ResetDbType();
p3.ResetDbType();
p1.Value = "One";
p2.Value = "2001-01-01";
p3.Value = (Decimal)1.0;
cmd.ExecuteNonQuery();
p1.ResetDbType();
p2.ResetDbType();
p3.ResetDbType();
p1.Value = 1.01;
p2.Value = now;
p3.Value = (Decimal)9.91;
cmd.ExecuteNonQuery();
// Read using a different current culture
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
System.Threading.Thread.CurrentThread.CurrentUICulture = System.Threading.Thread.CurrentThread.CurrentCulture;
cmd.CommandText = "select myvalue, datetimevalue, decimalvalue from datatypetest";
cmd.Parameters.Clear();
using (DbDataReader reader = cmd.ExecuteReader())
{
for (int n = 0; n < 3; n++)
{
reader.Read();
if (reader.GetValue(1).GetType() != reader.GetDateTime(1).GetType()) throw new Exception("DateTime type non-match");
if (reader.GetValue(2).GetType() != reader.GetDecimal(2).GetType()) throw new Exception("Decimal type non-match");
switch (n)
{
case 0:
if (reader.GetValue(0).GetType() != typeof(long)) throw new Exception("long type non-match");
if (reader.GetValue(0).Equals((long)1) == false) throw new Exception("long value non-match");
if (reader.GetValue(1).Equals(new DateTime(1753, 1, 1)) == false) throw new Exception(String.Format("DateTime value non-match expected {0} got {1}", new DateTime(1753, 1, 1), reader.GetValue(1)));
if (reader.GetValue(2).Equals((Decimal)1.05) == false) throw new Exception("Decimal value non-match");
if (reader.GetValue(0).Equals(reader.GetInt64(0)) == false) throw new Exception(String.Format("long value failed to match itself, {0} and {1}", reader.GetValue(0), reader.GetInt64(0)));
if (reader.GetValue(1).Equals(reader.GetDateTime(1)) == false) throw new Exception(String.Format("DateTime failed to match itself {0} and {1}", reader.GetValue(1), reader.GetDateTime(1)));
if (reader.GetValue(2).Equals(reader.GetDecimal(2)) == false) throw new Exception(String.Format("Decimal failed to match itself {0} and {1}", reader.GetValue(2), reader.GetDecimal(2)));
break;
case 1:
if (reader.GetValue(0).GetType() != typeof(string)) throw new Exception("String type non-match");
if (reader.GetValue(0).Equals("One") == false) throw new Exception("String value non-match");
if (reader.GetValue(1).Equals(new DateTime(2001, 1, 1)) == false) throw new Exception(String.Format("DateTime value non-match expected {0} got {1}", new DateTime(2001, 1, 1), reader.GetValue(1)));
if (reader.GetValue(2).Equals((Decimal)1.0) == false) throw new Exception("Decimal value non-match");
if (reader.GetString(0) != "One") throw new Exception("String value non-match");
if (reader.GetValue(1).Equals(reader.GetDateTime(1)) == false) throw new Exception(String.Format("DateTime failed to match itself {0} and {1}", reader.GetValue(1), reader.GetDateTime(1)));
if (reader.GetValue(2).Equals(reader.GetDecimal(2)) == false) throw new Exception(String.Format("Decimal failed to match itself {0} and {1}", reader.GetValue(2), reader.GetDecimal(2)));
break;
case 2:
if (reader.GetValue(0).GetType() != typeof(double)) throw new Exception("Double type non-match");
if (reader.GetValue(0).Equals(1.01) == false) throw new Exception("Double value non-match");
if (reader.GetValue(1).ToString() != now.ToString()) throw new Exception(String.Format("DateTime value non-match, expected {0} got {1}", now, reader.GetValue(1)));
if (reader.GetValue(2).Equals((Decimal)9.91) == false) throw new Exception("Decimal value non-match");
if (reader.GetDouble(0) != 1.01) throw new Exception("Double value non-match");
if (reader.GetValue(1).Equals(reader.GetDateTime(1)) == false) throw new Exception(String.Format("DateTime failed to match itself {0} and {1}", reader.GetValue(1), reader.GetDateTime(1)));
if (reader.GetValue(2).Equals(reader.GetDecimal(2)) == false) throw new Exception(String.Format("Decimal failed to match itself {0} and {1}", reader.GetValue(2), reader.GetDecimal(2)));
break;
}
}
}
}
finally
{
System.Threading.Thread.CurrentThread.CurrentCulture = oldculture;
System.Threading.Thread.CurrentThread.CurrentUICulture = olduiculture;
}
}
}
/// <summary>
/// This is an mean ugly test that leaves a lot of open datareaders out on many connections
/// to see if the database can survive being cloned a lot and disposed while active readers are up.
/// </summary>
[Test(Sequence = 40)]
internal void LeakyDataReaders()
{
try
{
{
DbConnection newcnn = null;
try
{
for (int x = 0; x < 10000; x++)
{
if (newcnn == null)
{
newcnn = ((ICloneable)_cnn).Clone() as DbConnection;
}
if (newcnn.State != ConnectionState.Open)
newcnn.Open();
DbCommand cmd = newcnn.CreateCommand();
cmd.CommandText = "SELECT * FROM TestCase";
DbDataReader reader = cmd.ExecuteReader();
reader.Read();
object obj = reader[0];
if (x % 500 == 0)
{
newcnn.Close();
newcnn = null;
}
}
}
finally
{
if (newcnn != null)
newcnn.Close();
newcnn = null;
}
}
CheckLocked();
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine(e.Message);
}
}
[Test(Sequence = int.MaxValue)]
internal void DropTable()
{
DropTables(true);
}
internal void DropTables(bool throwError)
{
//string[] arr = new string[] { "TestCase", "datatypetest", "MultiThreadedTest", "fulltext", "guidtest", "keyinfotest", "stepreader", "nonexistent" };
string errors = String.Empty;
using (DbCommand cmd = _cnn.CreateCommand())
{
foreach(string table in droptables)
{
try
{
cmd.CommandText = String.Format("DROP TABLE{1} [{0}]", table, (throwError == false) ? " IF EXISTS" : "");
cmd.ExecuteNonQuery();
}
catch (Exception e)
{
if (throwError == true)
errors += String.Format("{0}\r\n", e.Message);
}
}
foreach (string table in maydroptable)
{
try
{
cmd.CommandText = String.Format("DROP TABLE{1} [{0}]", table, (throwError == false) ? " IF EXISTS" : "");
cmd.ExecuteNonQuery();
}
catch (Exception)
{
}
}
}
if (String.IsNullOrEmpty(errors) == false)
throw new Exception(errors);
}
[Test(Sequence = 1000)]
internal string FastInsertMany()
{
StringBuilder builder = new StringBuilder();
using (DbTransaction dbTrans = _cnn.BeginTransaction())
{
int dtStart;
int dtEnd;
using (DbCommand cmd = _cnn.CreateCommand())
{
cmd.Transaction = dbTrans;
cmd.CommandText = "INSERT INTO TestCase(Field1) VALUES(@p1)";
DbParameter Field1 = cmd.CreateParameter();
Field1.ParameterName = "@p1";
cmd.Parameters.Add(Field1);
//Console.WriteLine(String.Format(" Fast insert using parameters and prepared statement\r\n -> (100,000 rows) Begins ... "));
dtStart = Environment.TickCount;
for (int n = 0; n < 100000; n++)
{
Field1.Value = n + 200000;
cmd.ExecuteNonQuery();
}
dtEnd = Environment.TickCount;
dtEnd -= dtStart;
builder.AppendFormat("Ends in {0} ms ... ", (dtEnd));
}
dtStart = Environment.TickCount;
dbTrans.Commit();
dtEnd = Environment.TickCount;
dtEnd -= dtStart;
builder.AppendFormat("Commits in {0} ms", (dtEnd));
}
return builder.ToString();
}
[Test]
internal void FullTextTest()
{
CheckSQLite();
using (DbCommand cmd = _cnn.CreateCommand())
{
droptables.Add("FullText");
cmd.CommandText = "CREATE VIRTUAL TABLE FullText USING FTS3(name, ingredients);";
cmd.ExecuteNonQuery();
string[] names = { "broccoli stew", "pumpkin stew", "broccoli pie", "pumpkin pie" };
string[] ingredients = { "broccoli peppers cheese tomatoes", "pumpkin onions garlic celery", "broccoli cheese onions flour", "pumpkin sugar flour butter" };
int n;
cmd.CommandText = "insert into FullText (name, ingredients) values (@name, @ingredient);";
DbParameter name = cmd.CreateParameter();
DbParameter ingredient = cmd.CreateParameter();
name.ParameterName = "@name";
ingredient.ParameterName = "@ingredient";
cmd.Parameters.Add(name);
cmd.Parameters.Add(ingredient);
for (n = 0; n < names.Length; n++)
{
name.Value = names[n];
ingredient.Value = ingredients[n];
cmd.ExecuteNonQuery();
}
cmd.CommandText = "select rowid, name, ingredients from FullText where name match 'pie';";
cmd.Parameters.Clear();
int[] rowids = { 3, 4 };
n = 0;
using (DbDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
if (reader.GetInt64(0) != rowids[n++])
throw new Exception("Unexpected rowid returned");
if (n > rowids.Length) throw new Exception("Too many rows returned");
}
}
}
}
[Test]
internal void GuidTest()
{
using (DbCommand cmd = _cnn.CreateCommand())
{
Guid guid = Guid.NewGuid();
droptables.Add("GuidTest");
cmd.CommandText = "CREATE TABLE GuidTest(MyGuid uniqueidentifier)";
cmd.ExecuteNonQuery();
// Insert a guid as a default binary representation
cmd.CommandText = "INSERT INTO GuidTest(MyGuid) VALUES(@b)";
DbParameter parm = cmd.CreateParameter();
parm.ParameterName = "@b";
parm.Value = guid;
cmd.Parameters.Add(parm);
//((SQLiteParameterCollection)cmd.Parameters).AddWithValue("@b", guid);
// Insert a guid as text
cmd.ExecuteNonQuery();
cmd.Parameters[0].Value = guid.ToString();
cmd.Parameters[0].DbType = DbType.String;
cmd.ExecuteNonQuery();
cmd.CommandText = "SELECT MyGuid FROM GuidTest";
cmd.Parameters.Clear();
using (DbDataReader reader = cmd.ExecuteReader())
{
reader.Read();
if (reader.GetFieldType(0) != typeof(Guid)) throw new Exception("Column is not a Guid");
if (reader.GetGuid(0) != guid) throw new Exception(String.Format("Got guid {0}, expected {1}", reader.GetGuid(0), guid));
reader.Read();
if (reader.GetFieldType(0) != typeof(Guid)) throw new Exception("Column is not a Guid");
if (reader.GetGuid(0) != guid) throw new Exception(String.Format("Got guid {0}, expected {1}", reader.GetGuid(0), guid));
}
}
}
[Test(Sequence = 20)]
internal void InsertTable()
{
using (DbCommand cmd = _cnn.CreateCommand())
{
cmd.CommandText = "INSERT INTO TestCase(Field1, Field2, [Fiëld3], [Fiæld4], Field5) VALUES(1, 3.14159, 'Fiëld3', 'Fiæld4', '2005-01-01 13:49:00')";
cmd.ExecuteNonQuery();
}
}
[Test]
internal string IterationTest1()
{
CheckSQLite();
using (DbCommand cmd = _cnn.CreateCommand())
{
int dtStart;
int dtEnd;
int nCount;
long n;
cmd.CommandText = "SELECT Foo(ID, ID) FROM TestCase";
cmd.Prepare();
dtStart = Environment.TickCount;
nCount = 0;
using (DbDataReader rd = cmd.ExecuteReader())
{
while (rd.Read())
{
n = rd.GetInt64(0);
nCount++;
}
dtEnd = Environment.TickCount;
}
return String.Format("User Function iteration of {0} records in {1} ms", nCount, (dtEnd - dtStart));
}
}
[Test]
internal string IterationTest2()
{
StringBuilder builder = new StringBuilder();
using (DbCommand cmd = _cnn.CreateCommand())
{
int dtStart;
int dtEnd;
int nCount;
long n;
cmd.CommandText = "SELECT ID FROM TestCase";
cmd.Prepare();
dtStart = Environment.TickCount;
nCount = 0;
using (DbDataReader rd = cmd.ExecuteReader())
{
while (rd.Read())
{
n = rd.GetInt64(0);
nCount++;
}
dtEnd = Environment.TickCount;
}
return String.Format("Raw iteration of {0} records in {1} ms", nCount, (dtEnd - dtStart));
}
}
[Test]
internal string IterationTest3()
{
StringBuilder builder = new StringBuilder();
using (DbCommand cmd = _cnn.CreateCommand())
{
int dtStart;
int dtEnd;
int nCount;
long n;
cmd.CommandText = "SELECT ABS(ID) FROM TestCase";
cmd.Prepare();
dtStart = Environment.TickCount;
nCount = 0;
using (DbDataReader rd = cmd.ExecuteReader())
{
while (rd.Read())
{
n = rd.GetInt64(0);
nCount++;
}
dtEnd = Environment.TickCount;
}
return String.Format("Intrinsic Function iteration of {0} records in {1} ms", nCount, (dtEnd - dtStart));
}
}
[Test(Sequence=21)]
internal void KeyInfoTest()
{
using (DbCommand cmd = _cnn.CreateCommand())
{
try
{
// First test against integer primary key (optimized) keyinfo fetch
droptables.Add("keyinfotest");
cmd.CommandText = "Create table keyinfotest (id integer primary key, myuniquevalue integer unique not null, myvalue varchar(50))";
cmd.ExecuteNonQuery();
cmd.CommandText = "Select * from keyinfotest";
using (DbDataReader reader = cmd.ExecuteReader(CommandBehavior.KeyInfo | CommandBehavior.SchemaOnly))
{
using (DataTable tbl = reader.GetSchemaTable())
{
if (tbl.Rows.Count != 3) throw new Exception("Wrong number of columns returned");
}
}
cmd.CommandText = "SELECT MyValue FROM keyinfotest";
using (DbDataReader reader = cmd.ExecuteReader(CommandBehavior.KeyInfo | CommandBehavior.SchemaOnly))
{
using (DataTable tbl = reader.GetSchemaTable())
{
if (tbl.Rows.Count != 2) throw new Exception("Wrong number of columns returned");
}
}
}
finally
{
}
cmd.CommandText = "DROP TABLE keyinfotest";
cmd.ExecuteNonQuery();
droptables.Remove("keyinfotest");
try
{
// Now test against non-integer primary key (unoptimized) subquery keyinfo fetch
droptables.Add("keyinfotest");
cmd.CommandText = "Create table keyinfotest (id char primary key, myuniquevalue integer unique not null, myvalue varchar(50))";
cmd.ExecuteNonQuery();
cmd.CommandText = "SELECT MyValue FROM keyinfotest";
using (DbDataReader reader = cmd.ExecuteReader(CommandBehavior.KeyInfo | CommandBehavior.SchemaOnly))
{
using (DataTable tbl = reader.GetSchemaTable())
{
if (tbl.Rows.Count != 2) throw new Exception("Wrong number of columns returned");
}
}
cmd.CommandText = "Select * from keyinfotest";
using (DbDataReader reader = cmd.ExecuteReader(CommandBehavior.KeyInfo | CommandBehavior.SchemaOnly))
{
using (DataTable tbl = reader.GetSchemaTable())
{
if (tbl.Rows.Count != 3) throw new Exception("Wrong number of columns returned");
}
}
// Make sure commandbuilder can generate an update command with the correct parameter count
using (DbDataAdapter adp = _fact.CreateDataAdapter())
using (DbCommandBuilder builder = _fact.CreateCommandBuilder())
{
adp.SelectCommand = cmd;
builder.DataAdapter = adp;
builder.ConflictOption = ConflictOption.OverwriteChanges;
using (DbCommand updatecmd = builder.GetUpdateCommand())
{
if (updatecmd.Parameters.Count != 4)
throw new Exception("Wrong number of parameters in update command!");
}
}
}
finally
{
}
}
}
[Test]
internal void ConnectionStringBuilder()
{
DbConnectionStringBuilder builder = _fact.CreateConnectionStringBuilder();
if (builder is SQLiteConnectionStringBuilder)
{
bool pool = ((SQLiteConnectionStringBuilder)builder).Pooling;
}
}
[Test]
internal void LeakyCommands()
{
for (int n = 0; n < 100000; n++)
{
DbCommand cmd = _cnn.CreateCommand();
cmd.CommandText = "SELECT * FROM sqlite_master";
cmd.Prepare();
}
CheckLocked();
}
[Test(Sequence = 60)]
internal void LockTest()
{
CheckSQLite();
using (DbCommand cmd = _cnn.CreateCommand())
{
cmd.CommandText = "SELECT Field6 FROM TestCase WHERE Field6 IS NOT NULL";
byte[] b = new byte[4000];
using (DbDataReader rd = cmd.ExecuteReader())
{
if (rd.Read() == false) throw new Exception("No data to read!");
rd.GetBytes(0, 0, b, 0, 4000);
if (b[0] != 1) throw new Exception("Binary value non-match byte 0");
if (b[100] != 2) throw new Exception("Binary value non-match byte 100");
if (b[1000] != 3) throw new Exception("Binary value non-match byte 1000");
if (b[2000] != 4) throw new Exception("Binary value non-match byte 2000");
if (b[3000] != 5) throw new Exception("Binary value non-match byte 3000");
using (DbConnection clone = (DbConnection)((ICloneable)_cnn).Clone())
{
if (clone.State != ConnectionState.Open) clone.Open();
using (DbCommand newcmd = clone.CreateCommand())
{
newcmd.CommandText = "DELETE FROM TestCase WHERE Field6 IS NULL";
newcmd.CommandTimeout = 2;
int cmdStart = Environment.TickCount;
int cmdEnd;
try
{
newcmd.ExecuteNonQuery(); // should fail because there's a reader on the database
throw new ArgumentException("Should not have allowed an execute with an open reader"); // If we got here, the test failed
}
catch (Exception e)
{
if (e is ArgumentException) throw new Exception(e.Message);
cmdEnd = Environment.TickCount;
if (cmdEnd - cmdStart < 2000 || cmdEnd - cmdStart > 3000)
throw new Exception("Did not give up the lock at the right time!"); // Didn't wait the right amount of time
}
}
}
}
}
}
/// <summary>
/// Execute multiple steps in a command and verify the results. Makes sure that commands after a select still
/// get executed even if MoveNext() isn't called explicitly to move things along.
/// </summary>
[Test]
internal void MultiStepReaderTest()
{
using (DbCommand cmd = _cnn.CreateCommand())
{
droptables.Add("stepreader");
cmd.CommandText = "CREATE TABLE stepreader (id int primary key);INSERT INTO stepreader values(1);SELECT * FROM stepreader;UPDATE stepreader set id = id + 1;";
using (DbDataReader reader = cmd.ExecuteReader())
{
if (reader.Read() == false) throw new Exception("Failed to read from the table");
if (reader.GetInt32(0) != 1) throw new Exception(String.Format("Expected {0} got {1}", 1, reader.GetInt32(0)));
}
cmd.CommandText = "SELECT * FROM stepreader";
using (DbDataReader reader = cmd.ExecuteReader())
{
if (reader.Read() == false) throw new Exception("Failed to read from the table");
if (reader.GetInt32(0) != 2) throw new Exception(String.Format("Expected {0} got {1}", 2, reader.GetInt32(0)));
}
}
}
internal class MTTest
{
internal DbConnection cnn;
internal Exception e;
internal System.Threading.Thread t;
internal int value;
}
[Test(Sequence=11)]
internal void MultithreadingTest()
{
using (DbCommand cmd = _cnn.CreateCommand())
{
droptables.Add("MultiThreadedTest");
if (_fact.GetType().Name.IndexOf("SQLite", StringComparison.OrdinalIgnoreCase) == -1)
cmd.CommandText = "CREATE TABLE MultiThreadedTest(ID integer identity primary key, ThreadId integer, MyValue integer)";
else
cmd.CommandText = "CREATE TABLE MultiThreadedTest(ID integer primary key, ThreadId integer, MyValue integer)";
cmd.ExecuteNonQuery();
}
MTTest[] arr = new MTTest[8];
for (int n = 0; n < arr.Length; n++)
{
arr[n] = new MTTest();
arr[n].t = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(MultithreadedTestThread));
arr[n].t.IsBackground = true;
arr[n].cnn = ((ICloneable)_cnn).Clone() as DbConnection;
arr[n].t.Start(arr[n]);
}
System.Threading.Thread.Sleep(8000);
bool failed = false;
Exception e = null;
for (int n = 0; n < arr.Length; n++)
{
if (arr[n].t.Join(0) == false)
{
failed = true;
arr[n].t.Abort();
}
if (arr[n].e != null) e = arr[n].e;
arr[n].cnn.Dispose();
}
if (failed) throw new Exception("One or more threads deadlocked");
if (e != null)
throw e;
}
internal void MultithreadedTestThread(object obj)
{
MTTest test = obj as MTTest;
if (test.cnn.State != ConnectionState.Open)
test.cnn.Open();
int start = Environment.TickCount;
try
{
using (DbCommand cmd = test.cnn.CreateCommand())
{
while (Environment.TickCount - start < 2000)
{
using (DbTransaction trans = test.cnn.BeginTransaction())
{
cmd.CommandText = String.Format("SELECT * FROM MultiThreadedTest WHERE ThreadId = {0}", test.t.ManagedThreadId);
cmd.Transaction = trans;
using (DbDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
test.value += Convert.ToInt32(reader[2]);
}
}
cmd.CommandText = String.Format("INSERT INTO MultiThreadedTest(ThreadId, MyValue) VALUES({0}, {1})", test.t.ManagedThreadId, Environment.TickCount);
cmd.ExecuteNonQuery();
trans.Commit();
}
}
}
}
catch (Exception e)
{
test.e = e;
}
}
[Test]
internal void ParameterizedInsert()
{
using (DbCommand cmd = _cnn.CreateCommand())
{
cmd.CommandText = "INSERT INTO TestCase(Field1, Field2, [Fiëld3], [Fiæld4], Field5) VALUES(@p1,@p2,@p3,@p4,@p5)";
DbParameter Field1 = cmd.CreateParameter();
DbParameter Field2 = cmd.CreateParameter();
DbParameter Field3 = cmd.CreateParameter();
DbParameter Field4 = cmd.CreateParameter();
DbParameter Field5 = cmd.CreateParameter();
Field1.ParameterName = "@p1";
Field2.ParameterName = "@p2";
Field3.ParameterName = "@p3";
Field4.ParameterName = "@p4";
Field5.ParameterName = "@p5";
Field1.Value = 2;
Field2.Value = 3.14159;
Field3.Value = "Param Field3";
Field4.Value = "Field4 Par";
Field5.Value = DateTime.Now;
cmd.Parameters.Add(Field1);
cmd.Parameters.Add(Field2);
cmd.Parameters.Add(Field3);
cmd.Parameters.Add(Field4);
cmd.Parameters.Add(Field5);
cmd.ExecuteNonQuery();
}
}
[Test]
internal void ParameterizedInsertMissingParams()
{
using (DbCommand cmd = _cnn.CreateCommand())
{
cmd.CommandText = "INSERT INTO TestCase(Field1, Field2, [Fiëld3], [Fiæld4], Field5) VALUES(@p1,@p2,@p3,@p4,@p5)";
DbParameter Field1 = cmd.CreateParameter();
DbParameter Field2 = cmd.CreateParameter();
DbParameter Field3 = cmd.CreateParameter();
DbParameter Field4 = cmd.CreateParameter();
DbParameter Field5 = cmd.CreateParameter();
Field1.ParameterName = "@p1";
Field2.ParameterName = "@p2";
Field3.ParameterName = "@p3";
Field4.ParameterName = "@p4";
Field5.ParameterName = "@p5";
Field1.DbType = System.Data.DbType.Int32;
Field1.Value = 2;
Field2.Value = 3.14159;
Field3.Value = "Field3 Param";
Field4.Value = "Field4 Par";
Field5.Value = DateTime.Now;
cmd.Parameters.Add(Field1);
cmd.Parameters.Add(Field2);
cmd.Parameters.Add(Field3);
cmd.Parameters.Add(Field4);
// Assertion here, not enough parameters
try
{
cmd.ExecuteNonQuery();
throw new Exception("Executed with a missing parameter");
}
catch (Exception) // Expected
{
}
}
}
/// <summary>
/// Call Prepare() on a multi-statement command text where the second command depends on the existence of the first.
/// </summary>
[Test]
internal void PrepareTest()
{
using (DbCommand cmd = _cnn.CreateCommand())
{
droptables.Add("nonexistent");
cmd.CommandText = "CREATE TABLE nonexistent(id int primary key);SELECT id FROM nonexistent UNION SELECT 1";
cmd.Prepare();
object ob = cmd.ExecuteScalar();
if (ob == null || ob == DBNull.Value) throw new Exception("Multiple statements may not be supported");
if (Convert.ToInt32(ob) != 1) throw new Exception(String.Format("Expected {0} got {1}", 1, ob));
}
}
/// <summary>
/// Checks to make sure transactions are rolled back before a connection goes back onto the pool
/// </summary>
[Test]
internal void PoolingWithStealthTransactionTest()
{
object value;
if (_cnnstring.TryGetValue("Pooling", out value) == false) throw new Exception("Pooling not present in connection string");
if ((bool)value == false) throw new InconclusiveException("Pooling not enabled in the connection string");
maydroptable.Add("PoolTest");
for (int n = 0; n < 100; n++)
{
using (DbConnection newcnn = ((ICloneable)_cnn).Clone() as DbConnection)
{
if (newcnn.State != ConnectionState.Open) newcnn.Open();
using (DbCommand cmd = newcnn.CreateCommand())
{
cmd.CommandText = "BEGIN TRANSACTION";
cmd.ExecuteNonQuery();
cmd.CommandText = "CREATE TABLE PoolTest(ID int primary key)";
cmd.ExecuteNonQuery();
}
}
}
}
/// <summary>
/// Checks to make sure transactions are rolled back before a connection goes back onto the pool
/// </summary>
[Test]
internal void PoolingWithTransactionTest()
{
object value;
if (_cnnstring.TryGetValue("Pooling", out value) == false) throw new Exception("Pooling not present in connection string");
if ((bool)value == false) throw new InconclusiveException("Pooling not enabled in the connection string");
maydroptable.Add("PoolTest");
for (int n = 0; n < 100; n++)
{
using (DbConnection newcnn = ((ICloneable)_cnn).Clone() as DbConnection)
{
if (newcnn.State != ConnectionState.Open) newcnn.Open();
DbTransaction trans = newcnn.BeginTransaction();
using (DbCommand cmd = newcnn.CreateCommand())
{
cmd.Transaction = trans;
cmd.CommandText = "CREATE TABLE PoolTest(ID int primary key)";
cmd.ExecuteNonQuery();
}
}
}
}
/// <summary>
/// Open a reader and then attempt to write to test the writer's command timeout property
/// SQLite doesn't allow a write when a reader is active.
/// *** NOTE AS OF 3.3.8 this test no longer blocks because SQLite now allows you to update table(s)
/// while a reader is active on the same connection. Therefore the timeout test is invalid
/// </summary>
internal void TimeoutTest()
{
CheckSQLite();
using (DbCommand cmdRead = _cnn.CreateCommand())
{
cmdRead.CommandText = "SELECT ID FROM TestCase";
using (DbDataReader rd = cmdRead.ExecuteReader())
{
using (DbCommand cmdwrite = _cnn.CreateCommand())
{
cmdwrite.CommandText = "UPDATE [KeyInfoTest] SET [ID] = [ID]";
cmdwrite.CommandTimeout = 5;
int dwtick = Environment.TickCount;
try
{
cmdwrite.ExecuteNonQuery();
}
catch (Exception)
{
dwtick = (Environment.TickCount - dwtick) / 1000;
if (dwtick < 5 || dwtick > 6)
throw new Exception("Timeout didn't wait long enough!");
return;
}
throw new Exception("Operation should have failed but completed successfully");
}
}
}
}
[Test(Sequence = 41)]
internal void TransactionScopeTest()
{
using (TransactionScope scope = new TransactionScope())
{
using (DbConnection cnn2 = ((ICloneable)_cnn).Clone() as DbConnection)
{
if (cnn2.State != ConnectionState.Open) cnn2.Open();
using (DbCommand cmd = cnn2.CreateCommand())
{
// Created a table inside the transaction scope
cmd.CommandText = "CREATE TABLE VolatileTable (ID INTEGER PRIMARY KEY, MyValue VARCHAR(50))";
cmd.ExecuteNonQuery();
maydroptable.Add("VolatileTable");
using (DbCommand cmd2 = cnn2.CreateCommand())
{
using (cmd2.Transaction = cnn2.BeginTransaction())
{
// Inserting a value inside the table, inside a transaction which is inside the transaction scope
cmd2.CommandText = "INSERT INTO VolatileTable (ID, MyValue) VALUES(1, 'Hello')";
cmd2.ExecuteNonQuery();
cmd2.Transaction.Commit();
}
}
}
// Connection is disposed before the transactionscope leaves, thereby forcing the connection to stay open
}
// Exit the transactionscope without committing it, causing a rollback of both the create table and the insert
}
// Verify that the table does not exist
using (DbCommand cmd = _cnn.CreateCommand())
{
cmd.CommandText = "SELECT COUNT(*) FROM VolatileTable";
try
{
object o = cmd.ExecuteScalar();
cmd.CommandText = "DROP TABLE VolatileTable";
cmd.ExecuteNonQuery();
throw new InvalidOperationException("Transaction failed! The table exists!");
}
catch(Exception e)
{
if (e is InvalidOperationException) throw new Exception(e.Message);
return; // Succeeded, the table should not have existed
}
}
}
/// <summary>
/// Causes the user-defined aggregate to be iterated through
/// </summary>
/// <returns></returns>
[Test]
internal string UserAggregate()
{
CheckSQLite();
StringBuilder builder = new StringBuilder();
using (DbCommand cmd = _cnn.CreateCommand())
{
int dtStart;
int n = 0;
int nCount;
cmd.CommandText = "SELECT MyCount(*) FROM TestCase";
nCount = 0;
dtStart = Environment.TickCount;
while (Environment.TickCount - dtStart < 1000)
{
n = Convert.ToInt32(cmd.ExecuteScalar());
nCount++;
}
if (n != 120003) throw new Exception("Unexpected count");
builder.Append(String.Format("UserAggregate executed {0} times in 1 second.", nCount));
}
return builder.ToString();
}
/// <summary>
/// Causes the user-defined collation sequence to be iterated through
/// </summary>
[Test]
internal void UserCollation()
{
CheckSQLite();
using (DbCommand cmd = _cnn.CreateCommand())
{
// Using a default collating sequence in descending order, "Param Field3" will appear at the top
// and "Field3" will be next, followed by a NULL. Our user-defined collating sequence will
// deliberately place them out of order so Field3 is first.
cmd.CommandText = "SELECT [Fiëld3] FROM TestCase ORDER BY [Fiëld3] COLLATE MYSEQUENCE DESC";
string s = (string)cmd.ExecuteScalar();
if (s != "Fiëld3") throw new Exception("MySequence didn't sort properly");
}
}
/// <summary>
/// Causes the user-defined function to be called
/// </summary>
/// <returns></returns>
[Test]
internal string UserFunction1()
{
CheckSQLite();
using (DbCommand cmd = _cnn.CreateCommand())
{
int nTimes;
int dtStart;
nTimes = 0;
cmd.CommandText = "SELECT Foo('ee','foo')";
dtStart = Environment.TickCount;
while (Environment.TickCount - dtStart < 1000)
{
cmd.ExecuteNonQuery();
nTimes++;
}
return String.Format("User (text) command executed {0} times in 1 second.", nTimes);
}
}
[Test]
internal string UserFunction2()
{
CheckSQLite();
using (DbCommand cmd = _cnn.CreateCommand())
{
int nTimes;
int dtStart;
nTimes = 0;
cmd.CommandText = "SELECT Foo(10,11)";
dtStart = Environment.TickCount;
while (Environment.TickCount - dtStart < 1000)
{
cmd.ExecuteNonQuery();
nTimes++;
}
return String.Format("UserFunction command executed {0} times in 1 second.", nTimes);
}
}
[Test]
internal string UserFunction3()
{
CheckSQLite();
using (DbCommand cmd = _cnn.CreateCommand())
{
int nTimes;
int dtStart;
nTimes = 0;
cmd.CommandText = "SELECT ABS(1)";
dtStart = Environment.TickCount;
while (Environment.TickCount - dtStart < 1000)
{
cmd.ExecuteNonQuery();
nTimes++;
}
return String.Format("Intrinsic command executed {0} times in 1 second.", nTimes);
}
}
[Test]
internal string UserFunction4()
{
CheckSQLite();
using (DbCommand cmd = _cnn.CreateCommand())
{
int nTimes;
int dtStart;
nTimes = 0;
cmd.CommandText = "SELECT lower('FOO')";
dtStart = Environment.TickCount;
while (Environment.TickCount - dtStart < 1000)
{
cmd.ExecuteNonQuery();
nTimes++;
}
return String.Format("Intrin (txt) command executed {0} times in 1 second.", nTimes);
}
}
[Test]
internal string UserFunction5()
{
CheckSQLite();
using (DbCommand cmd = _cnn.CreateCommand())
{
int nTimes;
int dtStart;
nTimes = 0;
cmd.CommandText = "SELECT 1";
dtStart = Environment.TickCount;
while (Environment.TickCount - dtStart < 1000)
{
cmd.ExecuteNonQuery();
nTimes++;
}
return String.Format("Raw Value command executed {0} times in 1 second.", nTimes);
}
}
[Test(Sequence = 42)]
internal void VerifyBinaryData()
{
BinaryInsert();
using (DbCommand cmd = _cnn.CreateCommand())
{
cmd.CommandText = "SELECT Field6 FROM TestCase WHERE Field6 IS NOT NULL";
byte[] b = new byte[4000];
using (DbDataReader rd = cmd.ExecuteReader())
{
if (rd.Read() == false) throw new Exception("No data to read!");
long n = rd.GetBytes(0, 0, null, 0, 0);
if (n != 4000) throw new Exception("Invalid byte length!");
rd.GetBytes(0, 0, b, 0, 4000);
if (b[0] != 1) throw new Exception("Binary value non-match byte 0");
if (b[100] != 2) throw new Exception("Binary value non-match byte 100");
if (b[1000] != 3) throw new Exception("Binary value non-match byte 1000");
if (b[2000] != 4) throw new Exception("Binary value non-match byte 2000");
if (b[3000] != 5) throw new Exception("Binary value non-match byte 3000");
}
}
}
[Test]
internal void DecimalTest()
{
using (DbCommand cmd = _cnn.CreateCommand())
{
droptables.Add("DECTEST");
cmd.CommandText = "CREATE TABLE DECTEST(x DECIMAL(38,18))";
cmd.ExecuteNonQuery();
cmd.CommandText = "INSERT INTO DECTEST(x) VALUES(0.00001)";
cmd.ExecuteNonQuery();
cmd.CommandText = "SELECT * FROM DECTEST";
using (DbDataReader reader = cmd.ExecuteReader())
{
reader.Read();
decimal d = (decimal)reader.GetValue(0);
d = reader.GetDecimal(0);
}
}
}
[Test(Sequence = 30)]
internal void VerifyInsert()
{
using (DbCommand cmd = _cnn.CreateCommand())
{
cmd.CommandText = "SELECT Field1, Field2, [Fiëld3], [Fiæld4], Field5 FROM TestCase";
cmd.Prepare();
using (DbDataReader rd = cmd.ExecuteReader())
{
if (rd.Read())
{
int Field1 = rd.GetInt32(0);
double Field2 = rd.GetDouble(1);
string Field3 = rd.GetString(2);
string Field4 = rd.GetString(3).TrimEnd();
DateTime Field5 = rd.GetDateTime(4);
if (Field1 != 1) throw new Exception(String.Format("Field1 {0} did not match {1}", Field1, 1));
if (Field2 != 3.14159) throw new Exception(String.Format("Field2 {0} did not match {1}", Field2, 3.14159));
if (Field3 != "Fiëld3") throw new Exception(String.Format("Field3 {0} did not match {1}", Field3, "Fiëld3"));
if (Field4 != "Fiæld4") throw new Exception(String.Format("Field4 {0} did not match {1}", Field4, "Fiæld4"));
if (Field5.CompareTo(DateTime.Parse("2005-01-01 13:49:00")) != 0) throw new Exception(String.Format("Field5 {0} did not match {1}", Field4, DateTime.Parse("2005-01-01 13:49:00")));
if (rd.GetName(0) != "Field1") throw new Exception("Non-Match column name Field1");
if (rd.GetName(1) != "Field2") throw new Exception("Non-Match column name Field2");
if (rd.GetName(2) != "Fiëld3") throw new Exception("Non-Match column name Field3");
if (rd.GetName(3) != "Fiæld4") throw new Exception("Non-Match column name Field4");
if (rd.GetName(4) != "Field5") throw new Exception("Non-Match column name Field5");
}
else throw new Exception("No data in table");
}
}
}
}
/// <summary>
/// Scalar user-defined function. In this example, the same class is declared twice with
/// different function names to demonstrate how to use alias names for user-defined functions.
/// </summary>
[SQLiteFunction(Name = "Foo", Arguments = 2, FuncType = FunctionType.Scalar)]
[SQLiteFunction(Name = "TestFunc", Arguments = 2, FuncType = FunctionType.Scalar)]
class TestFunc : SQLiteFunction
{
public override object Invoke(object[] args)
{
if (args[0].GetType() != typeof(int)) return args[0];
int Param1 = Convert.ToInt32(args[0]); // First parameter
int Param2 = Convert.ToInt32(args[1]); // Second parameter
return Param1 + Param2;
}
}
[SQLiteFunction(Name = "CASETEST", Arguments = 2, FuncType = FunctionType.Scalar)]
class CaseTestFunc : SQLiteFunctionEx
{
public override object Invoke(object[] args)
{
CollationSequence seq = GetCollationSequence();
return seq.Compare(args[0].ToString(), args[1].ToString());
}
}
/// <summary>
/// Aggregate user-defined function. Arguments = -1 means any number of arguments is acceptable
/// </summary>
[SQLiteFunction(Name = "MyCount", Arguments = -1, FuncType = FunctionType.Aggregate)]
class MyCount : SQLiteFunction
{
public override void Step(object[] args, int nStep, ref object contextData)
{
if (contextData == null)
{
contextData = 1;
}
else
contextData = (int)contextData + 1;
}
public override object Final(object contextData)
{
return contextData;
}
}
/// <summary>
/// Sample regular expression function. Example Usage:
/// SELECT * FROM foo WHERE name REGEXP '$bar'
/// SELECT * FROM foo WHERE REGEXP('$bar', name)
///
/// </summary>
[SQLiteFunction(Name = "REGEXP", Arguments = 2, FuncType = FunctionType.Scalar)]
class MyRegEx : SQLiteFunction
{
public override object Invoke(object[] args)
{
return System.Text.RegularExpressions.Regex.IsMatch(Convert.ToString(args[1]), Convert.ToString(args[0]));
}
}
/// <summary>
/// User-defined collating sequence.
/// </summary>
[SQLiteFunction(Name = "MYSEQUENCE", FuncType = FunctionType.Collation)]
class MySequence : SQLiteFunction
{
public override int Compare(string param1, string param2)
{
// Make sure the string "Fiëld3" is sorted out of order
if (param1 == "Fiëld3") return 1;
if (param2 == "Fiëld3") return -1;
return String.Compare(param1, param2, true);
}
}
[AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = false)]
public sealed class TestAttribute : Attribute, IComparable<TestAttribute>
{
private static int _start = 65535;
private int _sequence;
public TestAttribute()
{
_sequence = _start;
_start++;
}
public int Sequence
{
get { return _sequence; }
set { _sequence = value; }
}
#region IComparable<TestAttribute> Members
public int CompareTo(TestAttribute other)
{
return _sequence.CompareTo(other._sequence);
}
#endregion
}
internal enum TestResultEnum
{
Succeeded = 0,
Failed = 1,
Inconclusive = 2,
}
internal class InconclusiveException : Exception
{
internal InconclusiveException()
: base()
{
}
internal InconclusiveException(string message)
: base(message)
{
}
}
internal class TestEventArgs : EventArgs
{
public readonly string TestName;
public readonly TestResultEnum Result;
public readonly Exception Exception;
public readonly string Message;
public readonly int Duration;
internal TestEventArgs(string testName, TestResultEnum success, int duration, Exception e, string message)
{
TestName = testName;
Result = success;
Exception = e;
Message = message;
Duration = duration;
}
}
delegate void TestCompletedEvent(object sender, TestEventArgs args);
delegate void TestStartingEvent(object sender, TestEventArgs args);
internal abstract class TestCaseBase
{
protected DbProviderFactory _fact;
protected DbConnection _cnn = null;
protected DbConnectionStringBuilder _cnnstring;
protected Dictionary<string, bool> _tests = new Dictionary<string,bool>();
public event TestCompletedEvent OnTestFinished;
public event TestStartingEvent OnTestStarting;
public event EventHandler OnAllTestsDone;
protected TestCaseBase()
{
SortedList<TestAttribute, System.Reflection.MethodInfo> items = new SortedList<TestAttribute, System.Reflection.MethodInfo>();
foreach (System.Reflection.MethodInfo mi in GetType().GetMethods(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.InvokeMethod))
{
object[] att = mi.GetCustomAttributes(typeof(TestAttribute), false);
if (att.Length == 1)
{
items.Add((TestAttribute)att[0], mi);
}
}
foreach (KeyValuePair<TestAttribute, System.Reflection.MethodInfo> pair in items)
{
_tests.Add(pair.Value.Name, true);
}
}
protected TestCaseBase(DbProviderFactory factory, string connectionString)
{
_fact = factory;
_cnn = _fact.CreateConnection();
_cnn.ConnectionString = connectionString;
_cnnstring = _fact.CreateConnectionStringBuilder();
_cnnstring.ConnectionString = connectionString;
_cnn.Open();
}
internal Dictionary<string, bool> Tests
{
get
{
return _tests;
}
set
{
_tests = value;
}
}
internal void Run()
{
SortedList<TestAttribute, System.Reflection.MethodInfo> items = new SortedList<TestAttribute, System.Reflection.MethodInfo>();
foreach (System.Reflection.MethodInfo mi in GetType().GetMethods(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.InvokeMethod))
{
object[] att = mi.GetCustomAttributes(typeof(TestAttribute), false);
if (att.Length == 1 && _tests[mi.Name] == true)
{
items.Add((TestAttribute)att[0], mi);
}
}
foreach (KeyValuePair<TestAttribute, System.Reflection.MethodInfo> pair in items)
{
if (OnTestStarting != null)
OnTestStarting(this, new TestEventArgs(pair.Value.Name, TestResultEnum.Inconclusive, 0, null, null));
int start = Environment.TickCount;
try
{
object obj = pair.Value.Invoke(this, null);
int duration = Environment.TickCount - start;
if (OnTestFinished != null)
OnTestFinished(this, new TestEventArgs(pair.Value.Name, TestResultEnum.Succeeded, duration, null, (obj is string) ? (string)obj : String.Empty));
}
catch (Exception e)
{
int duration = Environment.TickCount - start;
Exception inner = e.InnerException;
if (OnTestFinished != null)
{
if (inner is InconclusiveException)
{
OnTestFinished(this, new TestEventArgs(pair.Value.Name, TestResultEnum.Inconclusive, duration, null, inner.Message));
}
else
{
OnTestFinished(this, new TestEventArgs(pair.Value.Name, TestResultEnum.Failed, duration, inner, null));
}
}
}
}
if (OnAllTestsDone != null)
OnAllTestsDone(this, EventArgs.Empty);
}
}
}