File: DatabaseManagers.cpp

package info (click to toggle)
kphotoalbum 4.2-1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 21,324 kB
  • sloc: cpp: 35,900; python: 743; xml: 483; sh: 146; perl: 34; makefile: 16
file content (195 lines) | stat: -rw-r--r-- 6,111 bytes parent folder | download
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
/*
  Copyright (C) 2007-2010 Tuomas Suutari <thsuut@utu.fi>

  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 (see the file COPYING); if not, write to the
  Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
  MA 02110-1301 USA.
*/

#include "DatabaseManagers.h"
#include "TransactionGuard.h"
#include "QueryErrors.h"
#include "QSqlConnection.h"
#include "Schema/MySQLCSG.h"
#include "Schema/PostgreSQLCSG.h"
#include "Schema/SQLiteCSG.h"
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QVariant>
#include <QFile>

using namespace SQLDB;

namespace
{
    static QString newDatabaseName(const QString& baseName)
    {
        // TODO: check that database name is not in use
        static int i(0);
        return baseName + QString::number(++i);
    }

    static void setConnectionParameters(QSqlDatabase& db,
                                        const ConnectionParameters& connParams)
    {
        if (!connParams.isLocal()) {
            db.setHostName(connParams.hostName());
            if (connParams.port())
                db.setPort(connParams.port());
        }
        if (!connParams.userName().isNull()) {
            db.setUserName(connParams.userName());
            if (!connParams.password().isNull())
                db.setPassword(connParams.password());
        }
    }
}


BaseDatabaseManager::
BaseDatabaseManager(const ConnectionParameters& connParams,
                    const QString& driverName,
                    const QString& someDbName,
                    const QString& selDbsQuery,
                    Schema::CreateStatementGenerator::APtr csg):
    _someDbName(someDbName),
    _selDbsQuery(selDbsQuery),
    _csg(csg),
    _connName(newDatabaseName(QString::fromLatin1("dbmgr"))),
    _db(QSqlDatabase::addDatabase(driverName, _connName))
{
    setConnectionParameters(_db, connParams);
    _db.setDatabaseName(_someDbName);
    if (!_db.open())
        throw QtSQLError(_db.lastError(), QLatin1String("Cannot open database"));
}

QStringList BaseDatabaseManager::databases() const
{
    QSqlQuery q(_db);

    if (!q.exec(_selDbsQuery))
        throw QtSQLError(q, QLatin1String("Error while listing databases"));

    QStringList dbList;
    while (q.next())
        dbList.push_back(q.value(0).toString());

    return dbList;
}

void BaseDatabaseManager::
createDatabase(const QString& databaseName,
               const Schema::DatabaseSchema& schema)
{
    using namespace Schema;

    QSqlQuery q(_db);

    if (!q.exec(QLatin1String("CREATE DATABASE ") + databaseName))
        throw QtSQLError(q, QLatin1String("Cannot create a database"));

    ConnectionSPtr newDb = connectToDatabase(databaseName);

    TransactionGuard transaction(*newDb);

    const list<string>& x = _csg->generateCreateStatements(schema);
    for (list<string>::const_iterator i = x.begin(); i != x.end(); ++i)
        newDb->executeStatement(i->c_str());

    transaction.commit();
}

ConnectionSPtr
BaseDatabaseManager::connectToDatabase(const QString& databaseName)
{
    QString newConnName(newDatabaseName(QString::fromLatin1("conn")));
    QSqlDatabase db = QSqlDatabase::cloneDatabase(_db, newConnName);
    db.setDatabaseName(databaseName);
    if (!db.open())
        throw QtSQLError(db.lastError(), QLatin1String("Cannot connect to database"));

    return ConnectionSPtr(new QSqlConnection(db));
}


MySQLDatabaseManager::
MySQLDatabaseManager(const ConnectionParameters& connParams):
    BaseDatabaseManager(connParams,
                        QLatin1String("QMYSQL"),
                        QLatin1String("INFORMATION_SCHEMA"),
                        QLatin1String("SHOW DATABASES"),
                        Schema::CreateStatementGenerator::APtr
                        (new Schema::MySQLCSG()))
{
}


PostgreSQLDatabaseManager::
PostgreSQLDatabaseManager(const ConnectionParameters& connParams):
    BaseDatabaseManager(connParams,
                        QLatin1String("QPSQL"),
                        QLatin1String("template1"),
                        QLatin1String("SELECT datname "
                                      "FROM pg_catalog.pg_database "
                                      "WHERE datallowconn "
                                      "AND NOT datistemplate"),
                        Schema::CreateStatementGenerator::APtr
                        (new Schema::PostgreSQLCSG()))
{
}


QStringList SQLiteDatabaseManager::databases() const
{
    return QStringList();
}

bool SQLiteDatabaseManager::databaseExists(const QString& databaseName) const
{
    return QFile(databaseName).exists();
}

void
SQLiteDatabaseManager::createDatabase(const QString& databaseName,
                                      const Schema::DatabaseSchema& schema)
{
    using namespace Schema;

    SQLiteCSG csg;

    ConnectionSPtr newDb = connectToDatabase(databaseName);

    TransactionGuard transaction(*newDb);

    const list<string>& x = csg.generateCreateStatements(schema);
    for (list<string>::const_iterator i = x.begin(); i != x.end(); ++i)
        newDb->executeStatement(i->c_str());

    transaction.commit();
}

ConnectionSPtr
SQLiteDatabaseManager::connectToDatabase(const QString& databaseName)
{
    QString newConnName(newDatabaseName(QString::fromLatin1("conn")));
    QSqlDatabase db = QSqlDatabase::addDatabase(QString::fromLatin1("QSQLITE"), newConnName);
    db.setDatabaseName(databaseName);

    if (!db.open())
        throw QtSQLError(db.lastError(), QLatin1String("Cannot open SQLite database"));

    return ConnectionSPtr(new QSqlConnection(db));
}