3 This file is part of Minitube.
4 Copyright 2009, Flavio Tordini <flavio.tordini@gmail.com>
6 Minitube is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
11 Minitube is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with Minitube. If not, see <http://www.gnu.org/licenses/>.
22 #include "constants.h"
23 #include "compatibility/pathsservice.h"
26 static const int DATABASE_VERSION = 1;
27 static const QString dbName = QLatin1String(Constants::UNIX_NAME) + ".db";
28 static Database *databaseInstance = 0;
30 Database::Database() {
31 QString dataLocation = Paths::getDataLocation();
33 if (!QDir().mkpath(dataLocation)) {
34 qCritical() << "Failed to create directory " << dataLocation;
36 dbLocation = dataLocation + "/" + dbName;
37 qDebug() << "dbLocation" << dbLocation;
39 QMutexLocker locker(&lock);
41 if (QFile::exists(dbLocation)) {
43 int databaseVersion = getAttribute("version").toInt();
44 if (databaseVersion > DATABASE_VERSION)
45 qWarning("Wrong database version: %d", databaseVersion);
47 if (!getAttribute("channelIdFix").toBool())
50 } else createDatabase();
53 Database::~Database() {
57 void Database::createDatabase() {
58 qDebug() << __PRETTY_FUNCTION__;
61 // Qt5 changed its "data" path. Try to move the old db to the new path
62 QString qt4DataLocation = Paths::getHomeLocation() + "/.local/share/data/" + Constants::ORG_NAME + "/" + Constants::NAME;
63 QString oldDbLocation = qt4DataLocation + "/" + dbName;
64 qDebug() << oldDbLocation;
65 if (QFile::exists(oldDbLocation)) {
66 if (QFile::copy(oldDbLocation, dbLocation)) {
67 qDebug() << "Moved db from" << oldDbLocation << "to" << dbLocation;
73 qWarning() << "Creating the database";
75 const QSqlDatabase db = getConnection();
77 QSqlQuery("create table subscriptions ("
78 "id integer primary key autoincrement,"
79 "user_id varchar," // this is really channel_id
80 "user_name varchar," // obsolete yt2 username
81 "name varchar," // this is really channel_title
82 "description varchar,"
86 "checked integer," // last check for videos on YT APIs
87 "updated integer," // most recent video added
88 "watched integer," // last time the user watched this channel
89 "loaded integer," // last time channel metadata was loaded from YT APIs
90 "notify_count integer," // new videos since "watched"
91 "views integer)" // number of times the user watched this channel
93 QSqlQuery("create unique index idx_user_id on subscriptions(user_id)", db);
95 QSqlQuery("create table subscriptions_videos ("
96 "id integer primary key autoincrement,"
98 "channel_id integer," // this is really subscription_id
103 "author varchar," // this is really channel_title
104 "user_id varchar," // this is really channel_id
105 "description varchar,"
111 QSqlQuery("create unique index idx_video_id on subscriptions_videos(video_id)", db);
113 QSqlQuery("create table attributes (name varchar, value)", db);
114 QSqlQuery("insert into attributes (name, value) values ('version', "
115 + QString::number(DATABASE_VERSION) + ")", db);
119 QString Database::getDbLocation() {
120 return Paths::getDataLocation() + "/" + dbName;
124 bool Database::exists() {
125 static bool fileExists = false;
127 fileExists = QFile::exists(getDbLocation());
130 QString qt4DataLocation = Paths::getHomeLocation() + "/.local/share/data/" + Constants::ORG_NAME + "/" + Constants::NAME;
131 QString oldDbLocation = qt4DataLocation + "/" + dbName;
132 qDebug() << "asd" << oldDbLocation;
133 fileExists = QFile::exists(oldDbLocation);
141 Database& Database::instance() {
143 QMutexLocker locker(&mutex);
144 if (!databaseInstance) databaseInstance = new Database();
145 return *databaseInstance;
148 QSqlDatabase Database::getConnection() {
149 QThread *currentThread = QThread::currentThread();
150 if (!currentThread) {
151 qDebug() << "current thread is null";
152 return QSqlDatabase();
155 const QString threadName = currentThread->objectName();
156 // qDebug() << "threadName" << threadName << currentThread;
157 if (connections.contains(currentThread)) {
158 return connections.value(currentThread);
160 // qDebug() << "Creating db connection for" << threadName;
161 QSqlDatabase connection = QSqlDatabase::addDatabase("QSQLITE", threadName);
162 connection.setDatabaseName(dbLocation);
163 if(!connection.open()) {
164 qWarning() << QString("Cannot connect to database %1 in thread %2").arg(dbLocation, threadName);
166 connections.insert(currentThread, connection);
171 QVariant Database::getAttribute(const QString &name) {
172 QSqlQuery query("select value from attributes where name=?", getConnection());
173 query.bindValue(0, name);
175 bool success = query.exec();
176 if (!success) qDebug() << query.lastQuery() << query.boundValues().values() << query.lastError().text();
178 return query.value(0);
182 void Database::setAttribute(const QString &name, const QVariant &value) {
183 QSqlQuery query(getConnection());
184 query.prepare("insert or replace into attributes (name, value) values (?,?)");
185 query.bindValue(0, name);
186 query.bindValue(1, value);
187 bool success = query.exec();
188 if (!success) qWarning() << query.lastError().text();
191 void Database::fixChannelIds() {
192 if (!getConnection().transaction())
193 qWarning() << "Transaction failed" << __PRETTY_FUNCTION__;
195 qWarning() << "Fixing channel ids";
197 QSqlQuery query(getConnection());
198 bool success = query.exec("update subscriptions set user_id='UC' || user_id where user_id not like 'UC%'");
199 if (!success) qWarning() << query.lastError().text();
201 query = QSqlQuery(getConnection());
202 success = query.exec("update subscriptions_videos set user_id='UC' || user_id where user_id not like 'UC%'");
203 if (!success) qWarning() << query.lastError().text();
205 setAttribute("channelIdFix", 1);
207 if (!getConnection().commit())
208 qWarning() << "Commit failed" << __PRETTY_FUNCTION__;
212 * After calling this method you have to reacquire a valid instance using instance()
214 void Database::drop() {
215 /// closeConnections();
216 if (!QFile::remove(dbLocation)) {
217 qWarning() << "Cannot delete database" << dbLocation;
219 // fallback to delete records in tables
220 const QSqlDatabase db = getConnection();
222 if (!query.exec("select name from sqlite_master where type='table'")) {
223 qWarning() << query.lastQuery() << query.lastError().text();
226 while (query.next()) {
227 QString tableName = query.value(0).toString();
228 if (tableName.startsWith("sqlite_") || tableName == QLatin1String("attributes")) continue;
229 QString dropSQL = "delete from " + tableName;
230 QSqlQuery query2(db);
231 if (!query2.exec(dropSQL))
232 qWarning() << query2.lastQuery() << query2.lastError().text();
235 query.exec("delete from sqlite_sequence");
238 if (databaseInstance) delete databaseInstance;
239 databaseInstance = 0;
242 void Database::closeConnections() {
243 foreach(QSqlDatabase connection, connections.values()) {
244 // qDebug() << "Closing connection" << connection;
250 void Database::closeConnection() {
251 QThread *currentThread = QThread::currentThread();
252 if (!connections.contains(currentThread)) return;
253 QSqlDatabase connection = connections.take(currentThread);
254 // qDebug() << "Closing connection" << connection;
258 void Database::shutdown() {
259 if (!databaseInstance) return;
260 QSqlQuery("vacuum", databaseInstance->getConnection());
261 databaseInstance->closeConnections();