Debian Codegraph @

src/serviceframework/servicedatabase.cpp

raw symbols SCIP
1 /****************************************************************************
2 **
3 ** Copyright (C) 2018 The Qt Company Ltd and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/legal
5 **
6 ** This file is part of the QtSystems module of the Qt Toolkit.
7 **
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** Commercial License Usage
10 ** Licensees holding valid commercial Qt licenses may use this file in
11 ** accordance with the commercial license agreement provided with the
12 ** Software or, alternatively, in accordance with the terms contained in
13 ** a written agreement between you and The Qt Company. For licensing terms
14 ** and conditions see https://www.qt.io/terms-conditions. For further
15 ** information use the contact form at https://www.qt.io/contact-us.
16 **
17 ** GNU Lesser General Public License Usage
18 ** Alternatively, this file may be used under the terms of the GNU Lesser
19 ** General Public License version 3 as published by the Free Software
20 ** Foundation and appearing in the file LICENSE.LGPL3 included in the
21 ** packaging of this file. Please review the following information to
22 ** ensure the GNU Lesser General Public License version 3 requirements
23 ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
24 **
25 ** GNU General Public License Usage
26 ** Alternatively, this file may be used under the terms of the GNU
27 ** General Public License version 2.0 or (at your option) the GNU General
28 ** Public license version 3 or any later version approved by the KDE Free
29 ** Qt Foundation. The licenses are as published by the Free Software
30 ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
31 ** included in the packaging of this file. Please review the following
32 ** information to ensure the GNU General Public License requirements will
33 ** be met: https://www.gnu.org/licenses/gpl-2.0.html and
34 ** https://www.gnu.org/licenses/gpl-3.0.html.
35 **
36 ** $QT_END_LICENSE$
37 **
38 ****************************************************************************/
39
40 // #define QT_SFW_SERVICEDATABASE_DEBUG
41
42 #include "servicedatabase_p.h"
43 #include <QDir>
44 #include <QSet>
45 #include "qserviceinterfacedescriptor.h"
46 #include "qserviceinterfacedescriptor_p.h"
47 #include <QUuid>
48 #include "dberror_p.h"
49
50 //database name
51 #define RESOLVERDATABASE "services.db"
52
53 //database table names
54 #define SERVICE_TABLE "Service"
55 #define INTERFACE_TABLE "Interface"
56 #define DEFAULTS_TABLE "Defaults"
57 #define SERVICE_PROPERTY_TABLE "ServiceProperty"
58 #define INTERFACE_PROPERTY_TABLE "InterfaceProperty"
59
60 //separator
61 #define RESOLVERDATABASE_PATH_SEPARATOR "//"
62
63 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
64 #include <QDebug>
65 #endif
66
67 #define SERVICE_DESCRIPTION_KEY "DESCRIPTION"
68 #ifdef QT_SFW_SERVICEDATABASE_USE_SECURITY_TOKEN
69 #define SECURITY_TOKEN_KEY "SECURITYTOKEN"
70 #endif
71 #define INTERFACE_DESCRIPTION_KEY "DESCRIPTION"
72 #define SERVICE_INITIALIZED_KEY SERVICE_INITIALIZED_ATTR
73 #define INTERFACE_CAPABILITY_KEY "CAPABILITIES"
74 #define INTERFACE_SERVICETYPE_KEY "SERVICETYPE"
75
76 //service prefixes
77 #define SERVICE_IPC_PREFIX "_q_ipc_addr:"
78
79 QT_BEGIN_NAMESPACE
80
81 enum TBindIndexes
82 {
83 EBindIndex=0,
84 EBindIndex1,
85 EBindIndex2,
86 EBindIndex3,
87 EBindIndex4,
88 EBindIndex5,
89 EBindIndex6,
90 EBindIndex7
91 };
92
93
94 /*
95 \class ServiceDatabase
96 The ServiceDatabase is responsible for the management of a single
97 service database. It provides operations for:
98 - opening and closing a connection with the database,
99 - registering and unregistering services
100 - querying for services and interfaces
101 - setting and getting default interface implementations.
102 */
103
104 /*
105 Constructor
106 */
107 ServiceDatabase::ServiceDatabase(void)
108 :m_isDatabaseOpen(false),m_inTransaction(false)
109 {
110 }
111
112 /*
113 Destructor
114 */
115 ServiceDatabase::~ServiceDatabase()
116 {
117 close();
118 }
119
120 /*
121 Opens the service database
122 The method creates or opens database and creates tables if they are not present
123 Returns true if the operation was successful, false if not.
124 */
125 bool ServiceDatabase::open()
126 {
127 if (m_isDatabaseOpen)
128 return true;
129
130 QString path;
131
132 //Create full path to database
133 if (m_databasePath.isEmpty ())
134 m_databasePath = databasePath();
135
136 path = m_databasePath;
137 QFileInfo dbFileInfo(path);
138 if (!dbFileInfo.dir().exists()) {
139 QDir::root().mkpath(dbFileInfo.path());
140 QFile file(path);
141 if (!file.open(QIODevice::ReadWrite)) {
142 QString errorText(QLatin1String("Could not create database directory: %1"));
143 m_lastError.setError(DBError::CannotCreateDbDir, errorText.arg(dbFileInfo.path()));
144 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
145 qWarning() << "ServiceDatabase::open():-"
146 << "Problem:" << qPrintable(m_lastError.text());
147 #endif
148 close();
149 return false;
150 }
151 file.close();
152 }
153
154 m_connectionName = dbFileInfo.completeBaseName() + QStringLiteral("--") + QString::number(reinterpret_cast<quintptr>(QThread::currentThreadId()));
155 QSqlDatabase database;
156 if (QSqlDatabase::contains(m_connectionName)) {
157 database = QSqlDatabase::database(m_connectionName);
158 } else {
159 database = QSqlDatabase::addDatabase(QLatin1String("QSQLITE"), m_connectionName);
160 database.setDatabaseName(path);
161 }
162
163 if (!database.isValid()){
164 m_lastError.setError(DBError::InvalidDatabaseConnection);
165 close();
166 return false;
167 }
168
169 //Create or open database
170 if (!database.isOpen()) {
171 if (!database.open()) {
172 m_lastError.setError(DBError::SqlError, database.lastError().text());
173 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
174 qWarning() << "ServiceDatabase::open():-"
175 << "Problem:" << "Could not open database. "
176 << "Reason:" << m_lastError.text();
177 #endif
178 close();
179 return false;
180 }
181 }
182 m_isDatabaseOpen = true;
183
184 //Check database structure (tables) and recreate tables if neccessary
185 //If one of tables is missing remove all tables and recreate them
186 //This operation is required in order to avoid data coruption
187 if (!checkTables()) {
188 if (dropTables()) {
189 if (createTables()) {
190 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
191 qDebug() << "ServiceDatabase::open():-"
192 << "Database tables recreated";
193 #endif
194 } else {
195 //createTable() should've handled error message
196 //and warning
197 close();
198 return false;
199 }
200 }
201 else {
202 //dropTables() should've handled error message
203 //and warning
204 close();
205 return false;
206 }
207 }
208 return true;
209 }
210
211 /*
212 Adds a \a service into the database.
213
214 May set the following error codes
215 DBError::NoError
216 DBError::LocationAlreadyRegistered
217 DBError::IfaceImplAlreadyRegistered
218 DBError::SqlError
219 DBError::DatabaseNotOpen
220 DBError::InvalidDatabaseConnection
221 DBError::NoWritePermissions
222 DBError::InvalidDatabaseFile
223 */
224 //bool ServiceDatabase::registerService(ServiceMetaData &service)
225 bool ServiceDatabase::registerService(const ServiceMetaDataResults &service, const QString &securityToken)
226 {
227 // Derive the location name with the service type prefix to be stored
228 QString locationPrefix = service.location;
229 int type = service.interfaces[0].d->attributes[QServiceInterfaceDescriptor::ServiceType].toInt();
230 if (type == QService::InterProcess)
231 locationPrefix = QLatin1String(SERVICE_IPC_PREFIX) + service.location;
232
233 #ifndef QT_SFW_SERVICEDATABASE_USE_SECURITY_TOKEN
234 Q_UNUSED(securityToken);
235 #else
236 if (securityToken.isEmpty()) {
237 QString errorText("Access denied, no security token provided (for registering service: \"%1\")");
238 m_lastError.setError(DBError::NoWritePermissions, errorText.arg(service.name));
239 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
240 qWarning() << "ServiceDatabase::registerService():-"
241 << "Problem: Unable to register service,"
242 << "reason:" << qPrintable(m_lastError.text());
243 #endif
244 return false;
245 }
246 #endif
247
248 if (!checkConnection()) {
249 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
250 qWarning() << "ServiceDatabase::registerService():-"
251 << "Problem:" << qPrintable(m_lastError.text());
252 #endif
253 return false;
254 }
255
256 QSqlDatabase database = QSqlDatabase::database(m_connectionName);
257 QSqlQuery query(database);
258
259 if (!beginTransaction(&query, Write)) {
260 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
261 qWarning() << "ServiceDatabase::registerService():-"
262 << "Unable to begin transaction,"
263 << "reason:" << qPrintable(m_lastError.text());
264 #endif
265 return false;
266 }
267 //See if the service's location has already been previously registered
268 QString statement(QLatin1String("SELECT Name from Service WHERE Location=? COLLATE NOCASE"));
269 QList<QVariant> bindValues;
270 bindValues.append(locationPrefix);
271 if (!executeQuery(&query, statement, bindValues)) {
272 rollbackTransaction(&query);
273 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
274 qWarning() << "ServiceDatabase::registerService():-"
275 << qPrintable(m_lastError.text());
276 #endif
277 return false;
278 }
279
280 if (query.next()) {
281 QString alreadyRegisteredService = query.value(EBindIndex).toString();
282 const QString errorText = QLatin1String("Cannot register service \"%1\". Service location \"%2\" is already "
283 "registered to service \"%3\". \"%3\" must first be deregistered "
284 "for new registration to take place.");
285
286 m_lastError.setError(DBError::LocationAlreadyRegistered,
287 errorText.arg(service.name)
288 .arg(service.location)
289 .arg(alreadyRegisteredService));
290
291 rollbackTransaction(&query);
292 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
293 qWarning() << "ServiceDatabase::registerService():-"
294 << "Problem:" << qPrintable(m_lastError.text());
295 #endif
296 return false;
297 }
298
299 #ifdef QT_SFW_SERVICEDATABASE_USE_SECURITY_TOKEN
300 // If service(s) have already been registered with same name, they must all come from
301 // same application. Fetch a service with given name and if such exists, check that its
302 // security ID equals to the security ID of the current registrar.
303 // One application may register multiple services with same name (different location),
304 // hence the keyword DISTINCT.
305 statement = "SELECT DISTINCT ServiceProperty.Value FROM Service, ServiceProperty "
306 "WHERE Service.ID = ServiceProperty.ServiceID "
307 "AND ServiceProperty.Key = ? "
308 "AND Service.Name = ?";
309 bindValues.clear();
310 bindValues.append(SECURITY_TOKEN_KEY);
311 bindValues.append(service.name);
312 if (!executeQuery(&query, statement, bindValues)) {
313 rollbackTransaction(&query);
314 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
315 qWarning() << "ServiceDatabase::registerService():-"
316 << qPrintable(m_lastError.text());
317 #endif
318 return false;
319 }
320 QString existingSecurityToken;
321 if (query.next()) {
322 existingSecurityToken = query.value(EBindIndex).toString();
323 }
324 if (!existingSecurityToken.isEmpty() && (existingSecurityToken != securityToken)) {
325 QString errorText("Access denied: \"%1\"");
326 m_lastError.setError(DBError::NoWritePermissions, errorText.arg(service.name));
327 rollbackTransaction(&query);
328 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
329 qWarning() << "ServiceDatabase::registerService():-"
330 << "Problem: Unable to register service,"
331 << "reason:" << qPrintable(m_lastError.text());
332 #endif
333 return false;
334 }
335 #endif // QT_SFW_SERVICEDATABASE_USE_SECURITY_TOKEN
336
337 // Checks done, create new rows into tables.
338 statement = QLatin1String("INSERT INTO Service(ID,Name,Location) VALUES(?,?,?)");
339
340 qsrand(QTime::currentTime().msec());
341 QString serviceID = QUuid::createUuid().toString();
342
343 bindValues.clear();
344 bindValues.append(serviceID);
345 bindValues.append(service.name);
346 bindValues.append(locationPrefix);
347
348 if (!executeQuery(&query, statement, bindValues)) {
349 rollbackTransaction(&query);
350 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
351 qWarning() << "ServiceDatabase::registerService():-"
352 << qPrintable(m_lastError.text());
353 #endif
354 return false;
355 }
356
357 statement = QLatin1String("INSERT INTO ServiceProperty(ServiceID,Key,Value) VALUES(?,?,?)");
358 bindValues.clear();
359 bindValues.append(serviceID);
360 bindValues.append(QLatin1String(SERVICE_DESCRIPTION_KEY));
361 if (service.description.isNull())
362 bindValues.append(QLatin1String("")); // This relies on !QString::isNull().
363 else
364 bindValues.append(service.description);
365
366 if (!executeQuery(&query, statement, bindValues)) {
367 rollbackTransaction(&query);
368 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
369 qWarning() << "ServiceDatabase::registerService():-"
370 << qPrintable(m_lastError.text());
371 #endif
372 return false;
373 }
374
375 #ifdef QT_SFW_SERVICEDATABASE_GENERATE
376 statement = "INSERT INTO ServiceProperty(ServiceId,Key,Value) VALUES(?,?,?)";
377 bindValues.clear();
378 bindValues.append(serviceID);
379 bindValues.append(SERVICE_INITIALIZED_KEY);
380 bindValues.append(QString("NO"));
381 if (!executeQuery(&query, statement, bindValues)) {
382 rollbackTransaction(&query);
383 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
384 qWarning() << "ServiceDatabase::registerService():-"
385 << qPrintable(m_lastError.text());
386 #endif
387 return false;
388 }
389 #endif
390
391 #ifdef QT_SFW_SERVICEDATABASE_USE_SECURITY_TOKEN
392 // Insert a security token for the particular service
393 statement = "INSERT INTO ServiceProperty(ServiceID,Key,Value) VALUES(?,?,?)";
394 bindValues.clear();
395 bindValues.append(serviceID);
396 bindValues.append(SECURITY_TOKEN_KEY);
397 bindValues.append(securityToken);
398
399 if (!executeQuery(&query, statement, bindValues)) {
400 rollbackTransaction(&query);
401 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
402 qWarning() << "ServiceDatabase::registerService():-"
403 << qPrintable(m_lastError.text());
404 #endif
405 return false;
406 }
407 #endif // QT_SFW_SERVICEDATABASE_USE_SECURITY_TOKEN
408
409 QList <QServiceInterfaceDescriptor> interfaces = service.interfaces;
410 QString interfaceID;;
411 foreach (const QServiceInterfaceDescriptor &serviceInterface, interfaces) {
412 interfaceID = getInterfaceID(&query, serviceInterface);
413 if (m_lastError.code() == DBError::NoError) {
414 QString errorText;
415 errorText = QLatin1String("Cannot register service \"%1\". \"%1\" is already registered "
416 "and implements interface \"%2\", Version \"%3.%4.\" \"%1\" must "
417 "first be deregistered for new registration to take place.");
418 m_lastError.setError(DBError::IfaceImplAlreadyRegistered,
419 errorText.arg(serviceInterface.serviceName())
420 .arg(serviceInterface.interfaceName())
421 .arg(serviceInterface.majorVersion())
422 .arg(serviceInterface.minorVersion()));
423
424 rollbackTransaction(&query);
425 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
426 qWarning() << "ServiceDatabase::registerService():-"
427 << "Problem:" << qPrintable(m_lastError.text());
428 #endif
429 return false;
430 } else if (m_lastError.code() == DBError::NotFound){
431 //No interface implementation already exists for the service
432 //so add it
433 if (!insertInterfaceData(&query, serviceInterface, serviceID)) {
434 rollbackTransaction(&query);
435 return false;
436 } else {
437 continue;
438 }
439 } else {
440 rollbackTransaction(&query);
441 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
442 qWarning() << "ServiceDatabase::registerService():-"
443 << "Unable to confirm if implementation version"
444 << (QString::number(serviceInterface.majorVersion()) + "."
445 + QString::number(serviceInterface.minorVersion())).toLatin1()
446 << "for interface" << serviceInterface.interfaceName()
447 << "is already registered for service "
448 << serviceInterface.serviceName()
449 << "\n" << m_lastError.text();
450 #endif
451 return false;
452 }
453 }
454
455 interfaces = service.latestInterfaces;
456 QServiceInterfaceDescriptor defaultInterface;
457 foreach (const QServiceInterfaceDescriptor &serviceInterface, interfaces) {
458 defaultInterface = interfaceDefault(serviceInterface.interfaceName(), NULL, true);
459 if (m_lastError.code() == DBError::NoError
460 || m_lastError.code() == DBError::ExternalIfaceIDFound) {
461 continue; //default already exists so don't do anything
462 } else if (m_lastError.code() == DBError::NotFound) {
463 //default does not already exist so create one
464 interfaceID = getInterfaceID(&query, serviceInterface);
465 if (m_lastError.code() != DBError::NoError) {
466 rollbackTransaction(&query);
467 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
468 qWarning() << "ServiceDatabase::registerService():-"
469 << "Unable to retrieve interfaceID for "
470 "interface" << serviceInterface.interfaceName()
471 << "\n" << m_lastError.text();
472 #endif
473 return false;
474 }
475
476 statement = QLatin1String("INSERT INTO Defaults(InterfaceName, InterfaceID) VALUES(?,?)");
477 bindValues.clear();
478 bindValues.append(serviceInterface.interfaceName());
479 bindValues.append(interfaceID);
480 if (!executeQuery(&query, statement, bindValues)) {
481 rollbackTransaction(&query);
482 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
483 qWarning() << "ServiceDatabase::registerService():-"
484 << qPrintable(m_lastError.text());
485 #endif
486 return false;
487 }
488 } else {
489 rollbackTransaction(&query);
490 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
491 qWarning() << "ServiceDatabase::registerService()"
492 << "Problem: Unable to confirm if interface"
493 << serviceInterface.interfaceName()
494 << "already has a default implementation";
495 #endif
496 return false;
497 }
498 }
499
500 if (!commitTransaction(&query)) {
501 rollbackTransaction(&query);
502 return false;
503 }
504 m_lastError.setError(DBError::NoError);
505 return true;
506 }
507
508 /*
509 Obtains an interface ID corresponding to a given interface \a descriptor
510
511 May set the following error codes:
512 DBError::NoError
513 DBError::NotFound
514 DBError::SqlError
515 DBError::DatabaseNotOpen
516 DBError::InvalidDatabaseConnection
517 */
518 QString ServiceDatabase::getInterfaceID(const QServiceInterfaceDescriptor &serviceInterface) {
519 QString interfaceID;
520 if (!checkConnection()) {
521 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
522 qWarning() << "ServiceDatabase::getInterfaceID():-"
523 << "Problem:" << qPrintable(m_lastError.text());
524 #endif
525 return interfaceID;
526 }
527
528 QSqlDatabase database = QSqlDatabase::database(m_connectionName);
529 QSqlQuery query(database);
530
531 return getInterfaceID(&query, serviceInterface);
532 }
533
534 /*
535 This function should only ever be called on a user scope database.
536 It returns a list of Interface Name and Interface ID pairs, where
537 the Interface ID refers to an external interface implementation
538 in the system scope database.
539
540 May set the last error to:
541 DBError::NoError
542 DBError::SqlError
543 DBError::DatabaseNotOpen
544 DBError::InvalidDatabaseConnection
545
546 Aside: There is only one query which implicitly gets
547 wrapped in it's own transaction.
548 */
549 QList<QPair<QString,QString> > ServiceDatabase::externalDefaultsInfo()
550 {
551 QList<QPair<QString,QString> > ret;
552 if (!checkConnection()) {
553 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
554 qWarning() << "ServiceDatabase::externalDefaultsInfo():-"
555 << "Problem:" << qPrintable(m_lastError.text());
556 #endif
557 return ret;
558 }
559
560 QSqlDatabase database = QSqlDatabase::database(m_connectionName);
561 QSqlQuery query(database);
562
563 //Prepare search query, bind criteria values and execute search
564 QString selectComponent = QLatin1String("SELECT InterfaceName, InterfaceID ");
565 QString fromComponent = QLatin1String("FROM Defaults ");
566 QString whereComponent = QLatin1String("WHERE InterfaceID NOT IN (SELECT Interface.ID FROM Interface) ");
567
568 //Aside: this individual query is implicitly wrapped in a transaction
569 if (!executeQuery(&query, selectComponent + fromComponent + whereComponent)) {
570 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
571 qWarning() << "ServiceDatabase::externalDefaultsInfo():-"
572 << "Problem:" << qPrintable(m_lastError.text());
573 #endif
574 return ret;
575 }
576
577 while (query.next()) {
578 ret.append(qMakePair(query.value(EBindIndex).toString(),
579 query.value(EBindIndex1).toString()));
580 }
581
582 m_lastError.setError(DBError::NoError);
583 return ret;
584 }
585
586 /*
587 Helper function that obtains an interfaceID for a given \a descriptor.
588
589 May set last error to one of the following error codes:
590 DBError::NoError
591 DBError::NotFound
592 DBError::SqlError
593
594 Aside: This function may be safely called standalone or within an explicit
595 transaction. If called standalone, it's single query is implicitly
596 wrapped in it's own transaction.
597 */
598 QString ServiceDatabase::getInterfaceID(QSqlQuery *query, const QServiceInterfaceDescriptor &serviceInterface)
599 {
600 QString statement = QLatin1String("SELECT Interface.ID "
601 "FROM Interface, Service "
602 "WHERE Service.ID = Interface.ServiceID "
603 "AND Service.Name = ? COLLATE NOCASE "
604 "AND Interface.Name = ? COLLATE NOCASE "
605 "AND Interface.VerMaj = ? AND Interface.VerMin = ?");
606 QList<QVariant> bindValues;
607 bindValues.append(serviceInterface.serviceName());
608 bindValues.append(serviceInterface.interfaceName());
609 bindValues.append(serviceInterface.majorVersion());
610 bindValues.append(serviceInterface.minorVersion());
611
612 if (!executeQuery(query, statement, bindValues)) {
613 return QString();
614 }
615
616 if (!query->next()) {
617 QString errorText(QLatin1String("No Interface Descriptor found with "
618 "Service name: %1 "
619 "Interface name: %2 "
620 "Version: %3.%4"));
621 m_lastError.setError(DBError::NotFound, errorText.arg(serviceInterface.serviceName())
622 .arg(serviceInterface.interfaceName())
623 .arg(serviceInterface.majorVersion())
624 .arg(serviceInterface.minorVersion()));
625 return QString();
626 }
627
628 m_lastError.setError(DBError::NoError);
629 return query->value(EBindIndex).toString();
630 }
631
632 /*
633 Helper functions that saves \a interface related data in the Interface table
634 The \a interface data is recorded as belonging to the service assocciated
635 with \a serviceID.
636
637 May set the last error to one of the following error codes:
638 DBError::NoError
639 DBError::SqlError
640
641 Aside: It is already assumed that a write transaction has been started by the
642 time this function is called; and this function will not rollback/commit
643 the transaction.
644 */
645 bool ServiceDatabase::insertInterfaceData(QSqlQuery *query,const QServiceInterfaceDescriptor &serviceInterface, const QString &serviceID)
646 {
647 QString statement = QLatin1String("INSERT INTO Interface(ID, ServiceID,Name,VerMaj, VerMin) "
648 "VALUES(?,?,?,?,?)");
649 QString interfaceID = QUuid::createUuid().toString();
650
651 QList<QVariant> bindValues;
652 bindValues.append(interfaceID);
653 bindValues.append(serviceID);
654 bindValues.append(serviceInterface.interfaceName());
655 bindValues.append(serviceInterface.majorVersion());
656 bindValues.append(serviceInterface.minorVersion());
657
658 if (!executeQuery(query, statement, bindValues)) {
659 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
660 qWarning() << "ServiceDatabase::insertInterfaceData():-"
661 << qPrintable(m_lastError.text());
662 #endif
663 return false;
664 }
665
666 statement = QLatin1String("INSERT INTO InterfaceProperty(InterfaceID, Key, Value) VALUES(?,?,?)");
667 QHash<QServiceInterfaceDescriptor::Attribute, QVariant>::const_iterator iter = serviceInterface.d->attributes.constBegin();
668 bool isValidInterfaceProperty;
669 QString capabilities;
670 QString interfaceDescription;
671 while (iter != serviceInterface.d->attributes.constEnd()) {
672 isValidInterfaceProperty = true;
673
674 bindValues.clear();
675 bindValues.append(interfaceID);
676 switch (iter.key()) {
677 case (QServiceInterfaceDescriptor::Capabilities):
678 bindValues.append(QLatin1String(INTERFACE_CAPABILITY_KEY));
679 capabilities = serviceInterface.attribute(QServiceInterfaceDescriptor::Capabilities).toStringList().join(QLatin1String(","));
680 if (capabilities.isNull())
681 capabilities = QLatin1String("");
682 bindValues.append(capabilities);
683 break;
684 case(QServiceInterfaceDescriptor::Location):
685 isValidInterfaceProperty = false;
686 break;
687 case(QServiceInterfaceDescriptor::ServiceDescription):
688 isValidInterfaceProperty = false;
689 break;
690 case(QServiceInterfaceDescriptor::InterfaceDescription):
691 bindValues.append(QLatin1String(INTERFACE_DESCRIPTION_KEY));
692 interfaceDescription = serviceInterface.attribute(QServiceInterfaceDescriptor::InterfaceDescription).toString();
693 if (interfaceDescription.isNull())
694 interfaceDescription = QLatin1String("");
695 bindValues.append(interfaceDescription);
696 break;
697 default:
698 isValidInterfaceProperty = false;
699 break;
700 }
701
702 if (isValidInterfaceProperty) {
703 if (!executeQuery(query, statement, bindValues)) {
704 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
705 qWarning() << "ServiceDatabase::insertInterfaceData():-"
706 << qPrintable(m_lastError.text());
707 #endif
708 return false;
709 }
710 }
711 ++iter;
712 }
713
714 // add custom attributes
715 QHash<QString, QString>::const_iterator customIter = serviceInterface.d->customAttributes.constBegin();
716 while (customIter!=serviceInterface.d->customAttributes.constEnd()) {
717 bindValues.clear();
718 bindValues.append(interfaceID);
719 // to avoid key clashes use separate c_ namespace ->is this sufficient?
720 bindValues.append(QVariant(QStringLiteral("c_") + customIter.key()));
721 bindValues.append(customIter.value());
722 if (!executeQuery(query, statement, bindValues)) {
723 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
724 qWarning() << "ServiceDatabase::insertInterfaceData(customProps):-"
725 << qPrintable(m_lastError.text());
726 #endif
727 return false;
728 }
729 ++customIter;
730 }
731 m_lastError.setError(DBError::NoError);
732
733 return true;
734 }
735
736 /*
737 Helper function that executes the sql query specified in \a statement.
738 It is assumed that the \a statement uses positional placeholders and
739 corresponding parameters are placed in the list of \a bindValues.
740
741 Aside: This function may be safely called standalone or within an explicit
742 transaction. If called standalone, it's single query is implicitly
743 wrapped in it's own transaction.
744
745 May set the last error to one of the following error codes:
746 DBError::NoError
747 DBError::SqlError
748 DBError::NoWritePermissions
749 DBError::InvalidDatabaseFile
750 */
751 bool ServiceDatabase::executeQuery(QSqlQuery *query, const QString &statement, const QList<QVariant> &bindValues)
752 {
753 Q_ASSERT(query != NULL);
754
755 bool success = false;
756 enum {Prepare =0 , Execute=1};
757 for (int stage=Prepare; stage <= Execute; ++stage) {
758 if ( stage == Prepare)
759 success = query->prepare(statement);
760 else // stage == Execute
761 success = query->exec();
762
763 if (!success) {
764 QString errorText;
765 errorText = QLatin1String("Problem: Could not %1 statement: %2"
766 "Reason: %3"
767 "Parameters: %4\n");
768 QString parameters;
769 if (bindValues.count() > 0) {
770 for (int i = 0; i < bindValues.count(); ++i) {
771 parameters.append(QStringLiteral("\n\t[") + QString::number(i) + QStringLiteral("]: ") + bindValues.at(i).toString());
772 }
773 } else {
774 parameters = QLatin1String("None");
775 }
776
777 DBError::ErrorCode errorType;
778 int result = query->lastError().number();
779 if (result == 26 || result == 11) {//SQLILTE_NOTADB || SQLITE_CORRUPT
780 qWarning() << "Service Framework:- Database file is corrupt or invalid:" << databasePath();
781 errorType = DBError::InvalidDatabaseFile;
782 }
783 else if ( result == 8) //SQLITE_READONLY
784 errorType = DBError::NoWritePermissions;
785 else
786 errorType = DBError::SqlError;
787
788 m_lastError.setError(errorType,
789 errorText
790 .arg(stage == Prepare ?QLatin1String("prepare"):QLatin1String("execute"))
791 .arg(statement)
792 .arg(query->lastError().text())
793 .arg(parameters));
794
795 query->finish();
796 query->clear();
797 return false;
798 }
799
800 if (stage == Prepare) {
801 foreach (const QVariant &bindValue, bindValues)
802 query->addBindValue(bindValue);
803 }
804 }
805
806 m_lastError.setError(DBError::NoError);
807 return true;
808 }
809
810 /*
811 Obtains a list of QServiceInterfaceDescriptors that match the constraints supplied
812 by \a filter.
813
814 May set last error to one of the following error codes:
815 DBError::NoError
816 DBError::SqlError
817 DBError::DatabaseNotOpen
818 DBError::InvalidDatabaseConnection
819 DBError::NoWritePermissions
820 DBError::InvalidDatabaseFile
821 */
822 QList<QServiceInterfaceDescriptor> ServiceDatabase::getInterfaces(const QServiceFilter &filter)
823 {
824 QList<QServiceInterfaceDescriptor> interfaces;
825 if (!checkConnection()) {
826 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
827 qWarning() << "ServiceDatabase::getInterfaces():-"
828 << "Problem:" << qPrintable(m_lastError.text());
829 #endif
830 return interfaces;
831 }
832
833 QSqlDatabase database = QSqlDatabase::database(m_connectionName);
834 QSqlQuery query(database);
835
836 //multiple read queries are performed so wrap them
837 //in a read only transaction
838 if (!beginTransaction(&query, Read)) {
839 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
840 qWarning() << "ServiceDatabase::getInterfaces():-"
841 << "Unable to begin transaction. "
842 << "Reason:" << qPrintable(m_lastError.text());
843 #endif
844 return interfaces;
845 }
846
847 //Prepare search query, bind criteria values
848 QString selectComponent = QLatin1String("SELECT Interface.Name, "
849 "Service.Name, Interface.VerMaj, "
850 "Interface.VerMin, "
851 "Service.Location, "
852 "Service.ID, "
853 "Interface.ID ");
854 QString fromComponent = QLatin1String("FROM Interface, Service ");
855 QString whereComponent = QLatin1String("WHERE Service.ID = Interface.ServiceID ");
856 QList<QVariant> bindValues;
857
858 if (filter.serviceName().isEmpty() && filter.interfaceName().isEmpty()) {
859 //do nothing, (don't add any extra constraints to the query
860 } else {
861
862 if (!filter.serviceName().isEmpty()) {
863 whereComponent.append(QLatin1String("AND Service.Name = ?")).append(QLatin1String(" COLLATE NOCASE "));
864 bindValues.append(filter.serviceName());
865 }
866 if (!filter.interfaceName().isEmpty()) {
867 whereComponent.append(QLatin1String("AND Interface.Name = ?")).append(QLatin1String(" COLLATE NOCASE "));
868 bindValues.append(filter.interfaceName());
869 if (filter.majorVersion() >=0 && filter.minorVersion() >=0) {
870 if (filter.versionMatchRule() == QServiceFilter::ExactVersionMatch) {
871 whereComponent.append(QLatin1String("AND Interface.VerMaj = ?")).append(QLatin1String(" AND Interface.VerMin = ? "));
872 bindValues.append(QString::number(filter.majorVersion()));
873 bindValues.append(QString::number(filter.minorVersion()));
874 }
875 else if (filter.versionMatchRule() == QServiceFilter::MinimumVersionMatch) {
876 whereComponent.append(QLatin1String("AND ((Interface.VerMaj > ?"))
877 .append(QLatin1String(") OR Interface.VerMaj = ?")).append(QLatin1String(" AND Interface.VerMin >= ?")).append(QLatin1String(") "));
878 bindValues.append(QString::number(filter.majorVersion()));
879 bindValues.append(QString::number(filter.majorVersion()));
880 bindValues.append(QString::number(filter.minorVersion()));
881 }
882 }
883 }
884 }
885
886 if (!executeQuery(&query, selectComponent + fromComponent + whereComponent, bindValues)) {
887 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
888 qWarning() << "ServiceDatabase::getInterfaces():-"
889 << "Problem:" << qPrintable(m_lastError.text());
890 #endif
891 rollbackTransaction(&query);
892 return interfaces;
893 }
894
895 QServiceInterfaceDescriptor serviceInterface;
896 serviceInterface.d = new QServiceInterfaceDescriptorPrivate;
897 QStringList capabilities;
898 QString serviceID;
899 QString interfaceID;
900 const QSet<QString> filterCaps = filter.capabilities().toSet();
901 QSet<QString> difference;
902
903 while (query.next()){
904 difference.clear();
905 serviceInterface.d->customAttributes.clear();
906 serviceInterface.d->attributes.clear();
907 serviceInterface.d->interfaceName = query.value(EBindIndex).toString();
908 serviceInterface.d->serviceName = query.value(EBindIndex1).toString();
909 serviceInterface.d->major = query.value(EBindIndex2).toInt();
910 serviceInterface.d->minor = query.value(EBindIndex3).toInt();
911
912 QString location = query.value(EBindIndex4).toString();
913 if (location.startsWith(QLatin1String(SERVICE_IPC_PREFIX))) {
914 serviceInterface.d->attributes[QServiceInterfaceDescriptor::ServiceType] = QService::InterProcess;
915 serviceInterface.d->attributes[QServiceInterfaceDescriptor::Location]
916 = location.remove(0,QString(QLatin1String(SERVICE_IPC_PREFIX)).size());
917 } else {
918 serviceInterface.d->attributes[QServiceInterfaceDescriptor::ServiceType] = QService::Plugin;
919 serviceInterface.d->attributes[QServiceInterfaceDescriptor::Location] = location;
920 }
921
922 serviceID = query.value(EBindIndex5).toString();
923 if (!populateServiceProperties(&serviceInterface, serviceID)) {
924 //populateServiceProperties should already give a warning message
925 //and set the last error
926 interfaces.clear();
927 rollbackTransaction(&query);
928 return interfaces;
929 }
930
931 interfaceID = query.value(EBindIndex6).toString();
932 if (!populateInterfaceProperties(&serviceInterface, interfaceID)) {
933 //populateInterfaceProperties should already give a warning message
934 //and set the last error
935 interfaces.clear();
936 rollbackTransaction(&query);
937 return interfaces;
938 }
939
940 const QSet<QString> ifaceCaps = serviceInterface.d->attributes.value(QServiceInterfaceDescriptor::Capabilities).toStringList().toSet();
941 difference = ((filter.capabilityMatchRule() == QServiceFilter::MatchMinimum) ? (filterCaps-ifaceCaps) : (ifaceCaps-filterCaps));
942 if (!difference.isEmpty())
943 continue;
944
945 //only return those interfaces that comply with set custom filters
946 if (filter.customAttributes().size() > 0) {
947 QSet<QString> keyDiff = filter.customAttributes().toSet();
948 keyDiff.subtract(serviceInterface.d->customAttributes.uniqueKeys().toSet());
949 if (keyDiff.isEmpty()) { //target descriptor has same custom keys as filter
950 bool isMatch = true;
951 const QStringList keys = filter.customAttributes();
952 for (int i = 0; i<keys.count(); i++) {
953 if (serviceInterface.d->customAttributes.value(keys[i]) !=
954 filter.customAttribute(keys[i])) {
955 isMatch = false;
956 break;
957 }
958 }
959 if (isMatch)
960 interfaces.append(serviceInterface);
961 }
962 } else { //no custom keys -> SQL statement ensures proper selection already
963 interfaces.append(serviceInterface);
964 }
965 }
966
967 rollbackTransaction(&query);//read-only operation so just rollback
968 m_lastError.setError(DBError::NoError);
969 return interfaces;
970 }
971
972 /*
973 Obtains a QServiceInterfaceDescriptor that
974 corresponds to a given \a interfaceID
975
976 May set last error to one of the following error codes:
977 DBError::NoError
978 DBError::NotFound
979 DBError::SqlError
980 DBError::DatabaseNotOpen
981 DBError::InvalidDatabaseConnection
982 DBError::NoWritePermissions
983 DBError::InvalidDatabaseFile
984 */
985 QServiceInterfaceDescriptor ServiceDatabase::getInterface(const QString &interfaceID)
986 {
987 QServiceInterfaceDescriptor serviceInterface;
988 if (!checkConnection()) {
989 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
990 qWarning() << "ServiceDatabase::getInterface():-"
991 << "Problem:" << qPrintable(m_lastError.text());
992 #endif
993 return serviceInterface;
994 }
995
996 QSqlDatabase database = QSqlDatabase::database(m_connectionName);
997 QSqlQuery query(database);
998
999 if (!beginTransaction(&query, Read)) {
1000 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
1001 qWarning() << "ServiceDatabase::getInterface():-"
1002 << "Unable to begin transaction. "
1003 << "Reason:" << qPrintable(m_lastError.text());
1004 #endif
1005 return serviceInterface;
1006 }
1007
1008 QString selectComponent = QLatin1String("SELECT Interface.Name, "
1009 "Service.Name, Interface.VerMaj, "
1010 "Interface.VerMin, "
1011 "Service.Location, "
1012 "Service.ID ");
1013 QString fromComponent = QLatin1String("FROM Interface, Service ");
1014 QString whereComponent = QLatin1String("WHERE Service.ID = Interface.ServiceID "
1015 "AND Interface.ID = ? ");
1016 QList<QVariant> bindValues;
1017 bindValues.append(interfaceID);
1018
1019 if (!executeQuery(&query, selectComponent + fromComponent + whereComponent, bindValues)) {
1020 rollbackTransaction(&query);
1021 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
1022 qWarning() << "ServiceDatabase::getInterfaces():-"
1023 << "Problem:" << qPrintable(m_lastError.text());
1024 #endif
1025 return serviceInterface;
1026 }
1027
1028 if (!query.next()) {
1029 rollbackTransaction(&query);
1030 QString errorText(QLatin1String("Interface implementation not found for Interface ID: %1"));
1031 m_lastError.setError(DBError::NotFound, errorText.arg(interfaceID));
1032 return serviceInterface;
1033 }
1034
1035 serviceInterface.d = new QServiceInterfaceDescriptorPrivate;
1036 serviceInterface.d->interfaceName =query.value(EBindIndex).toString();
1037 serviceInterface.d->serviceName = query.value(EBindIndex1).toString();
1038 serviceInterface.d->major = query.value(EBindIndex2).toInt();
1039 serviceInterface.d->minor = query.value(EBindIndex3).toInt();
1040
1041 QString location = query.value(EBindIndex4).toString();
1042 if (location.startsWith(QLatin1String(SERVICE_IPC_PREFIX))) {
1043 serviceInterface.d->attributes[QServiceInterfaceDescriptor::ServiceType] = QService::InterProcess;
1044 serviceInterface.d->attributes[QServiceInterfaceDescriptor::Location]
1045 = location.remove(0,QString(QLatin1String(SERVICE_IPC_PREFIX)).size());
1046 } else {
1047 serviceInterface.d->attributes[QServiceInterfaceDescriptor::ServiceType] = QService::Plugin;
1048 serviceInterface.d->attributes[QServiceInterfaceDescriptor::Location] = location;
1049 }
1050
1051 QString serviceID = query.value(EBindIndex5).toString();
1052 if (!populateServiceProperties(&serviceInterface, serviceID)) {
1053 //populateServiceProperties should already give a warning message
1054 //and set the last error
1055 rollbackTransaction(&query);
1056 return QServiceInterfaceDescriptor();
1057 }
1058
1059 if (!populateInterfaceProperties(&serviceInterface, interfaceID)) {
1060 //populateInterfaceProperties should already give a warning message
1061 //and set the last error
1062 rollbackTransaction(&query);
1063 return QServiceInterfaceDescriptor();
1064 }
1065
1066 rollbackTransaction(&query);//read only operation so just rollback
1067 m_lastError.setError(DBError::NoError);
1068 return serviceInterface;
1069 }
1070
1071 /*
1072 Obtains a list of services names. If \a interfaceName is empty,
1073 then all service names are returned. If \a interfaceName specifies
1074 an interface then the names of all services implementing that interface
1075 are returned
1076
1077 May set last error to one of the following error codes:
1078 DBError::NoError
1079 DBError::SqlError
1080 DBError::DatabaseNotOpen
1081 DBError::InvalidDatabaseConnection
1082 DBError::NoWritePermissions
1083 DBError::InvalidDatabaseFile
1084
1085 Aside: There is only one query which implicitly gets
1086 wrapped in it's own transaction.
1087 */
1088 QStringList ServiceDatabase::getServiceNames(const QString &interfaceName)
1089 {
1090 QStringList services;
1091 if (!checkConnection()) {
1092 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
1093 qWarning() << "ServiceDatabase::getServiceNames():-"
1094 << "Problem:" << qPrintable(m_lastError.text());
1095 #endif
1096 return services;
1097 }
1098 QSqlDatabase database = QSqlDatabase::database(m_connectionName);
1099 QSqlQuery query(database);
1100 QString selectComponent(QLatin1String("SELECT DISTINCT Service.Name COLLATE NOCASE "));
1101 QString fromComponent;
1102 QString whereComponent;
1103 QList<QVariant> bindValues;
1104 if (interfaceName.isEmpty()) {
1105 fromComponent = QLatin1String("FROM Service ");
1106 } else {
1107 fromComponent = QLatin1String("FROM Interface,Service ");
1108 whereComponent = QLatin1String("WHERE Service.ID = Interface.ServiceID AND Interface.Name = ? COLLATE NOCASE ");
1109 bindValues.append(interfaceName);
1110 }
1111
1112 if (!executeQuery(&query, selectComponent + fromComponent + whereComponent, bindValues)) {
1113 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
1114 qWarning() << "ServiceDatabase::getServiceNames():-"
1115 << qPrintable(m_lastError.text());
1116 #endif
1117 return services;
1118 }
1119
1120 while ( query.next()) {
1121 services.append(query.value(EBindIndex).toString());
1122 }
1123 query.finish();
1124 query.clear();
1125 m_lastError.setError(DBError::NoError);
1126 return services;
1127 }
1128
1129 /*
1130 Returns a descriptor for the default interface implementation of
1131 \a interfaceName.
1132
1133 For user scope databases only, \a defaultInterfaceID is set if the default
1134 in the user scope database refers to a interface implementation in the
1135 system scope database. In this case the descriptor will be invalid and
1136 the \a defaultInterfaceID must be used to query the system scope database,
1137 The last error set to DBError::ExternalIfaceIDFound
1138
1139 If this function is called within a transaction, \a inTransaction
1140 must be set to true. If \a inTransaction is false, this fuction
1141 will begin and end its own transaction.
1142
1143 The last error may be set to one of the following error codes:
1144 DBError::NoError
1145 DBError::ExternalIfaceIDFound
1146 DBError::SqlError
1147 DBError::DatabaseNotOpen
1148 DBError::InvalidDatabaseConnection
1149 DBError::NoWritePermissions
1150 DBError::InvalidDatabaseFile
1151 */
1152 QServiceInterfaceDescriptor ServiceDatabase::interfaceDefault(const QString &interfaceName, QString *defaultInterfaceID,
1153 bool inTransaction)
1154 {
1155 QServiceInterfaceDescriptor serviceInterface;
1156 if (!checkConnection())
1157 {
1158 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
1159 qWarning() << "ServiceDatabase::interfaceDefault():-"
1160 << "Problem:" << qPrintable(m_lastError.text());
1161 #endif
1162 return serviceInterface;
1163 }
1164
1165 QSqlDatabase database = QSqlDatabase::database(m_connectionName);
1166 QSqlQuery query(database);
1167
1168 if (!inTransaction && !beginTransaction(&query, Read)) {
1169 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
1170 qWarning() << "ServiceDatabase::interfaceDefault(QString, QString):-"
1171 << "Unable to begin transaction. "
1172 << "Reason:" << qPrintable(m_lastError.text());
1173 #endif
1174 return serviceInterface;
1175 }
1176
1177 QString statement(QLatin1String("SELECT InterfaceID FROM Defaults WHERE InterfaceName = ? COLLATE NOCASE"));
1178 QList<QVariant> bindValues;
1179 bindValues.append(interfaceName);
1180 if (!executeQuery(&query, statement, bindValues)) {
1181 if (!inTransaction)
1182 rollbackTransaction(&query);
1183 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
1184 qWarning() << "ServiceDatabase::interfaceDefault():-"
1185 << qPrintable(m_lastError.text());
1186 #endif
1187 return serviceInterface;
1188 }
1189
1190 QString interfaceID;
1191 if (!query.next())
1192 {
1193 if (!inTransaction)
1194 rollbackTransaction(&query);
1195 QString errorText(QLatin1String("No default service found for interface: \"%1\""));
1196 m_lastError.setError(DBError::NotFound, errorText.arg(interfaceName));
1197 return serviceInterface;
1198 }
1199 else
1200 interfaceID = query.value(EBindIndex).toString();
1201 Q_ASSERT(!interfaceID.isEmpty());
1202
1203 statement = QLatin1String("SELECT Interface.Name, "
1204 "Service.Name, Interface.VerMaj, "
1205 "Interface.VerMin, "
1206 "Service.Location, "
1207 "Service.ID "
1208 "FROM Service, Interface "
1209 "WHERE Service.ID = Interface.ServiceID AND Interface.ID = ?");
1210 bindValues.clear();
1211 bindValues.append(interfaceID);
1212 if (!executeQuery(&query, statement, bindValues))
1213 {
1214 if (!inTransaction)
1215 rollbackTransaction(&query);
1216 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
1217 qWarning() << "ServiceDatabase::interfaceDefault():-"
1218 << qPrintable(m_lastError.text());
1219 #endif
1220 return serviceInterface;
1221 }
1222
1223 if (!query.next()) {
1224 if (!inTransaction)
1225 rollbackTransaction(&query);
1226 if (defaultInterfaceID != NULL )
1227 *defaultInterfaceID = interfaceID;
1228 m_lastError.setError(DBError::ExternalIfaceIDFound);
1229 return serviceInterface;
1230 }
1231
1232 serviceInterface.d = new QServiceInterfaceDescriptorPrivate;
1233 serviceInterface.d->interfaceName =query.value(EBindIndex).toString();
1234 serviceInterface.d->serviceName = query.value(EBindIndex1).toString();
1235 serviceInterface.d->major = query.value(EBindIndex2).toInt();
1236 serviceInterface.d->minor = query.value(EBindIndex3).toInt();
1237
1238 QString location = query.value(EBindIndex4).toString();
1239 if (location.startsWith(QLatin1String(SERVICE_IPC_PREFIX))) {
1240 serviceInterface.d->attributes[QServiceInterfaceDescriptor::ServiceType] = QService::InterProcess;
1241 serviceInterface.d->attributes[QServiceInterfaceDescriptor::Location]
1242 = location.remove(0,QString(QLatin1String(SERVICE_IPC_PREFIX)).size());
1243 } else {
1244 serviceInterface.d->attributes[QServiceInterfaceDescriptor::ServiceType] = QService::Plugin;
1245 serviceInterface.d->attributes[QServiceInterfaceDescriptor::Location] = location;
1246 }
1247
1248 QString serviceID = query.value(EBindIndex5).toString();
1249 if (!populateServiceProperties(&serviceInterface, serviceID)) {
1250 //populateServiceProperties should already give a warning
1251 //and set the last error
1252 if (!inTransaction)
1253 rollbackTransaction(&query);
1254 return QServiceInterfaceDescriptor();
1255 }
1256
1257 if (!populateInterfaceProperties(&serviceInterface, interfaceID)) {
1258 //populateInterfaceProperties should already give a warning
1259 //and set the last error
1260 if (!inTransaction)
1261 rollbackTransaction(&query);
1262 return QServiceInterfaceDescriptor();
1263 }
1264
1265 if (!inTransaction)
1266 rollbackTransaction(&query); //Read only operation so just rollback
1267 m_lastError.setError(DBError::NoError);
1268 return serviceInterface;
1269 }
1270
1271 /*
1272 Sets a particular service's \a interface implementation as a the default
1273 implementation to look up when using the interface's name in
1274 interfaceDefault().
1275
1276 For a user scope database an \a externalInterfaceID can be provided
1277 so that the Defaults table will contain a "link" to an interface
1278 implmentation provided in the system scope database.
1279
1280 May set the last error to one of the following error codes:
1281 DBError::NoError
1282 DBerror::NotFound
1283 DBError::SqlError
1284 DBError::DatabaseNotOpen
1285 DBError::InvalidDatabaseConnection
1286 DBError::NoWritePermissions
1287 DBError::InvalidDatabaseFile
1288 */
1289 bool ServiceDatabase::setInterfaceDefault(const QServiceInterfaceDescriptor &serviceInterface, const QString &externalInterfaceID)
1290 {
1291 if (!checkConnection()) {
1292 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
1293 qWarning() << "ServiceDatabase::setInterfaceDefault(QServiceInterfaceDescriptor):-"
1294 << "Problem:" << qPrintable(m_lastError.text());
1295 #endif
1296 return false;
1297 }
1298
1299 QSqlDatabase database = QSqlDatabase::database(m_connectionName);
1300 QSqlQuery query(database);
1301
1302 //Begin Transaction
1303 if (!beginTransaction(&query, Write)) {
1304 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
1305 qWarning() << "ServiceDatabase::setInterfaceDefault(QServiceInterfaceDescriptor):-"
1306 << "Problem: Unable to begin transaction."
1307 << "Reason:" << qPrintable(m_lastError.text());
1308 #endif
1309 return false;
1310 }
1311
1312 QString statement;
1313 QList<QVariant> bindValues;
1314 QString interfaceID = externalInterfaceID;
1315 if (interfaceID.isEmpty()) {
1316 statement = QLatin1String("SELECT Interface.ID from Interface, Service "
1317 "WHERE Service.ID = Interface.ServiceID "
1318 "AND Service.Name = ? COLLATE NOCASE "
1319 "AND Interface.Name = ? COLLATE NOCASE "
1320 "AND Interface.VerMaj = ? "
1321 "AND Interface.VerMin = ? ");
1322 bindValues.append(serviceInterface.serviceName());
1323 bindValues.append(serviceInterface.interfaceName());
1324 bindValues.append(serviceInterface.majorVersion());
1325 bindValues.append(serviceInterface.minorVersion());
1326
1327 if (!executeQuery(&query, statement, bindValues)) {
1328 rollbackTransaction(&query);
1329 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
1330 qWarning() << "ServiceDatabase::setInterfaceDefault(QServiceInterfaceDescriptor):-"
1331 << qPrintable(m_lastError.text());
1332 #endif
1333 return false;
1334 }
1335
1336 if (!query.next()) {
1337 QString errorText;
1338 errorText = QLatin1String("No implementation for interface: %1, Version: %2.%3 found "
1339 "for service: %4");
1340 m_lastError.setNotFoundError(errorText.arg(serviceInterface.interfaceName())
1341 .arg(serviceInterface.majorVersion())
1342 .arg(serviceInterface.minorVersion())
1343 .arg(serviceInterface.serviceName()));
1344
1345 rollbackTransaction(&query);
1346 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
1347 qWarning() << "ServiceDatbase::setInterfaceDefault(QServiceInterfaceDescriptor):-"
1348 << "Problem: Unable to set default service. "
1349 << "Reason:" << qPrintable(m_lastError.text());
1350 #endif
1351 return false;
1352 }
1353
1354 interfaceID = query.value(EBindIndex).toString();
1355 Q_ASSERT(!interfaceID.isEmpty());
1356 }
1357
1358 statement = QLatin1String("SELECT InterfaceName FROM Defaults WHERE InterfaceName = ? COLLATE NOCASE");
1359 bindValues.clear();
1360 bindValues.append(serviceInterface.interfaceName());
1361 if (!executeQuery(&query, statement, bindValues)) {
1362 rollbackTransaction(&query);
1363 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
1364 qWarning() << "ServiceDatabase::setInterfaceDefault(QServiceInterfaceDescriptor):-"
1365 << qPrintable(m_lastError.text());
1366 #endif
1367 return false;
1368 }
1369
1370 if (query.next()) {
1371 statement = QLatin1String("UPDATE Defaults "
1372 "SET InterfaceID = ? "
1373 "WHERE InterfaceName = ? COLLATE NOCASE");
1374 bindValues.clear();
1375 bindValues.append(interfaceID);
1376 bindValues.append(serviceInterface.interfaceName());
1377
1378 if (!executeQuery(&query, statement, bindValues)) {
1379 rollbackTransaction(&query);
1380 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
1381 qWarning() << "ServiceDatabase::setInterfaceDefault(QServiceInterfaceDescriptor):-"
1382 << qPrintable(m_lastError.text());
1383 #endif
1384 return false;
1385 }
1386 } else {
1387 statement = QLatin1String("INSERT INTO Defaults(InterfaceName,InterfaceID) VALUES(?,?)");
1388 bindValues.clear();
1389 bindValues.append(serviceInterface.interfaceName());
1390 bindValues.append(interfaceID);
1391
1392 if (!executeQuery(&query, statement, bindValues)) {
1393 rollbackTransaction(&query);
1394 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
1395 qWarning() << "ServiceDatabase::setInterfaceDefault(QServiceInterfaceDescriptor):-"
1396 << qPrintable(m_lastError.text());
1397 #endif
1398 return false;
1399 }
1400 }
1401
1402 //End Transaction
1403 if (!commitTransaction(&query)) {
1404 rollbackTransaction(&query);
1405 return false;
1406 }
1407 m_lastError.setError(DBError::NoError);
1408 return true;
1409 }
1410
1411 /*
1412 Removes the service with name \a serviceName.
1413 If the service provides a default interface implementation, then
1414 another service implementing the highest interface implementation
1415 version becomes the new default(if any). If more than one service
1416 provides same the highest version number, an arbitrary choice is made
1417 between them.
1418
1419 May set the last error to the folowing error codes:
1420 DBError::NoError
1421 DBError::NotFound
1422 DBError::SqlError
1423 DBError::DatabaseNotOpen
1424 DBError::InvalidDatabaseConnection
1425 DBError::NoWritePermissions
1426 DBError::InvalidDatabaseFile
1427 */
1428 bool ServiceDatabase::unregisterService(const QString &serviceName, const QString &securityToken)
1429 {
1430 #ifndef QT_SFW_SERVICEDATABASE_USE_SECURITY_TOKEN
1431 Q_UNUSED(securityToken);
1432 #else
1433 if (securityToken.isEmpty()) {
1434 QString errorText(QLatin1String("Access denied, no security token provided (for unregistering service: \"%1\")"));
1435 m_lastError.setError(DBError::NoWritePermissions, errorText.arg(serviceName));
1436 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
1437 qWarning() << "ServiceDatabase::unregisterService():-"
1438 << "Problem: Unable to unregister service. "
1439 << "Reason:" << qPrintable(m_lastError.text());
1440 #endif
1441 return false;
1442 }
1443 #endif
1444
1445
1446 if (!checkConnection()) {
1447 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
1448 qWarning() << "ServiceDatabase::unregisterService():-"
1449 << "Problem:" << qPrintable(m_lastError.text());
1450 #endif
1451 return false;
1452 }
1453
1454 QSqlDatabase database = QSqlDatabase::database(m_connectionName);
1455 QSqlQuery query(database);
1456
1457 if (!beginTransaction(&query, Write)) {
1458 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
1459 qWarning() << "ServiceDatabase::unregisterService():-"
1460 << "Problem: Unable to begin transaction. "
1461 << "Reason:" << qPrintable(m_lastError.text());
1462 #endif
1463 return false;
1464 }
1465
1466 QString statement(QLatin1String("SELECT Service.ID from Service WHERE Service.Name = ? COLLATE NOCASE"));
1467 QList<QVariant> bindValues;
1468 bindValues.append(serviceName);
1469 if (!executeQuery(&query, statement, bindValues)) {
1470 rollbackTransaction(&query);
1471 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
1472 qWarning() << "ServiceDatabase::unregisterService():-"
1473 << qPrintable(m_lastError.text());
1474 #endif
1475 return false;
1476 }
1477
1478 QStringList serviceIDs;
1479 while (query.next()) {
1480 serviceIDs << query.value(EBindIndex).toString();
1481 }
1482
1483 #ifdef QT_SFW_SERVICEDATABASE_USE_SECURITY_TOKEN
1484 // Only the application that registered the service is allowed to unregister that
1485 // service. Fetch a security ID of a service (with given name) and verify that it matches
1486 // with current apps security id. Only one application is allowed to register services with
1487 // same name, hence a distinct (just any of the) security token will do because they are identical.
1488 if (!serviceIDs.isEmpty()) {
1489 statement = QLatin1String("SELECT DISTINCT Value FROM ServiceProperty WHERE ServiceID = ? AND Key = ?");
1490 bindValues.clear();
1491 bindValues.append(serviceIDs.first());
1492 bindValues.append(SECURITY_TOKEN_KEY);
1493
1494 if (!executeQuery(&query, statement, bindValues)) {
1495 rollbackTransaction(&query);
1496 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
1497 qWarning() << "ServiceDatabase::unregisterService():-"
1498 << qPrintable(m_lastError.text());
1499 #endif
1500 return false;
1501 }
1502 QString existingSecurityToken;
1503 if (query.next()) {
1504 existingSecurityToken = query.value(EBindIndex).toString();
1505 }
1506 if (existingSecurityToken != securityToken) {
1507 QString errorText(QLatin1String("Access denied: \"%1\""));
1508 m_lastError.setError(DBError::NoWritePermissions, errorText.arg(serviceName));
1509 rollbackTransaction(&query);
1510 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
1511 qWarning() << "ServiceDatabase::unregisterService():-"
1512 << "Problem: Unable to unregister service"
1513 << "Reason:" << qPrintable(m_lastError.text());
1514 #endif
1515 return false;
1516 }
1517 }
1518 #endif // QT_SFW_SERVICEDATABASE_USE_SECURITY_TOKEN
1519
1520 statement = QLatin1String("SELECT Interface.ID from Interface, Service "
1521 "WHERE Interface.ServiceID = Service.ID "
1522 "AND Service.Name =? COLLATE NOCASE");
1523 bindValues.clear();
1524 bindValues.append(serviceName);
1525 if (!executeQuery(&query, statement, bindValues)) {
1526 rollbackTransaction(&query);
1527 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
1528 qWarning() << "ServiceDatabase::unregisterService():-"
1529 << qPrintable(m_lastError.text());
1530 #endif
1531 return false;
1532 }
1533
1534 QStringList interfaceIDs;
1535 while (query.next()) {
1536 interfaceIDs << query.value(EBindIndex).toString();
1537 }
1538
1539 if (serviceIDs.count() == 0) {
1540 QString errorText(QLatin1String("Service not found: \"%1\""));
1541 m_lastError.setError(DBError::NotFound, errorText.arg(serviceName));
1542 rollbackTransaction(&query);
1543 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
1544 qWarning() << "ServiceDatabase::unregisterService():-"
1545 << "Problem: Unable to unregister service"
1546 << "Reason:" << qPrintable(m_lastError.text());
1547 #endif
1548 return false;
1549 }
1550
1551 statement = QLatin1String("SELECT Defaults.InterfaceName "
1552 "FROM Defaults, Interface, Service "
1553 "WHERE Defaults.InterfaceID = Interface.ID "
1554 "AND Interface.ServiceID = Service.ID "
1555 "AND Service.Name = ? COLLATE NOCASE");
1556 bindValues.clear();
1557 bindValues.append(serviceName);
1558 if (!executeQuery(&query, statement, bindValues)) {
1559 rollbackTransaction(&query);
1560 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
1561 qWarning() << "ServiceDatabase:unregisterService():-"
1562 << qPrintable(m_lastError.text());
1563 #endif
1564 return false;
1565 }
1566
1567 QStringList serviceDefaultInterfaces;
1568 while (query.next()) {
1569 serviceDefaultInterfaces << query.value(EBindIndex).toString();
1570 }
1571
1572
1573 statement = QLatin1String("DELETE FROM Service WHERE Service.Name = ? COLLATE NOCASE");
1574 bindValues.clear();
1575 bindValues.append(serviceName);
1576 if (!executeQuery(&query, statement, bindValues)) {
1577 rollbackTransaction(&query);
1578 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
1579 qWarning() << "ServiceDatabase::unregisterService():-"
1580 << qPrintable(m_lastError.text());
1581 #endif
1582 return false;
1583 }
1584
1585 statement = QLatin1String("DELETE FROM Interface WHERE Interface.ServiceID = ?");
1586 foreach (const QString &serviceID, serviceIDs) {
1587 bindValues.clear();
1588 bindValues.append(serviceID);
1589 if (!executeQuery(&query, statement, bindValues)) {
1590 rollbackTransaction(&query);
1591 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
1592 qWarning() << "ServiceDatabase::unregisterService():-"
1593 << qPrintable(m_lastError.text());
1594 #endif
1595 return false;
1596 }
1597 }
1598
1599 statement = QLatin1String("DELETE FROM ServiceProperty WHERE ServiceID = ?");
1600
1601 foreach (const QString &serviceID, serviceIDs) {
1602 bindValues.clear();
1603 bindValues.append(serviceID);
1604 if (!executeQuery(&query, statement, bindValues)) {
1605 rollbackTransaction(&query);
1606 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
1607 qWarning() << "ServiceDatabase::unregisterService():-"
1608 << qPrintable(m_lastError.text());
1609 #endif
1610 return false;
1611 }
1612 }
1613
1614 statement = QLatin1String("DELETE FROM InterfaceProperty WHERE InterfaceID = ?");
1615 foreach (const QString &interfaceID, interfaceIDs) {
1616 bindValues.clear();
1617 bindValues.append(interfaceID);
1618 if (!executeQuery(&query, statement, bindValues)) {
1619 rollbackTransaction(&query);
1620 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
1621 qWarning() << "ServiceDatabase::unregisterService():-"
1622 << qPrintable(m_lastError.text());
1623 #endif
1624 return false;
1625 }
1626 }
1627
1628 foreach (const QString &interfaceName, serviceDefaultInterfaces) {
1629 statement = QLatin1String("SELECT ID FROM Interface WHERE Interface.Name = ? COLLATE NOCASE "
1630 "ORDER BY Interface.VerMaj DESC, Interface.VerMin DESC");
1631 bindValues.clear();
1632 bindValues.append(interfaceName);
1633 if (!executeQuery(&query, statement, bindValues)) {
1634 rollbackTransaction(&query);
1635 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
1636 qWarning() << "ServiceDatabase::unregisterService():-"
1637 << qPrintable(m_lastError.text());
1638 #endif
1639 return false;
1640 }
1641
1642 if (query.next()) {
1643 QString newDefaultID = query.value(EBindIndex).toString();
1644 statement = QLatin1String("UPDATE Defaults SET InterfaceID = ? WHERE InterfaceName = ? COLLATE NOCASE ");
1645 bindValues.clear();
1646 bindValues.append(newDefaultID);
1647 bindValues.append(interfaceName);
1648 if (!executeQuery(&query, statement, bindValues)) {
1649 rollbackTransaction(&query);
1650 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
1651 qWarning() << "ServiceDatabase::unregisterService():-"
1652 << qPrintable(m_lastError.text());
1653 #endif
1654 return false;
1655 }
1656 } else {
1657 statement = QLatin1String("DELETE FROM Defaults WHERE InterfaceName = ? COLLATE NOCASE ");
1658 bindValues.clear();
1659 bindValues.append(interfaceName);
1660 if (!executeQuery(&query, statement, bindValues)) {
1661 rollbackTransaction(&query);
1662 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
1663 qWarning() << "ServiceDatabase::unregisterService():-"
1664 << qPrintable(m_lastError.text());
1665 #endif
1666 return false;
1667 }
1668 }
1669 }
1670
1671 //databaseCommit
1672 if (!commitTransaction(&query)) {
1673 rollbackTransaction(&query);
1674 return false;
1675 }
1676 m_lastError.setError(DBError::NoError);
1677 return true;
1678 }
1679
1680 /*
1681 Registers the service initialization into the database.
1682 */
1683 bool ServiceDatabase::serviceInitialized(const QString &serviceName, const QString &securityToken)
1684 {
1685 #ifndef QT_SFW_SERVICEDATABASE_USE_SECURITY_TOKEN
1686 Q_UNUSED(securityToken);
1687 #endif
1688
1689 if (!checkConnection()) {
1690 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
1691 qWarning() << "ServiceDatabase::unregisterService():-"
1692 << "Problem:" << qPrintable(m_lastError.text());
1693 #endif
1694 return false;
1695 }
1696
1697 QSqlDatabase database = QSqlDatabase::database(m_connectionName);
1698 QSqlQuery query(database);
1699
1700 if (!beginTransaction(&query, Write)) {
1701 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
1702 qWarning() << "ServiceDatabase::serviceInitialized():-"
1703 << "Problem: Unable to begin transaction"
1704 << "\nReason:" << qPrintable(m_lastError.text());
1705 #endif
1706 return false;
1707 }
1708
1709 QString statement(QLatin1String("SELECT Service.ID from Service WHERE Service.Name = ? COLLATE NOCASE"));
1710 QList<QVariant> bindValues;
1711 bindValues.append(serviceName);
1712 if (!executeQuery(&query, statement, bindValues)) {
1713 rollbackTransaction(&query);
1714 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
1715 qWarning() << "ServiceDatabase::serviceInitialized():-"
1716 << qPrintable(m_lastError.text());
1717 #endif
1718 return false;
1719 }
1720
1721 QStringList serviceIDs;
1722 while (query.next()) {
1723 serviceIDs << query.value(EBindIndex).toString();
1724 }
1725
1726
1727 #ifdef QT_SFW_SERVICEDATABASE_USE_SECURITY_TOKEN
1728 statement = QLatin1String("SELECT Value FROM ServiceProperty WHERE ServiceID = ? AND Key = ?");
1729 bindValues.clear();
1730 bindValues.append(serviceName);
1731 bindValues.append(SECURITY_TOKEN_KEY);
1732 if (!executeQuery(&query, statement, bindValues)) {
1733 rollbackTransaction(&query);
1734 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
1735 qWarning() << "ServiceDatabase::unregisterService():-"
1736 << qPrintable(m_lastError.text());
1737 #endif
1738 return false;
1739 }
1740
1741 QStringList securityTokens;
1742 while (query.next()) {
1743 securityTokens << query.value(EBindIndex).toString();
1744 }
1745
1746 if (!securityTokens.isEmpty() && (securityTokens.first() != securityToken)) {
1747 QString errorText(QLatin1String("Access denied: \"%1\""));
1748 m_lastError.setError(DBError::NoWritePermissions, errorText.arg(serviceName));
1749 rollbackTransaction(&query);
1750 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
1751 qWarning() << "ServiceDatabase::serviceInitialized():-"
1752 << "Problem: Unable to update service initialization"
1753 << "\nReason:" << qPrintable(m_lastError.text());
1754 #endif
1755 }
1756 #endif
1757
1758 statement = QLatin1String("DELETE FROM ServiceProperty WHERE ServiceID = ? AND Key = ?");
1759 foreach (const QString &serviceID, serviceIDs) {
1760 bindValues.clear();
1761 bindValues.append(serviceID);
1762 bindValues.append(QLatin1String(SERVICE_INITIALIZED_KEY));
1763 if (!executeQuery(&query, statement, bindValues)) {
1764 rollbackTransaction(&query);
1765 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
1766 qWarning() << "ServiceDatabase::serviceInitialized():-"
1767 << qPrintable(m_lastError.text());
1768 #endif
1769 return false;
1770 }
1771 }
1772
1773 //databaseCommit
1774 if (!commitTransaction(&query)) {
1775 rollbackTransaction(&query);
1776 return false;
1777 }
1778 m_lastError.setError(DBError::NoError);
1779 return true;
1780 }
1781
1782 /*
1783 Closes the database
1784
1785 May set the following error codes:
1786 DBError::NoError
1787 DBError::InvalidDatabaseConnection
1788 */
1789 bool ServiceDatabase::close()
1790 {
1791 if (m_isDatabaseOpen) {
1792 QSqlDatabase database = QSqlDatabase::database(m_connectionName, false);
1793 if (database.isValid()) {
1794 if (database.isOpen()) {
1795 database.close();
1796 m_isDatabaseOpen = false;
1797 return true;
1798 }
1799 } else {
1800 m_lastError.setError(DBError::InvalidDatabaseConnection);
1801 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
1802 qWarning() << "ServiceDatabase::close():-"
1803 << "Problem: " << qPrintable(m_lastError.text());
1804 #endif
1805 return false;
1806 }
1807 }
1808 m_lastError.setError(DBError::NoError);
1809 return true;
1810 }
1811
1812 /*
1813 Sets the path of the service database to \a databasePath
1814 */
1815 void ServiceDatabase::setDatabasePath(const QString &databasePath)
1816 {
1817 m_databasePath = QDir::toNativeSeparators(databasePath);
1818 }
1819
1820 /*
1821 Returns the path of the service database
1822 */
1823 QString ServiceDatabase::databasePath() const
1824 {
1825 QString path;
1826 if (m_databasePath.isEmpty()) {
1827 QSettings settings(QSettings::SystemScope, QLatin1String("Nokia"), QLatin1String("Services"));
1828 path = settings.value(QLatin1String("ServicesDB/Path")).toString();
1829 if (path.isEmpty()) {
1830 path = QDir::currentPath();
1831 if (path.lastIndexOf(QLatin1String(RESOLVERDATABASE_PATH_SEPARATOR)) != path.length() -1) {
1832 path.append(QLatin1String(RESOLVERDATABASE_PATH_SEPARATOR));
1833 }
1834 path.append(QLatin1String(RESOLVERDATABASE));
1835 }
1836 path = QDir::toNativeSeparators(path);
1837 } else {
1838 path = m_databasePath;
1839 }
1840
1841 return path;
1842 }
1843
1844 /*
1845 Helper method that creates the database tables: Service, Interface,
1846 Defaults, ServiceProperty and InterfaceProperty
1847
1848 May set the last error to one of the following error codes:
1849 DBError::NoError
1850 DBError::SqlError
1851 DBError::NoWritePermissions
1852 DBError::InvalidDatabaseFile
1853 */
1854 bool ServiceDatabase::createTables()
1855 {
1856 QSqlDatabase database = QSqlDatabase::database(m_connectionName);
1857 QSqlQuery query(database);
1858
1859 //Begin Transaction
1860 if (!beginTransaction(&query, Write)) {
1861 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
1862 qWarning() << "ServiceDatabase::createTables():-"
1863 << "Unable to begin transaction. "
1864 << "Reason:" << qPrintable(m_lastError.text());
1865 #endif
1866 return false;
1867 }
1868
1869 QString statement(QLatin1String("CREATE TABLE Service("
1870 "ID TEXT NOT NULL PRIMARY KEY UNIQUE,"
1871 "Name TEXT NOT NULL, "
1872 "Location TEXT NOT NULL)"));
1873 if (!executeQuery(&query, statement)) {
1874 rollbackTransaction(&query);
1875 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
1876 qWarning() << "ServiceDatabase::createTables():-"
1877 << qPrintable(m_lastError.text());
1878 #endif
1879 return false;
1880 }
1881
1882 statement = QLatin1String("CREATE TABLE Interface("
1883 "ID TEXT NOT NULL PRIMARY KEY UNIQUE,"
1884 "ServiceID TEXT NOT NULL, "
1885 "Name TEXT NOT NULL, "
1886 "VerMaj INTEGER NOT NULL, "
1887 "VerMin INTEGER NOT NULL)");
1888 if (!executeQuery(&query, statement)) {
1889 rollbackTransaction(&query);
1890 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
1891 qWarning() << "ServiceDatabase::createTables():-"
1892 << qPrintable(m_lastError.text());
1893 #endif
1894 return false;
1895 }
1896
1897 statement = QLatin1String("CREATE TABLE Defaults("
1898 "InterfaceName TEXT PRIMARY KEY UNIQUE NOT NULL,"
1899 "InterfaceID TEXT NOT NULL)");
1900 if (!executeQuery(&query, statement)) {
1901 rollbackTransaction(&query);
1902 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
1903 qWarning() << "ServiceDatabase::createTables():-"
1904 << qPrintable(m_lastError.text());
1905 #endif
1906 return false;
1907 }
1908
1909 statement = QLatin1String("CREATE TABLE ServiceProperty("
1910 "ServiceID TEXT NOT NULL,"
1911 "Key TEXT NOT NULL,"
1912 "Value TEXT NOT NULL)");
1913 if (!executeQuery(&query, statement)) {
1914 rollbackTransaction(&query);
1915 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
1916 qWarning() << "ServiceDatabase::createTables():-"
1917 << qPrintable(m_lastError.text());
1918 #endif
1919 return false;
1920 }
1921
1922 statement = QLatin1String("CREATE TABLE InterfaceProperty("
1923 "InterfaceID TEXT NOT NULL,"
1924 "Key TEXT NOT NULL,"
1925 "Value TEXT NOT NULL)");
1926
1927 if (!executeQuery(&query, statement)) {
1928 rollbackTransaction(&query);
1929 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
1930 qWarning() << "ServiceDatabase::createTables():-"
1931 << qPrintable(m_lastError.text());
1932 #endif
1933 return false;
1934 }
1935
1936 if (!commitTransaction(&query)) {
1937 rollbackTransaction(&query);
1938 return false;
1939 }
1940 m_lastError.setError(DBError::NoError);
1941 return true;
1942 }
1943
1944 /*!
1945 Helper method that checks if the all expected tables exist in the database
1946 Returns true if they all exist and false if any of them don't
1947 */
1948 bool ServiceDatabase::checkTables()
1949 {
1950 bool bTables(false);
1951 QStringList tables = QSqlDatabase::database(m_connectionName).tables();
1952 if (tables.contains(QLatin1String(SERVICE_TABLE))
1953 && tables.contains(QLatin1String(INTERFACE_TABLE))
1954 && tables.contains(QLatin1String(DEFAULTS_TABLE))
1955 && tables.contains(QLatin1String(SERVICE_PROPERTY_TABLE))
1956 && tables.contains(QLatin1String(INTERFACE_PROPERTY_TABLE))){
1957 bTables = true;
1958 }
1959 return bTables;
1960 }
1961
1962 /*
1963 This function should only ever be used on a user scope database
1964 It removes an entry from the Defaults table where the default
1965 refers to an interface implementation in the system scope database.
1966 The particular default that is removed is specified by
1967 \a interfaceID.
1968
1969 May set the last error to one of the following error codes:
1970 DBError::NoError
1971 DBError::IfaceIDNotExternal
1972 DBError::SqlError
1973 DBError::NoWritePermissions
1974 DBError::InvalidDatabaseFile
1975 */
1976 bool ServiceDatabase::removeExternalDefaultServiceInterface(const QString &interfaceID)
1977 {
1978 QSqlDatabase database = QSqlDatabase::database(m_connectionName);
1979 QSqlQuery query(database);
1980
1981 //begin transaction
1982 if (!beginTransaction(&query, Write)) {
1983 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
1984 qWarning() << "ServiceDatabase::removeExternalDefaultServiceInterface():-"
1985 << "Problem: Unable to begin transaction. "
1986 << "Reason:" << qPrintable(m_lastError.text());
1987 #endif
1988 return false;
1989 }
1990
1991 QString statement(QLatin1String("SELECT Name FROM Interface WHERE Interface.ID = ?"));
1992 QList<QVariant> bindValues;
1993 bindValues.append(interfaceID);
1994 if (!executeQuery(&query, statement, bindValues)) {
1995 rollbackTransaction(&query);
1996 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
1997 qWarning() << "ServiceDatabase::removeDefaultServiceInterface():-"
1998 << qPrintable(m_lastError.text());
1999 #endif
2000 return false;
2001 }
2002 if (query.next()) {
2003 QString interfaceName = query.value(EBindIndex).toString();
2004 QString errorText(QLatin1String("Local interface implementation exists for interface \"%1\" "
2005 "with interfaceID: \"%2\""));
2006 m_lastError.setError(DBError::IfaceIDNotExternal,
2007 errorText.arg(interfaceName).arg(interfaceID));
2008 rollbackTransaction(&query);
2009 return false;
2010 }
2011
2012 statement = QLatin1String("DELETE FROM Defaults WHERE InterfaceID = ? COLLATE NOCASE");
2013 bindValues.clear();
2014 bindValues.append(interfaceID);
2015 if (!executeQuery(&query, statement, bindValues)) {
2016 rollbackTransaction(&query);
2017 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
2018 qWarning() << "ServiceDatabase::removeDefaultServiceInterface():-"
2019 << qPrintable(m_lastError.text());
2020 #endif
2021 return false;
2022 }
2023
2024 //end transaction
2025 if (!commitTransaction(&query)){
2026 rollbackTransaction(&query);
2027 return false;
2028 }
2029 m_lastError.setError(DBError::NoError);
2030 return true;
2031 }
2032
2033 /*
2034 Removes all tables from the database
2035
2036 In future this function may be deprecated or removed.
2037
2038 May set the last error to one of the following error codes:
2039 DBError::NoError
2040 DBError::SqlError
2041 DBError::NoWritePermissions
2042 DBError::InvalidDatabaseFile
2043 */
2044 bool ServiceDatabase::dropTables()
2045 {
2046 //Execute transaction for deleting the database tables
2047 QSqlDatabase database = QSqlDatabase::database(m_connectionName);
2048 QSqlQuery query(database);
2049 QStringList expectedTables;
2050 expectedTables << QLatin1String(SERVICE_TABLE)
2051 << QLatin1String(INTERFACE_TABLE)
2052 << QLatin1String(DEFAULTS_TABLE)
2053 << QLatin1String(SERVICE_PROPERTY_TABLE)
2054 << QLatin1String(INTERFACE_PROPERTY_TABLE);
2055
2056 if (database.tables().count() > 0) {
2057 if (!beginTransaction(&query, Write)) {
2058 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
2059 qWarning() << "ServiceDatabase::dropTables():-"
2060 << "Unable to begin transaction. "
2061 << "Reason:" << qPrintable(m_lastError.text());
2062 #endif
2063 return false;
2064 }
2065 QStringList actualTables = database.tables();
2066
2067 foreach (const QString expectedTable, expectedTables) {
2068 if ((actualTables.contains(expectedTable))
2069 && (!executeQuery(&query, QLatin1String("DROP TABLE ") + expectedTable))) {
2070 rollbackTransaction(&query);
2071 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
2072 qWarning() << "ServiceDatabase::dropTables():-"
2073 << qPrintable(m_lastError.text());
2074 #endif
2075 return false;
2076 }
2077 }
2078 if (!commitTransaction(&query)) {
2079 rollbackTransaction(&query);
2080 return false;
2081 }
2082 }
2083 m_lastError.setError(DBError::NoError);
2084 return true;
2085 }
2086
2087 /*
2088 Checks if the database is open
2089 */
2090 bool ServiceDatabase::isOpen() const
2091 {
2092 return m_isDatabaseOpen;
2093 }
2094
2095 /*
2096 Checks the database connection.
2097
2098 May set the last error to one of the following error codes:
2099 DBError::DatabaseNotOpen
2100 DBError::InvalidDatabaseConnection
2101 */
2102 bool ServiceDatabase::checkConnection()
2103 {
2104 if (!m_isDatabaseOpen)
2105 {
2106 m_lastError.setError(DBError::DatabaseNotOpen);
2107 return false;
2108 }
2109
2110 if (!QSqlDatabase::database(m_connectionName).isValid())
2111 {
2112 m_lastError.setError(DBError::InvalidDatabaseConnection);
2113 return false;
2114 }
2115
2116 return true;
2117 }
2118
2119 /*
2120 Begins a transcaction based on the \a type which can be Read or Write.
2121
2122 May set the last error to one of the following error codes:
2123 DBError::NoError
2124 DBError::SqlError
2125 DBError::NoWritePermissions
2126 DBError::InvalidDatabaseFile
2127 */
2128 bool ServiceDatabase::beginTransaction(QSqlQuery *query, TransactionType type)
2129 {
2130 bool success;
2131 if (type == Read)
2132 success = query->exec(QLatin1String("BEGIN"));
2133 else
2134 success = query->exec(QLatin1String("BEGIN IMMEDIATE"));
2135
2136 if (!success) {
2137 int result = query->lastError().number();
2138 if (result == 26 || result == 11) {//SQLITE_NOTADB || SQLITE_CORRUPT
2139 qWarning() << "Service Framework:- Database file is corrupt or invalid:" << databasePath();
2140 m_lastError.setError(DBError::InvalidDatabaseFile, query->lastError().text());
2141 }
2142 else if (result == 8) { //SQLITE_READONLY
2143 qWarning() << "Service Framework:- Insufficient permissions to write to database:" << databasePath();
2144 m_lastError.setError(DBError::NoWritePermissions, query->lastError().text());
2145 }
2146 else
2147 m_lastError.setError(DBError::SqlError, query->lastError().text());
2148 return false;
2149 }
2150
2151 m_lastError.setError(DBError::NoError);
2152 return true;
2153 }
2154
2155 /*
2156 Commits a transaction
2157
2158 May set the last error to one of the following error codes:
2159 DBError::NoError
2160 DBError::SqlError
2161 */
2162 bool ServiceDatabase::commitTransaction(QSqlQuery *query)
2163 {
2164 Q_ASSERT(query != NULL);
2165 query->finish();
2166 query->clear();
2167 if (!query->exec(QLatin1String("COMMIT"))) {
2168 m_lastError.setError(DBError::SqlError, query->lastError().text());
2169 return false;
2170 }
2171 m_lastError.setError(DBError::NoError);
2172 return true;
2173 }
2174
2175 /*
2176 Rolls back a transaction
2177
2178 May set the last error to one of the following error codes:
2179 DBError::NoError
2180 DBError::SqlError
2181 */
2182 bool ServiceDatabase::rollbackTransaction(QSqlQuery *query)
2183 {
2184 Q_ASSERT(query !=NULL);
2185 query->finish();
2186 query->clear();
2187
2188 if (!query->exec(QLatin1String("ROLLBACK"))) {
2189 m_lastError.setError(DBError::SqlError, query->lastError().text());
2190 return false;
2191 }
2192 return true;
2193 }
2194
2195 /*
2196 Helper function that populates a service \a interface descriptor
2197 with interface related attributes corresponding to the interface
2198 represented by \a interfaceID
2199
2200 It is already assumed that a transaction has been started by the time
2201 this function is called. This function will not rollback/commit the
2202 transaction.
2203
2204 May set the last error to one of the following error codes:
2205 DBError::NoError
2206 DBError::SqlError
2207 */
2208 bool ServiceDatabase::populateInterfaceProperties(QServiceInterfaceDescriptor *serviceInterface, const QString &interfaceID)
2209 {
2210 QSqlQuery query(QSqlDatabase::database(m_connectionName));
2211 QString statement(QLatin1String("SELECT Key, Value FROM InterfaceProperty WHERE InterfaceID = ?"));
2212 QList<QVariant> bindValues;
2213 bindValues.append(interfaceID);
2214 if (!executeQuery(&query, statement, bindValues)) {
2215 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
2216 qWarning() << "ServiceDatabase::populateInterfaceProperties():-"
2217 << qPrintable(m_lastError.text());
2218 #endif
2219 return false;
2220 }
2221
2222 bool isFound = false;
2223 QString attribute;
2224 while (query.next()) {
2225 isFound = true;
2226 attribute = query.value(EBindIndex).toString();
2227 if (attribute == QLatin1String(INTERFACE_CAPABILITY_KEY)) {
2228 const QStringList capabilities = query.value(EBindIndex1).toString().split(QLatin1String(","));
2229 if (capabilities.count() == 1 && capabilities[0].isEmpty()) {
2230 serviceInterface->d->attributes[QServiceInterfaceDescriptor::Capabilities]
2231 = QStringList();
2232 } else {
2233 serviceInterface->d->attributes[QServiceInterfaceDescriptor::Capabilities]
2234 = capabilities;
2235 }
2236 } else if (attribute == QLatin1String(INTERFACE_DESCRIPTION_KEY)) {
2237 serviceInterface->d->attributes[QServiceInterfaceDescriptor::InterfaceDescription]
2238 = query.value(EBindIndex1).toString();
2239 } else if (attribute.startsWith(QLatin1String("c_"))) {
2240 serviceInterface->d->customAttributes[attribute.mid(2)]
2241 = query.value(EBindIndex1).toString();
2242 }
2243 }
2244
2245 if (!isFound) {
2246 QString errorText(QLatin1String("Database integrity corrupted, Properties for InterfaceID: %1 does not exist in the InterfaceProperty table for interface \"%2\""));
2247 m_lastError.setError(DBError::SqlError, errorText.arg(interfaceID).arg(serviceInterface->interfaceName()));
2248 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
2249 qWarning() << "ServiceDatabase::populateInterfaceProperties():-"
2250 << "Problem:" << qPrintable(m_lastError.text());
2251 #endif
2252 return false;
2253 }
2254 m_lastError.setError(DBError::NoError);
2255 return true;
2256 }
2257
2258 /*
2259 Helper function that populates a service \a interface descriptor
2260 with service related attributes corresponding to the service
2261 represented by \a serviceID
2262
2263 It is already assumed that a transaction has been started by the time
2264 this function is called. This function will not rollback/commit the
2265 transaction.
2266
2267 May set the last error to one of the following error codes:
2268 DBError::NoError
2269 DBError::SqlError
2270 */
2271 bool ServiceDatabase::populateServiceProperties(QServiceInterfaceDescriptor *serviceInterface, const QString &serviceID)
2272 {
2273 QSqlQuery query(QSqlDatabase::database(m_connectionName));
2274 QString statement(QLatin1String("SELECT Key, Value FROM ServiceProperty WHERE ServiceID = ?"));
2275 QList<QVariant> bindValues;
2276 bindValues.append(serviceID);
2277 if (!executeQuery(&query, statement, bindValues)) {
2278 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
2279 qWarning() << "ServiceDatabase::populateServiceProperties():-"
2280 << qPrintable(m_lastError.text());
2281 #endif
2282 return false;
2283 }
2284
2285 bool isFound = false;
2286 QString attribute;
2287 while (query.next()) {
2288 isFound = true;
2289 attribute = query.value(EBindIndex).toString();
2290 if (attribute == QLatin1String(SERVICE_DESCRIPTION_KEY)) {
2291 serviceInterface->d->attributes[QServiceInterfaceDescriptor::ServiceDescription]
2292 = query.value(EBindIndex1).toString();
2293 }
2294 // fetch initialized and put it as a custom attribute
2295 if (attribute == QLatin1String(SERVICE_INITIALIZED_KEY)) {
2296 serviceInterface->d->customAttributes[attribute] = query.value(EBindIndex1).toString();
2297 }
2298 }
2299
2300 if (!isFound) {
2301 QString errorText(QLatin1String("Database integrity corrupted, Service Properties for ServiceID: \"%1\" does not exist in the ServiceProperty table for service \"%2\""));
2302 m_lastError.setError(DBError::SqlError, errorText.arg(serviceID).arg(serviceInterface->serviceName()));
2303 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
2304 qWarning() << "ServiceDatabase::populateServiceProperties():-"
2305 << "Problem:" << qPrintable(m_lastError.text());
2306 #endif
2307 return false;
2308 }
2309 m_lastError.setError(DBError::NoError);
2310 return true;
2311 }
2312
2313 #include "moc_servicedatabase_p.cpp"
2314
2315 QT_END_NAMESPACE