forked from KDAB/Charm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSqLiteStorage.cpp
316 lines (259 loc) · 9.42 KB
/
SqLiteStorage.cpp
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
/*
SqLiteStorage.cpp
This file is part of Charm, a task-based time tracking application.
Copyright (C) 2007-2015 Klarälvdalens Datakonsult AB, a KDAB Group company, [email protected]
Author: Mirko Boehm <[email protected]>
Author: Frank Osterfeld <[email protected]>
Author: Mike McQuaid <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "SqLiteStorage.h"
#include "CharmConstants.h"
#include "CharmExceptions.h"
#include "Configuration.h"
#include "Event.h"
#include <QDir>
#include <QtDebug>
#include <QFileInfo>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <cerrno>
// DATABASE STRUCTURE DEFINITION
static const QString Tables[] =
{ "MetaData", "Installations", "Tasks", "Events", "Subscriptions", "Users" };
static const int NumberOfTables = sizeof Tables / sizeof Tables[0];
struct Field
{
QString name;
QString type;
};
typedef Field Fields;
const Field LastField =
{ QString::null, QString::null};
static const Fields MetaData_Fields[] =
{
{ "id", "INTEGER PRIMARY KEY" },
{ "key", "VARCHAR( 128 ) NOT NULL" },
{ "value", "VARCHAR( 128 )" }, LastField };
static const Fields Installations_Fields[] =
{
{ "id", "INTEGER PRIMARY KEY" },
{ "inst_id", "INTEGER" },
{ "user_id", "INTEGER" },
{ "name", "varchar(256)" }, LastField };
static const Fields Tasks_Fields[] =
{
{ "id", "INTEGER PRIMARY KEY" },
{ "task_id", "INTEGER UNIQUE" },
{ "parent", "INTEGER" },
{ "validfrom", "timestamp" },
{ "validuntil", "timestamp" },
{ "trackable", "INTEGER" },
{ "name", "varchar(256)" }, LastField };
static const Fields Event_Fields[] =
{
{ "id", "INTEGER PRIMARY KEY" },
{ "user_id", "INTEGER" },
{ "event_id", "INTEGER" },
{ "installation_id", "INTEGER" },
{ "report_id", "INTEGER NULL" },
{ "task", "INTEGER" },
{ "comment", "varchar(256)" },
{ "start", "date" },
{ "end", "date" }, LastField };
static const Fields Subscriptions_Fields[] =
{
{ "id", "INTEGER PRIMARY KEY" },
{ "user_id", "INTEGER" },
{ "task", "INTEGER" }, LastField };
static const Fields Users_Fields[] =
{
{ "id", "INTEGER PRIMARY KEY" },
{ "user_id", "INTEGER UNIQUE" },
{ "name", "varchar(256)" }, LastField };
static const Fields* Database_Fields[NumberOfTables] =
{ MetaData_Fields, Installations_Fields, Tasks_Fields, Event_Fields,
Subscriptions_Fields, Users_Fields };
const char DatabaseName[] = "charm.kdab.com";
const char DriverName[] = "QSQLITE";
SqLiteStorage::SqLiteStorage()
: SqlStorage()
, m_database( QSqlDatabase::addDatabase( DriverName, DatabaseName ) )
, m_installationId( 0 )
{
if ( ! QSqlDatabase::isDriverAvailable( DriverName ) ) {
throw CharmException( QObject::tr( "QSQLITE driver not available" ) );
}
}
SqLiteStorage::~SqLiteStorage()
{
}
QString SqLiteStorage::lastInsertRowFunction() const
{
return QString::fromLocal8Bit("last_insert_rowid");
}
QString SqLiteStorage::description() const
{
return QObject::tr( "local database" );
}
bool SqLiteStorage::createDatabaseTables()
{
Q_ASSERT_X(database().open(), Q_FUNC_INFO,
"Connection to database must be established first");
bool error = false;
// create tables:
for (int i = 0; i < NumberOfTables; ++i)
{
if (!database().tables().contains(Tables[i]))
{
QString statement;
QTextStream stream(&statement, QIODevice::WriteOnly);
stream << "CREATE table `" << Tables[i] << "` (";
const Field* field = Database_Fields[i];
while (field->name != QString::null )
{
stream << " `" << field->name << "` "
<< field->type;
++field;
if ( field->name != QString::null ) stream << ", ";
}
stream << ");";
QSqlQuery query( database() );
query.prepare( statement );
if ( ! runQuery( query ) )
{
error = true;
}
}
}
error = error || ! setMetaData(CHARM_DATABASE_VERSION_DESCRIPTOR, QString().setNum( CHARM_DATABASE_VERSION) );
return ! error;
}
bool SqLiteStorage::connect( Configuration& configuration )
{ // make sure the database folder exits:
m_installationId = configuration.installationId;
configuration.failure = true;
const QFileInfo fileInfo( configuration.localStorageDatabase ); // this is the full path
// make sure the path exists, file will be created by sqlite
if ( ! QDir().mkpath( fileInfo.absolutePath() ) )
{
configuration.failureMessage = QObject::tr( "Cannot make database directory: %1").arg( qt_error_string(errno) );
return false;
}
if ( ! QDir( fileInfo.absolutePath() ).exists() )
{
configuration.failureMessage = QObject::tr("I made a directory, but it is not there. Weird.");
return false;
}
// connect:
// qDebug() << "SqLiteStorage::connect: creating or opening local sqlite database at "
// << fileInfo.absoluteFilePath();
const QDir oldDatabaseDirectory( QDir::homePath() + QDir::separator() + ".Charm" );
if ( oldDatabaseDirectory.exists() )
migrateDatabaseDirectory( oldDatabaseDirectory, fileInfo.dir() );
m_database.setHostName( "localhost" );
const QString databaseName = fileInfo.absoluteFilePath();
m_database.setDatabaseName( databaseName );
bool error = false;
if ( ! fileInfo.exists() && ! configuration.newDatabase )
{
error = true;
configuration.failureMessage = QObject::tr(
"<html><head><meta name=\"qrichtext\" content=\"1\" /></head>"
"<body><p>The configuration seems to be valid, but the database "
"file does not exist.</p>"
"<p>The file will automatically be generated. Please verify "
"the configuration.</p>"
"<p>If the configuration is correct, just close the dialog.</p>"
"</body></html>");
}
if ( !m_database.open() )
{
configuration.failureMessage = QObject::tr("Could not open SQLite database %1").arg( databaseName );
return false;
}
// qDebug() << "SqLiteStorage::connect: SUCCESS - connected to database";
if ( ! verifyDatabase() )
{
// qDebug() << "SqLiteStorage::connect: empty database, filling in the blanks";
if ( !createDatabase( configuration ) )
{
configuration.failureMessage = QObject::tr( "SqLiteStorage::connect: error creating default database contents" );
return false;
}
}
if ( !configuration.newDatabase )
{
const int userid = configuration.user.id();
const User user = getUser( userid );
// qDebug() << "SqLiteStorage::connect: found user" << user.name()
// << "for id" << userid << ( user.isValid() ? "(valid)" : "(invalid)");
if ( !user.isValid() )
return false;
configuration.user = user;
}
// FIXME verify that a database user id has been generated
if ( error )
return false;
configuration.failure = false;
return true;
}
bool SqLiteStorage::migrateDatabaseDirectory( QDir oldDirectory, const QDir &newDirectory ) const
{
if ( oldDirectory == newDirectory )
return true;
qDebug() << "Application::configure: migrating Charm database directory contents from"
<< oldDirectory.absolutePath() << "to" << newDirectory.absolutePath();
oldDirectory.setFilter( QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot );
Q_FOREACH ( const QString& entry, oldDirectory.entryList() )
oldDirectory.rename( entry, newDirectory.path() + QDir::separator() + entry );
QDir oldDirectoryParent( oldDirectory );
oldDirectoryParent.cdUp();
return oldDirectoryParent.rmpath( oldDirectory.dirName() );
}
bool SqLiteStorage::disconnect()
{
m_database.removeDatabase( DatabaseName );
m_database.close();
return true; // neither of the two methods return a value
}
int SqLiteStorage::installationId() const
{
return m_installationId;
}
QSqlDatabase& SqLiteStorage::database()
{
return m_database;
}
bool SqLiteStorage::createDatabase( Configuration& configuration )
{
bool success = createDatabaseTables();
if ( !success ) return false;
// add installation id and user id:
const QString userName = configuration.user.name();
configuration.user = makeUser( userName );
if ( ! configuration.user.isValid() ) {
qDebug() << "SqLiteStorage::createDatabase: cannot store user name";
return false;
}
// make an installation:
// FIXME make a useful name for it
QString installationName = "Unnamed Installation";
Installation installation = createInstallation( installationName );
if ( ! installation.isValid() ) {
qDebug() << "SqLiteStorage::createDatabase: cannot create default installation id";
return false;
} else {
configuration.installationId = installation.id();
}
return true;
}