summaryrefslogtreecommitdiffstats
path: root/tests/auto/qsqldatabase/tst_qsqldatabase.cpp
blob: e10a0ca7e49f63024792ab9de3ee02a5523e95c2 (plain)
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
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/


#include <QtTest/QtTest>
#include <qsqldatabase.h>
#include <qsqlquery.h>
#include <qsqldriver.h>
#ifdef QT3_SUPPORT
#include <q3sqlcursor.h>
#include <q3sqlrecordinfo.h>
#include <q3cstring.h>
#endif
#include <qsqlrecord.h>
#include <qsqlfield.h>
#include <qsqlindex.h>
#include <qregexp.h>
#include <qvariant.h>
#include <qdatetime.h>
#include <qdebug.h>

#define NODATABASE_SKIP "No database drivers are available in this Qt configuration"

#include "tst_databases.h"

//TESTED_FILES=

QT_FORWARD_DECLARE_CLASS(QSqlDatabase)
struct FieldDef;

class tst_QSqlDatabase : public QObject
{
    Q_OBJECT

public:
    tst_QSqlDatabase();
    virtual ~tst_QSqlDatabase();

public slots:
    void initTestCase();
    void cleanupTestCase();
    void init();
    void cleanup();
private slots:
    void record_data() { generic_data(); }
    //void record();
    void open_data() { generic_data(); }
    void open();
    void tables_data() { generic_data(); }
    void tables();
    void transaction_data() { generic_data(); }
    void transaction();
    void eventNotification_data() { generic_data(); }
    void eventNotification();
    void addDatabase();

    //database specific tests
    void recordMySQL_data() { generic_data("QMYSQL"); }
    void recordMySQL();
    void recordPSQL_data() { generic_data("QPSQL"); }
    void recordPSQL();
    void recordOCI_data() { generic_data("QOCI"); }
    void recordOCI();
    void recordTDS_data() { generic_data("QTDS"); }
    void recordTDS();
    void recordDB2_data() { generic_data("QDB2"); }
    void recordDB2();
    void recordSQLite_data() { generic_data("QSQLITE"); }
    void recordSQLite();
    void recordAccess_data() { generic_data("QODBC"); }
    void recordAccess();
    void recordSQLServer_data() { generic_data("QODBC"); }
    void recordSQLServer();
    void recordIBase_data() {generic_data("QIBASE"); }
    void recordIBase();

    void eventNotificationIBase_data() { generic_data("QIBASE"); }
    void eventNotificationIBase();
    void eventNotificationPSQL_data() { generic_data("QPSQL"); }
    void eventNotificationPSQL();

    //database specific 64 bit integer test
    void bigIntField_data() { generic_data(); }
    void bigIntField();

    // general tests
    void getConnectionName_data() { generic_data(); }
    void getConnectionName(); // For task 129992

    //problem specific tests
    void alterTable_data() { generic_data(); }
    void alterTable();
    void recordNonSelect_data() { generic_data(); }
    void recordNonSelect();
    void caseSensivity_data() { generic_data(); }
    void caseSensivity();
    void noEscapedFieldNamesInRecord_data() { generic_data(); }
    void noEscapedFieldNamesInRecord();
    void whitespaceInIdentifiers_data() { generic_data(); }
    void whitespaceInIdentifiers();
    void formatValueTrimStrings_data() { generic_data(); }
    void formatValueTrimStrings();
    void precisionPolicy_data() { generic_data(); }
    void precisionPolicy();

    void db2_valueCacheUpdate_data() { generic_data("QDB2"); }
    void db2_valueCacheUpdate();

    void psql_schemas_data() { generic_data("QPSQL"); }
    void psql_schemas();
    void psql_escapedIdentifiers_data() { generic_data("QPSQL"); }
    void psql_escapedIdentifiers();
    void psql_escapeBytea_data() { generic_data("QPSQL"); }
    void psql_escapeBytea();
    void bug_249059_data() { generic_data("QPSQL"); }
    void bug_249059();

    void mysqlOdbc_unsignedIntegers_data() { generic_data(); }
    void mysqlOdbc_unsignedIntegers();
    void mysql_multiselect_data() { generic_data("QMYSQL"); }
    void mysql_multiselect();  // For task 144331

    void accessOdbc_strings_data() { generic_data(); }
    void accessOdbc_strings();

    void ibase_numericFields_data() { generic_data("QIBASE"); }
    void ibase_numericFields(); // For task 125053
    void ibase_fetchBlobs_data() { generic_data("QIBASE"); }
    void ibase_fetchBlobs(); // For task 143471
    void ibase_useCustomCharset_data() { generic_data("QIBASE"); }
    void ibase_useCustomCharset(); // For task 134608
    void ibase_procWithoutReturnValues_data() { generic_data("QIBASE"); } // For task 165423
    void ibase_procWithoutReturnValues();
    void ibase_procWithReturnValues_data() { generic_data("QIBASE"); } // For task 177530
    void ibase_procWithReturnValues();

    void odbc_reopenDatabase_data() { generic_data("QODBC"); }
    void odbc_reopenDatabase();
    void odbc_uniqueidentifier_data() { generic_data("QODBC"); }
    void odbc_uniqueidentifier(); // For task 141822
    void odbc_uintfield_data() { generic_data("QODBC"); }
    void odbc_uintfield();
    void odbc_bindBoolean_data() { generic_data("QODBC"); }
    void odbc_bindBoolean();

    void oci_serverDetach_data() { generic_data("QOCI"); }
    void oci_serverDetach(); // For task 154518
    void oci_xmltypeSupport_data() { generic_data("QOCI"); }
    void oci_xmltypeSupport();
    void oci_fieldLength_data() { generic_data("QOCI"); }
    void oci_fieldLength();

    void sqlite_bindAndFetchUInt_data() { generic_data("QSQLITE3"); }
    void sqlite_bindAndFetchUInt();

private:
    void createTestTables(QSqlDatabase db);
    void dropTestTables(QSqlDatabase db);
    void populateTestTables(QSqlDatabase db);
    void generic_data(const QString &engine=QString());

#ifdef QT3_SUPPORT
    void testRecordInfo(const FieldDef fieldDefs[], const Q3SqlRecordInfo& inf);
#endif
    void testRecord(const FieldDef fieldDefs[], const QSqlRecord& inf, QSqlDatabase db);
    void commonFieldTest(const FieldDef fieldDefs[], QSqlDatabase, const int);
    void checkValues(const FieldDef fieldDefs[], QSqlDatabase db);
    void checkNullValues(const FieldDef fieldDefs[], QSqlDatabase db);

    tst_Databases dbs;
};

// number of records to be inserted per testfunction
static const int ITERATION_COUNT = 2;
static int pkey = 1;

//helper class for database specific tests
struct FieldDef {
    FieldDef(QString tn = QString(),
          QVariant::Type t = QVariant::Invalid,
          QVariant v = QVariant(),
          bool nl = true):
        typeName(tn), type(t), val(v), nullable(nl) {}

    QString fieldName() const
    {
        QString rt = typeName;
        rt.replace(QRegExp("\\s"), QString("_"));
#ifdef QT3_SUPPORT
        int i = rt.find("(");
#else
        int i = rt.indexOf("(");
#endif
        if (i == -1)
            i = rt.length();
        if (i > 20)
            i = 20;
        return "t_" + rt.left(i);
    }
    QString typeName;
    QVariant::Type type;
    QVariant val;
    bool nullable;
};

// creates a table out of the FieldDefs and returns the number of fields
// excluding the primary key field
static int createFieldTable(const FieldDef fieldDefs[], QSqlDatabase db)
{
    tst_Databases::safeDropTables(db, QStringList() << qTableName("qtestfields"));
    QSqlQuery q(db);
    // construct a create table statement consisting of all fieldtypes
    QString qs = "create table " + qTableName("qtestfields");
    QString autoName = tst_Databases::autoFieldName(db);
    if (tst_Databases::isMSAccess(db))
        qs.append(" (id int not null");
    else
        qs.append(QString("(id integer not null %1 primary key").arg(autoName));

    int i = 0;
    for (i = 0; !fieldDefs[ i ].typeName.isNull(); ++i) {
        qs += QString(",\n %1 %2").arg(fieldDefs[ i ].fieldName()).arg(fieldDefs[ i ].typeName);
        if ((db.driverName().startsWith("QTDS") || tst_Databases::isSqlServer(db)) && fieldDefs[ i ].nullable) {
            qs += " null";
        }
    }

    if (tst_Databases::isMSAccess(db))
        qs.append(",\n primary key (id)");

    qs += ')';
    if (!q.exec(qs)) {
        qDebug() << "Creation of Table failed:" << tst_Databases::printError(q.lastError(), db);
        qDebug() << "Query: " << qs;
        return -1;
    }
    return i;
}

tst_QSqlDatabase::tst_QSqlDatabase()
{
}

tst_QSqlDatabase::~tst_QSqlDatabase()
{
}

void tst_QSqlDatabase::createTestTables(QSqlDatabase db)
{
    if (!db.isValid())
    return;
    QSqlQuery q(db);
    if (db.driverName().startsWith("QMYSQL"))
        // ### stupid workaround until we find a way to hardcode this
        // in the MySQL server startup script
        q.exec("set table_type=innodb");

    // please never ever change this table; otherwise fix all tests ;)
    if (tst_Databases::isMSAccess(db)) {
        QVERIFY_SQL(q, exec("create table " + qTableName("qtest") +
                   " (id int not null, t_varchar varchar(40) not null, t_char char(40), "
                   "t_numeric number, primary key (id, t_varchar))"));
    } else {
        QVERIFY_SQL(q, exec("create table " + qTableName("qtest") +
               " (id integer not null, t_varchar varchar(40) not null, "
               "t_char char(40), t_numeric numeric(6, 3), primary key (id, t_varchar))"));
    }

    if (testWhiteSpaceNames(db.driverName())) {
        QString qry = "create table "
            + db.driver()->escapeIdentifier(qTableName("qtest") + " test", QSqlDriver::TableName)
            + '('
            + db.driver()->escapeIdentifier(QLatin1String("test test"), QSqlDriver::FieldName)
            + " int not null primary key)";
        QVERIFY_SQL(q, exec(qry));
    }
}

void tst_QSqlDatabase::dropTestTables(QSqlDatabase db)
{
    if (!db.isValid())
        return;
    // drop the view first, otherwise we'll get dependency problems
    tst_Databases::safeDropViews(db, QStringList() << qTableName("qtest_view") << qTableName("qtest_view2"));

    QStringList tableNames;
    tableNames << qTableName("qtest")
            << qTableName("qtestfields")
            << qTableName("qtestalter")
            << qTableName("qtest_temp")
            << qTableName("qtest_bigint")
            << qTableName("qtest_xmltype")
            << qTableName("latin1table")
            << qTableName("qtest_sqlguid")
            << qTableName("batable")
            << qTableName("qtest_prec")
            << qTableName("uint")
            << qTableName("strings")
            << qTableName("numericfields")
            << qTableName("qtest_ibaseblobs")
            << qTableName("qtestBindBool")
            << qTableName("qtest_sqlguid")
            << qTableName("uint_table")
            << qTableName("uint_test")
            << qTableName("bug_249059");

    QSqlQuery q(0, db);
    if (db.driverName().startsWith("QPSQL"))
        q.exec("drop schema " + qTableName("qtestschema") + " cascade");

    if (testWhiteSpaceNames(db.driverName()))
        tableNames <<  (qTableName("qtest") + " test");

    tst_Databases::safeDropTables(db, tableNames);
}

void tst_QSqlDatabase::populateTestTables(QSqlDatabase db)
{
    if (!db.isValid())
        return;
    QSqlQuery q(db);

    q.exec("delete from " + qTableName("qtest")); //non-fatal
    QVERIFY_SQL(q, exec("insert into " + qTableName("qtest") + " (id, t_varchar, t_char, t_numeric) values (0, 'VarChar0', 'Char0', 1.1)"));
    QVERIFY_SQL(q, exec("insert into " + qTableName("qtest") + " (id, t_varchar, t_char, t_numeric) values (1, 'VarChar1', 'Char1', 2.2)"));
    QVERIFY_SQL(q, exec("insert into " + qTableName("qtest") + " (id, t_varchar, t_char, t_numeric) values (2, 'VarChar2', 'Char2', 3.3)"));
    QVERIFY_SQL(q, exec("insert into " + qTableName("qtest") + " (id, t_varchar, t_char, t_numeric) values (3, 'VarChar3', 'Char3', 4.4)"));
}

void tst_QSqlDatabase::initTestCase()
{
    dbs.open();

    for (QStringList::ConstIterator it = dbs.dbNames.begin(); it != dbs.dbNames.end(); ++it) {
        QSqlDatabase db = QSqlDatabase::database((*it));
        CHECK_DATABASE(db);
        dropTestTables(db); //in case of leftovers
        createTestTables(db);
        populateTestTables(db);
    }
}

void tst_QSqlDatabase::cleanupTestCase()
{
    for (QStringList::ConstIterator it = dbs.dbNames.begin(); it != dbs.dbNames.end(); ++it) {
        QSqlDatabase db = QSqlDatabase::database((*it));
        CHECK_DATABASE(db);
        dropTestTables(db);
    }

    dbs.close();
}

void tst_QSqlDatabase::init()
{
}

void tst_QSqlDatabase::cleanup()
{
}

void tst_QSqlDatabase::generic_data(const QString& engine)
{
    if ( dbs.fillTestTable(engine) == 0 ) {
        if(engine.isEmpty())
           QSKIP( "No database drivers are available in this Qt configuration", SkipAll );
        else
           QSKIP( (QString("No database drivers of type %1 are available in this Qt configuration").arg(engine)).toLocal8Bit(), SkipAll );
    }
}

void tst_QSqlDatabase::addDatabase()
{
    QTest::ignoreMessage(QtWarningMsg, "QSqlDatabase: BLAH_FOO_NONEXISTENT_DRIVER driver not loaded");
    QTest::ignoreMessage(QtWarningMsg, qPrintable("QSqlDatabase: available drivers: " + QSqlDatabase::drivers().join(QLatin1String(" "))));
    {
        QSqlDatabase db = QSqlDatabase::addDatabase("BLAH_FOO_NONEXISTENT_DRIVER",
                                                    "INVALID_CONNECTION");
        QVERIFY(!db.isValid());
    }
    QVERIFY(QSqlDatabase::contains("INVALID_CONNECTION"));
    QSqlDatabase::removeDatabase("INVALID_CONNECTION");
    QVERIFY(!QSqlDatabase::contains("INVALID_CONNECTION"));
}

void tst_QSqlDatabase::open()
{
    QFETCH(QString, dbName);
    QSqlDatabase db = QSqlDatabase::database(dbName);
    CHECK_DATABASE(db);

    int i;
    for (i = 0; i < 10; ++i) {
        db.close();
        QVERIFY(!db.isOpen());
        QVERIFY_SQL(db, open());
        QVERIFY(db.isOpen());
        QVERIFY(!db.isOpenError());
    }

    if (db.driverName().startsWith("QSQLITE") && db.databaseName() == ":memory:") {
        // tables in in-memory databases don't survive an open/close
        createTestTables(db);
        populateTestTables(db);
    }
}

void tst_QSqlDatabase::recordNonSelect()
{
#ifdef QT3_SUPPORT
    QFETCH(QString, dbName);
    QSqlDatabase db = QSqlDatabase::database(dbName);
    CHECK_DATABASE(db);

    QSqlQuery q(db);

    // nothing should happen on an empty query
    QSqlRecord rec = db.record(q);
    QVERIFY(rec.isEmpty());
    Q3SqlRecordInfo rInf = db.recordInfo(q);
    QVERIFY(rInf.isEmpty());

    QVERIFY_SQL(q, exec("create table " + qTableName("qtest_temp") + " (id int)"));

    // query without result set should return empty record
    rec = db.record(q);
    QVERIFY(rec.isEmpty());
    rInf = db.recordInfo(q);
    QVERIFY(rInf.isEmpty());
#endif
}

void tst_QSqlDatabase::tables()
{
    QFETCH(QString, dbName);
    QSqlDatabase db = QSqlDatabase::database(dbName);
    CHECK_DATABASE(db);

    bool views = true;
    bool tempTables = false;

    QSqlQuery q(db);
    if ( db.driverName().startsWith( "QMYSQL" ) && tst_Databases::getMySqlVersion( db ).section( QChar('.'), 0, 0 ).toInt()<5 )
        QSKIP( "Test requires MySQL >= 5.0", SkipSingle );


    if (!q.exec("CREATE VIEW " + qTableName("qtest_view") + " as select * from " + qTableName("qtest"))) {
        qDebug(QString("DBMS '%1' cannot handle VIEWs: %2").arg(
                tst_Databases::dbToString(db)).arg(QString(tst_Databases::printError(q.lastError()))).toLatin1());
        views = false;
    }

    if (db.driverName().startsWith("QSQLITE3")) {
        QVERIFY_SQL(q, exec("CREATE TEMPORARY TABLE " + qTableName("temp_tab") + " (id int)"));
        tempTables = true;
    }

    QStringList tables = db.tables(QSql::Tables);
    QVERIFY(tables.contains(qTableName("qtest"), Qt::CaseInsensitive));
    QVERIFY(!tables.contains("sql_features", Qt::CaseInsensitive)); //check for postgres 7.4 internal tables
    if (views) {
        if (db.driverName().startsWith("QMYSQL"))
            // MySQL doesn't differentiate between tables and views when calling QSqlDatabase::tables()
            // May be fixable by doing a select on informational_schema.tables instead of using the client library api
            QEXPECT_FAIL("", "MySQL driver thinks that views are tables", Continue);
        QVERIFY(!tables.contains(qTableName("qtest_view"), Qt::CaseInsensitive));
    }
    if (tempTables)
        QVERIFY(tables.contains(qTableName("temp_tab"), Qt::CaseInsensitive));

    tables = db.tables(QSql::Views);
    if (views) {
        if (db.driverName().startsWith("QMYSQL"))
            // MySQL doesn't give back anything when calling QSqlDatabase::tables() with QSql::Views
            // May be fixable by doing a select on informational_schema.views instead of using the client library api
            QEXPECT_FAIL("", "MySQL driver thinks that views are tables", Continue);
        QVERIFY(tables.contains(qTableName("qtest_view"), Qt::CaseInsensitive));
    }
    if (tempTables)
        QVERIFY(!tables.contains(qTableName("temp_tab"), Qt::CaseInsensitive));
    QVERIFY(!tables.contains(qTableName("qtest"), Qt::CaseInsensitive));

    tables = db.tables(QSql::SystemTables);
    QVERIFY(!tables.contains(qTableName("qtest"), Qt::CaseInsensitive));
    QVERIFY(!tables.contains(qTableName("qtest_view"), Qt::CaseInsensitive));
    QVERIFY(!tables.contains(qTableName("temp_tab"), Qt::CaseInsensitive));

    tables = db.tables(QSql::AllTables);
    if (views)
        QVERIFY(tables.contains(qTableName("qtest_view"), Qt::CaseInsensitive));
    if (tempTables)
        QVERIFY(tables.contains(qTableName("temp_tab"), Qt::CaseInsensitive));
    QVERIFY(tables.contains(qTableName("qtest"), Qt::CaseInsensitive));

    if (tst_Databases::isMSAccess(db))
        QSqlQuery("drop table " + qTableName("qtest_view"), db);
    else
        QSqlQuery("drop view " + qTableName("qtest_view"), db);

    if (db.driverName().startsWith("QPSQL")) {
        QVERIFY(tables.contains(qTableName("qtest") + " test"));
    }
}

void tst_QSqlDatabase::whitespaceInIdentifiers()
{
    QFETCH(QString, dbName);
    QSqlDatabase db = QSqlDatabase::database(dbName);
    CHECK_DATABASE(db);

    if (testWhiteSpaceNames(db.driverName())) {
        QString tableName = qTableName("qtest") + " test";
        QVERIFY(db.tables().contains(tableName, Qt::CaseInsensitive));

        QSqlRecord rec = db.record(tableName);
        QCOMPARE(rec.count(), 1);
        QCOMPARE(rec.fieldName(0), QString("test test"));
        if(db.driverName().startsWith("QOCI"))
            QCOMPARE(rec.field(0).type(), QVariant::String);
        else
            QCOMPARE(rec.field(0).type(), QVariant::Int);

        QSqlIndex idx = db.primaryIndex(tableName);
        QCOMPARE(idx.count(), 1);
        QCOMPARE(idx.fieldName(0), QString("test test"));
        if(db.driverName().startsWith("QOCI"))
            QCOMPARE(idx.field(0).type(), QVariant::String);
        else
            QCOMPARE(idx.field(0).type(), QVariant::Int);
    } else {
        QSKIP("DBMS does not support whitespaces in identifiers", SkipSingle);
    }
}

void tst_QSqlDatabase::alterTable()
{
    QFETCH(QString, dbName);
    QSqlDatabase db = QSqlDatabase::database(dbName);
    CHECK_DATABASE(db);

    QSqlQuery q(db);

    QVERIFY_SQL(q, exec("create table " + qTableName("qtestalter") + " (F1 char(20), F2 char(20), F3 char(20))"));
    QSqlRecord rec = db.record(qTableName("qtestalter"));
    QCOMPARE((int)rec.count(), 3);
#ifdef QT3_SUPPORT
    Q3SqlRecordInfo rinf = db.recordInfo(qTableName("qtestalter"));
    QCOMPARE((int)rinf.count(), 3);
#endif


    int i;
    for (i = 0; i < 3; ++i) {
        QCOMPARE(rec.field(i).name().toUpper(), QString("F%1").arg(i + 1));
#ifdef QT3_SUPPORT
        QCOMPARE(rinf[ i ].name().upper(), QString("F%1").arg(i + 1));
#endif
    }

    if (!q.exec("alter table " + qTableName("qtestalter") + " drop column F2")) {
        QSKIP("DBMS doesn't support dropping columns in ALTER TABLE statement", SkipSingle);
    }

    rec = db.record(qTableName("qtestalter"));
#ifdef QT3_SUPPORT
    rinf = db.recordInfo(qTableName("qtestalter"));
#endif

    QCOMPARE((int)rec.count(), 2);
#ifdef QT3_SUPPORT
    QCOMPARE((int)rinf.count(), 2);
#endif

    QCOMPARE(rec.field(0).name().toUpper(), QString("F1"));
    QCOMPARE(rec.field(1).name().toUpper(), QString("F3"));
#ifdef QT3_SUPPORT
    QCOMPARE(rinf[ 0 ].name().upper(), QString("F1"));
    QCOMPARE(rinf[ 1 ].name().upper(), QString("F3"));
#endif

    q.exec("select * from " + qTableName("qtestalter"));

#ifdef QT3_SUPPORT
    rec = db.record(q);
    rinf = db.recordInfo(q);

    QCOMPARE((int)rec.count(), 2);
    QCOMPARE((int)rinf.count(), 2);

    QCOMPARE(rec.field(0).name().upper(), QString("F1"));
    QCOMPARE(rec.field(1).name().upper(), QString("F3"));
    QCOMPARE(rinf[ 0 ].name().upper(), QString("F1"));
    QCOMPARE(rinf[ 1 ].name().upper(), QString("F3"));
#endif
}

#if 0
// this is the general test that should work on all databases.
// unfortunately no DBMS supports SQL 92/ 99 so the general
// test is more or less a joke. Please write a test for each
// database plugin (see recordOCI and so on). Use this test
// as a template.
void tst_QSqlDatabase::record()
{
    QFETCH(QString, dbName);
    QSqlDatabase db = QSqlDatabase::database(dbName);
    CHECK_DATABASE(db);

    static const FieldDef fieldDefs[] = {
        FieldDef("char(20)", QVariant::String,         QString("blah1"), false),
        FieldDef("varchar(20)", QVariant::String,      QString("blah2"), false),
        FieldDef()
    };

    const int fieldCount = createFieldTable(fieldDefs, db);
    QVERIFY(fieldCount > 0);

// doesn't work with oracle:   checkNullValues(fieldDefs, db);
    commonFieldTest(fieldDefs, db, fieldCount);
    for (int i = 0; i < ITERATION_COUNT; ++i) {
        checkValues(fieldDefs, db);
    }
}
#endif

#ifdef QT3_SUPPORT
void tst_QSqlDatabase::testRecordInfo(const FieldDef fieldDefs[], const Q3SqlRecordInfo& inf)
{
    int i = 0;
    for (i = 0; !fieldDefs[ i ].typeName.isNull(); ++i) {
        QCOMPARE(inf[i+1].name().upper(), fieldDefs[ i ].fieldName().upper());
        if (inf[i+1].type() != fieldDefs[ i ].type) {
            QFAIL(QString(" Expected: '%1' Received: '%2' for field %3 in testRecordInfo").arg(
            QVariant::typeToName(fieldDefs[ i ].type)).arg(
              QVariant::typeToName(inf[i+1].type())).arg(
            fieldDefs[ i ].fieldName()));
        }
    }
}
#endif

void tst_QSqlDatabase::testRecord(const FieldDef fieldDefs[], const QSqlRecord& inf, QSqlDatabase db)
{
    int i = 0;
    if (!tst_Databases::autoFieldName(db).isEmpty()) // Currently only MySQL is tested
        QVERIFY2(inf.field(i).isAutoValue(), qPrintable(inf.field(i).name() + " should be reporting as an autovalue"));
    for (i = 0; !fieldDefs[ i ].typeName.isNull(); ++i) {
        QCOMPARE(inf.field(i+1).name().toUpper(), fieldDefs[ i ].fieldName().toUpper());
        if (inf.field(i+1).type() != fieldDefs[ i ].type) {
            QFAIL(qPrintable(QString(" Expected: '%1' Received: '%2' for field %3 in testRecord").arg(
              QVariant::typeToName(fieldDefs[ i ].type)).arg(
            QVariant::typeToName(inf.field(i+1).type())).arg(
              fieldDefs[ i ].fieldName())));
        }
        QVERIFY(!inf.field(i+1).isAutoValue());

//	qDebug(QString(" field: %1 type: %2 variant type: %3").arg(fieldDefs[ i ].fieldName()).arg(QVariant::typeToName(inf.field(i+1)->type())).arg(QVariant::typeToName(inf.field(i+1)->value().type())));
    }
}

// non-dbms specific tests
void tst_QSqlDatabase::commonFieldTest(const FieldDef fieldDefs[], QSqlDatabase db, const int fieldCount)
{
    CHECK_DATABASE(db);

    // check whether recordInfo returns the right types
#ifdef QT3_SUPPORT
    Q3SqlRecordInfo inf = db.recordInfo(qTableName("qtestfields"));
    QCOMPARE((int)inf.count(), fieldCount+1);
    testRecordInfo(fieldDefs, inf);
#endif

    QSqlRecord rec = db.record(qTableName("qtestfields"));
    QCOMPARE((int)rec.count(), fieldCount+1);
    testRecord(fieldDefs, rec, db);

    QSqlQuery q(db);
    QVERIFY_SQL(q, exec("select * from " + qTableName("qtestfields")));

#ifdef QT3_SUPPORT
    inf = db.recordInfo(q);
    QCOMPARE((int)inf.count(), fieldCount+1);
    testRecordInfo(fieldDefs, inf);

    rec = db.record(q);
    QCOMPARE((int)rec.count(), fieldCount+1);
    testRecord(fieldDefs, rec, db);
#endif
}

// inserts testdata into the testtable, fetches and compares them
void tst_QSqlDatabase::checkValues(const FieldDef fieldDefs[], QSqlDatabase db)
{
    Q_UNUSED(fieldDefs);
#ifdef QT3_SUPPORT
    CHECK_DATABASE(db);

    Q3SqlCursor cur(qTableName("qtestfields"), true, db);
    QVERIFY_SQL(cur, select());
    QSqlRecord* rec = cur.primeInsert();
    Q_ASSERT(rec);
    rec->setValue("id", pkey++);
    int i = 0;
    for (i = 0; !fieldDefs[ i ].typeName.isNull(); ++i) {
        rec->setValue(fieldDefs[ i ].fieldName(), fieldDefs[ i ].val);
//     qDebug(QString("inserting %1 into %2").arg(fieldDefs[ i ].val.toString()).arg(fieldDefs[ i ].fieldName()));
    }
    if (!cur.insert()) {
        QFAIL(QString("Couldn't insert record: %1 %2").arg(cur.lastError().databaseText()).arg(cur.lastError().driverText()));
    }
    cur.setForwardOnly(true);
    QVERIFY_SQL(cur, select("id = " + QString::number(pkey - 1)));
    QVERIFY_SQL(cur, next());

    for (i = 0; !fieldDefs[ i ].typeName.isNull(); ++i) {
        bool ok = false;
        QVariant val1 = cur.value(fieldDefs[ i ].fieldName());
        QVariant val2 = fieldDefs[ i ].val;
        if (val1.type() == QVariant::String)
            //TDS Workaround
            val1 = val1.toString().stripWhiteSpace();
        if (fieldDefs[ i ].fieldName() == "t_real") {
            // strip precision
            val1 = (float)val1.toDouble();
            val2 = (float)val2.toDouble();
        }
        if (val1.canCast(QVariant::Double) && val2.type() == QVariant::Double) {
            // we don't care about precision here, we just want to know whether
            // we can insert/fetch the right values
            ok = (val1.toDouble() - val2.toDouble() < 0.00001);
        } else if (val1.type() == val2.type()) {
                ok = (val1 == val2);
        } else {
            ok = (val1.toString() == val2.toString());
        }
        if (!ok) {
            if (val2.type() == QVariant::DateTime || val2.type() == QVariant::Time)
               qDebug("Expected Time: " + val2.toTime().toString("hh:mm:ss.zzz"));
            if (val1.type() == QVariant::DateTime || val1.type() == QVariant::Time)
               qDebug("Received Time: " + val1.toTime().toString("hh:mm:ss.zzz"));
            QFAIL(QString(" Expected: '%1' Received: '%2' for field %3 (etype %4 rtype %5) in checkValues").arg(
            val2.toString()).arg(
            val1.toString()).arg(
            fieldDefs[ i ].fieldName()).arg(
            val2.typeName()).arg(
            val1.typeName())
            );
        }
    }
#endif
}

// inserts a NULL value for each nullable field in testdata, fetches and checks whether
// we get back NULL
void tst_QSqlDatabase::checkNullValues(const FieldDef fieldDefs[], QSqlDatabase db)
{
    Q_UNUSED(fieldDefs);
#ifdef QT3_SUPPORT
    CHECK_DATABASE(db);

    Q3SqlCursor cur(qTableName("qtestfields"), true, db);
    QVERIFY_SQL(cur, select());
    QSqlRecord* rec = cur.primeInsert();
    Q_ASSERT(rec);
    rec->setValue("id", pkey++);
    int i = 0;
    for (i = 0; !fieldDefs[ i ].typeName.isNull(); ++i) {
        if (fieldDefs[ i ].fieldName(), fieldDefs[ i ].nullable)
            rec->setNull(fieldDefs[ i ].fieldName());
        else
            rec->setValue(fieldDefs[ i ].fieldName(), fieldDefs[ i ].val);
    }
    if (!cur.insert()) {
        QFAIL(QString("Couldn't insert record: %1 %2").arg(cur.lastError().databaseText()).arg(cur.lastError().driverText()));
    }
    cur.setForwardOnly(true);
    QVERIFY_SQL(cur, select("id = " + QString::number(pkey - 1)));
    QVERIFY_SQL(cur, next());

    for (i = 0; !fieldDefs[ i ].typeName.isNull(); ++i) {
        if (fieldDefs[ i ].nullable == false)
            continue;
        // multiple inheritance sucks so much
        QVERIFY2(((QSqlQuery)cur).isNull(i + 1), "Check whether '" + fieldDefs[ i ].fieldName() + "' is null in QSqlQuery");
        QVERIFY2(((QSqlRecord)cur).isNull(fieldDefs[ i ].fieldName()), "Check whether '" + fieldDefs[ i ].fieldName() + "' is null in QSqlRecord");
        if (!cur.value(fieldDefs[ i ].fieldName()).isNull())
            qDebug(QString("QVariant is not null for NULL-Value in Field '%1'").arg(fieldDefs[ i ].fieldName()));
    }
#endif
}

void tst_QSqlDatabase::recordTDS()
{
    QFETCH(QString, dbName);
    QSqlDatabase db = QSqlDatabase::database(dbName);
    CHECK_DATABASE(db);

    static const FieldDef fieldDefs[] = {
    FieldDef("tinyint", QVariant::Int,		255),
    FieldDef("smallint", QVariant::Int,		32767),
    FieldDef("int", QVariant::Int,			2147483647),
    FieldDef("numeric(10,9)", QVariant::Double,	1.23456789),
    FieldDef("decimal(10,9)", QVariant::Double,	1.23456789),
    FieldDef("float(4)", QVariant::Double,		1.23456789),
    FieldDef("double precision", QVariant::Double,	1.23456789),
    FieldDef("real", QVariant::Double,		1.23456789),
    FieldDef("smallmoney", QVariant::Double,	100.42),
    FieldDef("money", QVariant::Double,		200.42),
    // accuracy is that of a minute
    FieldDef("smalldatetime", QVariant::DateTime,	QDateTime(QDate::currentDate(), QTime(1, 2, 0, 0))),
    // accuracy is that of a second
    FieldDef("datetime", QVariant::DateTime,	QDateTime(QDate::currentDate(), QTime(1, 2, 3, 0))),
    FieldDef("char(20)", QVariant::String,		"blah1"),
    FieldDef("varchar(20)", QVariant::String,	"blah2"),
    FieldDef("nchar(20)", QVariant::String,	"blah3"),
    FieldDef("nvarchar(20)", QVariant::String,	"blah4"),
    FieldDef("text", QVariant::String,		"blah5"),
#ifdef QT3_SUPPORT
    FieldDef("binary(20)", QVariant::ByteArray,	Q3CString("blah6")),
    FieldDef("varbinary(20)", QVariant::ByteArray, Q3CString("blah7")),
    FieldDef("image", QVariant::ByteArray,		Q3CString("blah8")),
#endif
    FieldDef("bit", QVariant::Int,			1, false),

    FieldDef()
    };

    const int fieldCount = createFieldTable(fieldDefs, db);
    QVERIFY(fieldCount > 0);

    commonFieldTest(fieldDefs, db, fieldCount);
    checkNullValues(fieldDefs, db);
    for (int i = 0; i < ITERATION_COUNT; ++i) {
    checkValues(fieldDefs, db);
    }
}

void tst_QSqlDatabase::recordOCI()
{
    bool hasTimeStamp = false;

    QFETCH(QString, dbName);
    QSqlDatabase db = QSqlDatabase::database(dbName);
    CHECK_DATABASE(db);

    // runtime check for Oracle version since V8 doesn't support TIMESTAMPs
    if (tst_Databases::getOraVersion(db) >= 9) {
    qDebug("Detected Oracle >= 9, TIMESTAMP test enabled");
    hasTimeStamp = true;
    } else {
    qDebug("Detected Oracle < 9, TIMESTAMP test disabled");
    }

    FieldDef tsdef;
    FieldDef tstzdef;
    FieldDef tsltzdef;
    FieldDef intytm;
    FieldDef intdts;

    static const QDateTime dt(QDate::currentDate(), QTime(1, 2, 3, 0));

    if (hasTimeStamp) {
    tsdef = FieldDef("timestamp", QVariant::DateTime,  dt);
    tstzdef = FieldDef("timestamp with time zone", QVariant::DateTime, dt);
    tsltzdef = FieldDef("timestamp with local time zone", QVariant::DateTime, dt);
    intytm = FieldDef("interval year to month", QVariant::String, QString("+01-01"));
    intdts = FieldDef("interval day to second", QVariant::String, QString("+01 00:00:01.000000"));
    }

    const FieldDef fieldDefs[] = {
        FieldDef("char(20)", QVariant::String,          QString("blah1")),
        FieldDef("varchar(20)", QVariant::String,       QString("blah2")),
        FieldDef("nchar(20)", QVariant::String,         QString("blah3")),
        FieldDef("nvarchar2(20)", QVariant::String,     QString("blah4")),
        FieldDef("number(10,5)", QVariant::String,      1.1234567),
        FieldDef("date", QVariant::DateTime,            dt),
#ifdef QT3_SUPPORT
//X?    FieldDef("long raw", QVariant::ByteArray,       QByteArray(Q3CString("blah5"))),
        FieldDef("raw(2000)", QVariant::ByteArray,      QByteArray(Q3CString("blah6")), false),
        FieldDef("blob", QVariant::ByteArray,           QByteArray(Q3CString("blah7"))),
#endif
//FIXME FieldDef("clob", QVariant::CString,             Q3CString("blah8")),
//FIXME FieldDef("nclob", QVariant::CString,            Q3CString("blah9")),
//X     FieldDef("bfile", QVariant::ByteArray,          QByteArray(Q3CString("blah10"))),

    intytm,
    intdts,
    tsdef,
    tstzdef,
    tsltzdef,
    FieldDef()
    };

    const int fieldCount = createFieldTable(fieldDefs, db);
    QVERIFY(fieldCount > 0);

    commonFieldTest(fieldDefs, db, fieldCount);
    checkNullValues(fieldDefs, db);
    for (int i = 0; i < ITERATION_COUNT; ++i) {
    checkValues(fieldDefs, db);
    }

    // some additional tests
    QSqlRecord rec = db.record(qTableName("qtestfields"));
    QCOMPARE(rec.field("T_NUMBER").length(), 10);
    QCOMPARE(rec.field("T_NUMBER").precision(), 5);

    QSqlQuery q(db);
    QVERIFY_SQL(q, exec("SELECT * FROM " + qTableName("qtestfields")));
    rec = q.record();
    QCOMPARE(rec.field("T_NUMBER").length(), 10);
    QCOMPARE(rec.field("T_NUMBER").precision(), 5);
}

void tst_QSqlDatabase::recordPSQL()
{
    QFETCH(QString, dbName);
    QSqlDatabase db = QSqlDatabase::database(dbName);
    CHECK_DATABASE(db);

    FieldDef byteadef;
    if (db.driver()->hasFeature(QSqlDriver::BLOB))
#ifdef QT3_SUPPORT
    byteadef = FieldDef("bytea", QVariant::ByteArray, QByteArray(Q3CString("bl\\ah")));
#else
        byteadef = FieldDef("bytea", QVariant::ByteArray, QByteArray("bl\\ah"));
#endif
    static FieldDef fieldDefs[] = {
    FieldDef("bigint", QVariant::LongLong,	Q_INT64_C(9223372036854775807)),
    FieldDef("bigserial", QVariant::LongLong, 100, false),
    FieldDef("bit", QVariant::String,	"1"), // a bit in postgres is a bit-string
#ifdef QT3_SUPPORT
    FieldDef("boolean", QVariant::Bool,	QVariant(bool(true), 0)),
#endif
    FieldDef("box", QVariant::String,	"(5,6),(1,2)"),
    FieldDef("char(20)", QVariant::String, "blah5678901234567890"),
    FieldDef("varchar(20)", QVariant::String, "blah5678901234567890"),
    FieldDef("cidr", QVariant::String,	"12.123.0.0/24"),
    FieldDef("circle", QVariant::String,	"<(1,2),3>"),
    FieldDef("date", QVariant::Date,	QDate::currentDate()),
    FieldDef("float8", QVariant::Double,	1.12345678912),
    FieldDef("inet", QVariant::String,	"12.123.12.23"),
    FieldDef("integer", QVariant::Int,	2147483647),
    FieldDef("interval", QVariant::String, "1 day 12:59:10"),
//	LOL... you can create a "line" datatype in PostgreSQL <= 7.2.x but
//	as soon as you want to insert data you get a "not implemented yet" error
//	FieldDef("line", QVariant::Polygon, QPolygon(QRect(1, 2, 3, 4))),
    FieldDef("lseg", QVariant::String,     "[(1,1),(2,2)]"),
    FieldDef("macaddr", QVariant::String, "08:00:2b:01:02:03"),
    FieldDef("money", QVariant::String,	"$12.23"),
    FieldDef("numeric", QVariant::Double,  1.2345678912),
    FieldDef("path", QVariant::String,	"((1,2),(3,2),(3,5),(1,5))"),
    FieldDef("point", QVariant::String,	"(1,2)"),
    FieldDef("polygon", QVariant::String,	"((1,2),(3,2),(3,5),(1,5))"),
    FieldDef("real", QVariant::Double,	1.1234),
    FieldDef("smallint", QVariant::Int,	32767),
    FieldDef("serial", QVariant::Int,	100, false),
    FieldDef("text", QVariant::String,	"blah"),
    FieldDef("time(6)", QVariant::Time,	QTime(1, 2, 3)),
    FieldDef("timetz", QVariant::Time,	QTime(1, 2, 3)),
    FieldDef("timestamp(6)", QVariant::DateTime, QDateTime::currentDateTime()),
    FieldDef("timestamptz", QVariant::DateTime, QDateTime::currentDateTime()),
    byteadef,

    FieldDef()
    };

    QSqlQuery q(db);
    q.exec("drop sequence " + qTableName("qtestfields") + "_t_bigserial_seq");
    q.exec("drop sequence " + qTableName("qtestfields") + "_t_serial_seq");
    // older psql cut off the table name
    q.exec("drop sequence " + qTableName("qtestfields").left(15) + "_t_bigserial_seq");
    q.exec("drop sequence " + qTableName("qtestfields").left(18) + "_t_serial_seq");

    const int fieldCount = createFieldTable(fieldDefs, db);
    QVERIFY(fieldCount > 0);

    commonFieldTest(fieldDefs, db, fieldCount);
    checkNullValues(fieldDefs, db);
    for (int i = 0; i < ITERATION_COUNT; ++i) {
    // increase serial values
    for (int i2 = 0; !fieldDefs[ i2 ].typeName.isNull(); ++i2) {
        if (fieldDefs[ i2 ].typeName == "serial" ||
         fieldDefs[ i2 ].typeName == "bigserial") {

        FieldDef def = fieldDefs[ i2 ];
#ifdef QT3_SUPPORT
        def.val = def.val.asInt() + 1;
#else
        def.val = def.val.toInt() + 1;
#endif
        fieldDefs[ i2 ] = def;
        }
    }
    checkValues(fieldDefs, db);
    }
}

void tst_QSqlDatabase::recordMySQL()
{
    QFETCH(QString, dbName);
    QSqlDatabase db = QSqlDatabase::database(dbName);
    CHECK_DATABASE(db);

    FieldDef bin10, varbin10;
    int major = tst_Databases::getMySqlVersion( db ).section( QChar('.'), 0, 0 ).toInt();
    int minor = tst_Databases::getMySqlVersion( db ).section( QChar('.'), 1, 1 ).toInt();
    int revision = tst_Databases::getMySqlVersion( db ).section( QChar('.'), 2, 2 ).toInt();

    /* The below is broken in mysql below 5.0.15
        see http://dev.mysql.com/doc/refman/5.0/en/binary-varbinary.html
        specifically: Before MySQL 5.0.15, the pad value is space. Values are right-padded
        with space on insert, and trailing spaces are removed on select.
    */
    if ( major >5 || ( major == 5 && minor > 0) || ( major == 5 && minor == 0 && revision >= 15) ) {
        bin10 = FieldDef("binary(10)", QVariant::ByteArray, QByteArray(Q3CString("123abc    ")));
        varbin10 = FieldDef("varbinary(10)", QVariant::ByteArray, QByteArray(Q3CString("123abcv   ")));
    }

    static QDateTime dt(QDate::currentDate(), QTime(1, 2, 3, 0));
    static const FieldDef fieldDefs[] = {
    FieldDef("tinyint", QVariant::Int,	    127),
    FieldDef("tinyint unsigned", QVariant::UInt, 255),
    FieldDef("smallint", QVariant::Int,	    32767),
    FieldDef("smallint unsigned", QVariant::UInt, 65535),
    FieldDef("mediumint", QVariant::Int,	    8388607),
    FieldDef("mediumint unsigned", QVariant::UInt, 16777215),
    FieldDef("integer", QVariant::Int,	    2147483647),
    FieldDef("integer unsigned", QVariant::UInt, 4294967295u),
    FieldDef("bigint", QVariant::LongLong,	    Q_INT64_C(9223372036854775807)),
    FieldDef("bigint unsigned", QVariant::ULongLong, Q_UINT64_C(18446744073709551615)),
    FieldDef("float", QVariant::Double,	    1.12345),
    FieldDef("double", QVariant::Double,	    1.123456789),
    FieldDef("decimal(10, 9)", QVariant::String,1.123456789),
    FieldDef("numeric(5, 2)", QVariant::String, 123.67),
    FieldDef("date", QVariant::Date,	    QDate::currentDate()),
    FieldDef("datetime", QVariant::DateTime,   dt),
    FieldDef("timestamp", QVariant::DateTime,  dt, false),
    FieldDef("time", QVariant::Time,	    dt.time()),
    FieldDef("year", QVariant::Int,	    2003),
    FieldDef("char(20)", QVariant::String,	    "Blah"),
    FieldDef("varchar(20)", QVariant::String,  "BlahBlah"),
#ifdef QT3_SUPPORT
    FieldDef("tinyblob", QVariant::ByteArray,  QByteArray(Q3CString("blah1"))),
    FieldDef("blob", QVariant::ByteArray,	    QByteArray(Q3CString("blah2"))),
    FieldDef("mediumblob", QVariant::ByteArray,QByteArray(Q3CString("blah3"))),
    FieldDef("longblob", QVariant::ByteArray,  QByteArray(Q3CString("blah4"))),
#endif
    FieldDef("tinytext", QVariant::String,    QString("blah5")),
    FieldDef("text", QVariant::String,	    QString("blah6")),
    FieldDef("mediumtext", QVariant::String,  QString("blah7")),
    FieldDef("longtext", QVariant::String,    QString("blah8")),
#ifdef QT3_SUPPORT
    bin10,
    varbin10,
#endif
    // SET OF?

    FieldDef()
    };

    const int fieldCount = createFieldTable(fieldDefs, db);
    QVERIFY(fieldCount > 0);

    commonFieldTest(fieldDefs, db, fieldCount);
    checkNullValues(fieldDefs, db);
    for (int i = 0; i < ITERATION_COUNT; ++i) {
    checkValues(fieldDefs, db);
    }

    QSqlQuery q(db);
    QVERIFY_SQL(q, exec("SELECT DATE_SUB(CURDATE(), INTERVAL 2 DAY)"));
    QVERIFY(q.next());
    QCOMPARE(q.value(0).toDateTime().date(), QDate::currentDate().addDays(-2));
}

void tst_QSqlDatabase::recordDB2()
{
    QFETCH(QString, dbName);
    QSqlDatabase db = QSqlDatabase::database(dbName);
    CHECK_DATABASE(db);

    static const FieldDef fieldDefs[] = {
    FieldDef("char(20)", QVariant::String,		QString("Blah1")),
    FieldDef("varchar(20)", QVariant::String,	QString("Blah2")),
    FieldDef("long varchar", QVariant::String,	QString("Blah3")),
    // using BOOLEAN results in "SQL0486N  The BOOLEAN data type is currently only supported internally."
//X	FieldDef("boolean" , QVariant::Bool,		QVariant(true, 1)),
    FieldDef("smallint", QVariant::Int,		32767),
    FieldDef("integer", QVariant::Int,		2147483647),
    FieldDef("bigint", QVariant::LongLong,		Q_INT64_C(9223372036854775807)),
    FieldDef("real", QVariant::Double,		1.12345),
    FieldDef("double", QVariant::Double,		1.23456789),
    FieldDef("float", QVariant::Double,		1.23456789),
    FieldDef("decimal(10,9)", QVariant::Double,    1.234567891),
    FieldDef("numeric(10,9)", QVariant::Double,    1.234567891),
    FieldDef("date", QVariant::Date,		QDate::currentDate()),
    FieldDef("time", QVariant::Time,		QTime(1, 2, 3)),
    FieldDef("timestamp", QVariant::DateTime,	QDateTime::currentDateTime()),
//     FieldDef("graphic(20)", QVariant::String,	QString("Blah4")),
//     FieldDef("vargraphic(20)", QVariant::String,	QString("Blah5")),
//     FieldDef("long vargraphic", QVariant::String,	QString("Blah6")),
#ifdef QT3_SUPPORT
//     FieldDef("clob(20)", QVariant::CString,	QString("Blah7")),
//     FieldDef("dbclob(20)", QVariant::CString,	QString("Blah8")),
//     FieldDef("blob(20)", QVariant::ByteArray,	QByteArray(Q3CString("Blah9"))),
#endif
    //X	FieldDef("datalink", QVariant::String,		QString("DLVALUE('Blah10')")),
    FieldDef()
    };

    const int fieldCount = createFieldTable(fieldDefs, db);
    QVERIFY(fieldCount > 0);

    commonFieldTest(fieldDefs, db, fieldCount);
    checkNullValues(fieldDefs, db);
    for (int i = 0; i < ITERATION_COUNT; ++i) {
    checkValues(fieldDefs, db);
    }
}

void tst_QSqlDatabase::recordIBase()
{
    QFETCH(QString, dbName);
    QSqlDatabase db = QSqlDatabase::database(dbName);
    CHECK_DATABASE(db);

    static const FieldDef fieldDefs[] = {
        FieldDef("char(20)", QVariant::String, QString("Blah1"), false),
        FieldDef("varchar(20)", QVariant::String, QString("Blah2")),
        FieldDef("smallint", QVariant::Int, 32767),
        FieldDef("float", QVariant::Double, 1.2345),
        FieldDef("double precision", QVariant::Double, 1.2345678),
        FieldDef("timestamp", QVariant::DateTime, QDateTime::currentDateTime()),
        FieldDef("time", QVariant::Time, QTime::currentTime()),
        FieldDef("decimal(18)", QVariant::LongLong, Q_INT64_C(9223372036854775807)),
        FieldDef("numeric(5,2)", QVariant::Double, 123.45),

        FieldDef()
    };

    const int fieldCount = createFieldTable(fieldDefs, db);
    QVERIFY(fieldCount > 0);

    commonFieldTest(fieldDefs, db, fieldCount);
    checkNullValues(fieldDefs, db);
    for (int i = 0; i < ITERATION_COUNT; ++i) {
        checkValues(fieldDefs, db);
    }
}

void tst_QSqlDatabase::recordSQLite()
{
    QFETCH(QString, dbName);
    QSqlDatabase db = QSqlDatabase::database(dbName);
    CHECK_DATABASE(db);

    static const FieldDef fieldDefs[] = {
        // The affinity of these fields are TEXT so SQLite should give us strings, not ints or doubles.
        FieldDef("char(20)", QVariant::String,          QString("123")),
        FieldDef("varchar(20)", QVariant::String,       QString("123.4")),
        FieldDef("clob", QVariant::String,              QString("123.45")),
        FieldDef("text", QVariant::String,              QString("123.456")),

        FieldDef("integer", QVariant::Int,              QVariant(13)),
        FieldDef("int", QVariant::Int,                  QVariant(12)),

        FieldDef()
    };

    const int fieldCount = createFieldTable(fieldDefs, db);
    QVERIFY(fieldCount > 0);

    commonFieldTest(fieldDefs, db, fieldCount);
    checkNullValues(fieldDefs, db);
    for (int i = 0; i < ITERATION_COUNT; ++i) {
        checkValues(fieldDefs, db);
    }
}

void tst_QSqlDatabase::recordSQLServer()
{
    QFETCH(QString, dbName);
    QSqlDatabase db = QSqlDatabase::database(dbName);
    CHECK_DATABASE(db);

    if (!tst_Databases::isSqlServer(db)) {
    QSKIP("SQL server specific test", SkipSingle);
    return;
    }

    // ### TODO: Add the rest of the fields
    static const FieldDef fieldDefs[] = {
        FieldDef("varchar(20)", QVariant::String, QString("Blah1")),
        FieldDef("bigint", QVariant::LongLong, 12345),
        FieldDef("int", QVariant::Int, 123456),
        FieldDef("tinyint", QVariant::Int, 255),
#ifdef QT3_SUPPORT
        FieldDef("image", QVariant::ByteArray, Q3CString("Blah1")),
#endif
        FieldDef("float", QVariant::Double, 1.12345),
        FieldDef("numeric(5,2)", QVariant::Double, 123.45),
        FieldDef("uniqueidentifier", QVariant::String,
            QString("AA7DF450-F119-11CD-8465-00AA00425D90")),

        FieldDef()
    };

    const int fieldCount = createFieldTable(fieldDefs, db);
    QVERIFY(fieldCount > 0);

    commonFieldTest(fieldDefs, db, fieldCount);
    checkNullValues(fieldDefs, db);
    for (int i = 0; i < ITERATION_COUNT; ++i) {
        checkValues(fieldDefs, db);
    }
}

void tst_QSqlDatabase::recordAccess()
{
    QFETCH(QString, dbName);
    QSqlDatabase db = QSqlDatabase::database(dbName);
    CHECK_DATABASE(db);

    if (!tst_Databases::isMSAccess(db)) {
    QSKIP("MS Access specific test", SkipSingle);
    return;
    }

    QString memo;
    for (int i = 0; i < 32; i++)
        memo.append("ABCDEFGH12345678abcdefgh12345678");

    // ### TODO: Add the rest of the fields
    static const FieldDef fieldDefs[] = {
    FieldDef("varchar(20)", QVariant::String, QString("Blah1")),
    FieldDef("single", QVariant::Double, 1.12345),
    FieldDef("double", QVariant::Double, 1.123456),
        FieldDef("byte", QVariant::Int, 255),
#ifdef QT3_SUPPORT
    FieldDef("binary", QVariant::ByteArray, Q3CString("Blah2")),
#endif
    FieldDef("long", QVariant::Int, 2147483647),
        FieldDef("memo", QVariant::String, memo),
    FieldDef()
    };

    const int fieldCount = createFieldTable(fieldDefs, db);
    QVERIFY(fieldCount > 0);

    commonFieldTest(fieldDefs, db, fieldCount);
    checkNullValues(fieldDefs, db);
    for (int i = 0; i < ITERATION_COUNT; ++i) {
        checkValues(fieldDefs, db);
    }
}

void tst_QSqlDatabase::transaction()
{
    QFETCH(QString, dbName);
    QSqlDatabase db = QSqlDatabase::database(dbName);
    CHECK_DATABASE(db);

    if (!db.driver()->hasFeature(QSqlDriver::Transactions)) {
    QSKIP("DBMS not transaction capable", SkipSingle);
    }

    QVERIFY(db.transaction());

    QSqlQuery q(db);
    QVERIFY_SQL(q, exec("insert into " + qTableName("qtest") + " values (40, 'VarChar40', 'Char40', 40.40)"));
    QVERIFY_SQL(q, exec("select * from " + qTableName("qtest") + " where id = 40"));
    QVERIFY(q.next());
    QCOMPARE(q.value(0).toInt(), 40);
    q.clear();

    QVERIFY(db.commit());

    QVERIFY(db.transaction());
    QVERIFY_SQL(q, exec("select * from " + qTableName("qtest") + " where id = 40"));
    QVERIFY(q.next());
    QCOMPARE(q.value(0).toInt(), 40);
    q.clear();
    QVERIFY(db.commit());

    QVERIFY(db.transaction());
    QVERIFY_SQL(q, exec("insert into " + qTableName("qtest") + " values (41, 'VarChar41', 'Char41', 41.41)"));
    QVERIFY_SQL(q, exec("select * from " + qTableName("qtest") + " where id = 41"));
    QVERIFY(q.next());
    QCOMPARE(q.value(0).toInt(), 41);
    q.clear(); // for SQLite which does not allow any references on rows that shall be rolled back
    if (!db.rollback()) {
    if (db.driverName().startsWith("QMYSQL")) {
        qDebug("MySQL: " + tst_Databases::printError(db.lastError()));
        QSKIP("MySQL transaction failed ", SkipSingle); //non-fatal
    } else {
        QFAIL("Could not rollback transaction: " + tst_Databases::printError(db.lastError()));
        }
    }

    QVERIFY_SQL(q, exec("select * from " + qTableName("qtest") + " where id = 41"));
    QVERIFY(!q.next());

    populateTestTables(db);
}

void tst_QSqlDatabase::bigIntField()
{
    QFETCH(QString, dbName);
    QSqlDatabase db = QSqlDatabase::database(dbName);
    CHECK_DATABASE(db);

    QSqlQuery q(db);
    q.setForwardOnly(true);

    QString drvName = db.driverName();
    if (drvName.startsWith("QMYSQL")) {
        QVERIFY_SQL(q, exec("create table " + qTableName("qtest_bigint") + " (id int, t_s64bit bigint, t_u64bit bigint unsigned)"));
    } else if (drvName.startsWith("QPSQL")
                || drvName.startsWith("QDB2")
                || tst_Databases::isSqlServer(db)) {
        QVERIFY_SQL(q, exec("create table " + qTableName("qtest_bigint") + "(id int, t_s64bit bigint, t_u64bit bigint)"));
    } else if (drvName.startsWith("QOCI")) {
        QVERIFY_SQL(q, exec("create table " + qTableName("qtest_bigint") + " (id int, t_s64bit int, t_u64bit int)"));
    } else {
        QSKIP("no 64 bit integer support", SkipAll);
    }
    QVERIFY(q.prepare("insert into " + qTableName("qtest_bigint") + " values (?, ?, ?)"));
    qlonglong ll = Q_INT64_C(9223372036854775807);
    qulonglong ull = Q_UINT64_C(18446744073709551615);

    if (drvName.startsWith("QMYSQL") || drvName.startsWith("QOCI")) {
        q.bindValue(0, 0);
        q.bindValue(1, ll);
        q.bindValue(2, ull);
        QVERIFY_SQL(q, exec());
        q.bindValue(0, 1);
        q.bindValue(1, -ll);
        q.bindValue(2, ull);
        QVERIFY_SQL(q, exec());
    } else {
        // usinged bigint fields not supported - a cast is necessary
        q.bindValue(0, 0);
        q.bindValue(1, ll);
        q.bindValue(2, (qlonglong) ull);
        QVERIFY_SQL(q, exec());
        q.bindValue(0, 1);
        q.bindValue(1, -ll);
        q.bindValue(2,  (qlonglong) ull);
        QVERIFY_SQL(q, exec());
    }
    QVERIFY(q.exec("select * from " + qTableName("qtest_bigint") + " order by id"));
    QVERIFY(q.next());
    QCOMPARE(q.value(1).toLongLong(), ll);
    QCOMPARE(q.value(2).toULongLong(), ull);
    QVERIFY(q.next());
    QCOMPARE(q.value(1).toLongLong(), -ll);
    QCOMPARE(q.value(2).toULongLong(), ull);
}

void tst_QSqlDatabase::caseSensivity()
{
    QFETCH(QString, dbName);
    QSqlDatabase db = QSqlDatabase::database(dbName);
    CHECK_DATABASE(db);

    bool cs = false;
    if (db.driverName().startsWith("QMYSQL")
     || db.driverName().startsWith("QSQLITE")
     || db.driverName().startsWith("QTDS"))
    cs = true;

    QSqlRecord rec = db.record(qTableName("qtest"));
    QVERIFY((int)rec.count() > 0);
    if (!cs) {
    rec = db.record(qTableName("QTEST").toUpper());
    QVERIFY((int)rec.count() > 0);
    rec = db.record(qTableName("qTesT"));
    QVERIFY((int)rec.count() > 0);
    }

#ifdef QT3_SUPPORT
    Q3SqlRecordInfo rInf = db.recordInfo(qTableName("qtest"));
    QVERIFY((int)rInf.count() > 0);
    if (!cs) {
    rInf = db.recordInfo(qTableName("QTEST").upper());
    QVERIFY((int)rInf.count() > 0);
    rInf = db.recordInfo(qTableName("qTesT"));
    QVERIFY((int)rInf.count() > 0);
    }
#endif

    rec = db.primaryIndex(qTableName("qtest"));
    QVERIFY((int)rec.count() > 0);
    if (!cs) {
    rec = db.primaryIndex(qTableName("QTEST").toUpper());
    QVERIFY((int)rec.count() > 0);
    rec = db.primaryIndex(qTableName("qTesT"));
    QVERIFY((int)rec.count() > 0);
    }
}

void tst_QSqlDatabase::noEscapedFieldNamesInRecord()
{
    QFETCH(QString, dbName);
    QSqlDatabase db = QSqlDatabase::database(dbName);
    CHECK_DATABASE(db);

    QString fieldname("t_varchar");
    if (db.driverName().startsWith("QOCI") || db.driverName().startsWith("QIBASE") || db.driverName().startsWith("QDB2"))
        fieldname = fieldname.toUpper();

    QSqlQuery q(db);
    QString query = "SELECT " + db.driver()->escapeIdentifier(fieldname, QSqlDriver::FieldName) + " FROM " + qTableName("qtest");
    QVERIFY_SQL(q, exec(query));
    QCOMPARE(q.record().fieldName(0), fieldname);
}

void tst_QSqlDatabase::psql_schemas()
{
    QFETCH(QString, dbName);
    QSqlDatabase db = QSqlDatabase::database(dbName);
    CHECK_DATABASE(db);

    if (!db.tables(QSql::SystemTables).contains("pg_namespace"))
        QSKIP("server does not support schemas", SkipSingle);

    QSqlQuery q(db);
    QVERIFY_SQL(q, exec("CREATE SCHEMA " + qTableName("qtestschema")));

    QString table = qTableName("qtestschema") + '.' + qTableName("qtesttable");
    QVERIFY_SQL(q, exec("CREATE TABLE " + table + " (id int primary key, name varchar(20))"));

    QVERIFY(db.tables().contains(table));

    QSqlRecord rec = db.record(table);
    QCOMPARE(rec.count(), 2);
    QCOMPARE(rec.fieldName(0), QString("id"));
    QCOMPARE(rec.fieldName(1), QString("name"));

#ifdef QT3_SUPPORT
    rec = db.record(QSqlQuery("select * from " + table, db));
    QCOMPARE(rec.count(), 2);
    QCOMPARE(rec.fieldName(0), QString("id"));
    QCOMPARE(rec.fieldName(1), QString("name"));
#endif
    QSqlIndex idx = db.primaryIndex(table);
    QCOMPARE(idx.count(), 1);
    QCOMPARE(idx.fieldName(0), QString("id"));
}

void tst_QSqlDatabase::psql_escapedIdentifiers()
{
    QFETCH(QString, dbName);
    QSqlDatabase db = QSqlDatabase::database(dbName);
    QSqlDriver* drv = db.driver();
    CHECK_DATABASE(db);

    if (!db.tables(QSql::SystemTables).contains("pg_namespace"))
        QSKIP("server does not support schemas", SkipSingle);

    QSqlQuery q(db);

    QString schemaName = qTableName("qtestScHeMa");
    QString tableName = qTableName("qtestTaBlE");
    QString field1Name = QString("fIeLdNaMe");
    QString field2Name = QString("ZuLu");

    QString createSchema = QString("CREATE SCHEMA \"%1\"").arg(schemaName);
    QVERIFY_SQL(q, exec(createSchema));
    QString createTable = QString("CREATE TABLE \"%1\".\"%2\" (\"%3\" int PRIMARY KEY, \"%4\" varchar(20))").arg(schemaName).arg(tableName).arg(field1Name).arg(field2Name);
    QVERIFY_SQL(q, exec(createTable));

    QVERIFY(db.tables().contains(schemaName + '.' + tableName, Qt::CaseSensitive));

    QSqlField fld1(field1Name, QVariant::Int);
    QSqlField fld2(field2Name, QVariant::String);
    QSqlRecord rec;
    rec.append(fld1);
    rec.append(fld2);

    QVERIFY_SQL(q, exec(drv->sqlStatement(QSqlDriver::SelectStatement, schemaName + '.' + tableName, rec, false)));

    rec = q.record();
    QCOMPARE(rec.count(), 2);
    QCOMPARE(rec.fieldName(0), field1Name);
    QCOMPARE(rec.fieldName(1), field2Name);
    QCOMPARE(rec.field(0).type(), QVariant::Int);

    q.exec(QString("DROP SCHEMA \"%1\" CASCADE").arg(schemaName));
}


void tst_QSqlDatabase::psql_escapeBytea()
{
    QFETCH(QString, dbName);
    QSqlDatabase db = QSqlDatabase::database(dbName);
    CHECK_DATABASE(db);

    const char dta[4] = {'\x71', '\x14', '\x32', '\x81'};
    QByteArray ba(dta, 4);

    QSqlQuery q(db);
    QString tableName = qTableName("batable");
    QVERIFY_SQL(q, exec(QString("CREATE TABLE %1 (ba bytea)").arg(tableName)));

    QSqlQuery iq(db);
    QVERIFY_SQL(iq, prepare(QString("INSERT INTO %1 VALUES (?)").arg(tableName)));
    iq.bindValue(0, QVariant(ba));
    QVERIFY_SQL(iq, exec());

    QVERIFY_SQL(q, exec(QString("SELECT ba FROM %1").arg(tableName)));
    QVERIFY_SQL(q, next());

    QByteArray res = q.value(0).toByteArray();
    int i = 0;
    for (; i < ba.size(); ++i){
        if (ba[i] != res[i])
            break;
    }

    QCOMPARE(i, 4);
}

void tst_QSqlDatabase::bug_249059()
{
    QFETCH(QString, dbName);
    QSqlDatabase db = QSqlDatabase::database(dbName);
    CHECK_DATABASE(db);

    QSqlQuery q(db);
    QString tableName = qTableName("bug_249059");
    QVERIFY_SQL(q, exec(QString("CREATE TABLE %1 (dt timestamp, t time)").arg(tableName)));

    QSqlQuery iq(db);
    QVERIFY_SQL(iq, prepare(QString("INSERT INTO %1 VALUES (?, ?)").arg(tableName)));
    iq.bindValue(0, QVariant(QString("2001-09-09 04:05:06.789 -5:00")));
    iq.bindValue(1, QVariant(QString("04:05:06.789 -5:00")));
    QVERIFY_SQL(iq, exec());
    iq.bindValue(0, QVariant(QString("2001-09-09 04:05:06.789 +5:00")));
    iq.bindValue(1, QVariant(QString("04:05:06.789 +5:00")));
    QVERIFY_SQL(iq, exec());

    QVERIFY_SQL(q, exec(QString("SELECT dt, t FROM %1").arg(tableName)));
    QVERIFY_SQL(q, next());
    QDateTime dt1=q.value(0).toDateTime();
    QTime t1=q.value(1).toTime();
    QVERIFY_SQL(q, next());
    QDateTime dt2=q.value(0).toDateTime();
    QTime t2=q.value(1).toTime();

    // These will fail when timezone support is added, when that's the case, set the second record to 14:05:06.789 and it should work correctly
    QCOMPARE(dt1, dt2);
    QCOMPARE(t1, t2);
}

// This test should be rewritten to work with Oracle as well - or the Oracle driver
// should be fixed to make this test pass (handle overflows)
void tst_QSqlDatabase::precisionPolicy()
{
    QFETCH(QString, dbName);
    QSqlDatabase db = QSqlDatabase::database(dbName);
    CHECK_DATABASE(db);
//     DBMS_SPECIFIC(db, "QPSQL");

    QSqlQuery q(db);
    QString tableName = qTableName("qtest_prec");
    if(!db.driver()->hasFeature(QSqlDriver::LowPrecisionNumbers))
        QSKIP("Driver or database doesn't support setting precision policy", SkipSingle);

    // Create a test table with some data
    QVERIFY_SQL(q, exec(QString("CREATE TABLE %1 (id smallint, num numeric(20,0))").arg(tableName)));
    QVERIFY_SQL(q, prepare(QString("INSERT INTO %1 VALUES (?, ?)").arg(tableName)));
    q.bindValue(0, 1);
    q.bindValue(1, 123);
    QVERIFY_SQL(q, exec());
    q.bindValue(0, 2);
    q.bindValue(1, QString("18500000000000000000"));
    QVERIFY_SQL(q, exec());

    // These are expected to pass
    QString query = QString("SELECT num FROM %1 WHERE id = 1").arg(tableName);
    QVERIFY_SQL(q, exec(query));
    QVERIFY_SQL(q, next());
    QCOMPARE(q.value(0).type(), QVariant::String);

    q.setNumericalPrecisionPolicy(QSql::LowPrecisionInt64);
    QVERIFY_SQL(q, exec(query));
    QVERIFY_SQL(q, next());
    QCOMPARE(q.value(0).type(), QVariant::LongLong);
    QCOMPARE(q.value(0).toLongLong(), (qlonglong)123);

    q.setNumericalPrecisionPolicy(QSql::LowPrecisionInt32);
    QVERIFY_SQL(q, exec(query));
    QVERIFY_SQL(q, next());
    QCOMPARE(q.value(0).type(), QVariant::Int);
    QCOMPARE(q.value(0).toInt(), 123);

    q.setNumericalPrecisionPolicy(QSql::LowPrecisionDouble);
    QVERIFY_SQL(q, exec(query));
    QVERIFY_SQL(q, next());
    QCOMPARE(q.value(0).type(), QVariant::Double);
    QCOMPARE(q.value(0).toDouble(), (double)123);

    query = QString("SELECT num FROM %1 WHERE id = 2").arg(tableName);
    QVERIFY_SQL(q, exec(query));
    QVERIFY_SQL(q, next());
    QCOMPARE(q.value(0).type(), QVariant::Double);
    QCOMPARE(q.value(0).toDouble(), QString("18500000000000000000").toDouble());

    // Postgres returns invalid QVariants on overflow
    q.setNumericalPrecisionPolicy(QSql::HighPrecision);
    QVERIFY_SQL(q, exec(query));
    QVERIFY_SQL(q, next());
    QCOMPARE(q.value(0).type(), QVariant::String);

    q.setNumericalPrecisionPolicy(QSql::LowPrecisionInt64);
    QVERIFY_SQL(q, exec(query));
    QVERIFY_SQL(q, next());
    QCOMPARE(q.value(0).type(), QVariant::Invalid);

    q.setNumericalPrecisionPolicy(QSql::LowPrecisionInt32);
    QVERIFY_SQL(q, exec(query));
    QVERIFY_SQL(q, next());
    QCOMPARE(q.value(0).type(), QVariant::Invalid);
}

// This test needs a ODBC data source containing MYSQL in it's name
void tst_QSqlDatabase::mysqlOdbc_unsignedIntegers()
{
    QFETCH(QString, dbName);
    QSqlDatabase db = QSqlDatabase::database(dbName);
    CHECK_DATABASE(db);

    if (!db.driverName().startsWith("QODBC") || !dbName.toUpper().contains("MYSQL")) {
       QSKIP("MySQL through ODBC-driver specific test", SkipSingle);
       return;
    }

    QSqlQuery q(db);
    QString tableName = qTableName("uint");
    QVERIFY_SQL(q, exec(QString("CREATE TABLE %1 (foo integer(10) unsigned, bar integer(10))").arg(tableName)));
    QVERIFY_SQL(q, exec(QString("INSERT INTO %1 VALUES (-4000000000, -4000000000)").arg(tableName)));
    QVERIFY_SQL(q, exec(QString("INSERT INTO %1 VALUES (4000000000, 4000000000)").arg(tableName)));

    QVERIFY_SQL(q, exec(QString("SELECT foo, bar FROM %1").arg(tableName)));
    QVERIFY(q.next());
    QCOMPARE(q.value(0).toString(), QString("0"));
    QCOMPARE(q.value(1).toString(), QString("-2147483648"));
    QVERIFY(q.next());
    QCOMPARE(q.value(0).toString(), QString("4000000000"));
    QCOMPARE(q.value(1).toString(), QString("2147483647"));
}

void tst_QSqlDatabase::accessOdbc_strings()
{
    QFETCH(QString, dbName);
    QSqlDatabase db = QSqlDatabase::database(dbName);
    CHECK_DATABASE(db);

    if (!tst_Databases::isMSAccess(db)) {
    QSKIP("MS Access specific test", SkipSingle);
    return;
    }

    QSqlQuery q(db);
    QString tableName = qTableName("strings");
    QVERIFY_SQL(q, exec(QString("CREATE TABLE %1 (aStr memo, bStr memo, cStr memo, dStr memo"
            ", eStr memo, fStr memo, gStr memo, hStr memo)").arg(tableName)));

    QVERIFY_SQL(q, prepare(QString("INSERT INTO %1 VALUES (?, ?, ?, ?, ?, ?, ?, ?)").arg(tableName)));
    QString aStr, bStr, cStr, dStr, eStr, fStr, gStr, hStr;

    q.bindValue(0, aStr.fill('A', 32));
    q.bindValue(1, bStr.fill('B', 127));
    q.bindValue(2, cStr.fill('C', 128));
    q.bindValue(3, dStr.fill('D', 129));
    q.bindValue(4, eStr.fill('E', 254));
    q.bindValue(5, fStr.fill('F', 255));
    q.bindValue(6, gStr.fill('G', 256));
    q.bindValue(7, hStr.fill('H', 512));

    QVERIFY_SQL(q, exec());

    QVERIFY_SQL(q, exec(QString("SELECT aStr, bStr, cStr, dStr, eStr, fStr, gStr, hStr FROM %1").arg(tableName)));
    q.next();
    QCOMPARE(q.value(0).toString(), aStr);
    QCOMPARE(q.value(1).toString(), bStr);
    QCOMPARE(q.value(2).toString(), cStr);
    QCOMPARE(q.value(3).toString(), dStr);
    QCOMPARE(q.value(4).toString(), eStr);
    QCOMPARE(q.value(5).toString(), fStr);
    QCOMPARE(q.value(6).toString(), gStr);
    QCOMPARE(q.value(7).toString(), hStr);
}

// For task 125053
void tst_QSqlDatabase::ibase_numericFields()
{
    QFETCH(QString, dbName);
    QSqlDatabase db = QSqlDatabase::database(dbName);
    CHECK_DATABASE(db);

    QSqlQuery q(db);
    QString tableName = qTableName("numericfields");
    QVERIFY_SQL(q, exec(QString("CREATE TABLE %1 (id int not null, num1 NUMERIC(2,1), "
        "num2 NUMERIC(5,2), num3 NUMERIC(10,3), "
        "num4 NUMERIC(18,4))").arg(tableName)));

    QVERIFY_SQL(q, exec(QString("INSERT INTO %1 VALUES (1, 1.1, 123.45, 1234567.123, 10203040506070.8090)").arg(tableName)));

    QVERIFY_SQL(q, prepare(QString("INSERT INTO %1 VALUES (?, ?, ?, ?, ?)").arg(tableName)));

    double num1 = 1.1;
    double num2 = 123.45;
    double num3 = 1234567.123;
    double num4 = 10203040506070.8090;

    q.bindValue(0, 2);
    q.bindValue(1, QVariant(num1));
    q.bindValue(2, QVariant(num2));
    q.bindValue(3, QVariant(num3));
    q.bindValue(4, QVariant(num4));
    QVERIFY_SQL(q, exec());

    QVERIFY_SQL(q, exec(QString("SELECT id, num1, num2, num3, num4 FROM %1").arg(tableName)));

    int id = 0;
    while (q.next()) {
        QCOMPARE(q.value(0).toInt(), ++id);
        QCOMPARE(q.value(1).toString(), QString("%1").arg(num1));
        QCOMPARE(q.value(2).toString(), QString("%1").arg(num2));
        QCOMPARE(QString("%1").arg(q.value(3).toDouble()), QString("%1").arg(num3));
        QCOMPARE(QString("%1").arg(q.value(4).toDouble()), QString("%1").arg(num4));
        QVERIFY(q.value(0).type() == QVariant::Int);
        QVERIFY(q.value(1).type() == QVariant::Double);
        QVERIFY(q.value(2).type() == QVariant::Double);
        QVERIFY(q.value(3).type() == QVariant::Double);
        QVERIFY(q.value(4).type() == QVariant::Double);

        QCOMPARE(q.record().field(1).length(), 2);
        QCOMPARE(q.record().field(1).precision(), 1);
        QCOMPARE(q.record().field(2).length(), 5);
        QCOMPARE(q.record().field(2).precision(), 2);
        QCOMPARE(q.record().field(3).length(), 10);
        QCOMPARE(q.record().field(3).precision(), 3);
        QCOMPARE(q.record().field(4).length(), 18);
        QCOMPARE(q.record().field(4).precision(), 4);
        QVERIFY(q.record().field(0).requiredStatus() == QSqlField::Required);
        QVERIFY(q.record().field(1).requiredStatus() == QSqlField::Optional);
    }

    QSqlRecord r = db.record(tableName);
    QVERIFY(r.field(0).type() == QVariant::Int);
    QVERIFY(r.field(1).type() == QVariant::Double);
    QVERIFY(r.field(2).type() == QVariant::Double);
    QVERIFY(r.field(3).type() == QVariant::Double);
    QVERIFY(r.field(4).type() == QVariant::Double);
    QCOMPARE(r.field(1).length(), 2);
    QCOMPARE(r.field(1).precision(), 1);
    QCOMPARE(r.field(2).length(), 5);
    QCOMPARE(r.field(2).precision(), 2);
    QCOMPARE(r.field(3).length(), 10);
    QCOMPARE(r.field(3).precision(), 3);
    QCOMPARE(r.field(4).length(), 18);
    QCOMPARE(r.field(4).precision(), 4);
    QVERIFY(r.field(0).requiredStatus() == QSqlField::Required);
    QVERIFY(r.field(1).requiredStatus() == QSqlField::Optional);
}

void tst_QSqlDatabase::ibase_fetchBlobs()
{
    QFETCH(QString, dbName);
    QSqlDatabase db = QSqlDatabase::database(dbName);
    CHECK_DATABASE(db);

    QString tableName = qTableName("qtest_ibaseblobs");
    QSqlQuery q(db);
    QVERIFY_SQL(q, exec(QString("CREATE TABLE %1 (blob1 BLOB segment size 256)").arg(tableName)));

    QVERIFY_SQL(q, prepare(QString("INSERT INTO %1 VALUES (?)").arg(tableName)));
    q.bindValue(0, QByteArray().fill('x', 1024));
    QVERIFY_SQL(q, exec());

    QVERIFY_SQL(q, prepare(QString("INSERT INTO %1 VALUES (?)").arg(tableName)));
    q.bindValue(0, QByteArray().fill('x', 16383));
    QVERIFY_SQL(q, exec());

    QVERIFY_SQL(q, prepare(QString("INSERT INTO %1 VALUES (?)").arg(tableName)));
    q.bindValue(0, QByteArray().fill('x', 17408));
    QVERIFY_SQL(q, exec());

    QVERIFY_SQL(q, exec(QString("SELECT * FROM %1").arg(tableName)));

    QVERIFY_SQL(q, next());
    QCOMPARE(q.value(0).toByteArray().size(), 1024);
    QVERIFY_SQL(q, next());
    QCOMPARE(q.value(0).toByteArray().size(), 16383);
    QVERIFY_SQL(q, next());
    QCOMPARE(q.value(0).toByteArray().size(), 17408);
}

void tst_QSqlDatabase::ibase_procWithoutReturnValues()
{
    QFETCH(QString, dbName);
    QSqlDatabase db = QSqlDatabase::database(dbName);
    CHECK_DATABASE(db);

    QSqlQuery q(db);
    QString procName = qTableName("qtest_proc1");
    q.exec(QString("drop procedure %1").arg(procName));
    QVERIFY_SQL(q, exec("CREATE PROCEDURE " + procName + " (str VARCHAR(10))\nAS BEGIN\nstr='test';\nEND;"));
    QVERIFY_SQL(q, exec(QString("execute procedure %1('qtest')").arg(procName)));
    q.exec(QString("drop procedure %1").arg(procName));
}

void tst_QSqlDatabase::ibase_procWithReturnValues()
{
    QFETCH(QString, dbName);
    QSqlDatabase db = QSqlDatabase::database(dbName);
    CHECK_DATABASE(db);

    if (!db.driverName().startsWith("QIBASE")) {
       QSKIP("InterBase specific test", SkipSingle);
       return;
    }

    QString procName = qTableName("qtest_proc2");

    QSqlQuery q(db);
    q.exec(QString("drop procedure %1").arg(procName));
    QVERIFY_SQL(q, exec("CREATE PROCEDURE " + procName + " ("
                        "\nABC INTEGER)"
                        "\nRETURNS ("
                        "\nRESULT INTEGER)"
                        "\nAS"
                        "\nbegin"
                        "\nRESULT = 10;"
                        "\nsuspend;"
                        "\nend"));

    // Interbase procedures can be executed in two ways: EXECUTE PROCEDURE or SELECT
    QVERIFY_SQL(q, exec(QString("execute procedure %1(123)").arg(procName)));
    QVERIFY_SQL(q, next());
    QCOMPARE(q.value(0).toInt(), 10);
    QVERIFY_SQL(q, exec(QString("select result from %1(456)").arg(procName)));
    QVERIFY_SQL(q, next());
    QCOMPARE(q.value(0).toInt(), 10);

    q.exec(QString("drop procedure %1").arg(procName));
}

void tst_QSqlDatabase::formatValueTrimStrings()
{
    QFETCH(QString, dbName);
    QSqlDatabase db = QSqlDatabase::database(dbName);
    CHECK_DATABASE(db);

    QSqlQuery q(db);

    QVERIFY_SQL(q, exec(QString("INSERT INTO %1 (id, t_varchar, t_char) values (50, 'Trim Test ', 'Trim Test 2   ')").arg(qTableName("qtest"))));
    QVERIFY_SQL(q, exec(QString("INSERT INTO %1 (id, t_varchar, t_char) values (51, 'TrimTest', 'Trim Test 2')").arg(qTableName("qtest"))));
    QVERIFY_SQL(q, exec(QString("INSERT INTO %1 (id, t_varchar, t_char) values (52, ' ', '    ')").arg(qTableName("qtest"))));

    QVERIFY_SQL(q, exec(QString("SELECT t_varchar, t_char FROM %1 WHERE id >= 50 AND id <= 52 ORDER BY id").arg(qTableName("qtest"))));

    QVERIFY_SQL(q, next());

    QCOMPARE(db.driver()->formatValue(q.record().field(0), true), QString("'Trim Test'"));
    QCOMPARE(db.driver()->formatValue(q.record().field(1), true), QString("'Trim Test 2'"));

    QVERIFY_SQL(q, next());
    QCOMPARE(db.driver()->formatValue(q.record().field(0), true), QString("'TrimTest'"));
    QCOMPARE(db.driver()->formatValue(q.record().field(1), true), QString("'Trim Test 2'"));

    QVERIFY_SQL(q, next());
    QCOMPARE(db.driver()->formatValue(q.record().field(0), true), QString("''"));
    QCOMPARE(db.driver()->formatValue(q.record().field(1), true), QString("''"));

}

void tst_QSqlDatabase::odbc_reopenDatabase()
{
    QFETCH(QString, dbName);
    QSqlDatabase db = QSqlDatabase::database(dbName);
    CHECK_DATABASE(db);

    QSqlQuery q(db);
    QVERIFY_SQL(q, exec("SELECT * from " + qTableName("qtest")));
    QVERIFY_SQL(q, next());
    db.open();
    QVERIFY_SQL(q, exec("SELECT * from " + qTableName("qtest")));
    QVERIFY_SQL(q, next());
    db.open();
}

void tst_QSqlDatabase::odbc_bindBoolean()
{
    QFETCH(QString, dbName);
    QSqlDatabase db = QSqlDatabase::database(dbName);
    CHECK_DATABASE(db);

    QSqlQuery q(db);
    QVERIFY_SQL(q, exec("CREATE TABLE " + qTableName("qtestBindBool") + "(id int, boolvalue bit)"));

    // Bind and insert
    QVERIFY_SQL(q, prepare("INSERT INTO " + qTableName("qtestBindBool") + " VALUES(?, ?)"));
    q.bindValue(0, 1);
    q.bindValue(1, true);
    QVERIFY_SQL(q, exec());
    q.bindValue(0, 2);
    q.bindValue(1, false);
    QVERIFY_SQL(q, exec());

    // Retrive
    QVERIFY_SQL(q, exec("SELECT id, boolvalue FROM " + qTableName("qtestBindBool") + " ORDER BY id"));
    QVERIFY_SQL(q, next());
    QCOMPARE(q.value(0).toInt(), 1);
    QCOMPARE(q.value(1).toBool(), true);
    QVERIFY_SQL(q, next());
    QCOMPARE(q.value(0).toInt(), 2);
    QCOMPARE(q.value(1).toBool(), false);
}

void tst_QSqlDatabase::mysql_multiselect()
{
    QFETCH(QString, dbName);
    QSqlDatabase db = QSqlDatabase::database(dbName);
    CHECK_DATABASE(db);

    QSqlQuery q(db);
    QVERIFY_SQL(q, exec("select version()"));
    QVERIFY_SQL(q, next());
    QString version=tst_Databases::getMySqlVersion( db );
    int ver=version.section(QChar::fromLatin1('.'),0,1).toDouble();
    if (ver >= 4.1)
        QSKIP("Test requires MySQL >= 4.1", SkipSingle);

    QVERIFY_SQL(q, exec("SELECT * FROM " + qTableName("qtest") + "; SELECT * FROM " + qTableName("qtest")));
    QVERIFY_SQL(q, next());
    QVERIFY_SQL(q, exec("SELECT * FROM " + qTableName("qtest") + "; SELECT * FROM " + qTableName("qtest")));
    QVERIFY_SQL(q, next());
    QVERIFY_SQL(q, exec("SELECT * FROM " + qTableName("qtest")));
}

void tst_QSqlDatabase::ibase_useCustomCharset()
{
    QFETCH(QString, dbName);
    QSqlDatabase db = QSqlDatabase::database(dbName);
    CHECK_DATABASE(db);
    QString nonlatin1string("��");

    db.close();
    db.setConnectOptions("ISC_DPB_LC_CTYPE=Latin1");
    db.open();

    QString tableName = qTableName("latin1table");

    QSqlQuery q(db);
    QVERIFY_SQL(q, exec(QString("CREATE TABLE %1(text VARCHAR(6) CHARACTER SET Latin1)").arg(tableName)));
    QVERIFY_SQL(q, prepare(QString("INSERT INTO %1 VALUES(?)").arg(tableName)));
    q.addBindValue(nonlatin1string);
    QVERIFY_SQL(q, exec());
    QVERIFY_SQL(q, exec(QString("SELECT text FROM %1").arg(tableName)));
    QVERIFY_SQL(q, next());
    QCOMPARE(toHex(q.value(0).toString()), toHex(nonlatin1string));
}

void tst_QSqlDatabase::oci_serverDetach()
{
    QFETCH(QString, dbName);
    QSqlDatabase db = QSqlDatabase::database(dbName);
    CHECK_DATABASE(db);

    for (int i = 0; i < 2; i++) {
        db.close();
        if (db.open()) {
            QSqlQuery query(db);
            query.exec("SELECT 1 FROM DUAL");
            db.close();
        } else {
            QFAIL(tst_Databases::printError(db.lastError(), db));
        }
    }
    if(!db.open())
        qFatal(tst_Databases::printError(db.lastError(), db));
}

void tst_QSqlDatabase::oci_xmltypeSupport()
{
    QFETCH(QString, dbName);
    QSqlDatabase db = QSqlDatabase::database(dbName);
    CHECK_DATABASE(db);

    QString tableName = qTableName("qtest_xmltype");
    QString xml("<?xml version=\"1.0\"?><TABLE_NAME>MY_TABLE</TABLE_NAME>");
    QSqlQuery q(db);

    // Embedding the XML in the statement
    if(!q.exec(QString("CREATE TABLE %1(xmldata xmltype)").arg(tableName)))
        QSKIP("This test requries xml type support", SkipSingle);
    QVERIFY_SQL(q, exec(QString("INSERT INTO %1 values('%2')").arg(tableName).arg(xml)));
    QVERIFY_SQL(q, exec(QString("SELECT a.xmldata.getStringVal() FROM %1 a").arg(tableName)));
    QVERIFY_SQL(q, last());
    QCOMPARE(q.value(0).toString(), xml);

    // Binding the XML with a prepared statement
    QVERIFY_SQL(q, prepare(QString("INSERT INTO %1 values(?)").arg(tableName)));
    q.addBindValue(xml);
    QVERIFY_SQL(q, exec());
    QVERIFY_SQL(q, exec(QString("SELECT a.xmldata.getStringVal() FROM %1 a").arg(tableName)));
    QVERIFY_SQL(q, last());
    QCOMPARE(q.value(0).toString(), xml);
}


void tst_QSqlDatabase::oci_fieldLength()
{
    QFETCH(QString, dbName);
    QSqlDatabase db = QSqlDatabase::database(dbName);
    CHECK_DATABASE(db);

    QString tableName = qTableName("qtest");
    QSqlQuery q(db);

    QVERIFY_SQL(q, exec(QString("SELECT t_varchar, t_char FROM %1").arg(tableName)));
    QVERIFY_SQL(q, next());
    QCOMPARE(q.record().field(0).length(), 40);
    QCOMPARE(q.record().field(1).length(), 40);
}

// This test isn't really necessary as SQL_GUID / uniqueidentifier is
// already tested in recordSQLServer().
void tst_QSqlDatabase::odbc_uniqueidentifier()
{
    QFETCH(QString, dbName);
    QSqlDatabase db = QSqlDatabase::database(dbName);
    CHECK_DATABASE(db);
    if (!tst_Databases::isSqlServer(db)) {
        QSKIP("SQL Server (ODBC) specific test", SkipSingle);
        return;
    }

    QString tableName = qTableName("qtest_sqlguid");
    QString guid = QString("AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE");
    QString invalidGuid = QString("GAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE");

    QSqlQuery q(db);
    QVERIFY_SQL(q, exec(QString("CREATE TABLE %1(id uniqueidentifier)").arg(tableName)));

    q.prepare(QString("INSERT INTO %1 VALUES(?)").arg(tableName));;
    q.addBindValue(guid);
    QVERIFY_SQL(q, exec());

    q.addBindValue(invalidGuid);
    QEXPECT_FAIL("", "The GUID string is required to be correctly formated!",
        Continue);
    QVERIFY_SQL(q, exec());

    QVERIFY_SQL(q, exec(QString("SELECT id FROM %1").arg(tableName)));
    QVERIFY_SQL(q, next());
    QCOMPARE(q.value(0).toString(), guid);
}

void tst_QSqlDatabase::getConnectionName()
{
    QFETCH(QString, dbName);
    QSqlDatabase db = QSqlDatabase::database(dbName);
    CHECK_DATABASE(db);

    QCOMPARE(db.connectionName(), dbName);
    QSqlDatabase clone = QSqlDatabase::cloneDatabase(db, "clonedDatabase");
    QCOMPARE(clone.connectionName(), QString("clonedDatabase"));
    QTest::ignoreMessage(QtWarningMsg, "QSqlDatabasePrivate::removeDatabase: "
        "connection 'clonedDatabase' is still in use, all queries will cease to work.");
    QSqlDatabase::removeDatabase("clonedDatabase");
    QCOMPARE(clone.connectionName(), QString());
    QCOMPARE(db.connectionName(), dbName);
}

void tst_QSqlDatabase::odbc_uintfield()
{
    QFETCH(QString, dbName);
    QSqlDatabase db = QSqlDatabase::database(dbName);
    CHECK_DATABASE(db);

    QString tableName = qTableName("uint_table");
    unsigned int val = 4294967295U;

    QSqlQuery q(db);
    q.exec(QString("CREATE TABLE %1(num numeric(10))").arg(tableName));
    q.prepare(QString("INSERT INTO %1 VALUES(?)").arg(tableName));
    q.addBindValue(val);
    QVERIFY_SQL(q, exec());

    q.exec(QString("SELECT num FROM %1").arg(tableName));
    if (q.next())
        QCOMPARE(q.value(0).toUInt(), val);
}

void tst_QSqlDatabase::eventNotification()
{
    QFETCH(QString, dbName);
    QSqlDatabase db = QSqlDatabase::database(dbName);
    CHECK_DATABASE(db);

    QSqlDriver *driver = db.driver();
    if (!driver->hasFeature(QSqlDriver::EventNotifications))
        QSKIP("DBMS doesn't support event notifications", SkipSingle);

    // Not subscribed to any events yet
    QCOMPARE(driver->subscribedToNotifications().size(), 0);

    // Subscribe to "event_foo"
    QVERIFY_SQL(*driver, subscribeToNotification(QLatin1String("event_foo")));
    QCOMPARE(driver->subscribedToNotifications().size(), 1);
    QVERIFY(driver->subscribedToNotifications().contains("event_foo"));

    // Can't subscribe to the same event multiple times
    QVERIFY2(!driver->subscribeToNotification(QLatin1String("event_foo")), "Shouldn't be able to subscribe to event_foo twice");
    QCOMPARE(driver->subscribedToNotifications().size(), 1);

    // Unsubscribe from "event_foo"
    QVERIFY_SQL(*driver, unsubscribeFromNotification(QLatin1String("event_foo")));
    QCOMPARE(driver->subscribedToNotifications().size(), 0);

    // Re-subscribing to "event_foo" now is allowed
    QVERIFY_SQL(*driver, subscribeToNotification(QLatin1String("event_foo")));
    QCOMPARE(driver->subscribedToNotifications().size(), 1);

    // closing the connection causes automatically unsubscription from all events
    db.close();
    QCOMPARE(driver->subscribedToNotifications().size(), 0);

    // Can't subscribe to anything while database is closed
    QVERIFY2(!driver->subscribeToNotification(QLatin1String("event_foo")), "Shouldn't be able to subscribe to event_foo");
    QCOMPARE(driver->subscribedToNotifications().size(), 0);

    db.open();
}

void tst_QSqlDatabase::eventNotificationIBase()
{
    QFETCH(QString, dbName);
    QSqlDatabase db = QSqlDatabase::database(dbName);
    CHECK_DATABASE(db);

    QString procedureName = qTableName("posteventProc");
    QSqlDriver *driver=db.driver();
    QVERIFY_SQL(*driver, subscribeToNotification(procedureName));
    QTest::qWait(300);  // Interbase needs some time to call the driver callback.

    db.transaction();   // InterBase events are posted from within transactions.
    QSqlQuery q(db);
    q.exec(QString("DROP PROCEDURE %1").arg(procedureName));
    q.exec(QString("CREATE PROCEDURE %1\nAS BEGIN\nPOST_EVENT '%1';\nEND;").arg(procedureName));
    q.exec(QString("EXECUTE PROCEDURE %1").arg(procedureName));
    QSignalSpy spy(driver, SIGNAL(notification(const QString&)));
    db.commit();        // No notifications are posted until the transaction is committed.
    QTest::qWait(300);  // Interbase needs some time to post the notification and call the driver callback.
                        // This happends from another thread, and we have to process events in order for the
                        // event handler in the driver to be executed and emit the notification signal.

    QCOMPARE(spy.count(), 1);
    QList<QVariant> arguments = spy.takeFirst();
    QVERIFY(arguments.at(0).toString() == procedureName);
    QVERIFY_SQL(*driver, unsubscribeFromNotification(procedureName));
    q.exec(QString("DROP PROCEDURE %1").arg(procedureName));
}

void tst_QSqlDatabase::eventNotificationPSQL()
{
    QFETCH(QString, dbName);
    QSqlDatabase db = QSqlDatabase::database(dbName);
    CHECK_DATABASE(db);

    QSqlQuery query(db);
    QString procedureName = qTableName("posteventProc");

    QSqlDriver *driver=db.driver();
    QVERIFY_SQL(*driver, subscribeToNotification(procedureName));
    QSignalSpy spy(db.driver(), SIGNAL(notification(const QString&)));
    query.exec(QString("NOTIFY \"%1\"").arg(procedureName));
    QCoreApplication::processEvents();
    QCOMPARE(spy.count(), 1);
    QList<QVariant> arguments = spy.takeFirst();
    QVERIFY(arguments.at(0).toString() == procedureName);
    QVERIFY_SQL(*driver, unsubscribeFromNotification(procedureName));
}

void tst_QSqlDatabase::sqlite_bindAndFetchUInt()
{
    QFETCH(QString, dbName);
    QSqlDatabase db = QSqlDatabase::database(dbName);
    CHECK_DATABASE(db);

    QSqlQuery q(db);
    QString tableName = qTableName("uint_test");
    QVERIFY_SQL(q, exec(QString("CREATE TABLE %1(uint_field UNSIGNED INTEGER)").arg(tableName)));
    QVERIFY_SQL(q, prepare(QString("INSERT INTO %1 VALUES(?)").arg(tableName)));
    q.addBindValue(4000000000U);
    QVERIFY_SQL(q, exec());
    QVERIFY_SQL(q, exec(QString("SELECT uint_field FROM %1").arg(tableName)));
    QVERIFY_SQL(q, next());

    // All integers in SQLite are signed, so even though we bound the value
    // as an UInt it will come back as a LongLong
    QCOMPARE(q.value(0).type(), QVariant::LongLong);
    QCOMPARE(q.value(0).toUInt(), 4000000000U);
}

void tst_QSqlDatabase::db2_valueCacheUpdate()
{
    QFETCH(QString, dbName);
    QSqlDatabase db = QSqlDatabase::database(dbName);
    CHECK_DATABASE(db);

    QString tableName = qTableName("qtest");
    QSqlQuery q(db);
    q.exec(QString("SELECT id, t_varchar, t_char, t_numeric FROM %1").arg(tableName));
    q.next();
    QVariant c4 = q.value(3);
    QVariant c3 = q.value(2);
    QVariant c2 = q.value(1);
    QVariant c1 = q.value(0);
    QCOMPARE(c4.toString(), q.value(3).toString());
    QCOMPARE(c3.toString(), q.value(2).toString());
    QCOMPARE(c2.toString(), q.value(1).toString());
    QCOMPARE(c1.toString(), q.value(0).toString());
}

QTEST_MAIN(tst_QSqlDatabase)
#include "tst_qsqldatabase.moc"