summaryrefslogtreecommitdiffstats
path: root/src/serviceframework/servicedatabase.cpp
blob: 87a5a5e9c0530bd49b2cfb37b3dcae25c17f9857 (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
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
/****************************************************************************
**
** Copyright (C) 2018 The Qt Company Ltd and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtSystems module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

// #define QT_SFW_SERVICEDATABASE_DEBUG

#include "servicedatabase_p.h"
#include <QDir>
#include <QSet>
#include "qserviceinterfacedescriptor.h"
#include "qserviceinterfacedescriptor_p.h"
#include <QUuid>
#include "dberror_p.h"

//database name
#define RESOLVERDATABASE "services.db"

//database table names
#define SERVICE_TABLE "Service"
#define INTERFACE_TABLE "Interface"
#define DEFAULTS_TABLE "Defaults"
#define SERVICE_PROPERTY_TABLE "ServiceProperty"
#define INTERFACE_PROPERTY_TABLE "InterfaceProperty"

//separator
#define RESOLVERDATABASE_PATH_SEPARATOR "//"

#ifdef QT_SFW_SERVICEDATABASE_DEBUG
#include <QDebug>
#endif

#define SERVICE_DESCRIPTION_KEY "DESCRIPTION"
#ifdef QT_SFW_SERVICEDATABASE_USE_SECURITY_TOKEN
#define SECURITY_TOKEN_KEY "SECURITYTOKEN"
#endif
#define INTERFACE_DESCRIPTION_KEY "DESCRIPTION"
#define SERVICE_INITIALIZED_KEY SERVICE_INITIALIZED_ATTR
#define INTERFACE_CAPABILITY_KEY "CAPABILITIES"
#define INTERFACE_SERVICETYPE_KEY "SERVICETYPE"

//service prefixes
#define SERVICE_IPC_PREFIX "_q_ipc_addr:"

QT_BEGIN_NAMESPACE

enum TBindIndexes
    {
        EBindIndex=0,
        EBindIndex1,
        EBindIndex2,
        EBindIndex3,
        EBindIndex4,
        EBindIndex5,
        EBindIndex6,
        EBindIndex7
    };


/*
   \class ServiceDatabase
   The ServiceDatabase is responsible for the management of a single
   service database.  It provides operations for:
   - opening and closing a connection with the database,
   - registering and unregistering services
   - querying for services and interfaces
   - setting and getting default interface implementations.
*/

/*
    Constructor
*/
ServiceDatabase::ServiceDatabase(void)
:m_isDatabaseOpen(false),m_inTransaction(false)
{
}

/*
    Destructor
*/
ServiceDatabase::~ServiceDatabase()
{
    close();
}

/*
    Opens the service database
    The method creates or opens database and creates tables if they are not present
    Returns true if the operation was successful, false if not.
*/
bool ServiceDatabase::open()
{
    if (m_isDatabaseOpen)
        return true;

    QString path;

    //Create full path to database
    if (m_databasePath.isEmpty ())
        m_databasePath = databasePath();

    path = m_databasePath;
    QFileInfo dbFileInfo(path);
    if (!dbFileInfo.dir().exists()) {
       QDir::root().mkpath(dbFileInfo.path());
       QFile file(path);
       if (!file.open(QIODevice::ReadWrite)) {
           QString errorText(QLatin1String("Could not create database directory: %1"));
           m_lastError.setError(DBError::CannotCreateDbDir, errorText.arg(dbFileInfo.path()));
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
           qWarning() << "ServiceDatabase::open():-"
                        << "Problem:" << qPrintable(m_lastError.text());
#endif
           close();
           return false;
        }
        file.close();
    }

    m_connectionName = dbFileInfo.completeBaseName() + QStringLiteral("--") + QString::number(reinterpret_cast<quintptr>(QThread::currentThreadId()));
    QSqlDatabase  database;
    if (QSqlDatabase::contains(m_connectionName)) {
        database = QSqlDatabase::database(m_connectionName);
    } else {
        database = QSqlDatabase::addDatabase(QLatin1String("QSQLITE"), m_connectionName);
        database.setDatabaseName(path);
    }

    if (!database.isValid()){
        m_lastError.setError(DBError::InvalidDatabaseConnection);
        close();
        return false;
    }

    //Create or open database
    if (!database.isOpen()) {
        if (!database.open()) {
            m_lastError.setError(DBError::SqlError, database.lastError().text());
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
            qWarning() << "ServiceDatabase::open():-"
                        << "Problem:" << "Could not open database. "
                        << "Reason:" << m_lastError.text();
#endif
            close();
            return false;
        }
    }
    m_isDatabaseOpen = true;

    //Check database structure (tables) and recreate tables if neccessary
    //If one of tables is missing remove all tables and recreate them
    //This operation is required in order to avoid data coruption
    if (!checkTables()) {
        if (dropTables()) {
            if (createTables()) {
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
                qDebug() << "ServiceDatabase::open():-"
                    << "Database tables recreated";
#endif
            } else {
                //createTable() should've handled error message
                //and warning
                close();
                return false;
            }
        }
        else {
            //dropTables() should've handled error message
            //and warning
            close();
            return false;
        }
    }
    return true;
}

/*
   Adds a \a service into the database.

   May set the following error codes
   DBError::NoError
   DBError::LocationAlreadyRegistered
   DBError::IfaceImplAlreadyRegistered
   DBError::SqlError
   DBError::DatabaseNotOpen
   DBError::InvalidDatabaseConnection
   DBError::NoWritePermissions
   DBError::InvalidDatabaseFile
*/
//bool ServiceDatabase::registerService(ServiceMetaData &service)
bool ServiceDatabase::registerService(const ServiceMetaDataResults &service, const QString &securityToken)
{
    // Derive the location name with the service type prefix to be stored
    QString locationPrefix = service.location;
    int type = service.interfaces[0].d->attributes[QServiceInterfaceDescriptor::ServiceType].toInt();
    if (type == QService::InterProcess)
        locationPrefix = QLatin1String(SERVICE_IPC_PREFIX) + service.location;

#ifndef QT_SFW_SERVICEDATABASE_USE_SECURITY_TOKEN
    Q_UNUSED(securityToken);
#else
    if (securityToken.isEmpty()) {
        QString errorText("Access denied, no security token provided (for registering service: \"%1\")");
        m_lastError.setError(DBError::NoWritePermissions, errorText.arg(service.name));
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
        qWarning() << "ServiceDatabase::registerService():-"
                << "Problem: Unable to register service,"
                << "reason:" << qPrintable(m_lastError.text());
#endif
        return false;
    }
#endif

    if (!checkConnection()) {
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
        qWarning() << "ServiceDatabase::registerService():-"
                    << "Problem:" << qPrintable(m_lastError.text());
#endif
        return false;
    }

    QSqlDatabase database = QSqlDatabase::database(m_connectionName);
    QSqlQuery query(database);

    if (!beginTransaction(&query, Write)) {
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
        qWarning() << "ServiceDatabase::registerService():-"
                    << "Unable to begin transaction,"
                    << "reason:" << qPrintable(m_lastError.text());
#endif
        return false;
    }
    //See if the service's location has already been previously registered
    QString statement(QLatin1String("SELECT Name from Service WHERE Location=? COLLATE NOCASE"));
    QList<QVariant> bindValues;
    bindValues.append(locationPrefix);
    if (!executeQuery(&query, statement, bindValues)) {
        rollbackTransaction(&query);
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
        qWarning() << "ServiceDatabase::registerService():-"
                    << qPrintable(m_lastError.text());
#endif
        return false;
    }

    if (query.next()) {
        QString alreadyRegisteredService = query.value(EBindIndex).toString();
        const QString errorText = QLatin1String("Cannot register service \"%1\". Service location \"%2\" is already "
                    "registered to service \"%3\".  \"%3\" must first be deregistered "
                    "for new registration to take place.");

        m_lastError.setError(DBError::LocationAlreadyRegistered,
                errorText.arg(service.name)
                        .arg(service.location)
                        .arg(alreadyRegisteredService));

        rollbackTransaction(&query);
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
        qWarning() << "ServiceDatabase::registerService():-"
                    << "Problem:" << qPrintable(m_lastError.text());
#endif
        return false;
    }

#ifdef QT_SFW_SERVICEDATABASE_USE_SECURITY_TOKEN
    // If service(s) have already been registered with same name, they must all come from
    // same application. Fetch a service with given name and if such exists, check that its
    // security ID equals to the security ID of the current registrar.
    // One application may register multiple services with same name (different location),
    // hence the keyword DISTINCT.
    statement = "SELECT DISTINCT ServiceProperty.Value FROM Service, ServiceProperty "
                "WHERE Service.ID = ServiceProperty.ServiceID "
                "AND ServiceProperty.Key = ? "
                "AND Service.Name = ?";
    bindValues.clear();
    bindValues.append(SECURITY_TOKEN_KEY);
    bindValues.append(service.name);
    if (!executeQuery(&query, statement, bindValues)) {
        rollbackTransaction(&query);
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
        qWarning() << "ServiceDatabase::registerService():-"
                   << qPrintable(m_lastError.text());
#endif
        return false;
    }
    QString existingSecurityToken;
    if (query.next()) {
        existingSecurityToken = query.value(EBindIndex).toString();
    }
    if (!existingSecurityToken.isEmpty() && (existingSecurityToken != securityToken)) {
        QString errorText("Access denied: \"%1\"");
        m_lastError.setError(DBError::NoWritePermissions, errorText.arg(service.name));
        rollbackTransaction(&query);
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
        qWarning() << "ServiceDatabase::registerService():-"
                << "Problem: Unable to register service,"
                << "reason:" << qPrintable(m_lastError.text());
#endif
        return false;
    }
#endif // QT_SFW_SERVICEDATABASE_USE_SECURITY_TOKEN

    // Checks done, create new rows into tables.
    statement = QLatin1String("INSERT INTO Service(ID,Name,Location) VALUES(?,?,?)");

    qsrand(QTime::currentTime().msec());
    QString serviceID = QUuid::createUuid().toString();

    bindValues.clear();
    bindValues.append(serviceID);
    bindValues.append(service.name);
    bindValues.append(locationPrefix);

    if (!executeQuery(&query, statement, bindValues)) {
        rollbackTransaction(&query);
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
        qWarning() << "ServiceDatabase::registerService():-"
                    << qPrintable(m_lastError.text());
#endif
        return false;
    }

    statement = QLatin1String("INSERT INTO ServiceProperty(ServiceID,Key,Value) VALUES(?,?,?)");
    bindValues.clear();
    bindValues.append(serviceID);
    bindValues.append(QLatin1String(SERVICE_DESCRIPTION_KEY));
    if (service.description.isNull())
        bindValues.append(QLatin1String("")); // This relies on !QString::isNull().
    else
        bindValues.append(service.description);

    if (!executeQuery(&query, statement, bindValues)) {
        rollbackTransaction(&query);
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
        qWarning() << "ServiceDatabase::registerService():-"
                    << qPrintable(m_lastError.text());
#endif
        return false;
    }

#ifdef QT_SFW_SERVICEDATABASE_GENERATE
    statement = "INSERT INTO ServiceProperty(ServiceId,Key,Value) VALUES(?,?,?)";
    bindValues.clear();
    bindValues.append(serviceID);
    bindValues.append(SERVICE_INITIALIZED_KEY);
    bindValues.append(QString("NO"));
    if (!executeQuery(&query, statement, bindValues)) {
        rollbackTransaction(&query);
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
        qWarning() << "ServiceDatabase::registerService():-"
                    << qPrintable(m_lastError.text());
#endif
        return false;
    }
#endif

#ifdef QT_SFW_SERVICEDATABASE_USE_SECURITY_TOKEN
    // Insert a security token for the particular service
    statement = "INSERT INTO ServiceProperty(ServiceID,Key,Value) VALUES(?,?,?)";
    bindValues.clear();
    bindValues.append(serviceID);
    bindValues.append(SECURITY_TOKEN_KEY);
    bindValues.append(securityToken);

    if (!executeQuery(&query, statement, bindValues)) {
        rollbackTransaction(&query);
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
        qWarning() << "ServiceDatabase::registerService():-"
                << qPrintable(m_lastError.text());
#endif
        return false;
    }
#endif // QT_SFW_SERVICEDATABASE_USE_SECURITY_TOKEN

    QList <QServiceInterfaceDescriptor> interfaces = service.interfaces;
    QString interfaceID;;
    foreach (const QServiceInterfaceDescriptor &serviceInterface, interfaces) {
        interfaceID = getInterfaceID(&query, serviceInterface);
        if (m_lastError.code() == DBError::NoError) {
            QString errorText;
            errorText = QLatin1String("Cannot register service \"%1\". \"%1\" is already registered "
                        "and implements interface \"%2\", Version \"%3.%4.\"  \"%1\" must "
                        "first be deregistered for new registration to take place.");
            m_lastError.setError(DBError::IfaceImplAlreadyRegistered,
                                errorText.arg(serviceInterface.serviceName())
                                            .arg(serviceInterface.interfaceName())
                                            .arg(serviceInterface.majorVersion())
                                            .arg(serviceInterface.minorVersion()));

            rollbackTransaction(&query);
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
            qWarning() << "ServiceDatabase::registerService():-"
                        << "Problem:" << qPrintable(m_lastError.text());
#endif
            return false;
        } else if (m_lastError.code() == DBError::NotFound){
            //No interface implementation already exists for the service
            //so add it
            if (!insertInterfaceData(&query, serviceInterface, serviceID)) {
                rollbackTransaction(&query);
                return false;
            } else {
                continue;
            }
        } else {
            rollbackTransaction(&query);
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
            qWarning() << "ServiceDatabase::registerService():-"
                        << "Unable to confirm if implementation version"
                        << (QString::number(serviceInterface.majorVersion()) + "."
                           + QString::number(serviceInterface.minorVersion())).toLatin1()
                        << "for interface" << serviceInterface.interfaceName()
                        << "is already registered for service "
                        << serviceInterface.serviceName()
                        << "\n" << m_lastError.text();
#endif
            return false;
        }
    }

    interfaces = service.latestInterfaces;
    QServiceInterfaceDescriptor defaultInterface;
    foreach (const QServiceInterfaceDescriptor &serviceInterface, interfaces) {
        defaultInterface = interfaceDefault(serviceInterface.interfaceName(), NULL, true);
        if (m_lastError.code() == DBError::NoError
                || m_lastError.code() == DBError::ExternalIfaceIDFound) {
            continue; //default already exists so don't do anything
        } else if (m_lastError.code() == DBError::NotFound) {
            //default does not already exist so create one
            interfaceID = getInterfaceID(&query, serviceInterface);
            if (m_lastError.code() != DBError::NoError) {
                rollbackTransaction(&query);
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
                qWarning() << "ServiceDatabase::registerService():-"
                           << "Unable to retrieve interfaceID for "
                              "interface" << serviceInterface.interfaceName()
                           << "\n" << m_lastError.text();
#endif
                return false;
            }

            statement = QLatin1String("INSERT INTO Defaults(InterfaceName, InterfaceID) VALUES(?,?)");
            bindValues.clear();
            bindValues.append(serviceInterface.interfaceName());
            bindValues.append(interfaceID);
            if (!executeQuery(&query, statement, bindValues)) {
                rollbackTransaction(&query);
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
                qWarning() << "ServiceDatabase::registerService():-"
                    << qPrintable(m_lastError.text());
#endif
                return false;
            }
        } else {
            rollbackTransaction(&query);
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
            qWarning() << "ServiceDatabase::registerService()"
                        << "Problem: Unable to confirm if interface"
                        << serviceInterface.interfaceName()
                        << "already has a default implementation";
#endif
            return false;
        }
    }

    if (!commitTransaction(&query)) {
        rollbackTransaction(&query);
        return false;
    }
    m_lastError.setError(DBError::NoError);
    return true;
}

/*
    Obtains an interface ID corresponding to a given interface \a descriptor

    May set the following error codes:
    DBError::NoError
    DBError::NotFound
    DBError::SqlError
    DBError::DatabaseNotOpen
    DBError::InvalidDatabaseConnection
*/
QString ServiceDatabase::getInterfaceID(const QServiceInterfaceDescriptor &serviceInterface) {
    QString interfaceID;
    if (!checkConnection()) {
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
        qWarning() << "ServiceDatabase::getInterfaceID():-"
                    << "Problem:" << qPrintable(m_lastError.text());
#endif
        return interfaceID;
    }

    QSqlDatabase database = QSqlDatabase::database(m_connectionName);
    QSqlQuery query(database);

    return getInterfaceID(&query, serviceInterface);
}

/*
    This function should only ever be called on a user scope database.
    It returns a list of Interface Name and Interface ID pairs, where
    the Interface ID refers to an external interface implementation
    in the system scope database.

    May set the last error to:
    DBError::NoError
    DBError::SqlError
    DBError::DatabaseNotOpen
    DBError::InvalidDatabaseConnection

    Aside:  There is only one query which implicitly gets
    wrapped in it's own transaction.
*/
QList<QPair<QString,QString> > ServiceDatabase::externalDefaultsInfo()
{
    QList<QPair<QString,QString> > ret;
    if (!checkConnection()) {
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
        qWarning() << "ServiceDatabase::externalDefaultsInfo():-"
                    << "Problem:" << qPrintable(m_lastError.text());
#endif
        return ret;
    }

    QSqlDatabase database = QSqlDatabase::database(m_connectionName);
    QSqlQuery query(database);

    //Prepare search query, bind criteria values and execute search
    QString selectComponent = QLatin1String("SELECT InterfaceName, InterfaceID ");
    QString fromComponent = QLatin1String("FROM Defaults ");
    QString whereComponent = QLatin1String("WHERE InterfaceID NOT IN (SELECT Interface.ID FROM Interface) ");

    //Aside: this individual query is implicitly wrapped in a transaction
    if (!executeQuery(&query, selectComponent + fromComponent + whereComponent)) {
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
        qWarning() << "ServiceDatabase::externalDefaultsInfo():-"
                    << "Problem:" << qPrintable(m_lastError.text());
#endif
        return ret;
    }

    while (query.next()) {
        ret.append(qMakePair(query.value(EBindIndex).toString(),
                    query.value(EBindIndex1).toString()));
    }

    m_lastError.setError(DBError::NoError);
    return ret;
}

/*
    Helper function that obtains an interfaceID for a given \a descriptor.

    May set last error to one of the following error codes:
    DBError::NoError
    DBError::NotFound
    DBError::SqlError

    Aside: This function may be safely called standalone or within an explicit
    transaction.  If called standalone, it's single query is implicitly
    wrapped in it's own transaction.
*/
QString ServiceDatabase::getInterfaceID(QSqlQuery *query, const QServiceInterfaceDescriptor &serviceInterface)
{
    QString statement = QLatin1String("SELECT Interface.ID "
                        "FROM Interface, Service "
                        "WHERE Service.ID = Interface.ServiceID "
                        "AND Service.Name = ? COLLATE NOCASE "
                        "AND Interface.Name = ? COLLATE NOCASE "
                        "AND Interface.VerMaj = ? AND Interface.VerMin = ?");
    QList<QVariant> bindValues;
    bindValues.append(serviceInterface.serviceName());
    bindValues.append(serviceInterface.interfaceName());
    bindValues.append(serviceInterface.majorVersion());
    bindValues.append(serviceInterface.minorVersion());

    if (!executeQuery(query, statement, bindValues)) {
        return QString();
    }

    if (!query->next()) {
         QString errorText(QLatin1String("No Interface Descriptor found with "
                            "Service name: %1 "
                            "Interface name: %2 "
                            "Version: %3.%4"));
        m_lastError.setError(DBError::NotFound, errorText.arg(serviceInterface.serviceName())
                                                        .arg(serviceInterface.interfaceName())
                                                        .arg(serviceInterface.majorVersion())
                                                        .arg(serviceInterface.minorVersion()));
        return QString();
    }

    m_lastError.setError(DBError::NoError);
    return query->value(EBindIndex).toString();
}

/*
    Helper functions that saves \a interface related data in the Interface table
    The \a interface data is recorded as belonging to the service assocciated
    with \a serviceID.

    May set the last error to one of the following error codes:
    DBError::NoError
    DBError::SqlError

    Aside: It is already assumed that a write transaction has been started by the
    time this function is called; and this function will not rollback/commit
    the transaction.
*/
bool ServiceDatabase::insertInterfaceData(QSqlQuery *query,const QServiceInterfaceDescriptor &serviceInterface, const QString &serviceID)
{
    QString statement = QLatin1String("INSERT INTO Interface(ID, ServiceID,Name,VerMaj, VerMin) "
                        "VALUES(?,?,?,?,?)");
    QString interfaceID = QUuid::createUuid().toString();

    QList<QVariant> bindValues;
    bindValues.append(interfaceID);
    bindValues.append(serviceID);
    bindValues.append(serviceInterface.interfaceName());
    bindValues.append(serviceInterface.majorVersion());
    bindValues.append(serviceInterface.minorVersion());

    if (!executeQuery(query, statement, bindValues)) {
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
        qWarning() << "ServiceDatabase::insertInterfaceData():-"
                    << qPrintable(m_lastError.text());
#endif
        return false;
    }

    statement = QLatin1String("INSERT INTO InterfaceProperty(InterfaceID, Key, Value) VALUES(?,?,?)");
    QHash<QServiceInterfaceDescriptor::Attribute, QVariant>::const_iterator iter = serviceInterface.d->attributes.constBegin();
    bool isValidInterfaceProperty;
    QString capabilities;
    QString interfaceDescription;
    while (iter != serviceInterface.d->attributes.constEnd()) {
        isValidInterfaceProperty = true;

        bindValues.clear();
        bindValues.append(interfaceID);
        switch (iter.key()) {
            case (QServiceInterfaceDescriptor::Capabilities):
                bindValues.append(QLatin1String(INTERFACE_CAPABILITY_KEY));
                capabilities = serviceInterface.attribute(QServiceInterfaceDescriptor::Capabilities).toStringList().join(QLatin1String(","));
                if (capabilities.isNull())
                    capabilities = QLatin1String("");
                bindValues.append(capabilities);
                break;
            case(QServiceInterfaceDescriptor::Location):
                isValidInterfaceProperty = false;
                break;
            case(QServiceInterfaceDescriptor::ServiceDescription):
                isValidInterfaceProperty = false;
                break;
            case(QServiceInterfaceDescriptor::InterfaceDescription):
                bindValues.append(QLatin1String(INTERFACE_DESCRIPTION_KEY));
                interfaceDescription = serviceInterface.attribute(QServiceInterfaceDescriptor::InterfaceDescription).toString();
                if (interfaceDescription.isNull())
                    interfaceDescription = QLatin1String("");
                bindValues.append(interfaceDescription);
                break;
            default:
                isValidInterfaceProperty = false;
                break;
        }

        if (isValidInterfaceProperty) {
              if (!executeQuery(query, statement, bindValues)) {
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
                  qWarning() << "ServiceDatabase::insertInterfaceData():-"
                                << qPrintable(m_lastError.text());
#endif
                  return false;
              }
        }
        ++iter;
    }

    // add custom attributes
    QHash<QString, QString>::const_iterator customIter = serviceInterface.d->customAttributes.constBegin();
    while (customIter!=serviceInterface.d->customAttributes.constEnd()) {
        bindValues.clear();
        bindValues.append(interfaceID);
        // to avoid key clashes use separate c_ namespace ->is this sufficient?
        bindValues.append(QVariant(QStringLiteral("c_") + customIter.key()));
        bindValues.append(customIter.value());
        if (!executeQuery(query, statement, bindValues)) {
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
            qWarning() << "ServiceDatabase::insertInterfaceData(customProps):-"
                            << qPrintable(m_lastError.text());
#endif
            return false;
        }
        ++customIter;
    }
    m_lastError.setError(DBError::NoError);

    return true;
}

/*
    Helper function that executes the sql query specified in \a statement.
    It is assumed that the \a statement uses positional placeholders and
    corresponding parameters are placed in the list of \a bindValues.

    Aside: This function may be safely called standalone or within an explicit
    transaction.  If called standalone, it's single query is implicitly
    wrapped in it's own transaction.

    May set the last error to one of the following error codes:
    DBError::NoError
    DBError::SqlError
    DBError::NoWritePermissions
    DBError::InvalidDatabaseFile
*/
bool ServiceDatabase::executeQuery(QSqlQuery *query, const QString &statement, const QList<QVariant> &bindValues)
{
    Q_ASSERT(query != NULL);

    bool success = false;
    enum {Prepare =0 , Execute=1};
    for (int stage=Prepare; stage <= Execute; ++stage) {
        if ( stage == Prepare)
            success = query->prepare(statement);
        else // stage == Execute
            success = query->exec();

        if (!success) {
            QString errorText;
            errorText = QLatin1String("Problem: Could not %1 statement: %2"
                "Reason: %3"
                "Parameters: %4\n");
            QString parameters;
            if (bindValues.count() > 0) {
                for (int i = 0; i < bindValues.count(); ++i) {
                    parameters.append(QStringLiteral("\n\t[") + QString::number(i) + QStringLiteral("]: ") + bindValues.at(i).toString());
                }
            } else {
                parameters = QLatin1String("None");
            }

            DBError::ErrorCode errorType;
            int result = query->lastError().number();
            if (result == 26 || result == 11) {//SQLILTE_NOTADB || SQLITE_CORRUPT
                qWarning() << "Service Framework:- Database file is corrupt or invalid:" << databasePath();
                errorType = DBError::InvalidDatabaseFile;
            }
            else if ( result == 8) //SQLITE_READONLY
                errorType = DBError::NoWritePermissions;
            else
                errorType = DBError::SqlError;

            m_lastError.setError(errorType,
                    errorText
                    .arg(stage == Prepare ?QLatin1String("prepare"):QLatin1String("execute"))
                    .arg(statement)
                    .arg(query->lastError().text())
                    .arg(parameters));

            query->finish();
            query->clear();
            return false;
        }

        if (stage == Prepare) {
            foreach (const QVariant &bindValue, bindValues)
            query->addBindValue(bindValue);
        }
    }

    m_lastError.setError(DBError::NoError);
    return true;
}

/*
   Obtains a list of QServiceInterfaceDescriptors that match the constraints supplied
   by \a filter.

   May set last error to one of the following error codes:
   DBError::NoError
   DBError::SqlError
   DBError::DatabaseNotOpen
   DBError::InvalidDatabaseConnection
   DBError::NoWritePermissions
   DBError::InvalidDatabaseFile
*/
QList<QServiceInterfaceDescriptor> ServiceDatabase::getInterfaces(const QServiceFilter &filter)
{
    QList<QServiceInterfaceDescriptor> interfaces;
    if (!checkConnection()) {
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
        qWarning() << "ServiceDatabase::getInterfaces():-"
                    << "Problem:" << qPrintable(m_lastError.text());
#endif
        return interfaces;
    }

    QSqlDatabase database = QSqlDatabase::database(m_connectionName);
    QSqlQuery query(database);

    //multiple read queries are performed so wrap them
    //in a read only transaction
    if (!beginTransaction(&query, Read)) {
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
        qWarning() << "ServiceDatabase::getInterfaces():-"
                    << "Unable to begin transaction. "
                    << "Reason:" << qPrintable(m_lastError.text());
#endif
        return interfaces;
    }

    //Prepare search query, bind criteria values
    QString selectComponent = QLatin1String("SELECT Interface.Name, "
                                "Service.Name, Interface.VerMaj, "
                                "Interface.VerMin, "
                                "Service.Location, "
                                "Service.ID, "
                                "Interface.ID ");
    QString fromComponent = QLatin1String("FROM Interface, Service ");
    QString whereComponent = QLatin1String("WHERE Service.ID = Interface.ServiceID ");
    QList<QVariant> bindValues;

    if (filter.serviceName().isEmpty() && filter.interfaceName().isEmpty()) {
        //do nothing, (don't add any extra constraints to the query
    } else {

        if (!filter.serviceName().isEmpty()) {
            whereComponent.append(QLatin1String("AND Service.Name = ?")).append(QLatin1String(" COLLATE NOCASE "));
            bindValues.append(filter.serviceName());
        }
        if (!filter.interfaceName().isEmpty()) {
            whereComponent.append(QLatin1String("AND Interface.Name = ?")).append(QLatin1String(" COLLATE NOCASE "));
            bindValues.append(filter.interfaceName());
            if (filter.majorVersion() >=0 && filter.minorVersion() >=0) {
                if (filter.versionMatchRule() == QServiceFilter::ExactVersionMatch) {
                    whereComponent.append(QLatin1String("AND Interface.VerMaj = ?")).append(QLatin1String(" AND Interface.VerMin = ? "));
                    bindValues.append(QString::number(filter.majorVersion()));
                    bindValues.append(QString::number(filter.minorVersion()));
                }
                else if (filter.versionMatchRule() == QServiceFilter::MinimumVersionMatch) {
                    whereComponent.append(QLatin1String("AND ((Interface.VerMaj > ?"))
                        .append(QLatin1String(") OR Interface.VerMaj = ?")).append(QLatin1String(" AND Interface.VerMin >= ?")).append(QLatin1String(") "));
                    bindValues.append(QString::number(filter.majorVersion()));
                    bindValues.append(QString::number(filter.majorVersion()));
                    bindValues.append(QString::number(filter.minorVersion()));
                }
            }
        }
    }

    if (!executeQuery(&query, selectComponent + fromComponent + whereComponent, bindValues)) {
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
        qWarning() << "ServiceDatabase::getInterfaces():-"
                    << "Problem:" << qPrintable(m_lastError.text());
#endif
        rollbackTransaction(&query);
        return interfaces;
    }

    QServiceInterfaceDescriptor serviceInterface;
    serviceInterface.d = new QServiceInterfaceDescriptorPrivate;
    QStringList capabilities;
    QString serviceID;
    QString interfaceID;
    const QSet<QString> filterCaps = filter.capabilities().toSet();
    QSet<QString> difference;

    while (query.next()){
        difference.clear();
        serviceInterface.d->customAttributes.clear();
        serviceInterface.d->attributes.clear();
        serviceInterface.d->interfaceName = query.value(EBindIndex).toString();
        serviceInterface.d->serviceName = query.value(EBindIndex1).toString();
        serviceInterface.d->major = query.value(EBindIndex2).toInt();
        serviceInterface.d->minor = query.value(EBindIndex3).toInt();

        QString location = query.value(EBindIndex4).toString();
        if (location.startsWith(QLatin1String(SERVICE_IPC_PREFIX))) {
            serviceInterface.d->attributes[QServiceInterfaceDescriptor::ServiceType] = QService::InterProcess;
            serviceInterface.d->attributes[QServiceInterfaceDescriptor::Location]
                = location.remove(0,QString(QLatin1String(SERVICE_IPC_PREFIX)).size());
        } else {
            serviceInterface.d->attributes[QServiceInterfaceDescriptor::ServiceType] = QService::Plugin;
            serviceInterface.d->attributes[QServiceInterfaceDescriptor::Location] = location;
        }

        serviceID = query.value(EBindIndex5).toString();
        if (!populateServiceProperties(&serviceInterface, serviceID)) {
            //populateServiceProperties should already give a warning message
            //and set the last error
            interfaces.clear();
            rollbackTransaction(&query);
            return interfaces;
        }

        interfaceID = query.value(EBindIndex6).toString();
        if (!populateInterfaceProperties(&serviceInterface, interfaceID)) {
            //populateInterfaceProperties should already give a warning message
            //and set the last error
            interfaces.clear();
            rollbackTransaction(&query);
            return interfaces;
        }

        const QSet<QString> ifaceCaps = serviceInterface.d->attributes.value(QServiceInterfaceDescriptor::Capabilities).toStringList().toSet();
        difference = ((filter.capabilityMatchRule() == QServiceFilter::MatchMinimum) ? (filterCaps-ifaceCaps) : (ifaceCaps-filterCaps));
        if (!difference.isEmpty())
            continue;

        //only return those interfaces that comply with set custom filters
        if (filter.customAttributes().size() > 0) {
            QSet<QString> keyDiff = filter.customAttributes().toSet();
            keyDiff.subtract(serviceInterface.d->customAttributes.uniqueKeys().toSet());
            if (keyDiff.isEmpty()) { //target descriptor has same custom keys as filter
                bool isMatch = true;
                const QStringList keys = filter.customAttributes();
                for (int i = 0; i<keys.count(); i++) {
                    if (serviceInterface.d->customAttributes.value(keys[i]) !=
                            filter.customAttribute(keys[i])) {
                        isMatch = false;
                        break;
                    }
                }
                if (isMatch)
                    interfaces.append(serviceInterface);
            }
        } else { //no custom keys -> SQL statement ensures proper selection already
            interfaces.append(serviceInterface);
        }
    }

    rollbackTransaction(&query);//read-only operation so just rollback
    m_lastError.setError(DBError::NoError);
    return interfaces;
}

/*
   Obtains a QServiceInterfaceDescriptor that
   corresponds to a given \a interfaceID

   May set last error to one of the following error codes:
   DBError::NoError
   DBError::NotFound
   DBError::SqlError
   DBError::DatabaseNotOpen
   DBError::InvalidDatabaseConnection
   DBError::NoWritePermissions
   DBError::InvalidDatabaseFile
*/
QServiceInterfaceDescriptor ServiceDatabase::getInterface(const QString &interfaceID)
{
    QServiceInterfaceDescriptor serviceInterface;
    if (!checkConnection()) {
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
        qWarning() << "ServiceDatabase::getInterface():-"
                    << "Problem:" << qPrintable(m_lastError.text());
#endif
        return serviceInterface;
    }

    QSqlDatabase database = QSqlDatabase::database(m_connectionName);
    QSqlQuery query(database);

    if (!beginTransaction(&query, Read)) {
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
        qWarning() << "ServiceDatabase::getInterface():-"
                    << "Unable to begin transaction. "
                    << "Reason:" << qPrintable(m_lastError.text());
#endif
        return serviceInterface;
    }

    QString selectComponent = QLatin1String("SELECT Interface.Name, "
                                "Service.Name, Interface.VerMaj, "
                                "Interface.VerMin, "
                                "Service.Location, "
                                "Service.ID ");
    QString fromComponent = QLatin1String("FROM Interface, Service ");
    QString whereComponent = QLatin1String("WHERE Service.ID = Interface.ServiceID "
                                    "AND Interface.ID = ? ");
    QList<QVariant> bindValues;
    bindValues.append(interfaceID);

    if (!executeQuery(&query, selectComponent + fromComponent + whereComponent, bindValues)) {
        rollbackTransaction(&query);
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
        qWarning() << "ServiceDatabase::getInterfaces():-"
                    << "Problem:" << qPrintable(m_lastError.text());
#endif
        return serviceInterface;
    }

    if (!query.next()) {
        rollbackTransaction(&query);
        QString errorText(QLatin1String("Interface implementation not found for Interface ID: %1"));
        m_lastError.setError(DBError::NotFound, errorText.arg(interfaceID));
        return serviceInterface;
    }

    serviceInterface.d = new QServiceInterfaceDescriptorPrivate;
    serviceInterface.d->interfaceName =query.value(EBindIndex).toString();
    serviceInterface.d->serviceName = query.value(EBindIndex1).toString();
    serviceInterface.d->major = query.value(EBindIndex2).toInt();
    serviceInterface.d->minor = query.value(EBindIndex3).toInt();

    QString location = query.value(EBindIndex4).toString();
    if (location.startsWith(QLatin1String(SERVICE_IPC_PREFIX))) {
        serviceInterface.d->attributes[QServiceInterfaceDescriptor::ServiceType] = QService::InterProcess;
        serviceInterface.d->attributes[QServiceInterfaceDescriptor::Location]
            = location.remove(0,QString(QLatin1String(SERVICE_IPC_PREFIX)).size());
    } else {
        serviceInterface.d->attributes[QServiceInterfaceDescriptor::ServiceType] = QService::Plugin;
        serviceInterface.d->attributes[QServiceInterfaceDescriptor::Location] = location;
    }

    QString serviceID = query.value(EBindIndex5).toString();
    if (!populateServiceProperties(&serviceInterface, serviceID)) {
        //populateServiceProperties should already give a warning message
        //and set the last error
        rollbackTransaction(&query);
        return QServiceInterfaceDescriptor();
    }

    if (!populateInterfaceProperties(&serviceInterface, interfaceID)) {
        //populateInterfaceProperties should already give a warning message
        //and set the last error
        rollbackTransaction(&query);
        return QServiceInterfaceDescriptor();
    }

    rollbackTransaction(&query);//read only operation so just rollback
    m_lastError.setError(DBError::NoError);
    return serviceInterface;
}

/*
    Obtains a list of services names.  If \a interfaceName is empty,
    then all service names are returned.  If \a interfaceName specifies
    an interface then the names of all services implementing that interface
    are returned

    May set last error to one of the following error codes:
    DBError::NoError
    DBError::SqlError
    DBError::DatabaseNotOpen
    DBError::InvalidDatabaseConnection
    DBError::NoWritePermissions
    DBError::InvalidDatabaseFile

    Aside:  There is only one query which implicitly gets
    wrapped in it's own transaction.
*/
QStringList ServiceDatabase::getServiceNames(const QString &interfaceName)
{
    QStringList services;
    if (!checkConnection()) {
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
        qWarning() << "ServiceDatabase::getServiceNames():-"
                    << "Problem:" << qPrintable(m_lastError.text());
#endif
        return services;
    }
    QSqlDatabase database = QSqlDatabase::database(m_connectionName);
    QSqlQuery query(database);
    QString selectComponent(QLatin1String("SELECT DISTINCT Service.Name COLLATE NOCASE "));
    QString fromComponent;
    QString whereComponent;
    QList<QVariant> bindValues;
    if (interfaceName.isEmpty()) {
        fromComponent = QLatin1String("FROM Service ");
    } else {
        fromComponent = QLatin1String("FROM Interface,Service ");
        whereComponent = QLatin1String("WHERE Service.ID = Interface.ServiceID AND Interface.Name = ? COLLATE NOCASE ");
        bindValues.append(interfaceName);
    }

    if (!executeQuery(&query, selectComponent + fromComponent + whereComponent, bindValues)) {
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
        qWarning() << "ServiceDatabase::getServiceNames():-"
                    << qPrintable(m_lastError.text());
#endif
        return services;
    }

    while ( query.next()) {
        services.append(query.value(EBindIndex).toString());
    }
    query.finish();
    query.clear();
    m_lastError.setError(DBError::NoError);
    return services;
}

/*
    Returns a descriptor for the default interface implementation of
    \a interfaceName.

    For user scope databases only, \a defaultInterfaceID is set if the default
    in the user scope database refers to a interface implementation in the
    system scope database.  In this case the descriptor will be invalid and
    the \a defaultInterfaceID must be used to query the system scope database,
    The last error set to DBError::ExternalIfaceIDFound

    If this function is called within a transaction, \a inTransaction
    must be set to true.  If \a inTransaction is false, this fuction
    will begin and end its own transaction.

    The last error may be set to one of the following error codes:
    DBError::NoError
    DBError::ExternalIfaceIDFound
    DBError::SqlError
    DBError::DatabaseNotOpen
    DBError::InvalidDatabaseConnection
    DBError::NoWritePermissions
    DBError::InvalidDatabaseFile
*/
QServiceInterfaceDescriptor ServiceDatabase::interfaceDefault(const QString &interfaceName, QString *defaultInterfaceID,
                                                                    bool inTransaction)
{
    QServiceInterfaceDescriptor serviceInterface;
    if (!checkConnection())
    {
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
        qWarning() << "ServiceDatabase::interfaceDefault():-"
                    << "Problem:" << qPrintable(m_lastError.text());
#endif
        return serviceInterface;
    }

    QSqlDatabase database = QSqlDatabase::database(m_connectionName);
    QSqlQuery query(database);

    if (!inTransaction && !beginTransaction(&query, Read)) {
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
        qWarning() << "ServiceDatabase::interfaceDefault(QString, QString):-"
                    << "Unable to begin transaction. "
                    << "Reason:" << qPrintable(m_lastError.text());
#endif
        return serviceInterface;
    }

    QString statement(QLatin1String("SELECT InterfaceID FROM Defaults WHERE InterfaceName = ? COLLATE NOCASE"));
    QList<QVariant> bindValues;
    bindValues.append(interfaceName);
    if (!executeQuery(&query, statement, bindValues)) {
        if (!inTransaction)
            rollbackTransaction(&query);
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
        qWarning() << "ServiceDatabase::interfaceDefault():-"
                    << qPrintable(m_lastError.text());
#endif
        return serviceInterface;
    }

    QString interfaceID;
    if (!query.next())
    {
        if (!inTransaction)
            rollbackTransaction(&query);
        QString errorText(QLatin1String("No default service found for interface: \"%1\""));
        m_lastError.setError(DBError::NotFound, errorText.arg(interfaceName));
        return serviceInterface;
    }
    else
        interfaceID = query.value(EBindIndex).toString();
    Q_ASSERT(!interfaceID.isEmpty());

    statement = QLatin1String("SELECT Interface.Name, "
                        "Service.Name, Interface.VerMaj, "
                        "Interface.VerMin, "
                        "Service.Location, "
                        "Service.ID "
                    "FROM Service, Interface "
                    "WHERE Service.ID = Interface.ServiceID AND Interface.ID = ?");
    bindValues.clear();
    bindValues.append(interfaceID);
    if (!executeQuery(&query, statement, bindValues))
    {
        if (!inTransaction)
            rollbackTransaction(&query);
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
        qWarning() << "ServiceDatabase::interfaceDefault():-"
                    << qPrintable(m_lastError.text());
#endif
        return serviceInterface;
    }

    if (!query.next()) {
        if (!inTransaction)
            rollbackTransaction(&query);
        if (defaultInterfaceID != NULL )
            *defaultInterfaceID = interfaceID;
        m_lastError.setError(DBError::ExternalIfaceIDFound);
        return serviceInterface;
    }

    serviceInterface.d = new QServiceInterfaceDescriptorPrivate;
    serviceInterface.d->interfaceName =query.value(EBindIndex).toString();
    serviceInterface.d->serviceName = query.value(EBindIndex1).toString();
    serviceInterface.d->major = query.value(EBindIndex2).toInt();
    serviceInterface.d->minor = query.value(EBindIndex3).toInt();

    QString location = query.value(EBindIndex4).toString();
    if (location.startsWith(QLatin1String(SERVICE_IPC_PREFIX))) {
        serviceInterface.d->attributes[QServiceInterfaceDescriptor::ServiceType] = QService::InterProcess;
        serviceInterface.d->attributes[QServiceInterfaceDescriptor::Location]
            = location.remove(0,QString(QLatin1String(SERVICE_IPC_PREFIX)).size());
    } else {
        serviceInterface.d->attributes[QServiceInterfaceDescriptor::ServiceType] = QService::Plugin;
        serviceInterface.d->attributes[QServiceInterfaceDescriptor::Location] = location;
    }

    QString serviceID = query.value(EBindIndex5).toString();
    if (!populateServiceProperties(&serviceInterface, serviceID)) {
        //populateServiceProperties should already give a warning
        //and set the last error
        if (!inTransaction)
            rollbackTransaction(&query);
        return QServiceInterfaceDescriptor();
    }

    if (!populateInterfaceProperties(&serviceInterface, interfaceID)) {
        //populateInterfaceProperties should already give a warning
        //and set the last error
        if (!inTransaction)
            rollbackTransaction(&query);
        return QServiceInterfaceDescriptor();
    }

    if (!inTransaction)
        rollbackTransaction(&query); //Read only operation so just rollback
    m_lastError.setError(DBError::NoError);
    return serviceInterface;
}

/*
   Sets a particular service's \a interface implementation as a the default
   implementation to look up when using the interface's name in
   interfaceDefault().

   For a user scope database an \a externalInterfaceID can be provided
   so that the Defaults table will contain a "link" to an interface
   implmentation provided in the system scope database.

   May set the last error to one of the following error codes:
   DBError::NoError
   DBerror::NotFound
   DBError::SqlError
   DBError::DatabaseNotOpen
   DBError::InvalidDatabaseConnection
   DBError::NoWritePermissions
   DBError::InvalidDatabaseFile
*/
bool ServiceDatabase::setInterfaceDefault(const QServiceInterfaceDescriptor &serviceInterface, const QString &externalInterfaceID)
{
    if (!checkConnection()) {
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
        qWarning() << "ServiceDatabase::setInterfaceDefault(QServiceInterfaceDescriptor):-"
            << "Problem:" << qPrintable(m_lastError.text());
#endif
        return false;
    }

    QSqlDatabase database = QSqlDatabase::database(m_connectionName);
    QSqlQuery query(database);

    //Begin Transaction
    if (!beginTransaction(&query, Write)) {
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
        qWarning() << "ServiceDatabase::setInterfaceDefault(QServiceInterfaceDescriptor):-"
            << "Problem: Unable to begin transaction."
            << "Reason:" << qPrintable(m_lastError.text());
#endif
        return false;
    }

    QString statement;
    QList<QVariant> bindValues;
    QString interfaceID = externalInterfaceID;
    if (interfaceID.isEmpty()) {
        statement = QLatin1String("SELECT Interface.ID from Interface, Service "
                "WHERE Service.ID = Interface.ServiceID "
                "AND Service.Name = ? COLLATE NOCASE "
                "AND Interface.Name = ? COLLATE NOCASE "
                "AND Interface.VerMaj = ? "
                "AND Interface.VerMin = ? ");
        bindValues.append(serviceInterface.serviceName());
        bindValues.append(serviceInterface.interfaceName());
        bindValues.append(serviceInterface.majorVersion());
        bindValues.append(serviceInterface.minorVersion());

        if (!executeQuery(&query, statement, bindValues)) {
            rollbackTransaction(&query);
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
            qWarning() << "ServiceDatabase::setInterfaceDefault(QServiceInterfaceDescriptor):-"
                << qPrintable(m_lastError.text());
#endif
            return false;
        }

        if (!query.next()) {
            QString errorText;
            errorText = QLatin1String("No implementation for interface: %1, Version: %2.%3 found "
                "for service: %4");
            m_lastError.setNotFoundError(errorText.arg(serviceInterface.interfaceName())
                    .arg(serviceInterface.majorVersion())
                    .arg(serviceInterface.minorVersion())
                    .arg(serviceInterface.serviceName()));

            rollbackTransaction(&query);
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
            qWarning() << "ServiceDatbase::setInterfaceDefault(QServiceInterfaceDescriptor):-"
                << "Problem: Unable to set default service. "
                << "Reason:" << qPrintable(m_lastError.text());
#endif
            return false;
        }

        interfaceID = query.value(EBindIndex).toString();
        Q_ASSERT(!interfaceID.isEmpty());
    }

    statement = QLatin1String("SELECT InterfaceName FROM Defaults WHERE InterfaceName = ? COLLATE NOCASE");
    bindValues.clear();
    bindValues.append(serviceInterface.interfaceName());
    if (!executeQuery(&query, statement, bindValues)) {
        rollbackTransaction(&query);
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
        qWarning() << "ServiceDatabase::setInterfaceDefault(QServiceInterfaceDescriptor):-"
                    << qPrintable(m_lastError.text());
#endif
        return false;
    }

    if (query.next()) {
        statement = QLatin1String("UPDATE Defaults "
            "SET InterfaceID = ? "
            "WHERE InterfaceName = ? COLLATE NOCASE");
        bindValues.clear();
        bindValues.append(interfaceID);
        bindValues.append(serviceInterface.interfaceName());

        if (!executeQuery(&query, statement, bindValues)) {
            rollbackTransaction(&query);
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
            qWarning() << "ServiceDatabase::setInterfaceDefault(QServiceInterfaceDescriptor):-"
                << qPrintable(m_lastError.text());
#endif
            return false;
        }
    } else {
        statement = QLatin1String("INSERT INTO Defaults(InterfaceName,InterfaceID) VALUES(?,?)");
        bindValues.clear();
        bindValues.append(serviceInterface.interfaceName());
        bindValues.append(interfaceID);

        if (!executeQuery(&query, statement, bindValues)) {
            rollbackTransaction(&query);
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
            qWarning() << "ServiceDatabase::setInterfaceDefault(QServiceInterfaceDescriptor):-"
                << qPrintable(m_lastError.text());
#endif
            return false;
        }
    }

    //End Transaction
    if (!commitTransaction(&query)) {
        rollbackTransaction(&query);
        return false;
    }
    m_lastError.setError(DBError::NoError);
    return true;
}

/*
   Removes the service with name \a serviceName.
   If the service provides a default interface implementation, then
   another service implementing the highest interface implementation
   version becomes the new default(if any).  If more than one service
   provides same the highest version number, an arbitrary choice is made
   between them.

   May set the last error to the folowing error codes:
   DBError::NoError
   DBError::NotFound
   DBError::SqlError
   DBError::DatabaseNotOpen
   DBError::InvalidDatabaseConnection
   DBError::NoWritePermissions
   DBError::InvalidDatabaseFile
*/
bool ServiceDatabase::unregisterService(const QString &serviceName, const QString &securityToken)
{
#ifndef QT_SFW_SERVICEDATABASE_USE_SECURITY_TOKEN
    Q_UNUSED(securityToken);
#else
    if (securityToken.isEmpty()) {
        QString errorText(QLatin1String("Access denied, no security token provided (for unregistering service: \"%1\")"));
        m_lastError.setError(DBError::NoWritePermissions, errorText.arg(serviceName));
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
        qWarning() << "ServiceDatabase::unregisterService():-"
                << "Problem: Unable to unregister service. "
                << "Reason:" << qPrintable(m_lastError.text());
#endif
        return false;
    }
#endif


    if (!checkConnection()) {
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
        qWarning() << "ServiceDatabase::unregisterService():-"
                    << "Problem:" << qPrintable(m_lastError.text());
#endif
        return false;
    }

    QSqlDatabase database = QSqlDatabase::database(m_connectionName);
    QSqlQuery query(database);

    if (!beginTransaction(&query, Write)) {
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
        qWarning() << "ServiceDatabase::unregisterService():-"
                    << "Problem: Unable to begin transaction. "
                    << "Reason:" << qPrintable(m_lastError.text());
#endif
        return false;
    }

    QString statement(QLatin1String("SELECT Service.ID from Service WHERE Service.Name = ? COLLATE NOCASE"));
    QList<QVariant> bindValues;
    bindValues.append(serviceName);
    if (!executeQuery(&query, statement, bindValues)) {
        rollbackTransaction(&query);
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
        qWarning() << "ServiceDatabase::unregisterService():-"
                    << qPrintable(m_lastError.text());
#endif
        return false;
    }

    QStringList serviceIDs;
    while (query.next()) {
        serviceIDs << query.value(EBindIndex).toString();
    }

#ifdef QT_SFW_SERVICEDATABASE_USE_SECURITY_TOKEN
    // Only the application that registered the service is allowed to unregister that
    // service. Fetch a security ID of a service (with given name) and verify that it matches
    // with current apps security id. Only one application is allowed to register services with
    // same name, hence a distinct (just any of the) security token will do because they are identical.
    if (!serviceIDs.isEmpty()) {
        statement = QLatin1String("SELECT DISTINCT Value FROM ServiceProperty WHERE ServiceID = ? AND Key = ?");
        bindValues.clear();
        bindValues.append(serviceIDs.first());
        bindValues.append(SECURITY_TOKEN_KEY);

        if (!executeQuery(&query, statement, bindValues)) {
            rollbackTransaction(&query);
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
            qWarning() << "ServiceDatabase::unregisterService():-"
                    << qPrintable(m_lastError.text());
#endif
            return false;
        }
        QString existingSecurityToken;
        if (query.next()) {
            existingSecurityToken = query.value(EBindIndex).toString();
        }
        if (existingSecurityToken != securityToken) {
            QString errorText(QLatin1String("Access denied: \"%1\""));
            m_lastError.setError(DBError::NoWritePermissions, errorText.arg(serviceName));
            rollbackTransaction(&query);
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
            qWarning() << "ServiceDatabase::unregisterService():-"
                    << "Problem: Unable to unregister service"
                    << "Reason:" << qPrintable(m_lastError.text());
#endif
            return false;
        }
    }
#endif // QT_SFW_SERVICEDATABASE_USE_SECURITY_TOKEN

    statement = QLatin1String("SELECT Interface.ID from Interface, Service "
                "WHERE Interface.ServiceID = Service.ID "
                    "AND Service.Name =? COLLATE NOCASE");
    bindValues.clear();
    bindValues.append(serviceName);
    if (!executeQuery(&query, statement, bindValues)) {
        rollbackTransaction(&query);
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
        qWarning() << "ServiceDatabase::unregisterService():-"
                    << qPrintable(m_lastError.text());
#endif
        return false;
    }

    QStringList interfaceIDs;
    while (query.next()) {
        interfaceIDs << query.value(EBindIndex).toString();
    }

    if (serviceIDs.count() == 0) {
        QString errorText(QLatin1String("Service not found: \"%1\""));
        m_lastError.setError(DBError::NotFound, errorText.arg(serviceName));
        rollbackTransaction(&query);
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
        qWarning() << "ServiceDatabase::unregisterService():-"
                    << "Problem: Unable to unregister service"
                    << "Reason:" << qPrintable(m_lastError.text());
#endif
        return false;
    }

    statement = QLatin1String("SELECT Defaults.InterfaceName "
                "FROM Defaults, Interface, Service "
                "WHERE Defaults.InterfaceID = Interface.ID "
                    "AND Interface.ServiceID = Service.ID "
                    "AND Service.Name = ? COLLATE NOCASE");
    bindValues.clear();
    bindValues.append(serviceName);
    if (!executeQuery(&query, statement, bindValues)) {
        rollbackTransaction(&query);
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
        qWarning() << "ServiceDatabase:unregisterService():-"
                    << qPrintable(m_lastError.text());
#endif
        return false;
    }

    QStringList serviceDefaultInterfaces;
    while (query.next()) {
        serviceDefaultInterfaces << query.value(EBindIndex).toString();
    }


    statement = QLatin1String("DELETE FROM Service WHERE Service.Name = ? COLLATE NOCASE");
    bindValues.clear();
    bindValues.append(serviceName);
    if (!executeQuery(&query, statement, bindValues)) {
        rollbackTransaction(&query);
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
        qWarning() << "ServiceDatabase::unregisterService():-"
                    << qPrintable(m_lastError.text());
#endif
        return false;
    }

    statement = QLatin1String("DELETE FROM Interface WHERE Interface.ServiceID = ?");
    foreach (const QString &serviceID, serviceIDs) {
        bindValues.clear();
        bindValues.append(serviceID);
        if (!executeQuery(&query, statement, bindValues)) {
            rollbackTransaction(&query);
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
            qWarning() << "ServiceDatabase::unregisterService():-"
                        << qPrintable(m_lastError.text());
#endif
            return false;
        }
    }

    statement = QLatin1String("DELETE FROM ServiceProperty WHERE ServiceID = ?");

    foreach (const QString &serviceID, serviceIDs) {
        bindValues.clear();
        bindValues.append(serviceID);
        if (!executeQuery(&query, statement, bindValues)) {
            rollbackTransaction(&query);
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
            qWarning() << "ServiceDatabase::unregisterService():-"
                        << qPrintable(m_lastError.text());
#endif
            return false;
        }
    }

    statement = QLatin1String("DELETE FROM InterfaceProperty WHERE InterfaceID = ?");
    foreach (const QString &interfaceID,  interfaceIDs) {
        bindValues.clear();
        bindValues.append(interfaceID);
        if (!executeQuery(&query, statement, bindValues)) {
            rollbackTransaction(&query);
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
            qWarning() << "ServiceDatabase::unregisterService():-"
                        << qPrintable(m_lastError.text());
#endif
            return false;
        }
    }

    foreach (const QString &interfaceName, serviceDefaultInterfaces) {
        statement = QLatin1String("SELECT ID FROM Interface WHERE Interface.Name = ? COLLATE NOCASE "
                    "ORDER BY Interface.VerMaj DESC, Interface.VerMin DESC");
        bindValues.clear();
        bindValues.append(interfaceName);
        if (!executeQuery(&query, statement, bindValues)) {
            rollbackTransaction(&query);
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
            qWarning() << "ServiceDatabase::unregisterService():-"
                        << qPrintable(m_lastError.text());
#endif
            return false;
        }

        if (query.next()) {
            QString newDefaultID = query.value(EBindIndex).toString();
            statement = QLatin1String("UPDATE Defaults SET InterfaceID = ? WHERE InterfaceName = ? COLLATE NOCASE ");
            bindValues.clear();
            bindValues.append(newDefaultID);
            bindValues.append(interfaceName);
            if (!executeQuery(&query, statement, bindValues)) {
                rollbackTransaction(&query);
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
                qWarning() << "ServiceDatabase::unregisterService():-"
                            << qPrintable(m_lastError.text());
#endif
                return false;
            }
        } else {
            statement = QLatin1String("DELETE FROM Defaults WHERE InterfaceName = ? COLLATE NOCASE ");
            bindValues.clear();
            bindValues.append(interfaceName);
            if (!executeQuery(&query, statement, bindValues)) {
                rollbackTransaction(&query);
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
                qWarning() << "ServiceDatabase::unregisterService():-"
                            << qPrintable(m_lastError.text());
#endif
                return false;
            }
        }
    }

    //databaseCommit
    if (!commitTransaction(&query)) {
        rollbackTransaction(&query);
        return false;
    }
    m_lastError.setError(DBError::NoError);
    return true;
}

/*
    Registers the service initialization into the database.
*/
bool ServiceDatabase::serviceInitialized(const QString &serviceName, const QString &securityToken)
{
#ifndef QT_SFW_SERVICEDATABASE_USE_SECURITY_TOKEN
    Q_UNUSED(securityToken);
#endif

    if (!checkConnection()) {
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
        qWarning() << "ServiceDatabase::unregisterService():-"
                    << "Problem:" << qPrintable(m_lastError.text());
#endif
        return false;
    }

    QSqlDatabase database = QSqlDatabase::database(m_connectionName);
    QSqlQuery query(database);

    if (!beginTransaction(&query, Write)) {
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
        qWarning() << "ServiceDatabase::serviceInitialized():-"
                    << "Problem: Unable to begin transaction"
                    << "\nReason:" << qPrintable(m_lastError.text());
#endif
        return false;
    }

    QString statement(QLatin1String("SELECT Service.ID from Service WHERE Service.Name = ? COLLATE NOCASE"));
    QList<QVariant> bindValues;
    bindValues.append(serviceName);
    if (!executeQuery(&query, statement, bindValues)) {
        rollbackTransaction(&query);
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
        qWarning() << "ServiceDatabase::serviceInitialized():-"
                    << qPrintable(m_lastError.text());
#endif
        return false;
    }

    QStringList serviceIDs;
    while (query.next()) {
        serviceIDs << query.value(EBindIndex).toString();
    }


#ifdef QT_SFW_SERVICEDATABASE_USE_SECURITY_TOKEN
    statement = QLatin1String("SELECT Value FROM ServiceProperty WHERE ServiceID = ? AND Key = ?");
    bindValues.clear();
    bindValues.append(serviceName);
    bindValues.append(SECURITY_TOKEN_KEY);
    if (!executeQuery(&query, statement, bindValues)) {
        rollbackTransaction(&query);
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
        qWarning() << "ServiceDatabase::unregisterService():-"
                    << qPrintable(m_lastError.text());
#endif
        return false;
    }

    QStringList securityTokens;
    while (query.next()) {
        securityTokens << query.value(EBindIndex).toString();
    }

    if (!securityTokens.isEmpty() && (securityTokens.first() != securityToken)) {
        QString errorText(QLatin1String("Access denied: \"%1\""));
             m_lastError.setError(DBError::NoWritePermissions, errorText.arg(serviceName));
             rollbackTransaction(&query);
     #ifdef QT_SFW_SERVICEDATABASE_DEBUG
             qWarning() << "ServiceDatabase::serviceInitialized():-"
                         << "Problem: Unable to update service initialization"
                         << "\nReason:" << qPrintable(m_lastError.text());
     #endif
    }
#endif

    statement = QLatin1String("DELETE FROM ServiceProperty WHERE ServiceID = ? AND Key = ?");
    foreach (const QString &serviceID, serviceIDs) {
        bindValues.clear();
        bindValues.append(serviceID);
        bindValues.append(QLatin1String(SERVICE_INITIALIZED_KEY));
        if (!executeQuery(&query, statement, bindValues)) {
            rollbackTransaction(&query);
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
            qWarning() << "ServiceDatabase::serviceInitialized():-"
                        << qPrintable(m_lastError.text());
#endif
            return false;
        }
    }

    //databaseCommit
    if (!commitTransaction(&query)) {
        rollbackTransaction(&query);
        return false;
    }
    m_lastError.setError(DBError::NoError);
    return true;
}

/*
    Closes the database

    May set the following error codes:
    DBError::NoError
    DBError::InvalidDatabaseConnection
*/
bool ServiceDatabase::close()
{
    if (m_isDatabaseOpen) {
        QSqlDatabase database = QSqlDatabase::database(m_connectionName, false);
        if (database.isValid()) {
            if (database.isOpen()) {
                database.close();
                m_isDatabaseOpen = false;
                return true;
            }
        } else {
            m_lastError.setError(DBError::InvalidDatabaseConnection);
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
            qWarning() << "ServiceDatabase::close():-"
                        << "Problem: " << qPrintable(m_lastError.text());
#endif
            return false;
        }
    }
    m_lastError.setError(DBError::NoError);
    return true;
}

/*
    Sets the path of the service database to \a databasePath
*/
void ServiceDatabase::setDatabasePath(const QString &databasePath)
{
    m_databasePath = QDir::toNativeSeparators(databasePath);
}

/*
    Returns the path of the service database
*/
QString ServiceDatabase::databasePath() const
{
    QString path;
    if (m_databasePath.isEmpty()) {
        QSettings settings(QSettings::SystemScope, QLatin1String("Nokia"), QLatin1String("Services"));
        path = settings.value(QLatin1String("ServicesDB/Path")).toString();
        if (path.isEmpty()) {
            path = QDir::currentPath();
            if (path.lastIndexOf(QLatin1String(RESOLVERDATABASE_PATH_SEPARATOR)) != path.length() -1) {
                path.append(QLatin1String(RESOLVERDATABASE_PATH_SEPARATOR));
            }
            path.append(QLatin1String(RESOLVERDATABASE));
        }
        path = QDir::toNativeSeparators(path);
    } else {
        path = m_databasePath;
    }

    return path;
}

/*
    Helper method that creates the database tables: Service, Interface,
    Defaults, ServiceProperty and InterfaceProperty

    May set the last error to one of the following error codes:
    DBError::NoError
    DBError::SqlError
    DBError::NoWritePermissions
    DBError::InvalidDatabaseFile
*/
bool ServiceDatabase::createTables()
{
    QSqlDatabase database = QSqlDatabase::database(m_connectionName);
    QSqlQuery query(database);

    //Begin Transaction
    if (!beginTransaction(&query, Write)) {
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
        qWarning() << "ServiceDatabase::createTables():-"
                    << "Unable to begin transaction. "
                    << "Reason:" << qPrintable(m_lastError.text());
#endif
        return false;
    }

    QString statement(QLatin1String("CREATE TABLE Service("
                        "ID TEXT NOT NULL PRIMARY KEY UNIQUE,"
                        "Name TEXT NOT NULL, "
                        "Location TEXT NOT NULL)"));
    if (!executeQuery(&query, statement)) {
        rollbackTransaction(&query);
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
        qWarning() << "ServiceDatabase::createTables():-"
                    << qPrintable(m_lastError.text());
#endif
        return false;
    }

    statement = QLatin1String("CREATE TABLE Interface("
                "ID TEXT NOT NULL PRIMARY KEY UNIQUE,"
                "ServiceID TEXT NOT NULL, "
                "Name TEXT NOT NULL, "
                "VerMaj INTEGER NOT NULL, "
                "VerMin INTEGER NOT NULL)");
    if (!executeQuery(&query, statement)) {
        rollbackTransaction(&query);
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
        qWarning() << "ServiceDatabase::createTables():-"
                    << qPrintable(m_lastError.text());
#endif
        return false;
    }

    statement = QLatin1String("CREATE TABLE Defaults("
                "InterfaceName TEXT PRIMARY KEY UNIQUE NOT NULL,"
                "InterfaceID TEXT NOT NULL)");
    if (!executeQuery(&query, statement)) {
        rollbackTransaction(&query);
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
        qWarning() << "ServiceDatabase::createTables():-"
                    << qPrintable(m_lastError.text());
#endif
        return false;
    }

    statement = QLatin1String("CREATE TABLE ServiceProperty("
                "ServiceID TEXT NOT NULL,"
                "Key TEXT NOT NULL,"
                "Value TEXT NOT NULL)");
    if (!executeQuery(&query, statement)) {
        rollbackTransaction(&query);
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
        qWarning() << "ServiceDatabase::createTables():-"
                    << qPrintable(m_lastError.text());
#endif
        return false;
    }

    statement = QLatin1String("CREATE TABLE InterfaceProperty("
                "InterfaceID TEXT NOT NULL,"
                "Key TEXT NOT NULL,"
                "Value TEXT NOT NULL)");

    if (!executeQuery(&query, statement)) {
        rollbackTransaction(&query);
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
        qWarning() << "ServiceDatabase::createTables():-"
                    << qPrintable(m_lastError.text());
#endif
        return false;
    }

    if (!commitTransaction(&query)) {
        rollbackTransaction(&query);
        return false;
    }
    m_lastError.setError(DBError::NoError);
    return true;
}

/*!
    Helper method that checks if the all expected tables exist in the database
    Returns true if they all exist and false if any of them don't
*/
bool ServiceDatabase::checkTables()
{
    bool bTables(false);
    QStringList tables = QSqlDatabase::database(m_connectionName).tables();
    if (tables.contains(QLatin1String(SERVICE_TABLE))
        && tables.contains(QLatin1String(INTERFACE_TABLE))
        && tables.contains(QLatin1String(DEFAULTS_TABLE))
        && tables.contains(QLatin1String(SERVICE_PROPERTY_TABLE))
        && tables.contains(QLatin1String(INTERFACE_PROPERTY_TABLE))){
            bTables = true;
    }
    return bTables;
}

/*
   This function should only ever be used on a user scope database
   It removes an entry from the Defaults table where the default
   refers to an interface implementation in the system scope database.
   The particular default that is removed is specified by
   \a interfaceID.

   May set the last error to one of the following error codes:
   DBError::NoError
   DBError::IfaceIDNotExternal
   DBError::SqlError
   DBError::NoWritePermissions
   DBError::InvalidDatabaseFile
*/
bool ServiceDatabase::removeExternalDefaultServiceInterface(const QString &interfaceID)
{
    QSqlDatabase database = QSqlDatabase::database(m_connectionName);
    QSqlQuery query(database);

    //begin transaction
    if (!beginTransaction(&query, Write)) {
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
        qWarning() << "ServiceDatabase::removeExternalDefaultServiceInterface():-"
                    << "Problem: Unable to begin transaction. "
                    << "Reason:" << qPrintable(m_lastError.text());
#endif
        return false;
    }

    QString statement(QLatin1String("SELECT Name FROM Interface WHERE Interface.ID = ?"));
    QList<QVariant> bindValues;
    bindValues.append(interfaceID);
    if (!executeQuery(&query, statement, bindValues)) {
        rollbackTransaction(&query);
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
        qWarning() << "ServiceDatabase::removeDefaultServiceInterface():-"
                    << qPrintable(m_lastError.text());
#endif
        return false;
    }
    if (query.next()) {
        QString interfaceName = query.value(EBindIndex).toString();
        QString errorText(QLatin1String("Local interface implementation exists for interface \"%1\" "
                           "with interfaceID: \"%2\""));
        m_lastError.setError(DBError::IfaceIDNotExternal,
                errorText.arg(interfaceName).arg(interfaceID));
        rollbackTransaction(&query);
        return false;
    }

    statement = QLatin1String("DELETE FROM Defaults WHERE InterfaceID = ? COLLATE NOCASE");
    bindValues.clear();
    bindValues.append(interfaceID);
    if (!executeQuery(&query, statement, bindValues)) {
        rollbackTransaction(&query);
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
        qWarning() << "ServiceDatabase::removeDefaultServiceInterface():-"
                    << qPrintable(m_lastError.text());
#endif
        return false;
    }

    //end transaction
    if (!commitTransaction(&query)){
        rollbackTransaction(&query);
        return false;
    }
    m_lastError.setError(DBError::NoError);
    return true;
}

/*
    Removes all tables from the database

    In future this function may be deprecated or removed.

    May set the last error to one of the following error codes:
    DBError::NoError
    DBError::SqlError
    DBError::NoWritePermissions
    DBError::InvalidDatabaseFile
*/
bool ServiceDatabase::dropTables()
{
    //Execute transaction for deleting the database tables
    QSqlDatabase database = QSqlDatabase::database(m_connectionName);
    QSqlQuery query(database);
    QStringList expectedTables;
    expectedTables << QLatin1String(SERVICE_TABLE)
                << QLatin1String(INTERFACE_TABLE)
                << QLatin1String(DEFAULTS_TABLE)
                << QLatin1String(SERVICE_PROPERTY_TABLE)
                << QLatin1String(INTERFACE_PROPERTY_TABLE);

    if (database.tables().count() > 0) {
        if (!beginTransaction(&query, Write)) {
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
            qWarning() << "ServiceDatabase::dropTables():-"
                        << "Unable to begin transaction. "
                        << "Reason:" << qPrintable(m_lastError.text());
#endif
            return false;
        }
        QStringList actualTables = database.tables();

        foreach (const QString expectedTable, expectedTables) {
            if ((actualTables.contains(expectedTable))
                && (!executeQuery(&query, QLatin1String("DROP TABLE ") + expectedTable))) {
                rollbackTransaction(&query);
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
                qWarning() << "ServiceDatabase::dropTables():-"
                           << qPrintable(m_lastError.text());
#endif
                return false;
            }
        }
        if (!commitTransaction(&query)) {
            rollbackTransaction(&query);
            return false;
        }
    }
    m_lastError.setError(DBError::NoError);
    return true;
}

/*
    Checks if the database is open
*/
bool ServiceDatabase::isOpen() const
{
  return m_isDatabaseOpen;
}

/*
   Checks the database connection.

   May set the last error to one of the following error codes:
   DBError::DatabaseNotOpen
   DBError::InvalidDatabaseConnection
*/
bool ServiceDatabase::checkConnection()
{
    if (!m_isDatabaseOpen)
    {
        m_lastError.setError(DBError::DatabaseNotOpen);
        return false;
    }

    if (!QSqlDatabase::database(m_connectionName).isValid())
    {
        m_lastError.setError(DBError::InvalidDatabaseConnection);
        return false;
    }

    return true;
}

/*
   Begins a transcaction based on the \a type which can be Read or Write.

   May set the last error to one of the following error codes:
   DBError::NoError
   DBError::SqlError
   DBError::NoWritePermissions
   DBError::InvalidDatabaseFile
*/
bool ServiceDatabase::beginTransaction(QSqlQuery *query, TransactionType type)
{
    bool success;
    if (type == Read)
        success = query->exec(QLatin1String("BEGIN"));
    else
        success = query->exec(QLatin1String("BEGIN IMMEDIATE"));

    if (!success) {
        int result = query->lastError().number();
        if (result == 26 || result == 11) {//SQLITE_NOTADB || SQLITE_CORRUPT
            qWarning() << "Service Framework:- Database file is corrupt or invalid:" << databasePath();
            m_lastError.setError(DBError::InvalidDatabaseFile, query->lastError().text());
        }
        else if (result == 8) { //SQLITE_READONLY
            qWarning() << "Service Framework:-  Insufficient permissions to write to database:" << databasePath();
            m_lastError.setError(DBError::NoWritePermissions, query->lastError().text());
        }
        else
            m_lastError.setError(DBError::SqlError, query->lastError().text());
        return false;
    }

    m_lastError.setError(DBError::NoError);
    return true;
}

/*
    Commits a transaction

    May set the last error to one of the following error codes:
    DBError::NoError
    DBError::SqlError
*/
bool ServiceDatabase::commitTransaction(QSqlQuery *query)
{
    Q_ASSERT(query != NULL);
    query->finish();
    query->clear();
    if (!query->exec(QLatin1String("COMMIT"))) {
        m_lastError.setError(DBError::SqlError, query->lastError().text());
        return false;
    }
    m_lastError.setError(DBError::NoError);
    return true;
}

/*
    Rolls back a transaction

    May set the last error to one of the following error codes:
    DBError::NoError
    DBError::SqlError
*/
bool ServiceDatabase::rollbackTransaction(QSqlQuery *query)
{
    Q_ASSERT(query !=NULL);
    query->finish();
    query->clear();

    if (!query->exec(QLatin1String("ROLLBACK"))) {
        m_lastError.setError(DBError::SqlError, query->lastError().text());
        return false;
    }
    return true;
}

/*
    Helper function that populates a service \a interface descriptor
    with interface related attributes corresponding to the interface
    represented by \a interfaceID

    It is already assumed that a transaction has been started by the time
    this function is called.  This function will not rollback/commit the
    transaction.

    May set the last error to one of the following error codes:
    DBError::NoError
    DBError::SqlError
*/
bool ServiceDatabase::populateInterfaceProperties(QServiceInterfaceDescriptor *serviceInterface, const QString &interfaceID)
{
    QSqlQuery query(QSqlDatabase::database(m_connectionName));
    QString statement(QLatin1String("SELECT Key, Value FROM InterfaceProperty WHERE InterfaceID = ?"));
    QList<QVariant> bindValues;
    bindValues.append(interfaceID);
    if (!executeQuery(&query, statement, bindValues)) {
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
        qWarning() << "ServiceDatabase::populateInterfaceProperties():-"
                    << qPrintable(m_lastError.text());
#endif
        return false;
    }

    bool isFound = false;
    QString attribute;
    while (query.next()) {
        isFound = true;
        attribute = query.value(EBindIndex).toString();
        if (attribute == QLatin1String(INTERFACE_CAPABILITY_KEY)) {
            const QStringList capabilities = query.value(EBindIndex1).toString().split(QLatin1String(","));
            if (capabilities.count() == 1 && capabilities[0].isEmpty()) {
                serviceInterface->d->attributes[QServiceInterfaceDescriptor::Capabilities]
                    = QStringList();
            } else {
                serviceInterface->d->attributes[QServiceInterfaceDescriptor::Capabilities]
                = capabilities;
            }
        } else if (attribute == QLatin1String(INTERFACE_DESCRIPTION_KEY)) {
            serviceInterface->d->attributes[QServiceInterfaceDescriptor::InterfaceDescription]
               = query.value(EBindIndex1).toString();
        } else if (attribute.startsWith(QLatin1String("c_"))) {
            serviceInterface->d->customAttributes[attribute.mid(2)]
               = query.value(EBindIndex1).toString();
        }
    }

    if (!isFound) {
        QString errorText(QLatin1String("Database integrity corrupted, Properties for InterfaceID: %1 does not exist in the InterfaceProperty table for interface \"%2\""));
        m_lastError.setError(DBError::SqlError, errorText.arg(interfaceID).arg(serviceInterface->interfaceName()));
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
        qWarning() << "ServiceDatabase::populateInterfaceProperties():-"
                    << "Problem:" << qPrintable(m_lastError.text());
#endif
        return false;
    }
    m_lastError.setError(DBError::NoError);
    return true;
}

/*
    Helper function that populates a service \a interface descriptor
    with service related attributes corresponding to the service
    represented by \a serviceID

    It is already assumed that a transaction has been started by the time
    this function is called.  This function will not rollback/commit the
    transaction.

    May set the last error to one of the following error codes:
    DBError::NoError
    DBError::SqlError
*/
bool ServiceDatabase::populateServiceProperties(QServiceInterfaceDescriptor *serviceInterface, const QString &serviceID)
{
    QSqlQuery query(QSqlDatabase::database(m_connectionName));
    QString statement(QLatin1String("SELECT Key, Value FROM ServiceProperty WHERE ServiceID = ?"));
    QList<QVariant> bindValues;
    bindValues.append(serviceID);
    if (!executeQuery(&query, statement, bindValues)) {
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
        qWarning() << "ServiceDatabase::populateServiceProperties():-"
                    << qPrintable(m_lastError.text());
#endif
        return false;
    }

    bool isFound = false;
    QString attribute;
    while (query.next()) {
        isFound = true;
        attribute = query.value(EBindIndex).toString();
        if (attribute == QLatin1String(SERVICE_DESCRIPTION_KEY)) {
                serviceInterface->d->attributes[QServiceInterfaceDescriptor::ServiceDescription]
                    = query.value(EBindIndex1).toString();
        }
        // fetch initialized and put it as a custom attribute
        if (attribute == QLatin1String(SERVICE_INITIALIZED_KEY)) {
            serviceInterface->d->customAttributes[attribute] = query.value(EBindIndex1).toString();
        }
    }

    if (!isFound) {
        QString errorText(QLatin1String("Database integrity corrupted, Service Properties for ServiceID: \"%1\" does not exist in the ServiceProperty table for service \"%2\""));
        m_lastError.setError(DBError::SqlError, errorText.arg(serviceID).arg(serviceInterface->serviceName()));
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
        qWarning() << "ServiceDatabase::populateServiceProperties():-"
                    << "Problem:" << qPrintable(m_lastError.text());
#endif
        return false;
    }
    m_lastError.setError(DBError::NoError);
    return true;
}

#include "moc_servicedatabase_p.cpp"

QT_END_NAMESPACE