-
Notifications
You must be signed in to change notification settings - Fork 1
/
bookmarkdb.cpp
99 lines (90 loc) · 2.81 KB
/
bookmarkdb.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
#include "bookmarkdb.h"
#include <QString>
#include <QUrl>
#include <QStandardPaths>
#include <QDir>
#include <QtSql/QSqlError>
#include <QDebug>
/* BookmarkDB uses SQLite database to store
* all the bookmarks. It's a simple table in which
* each record has two fields title and url. Title
* represents web page title and url a address of
* a web page.
*/
BookmarkDB::BookmarkDB(QObject *parent) : QObject(parent)
{
createConnection();
}
void BookmarkDB::createConnection()
{
db = QSqlDatabase::addDatabase("QSQLITE");
QString databaseDir =
QStandardPaths::writableLocation(QStandardPaths::DataLocation);
const QString dbFileName = QString("_mybookmarks.db");
QDir dir(databaseDir);
if (!QDir().mkpath(databaseDir)) {
qWarning("Cannot create directory %s",
qPrintable(QStandardPaths::writableLocation(
QStandardPaths::DataLocation)));
return;
}
db.setDatabaseName(dir.absoluteFilePath(dbFileName));
if (!db.open())
qFatal("Error while opening the database: %s",
qPrintable(db.lastError().text()));
createInitialData();
}
QSqlQuery BookmarkDB::prepare(const QString &statement) const
{
QSqlQuery query(db);
query.setForwardOnly(true);
if (!query.prepare(statement)) {
qWarning() << Q_FUNC_INFO << "failed to prepare query";
qWarning() << query.lastQuery();
qWarning() << query.lastError().text();
return QSqlQuery();
}
return query;
}
bool BookmarkDB::execute(QSqlQuery &query) const
{
if (!query.exec()) {
qWarning() << Q_FUNC_INFO << "failed execute query";
qWarning() << query.lastQuery();
qWarning() << query.lastError().text();
return false;
}
return true;
}
void BookmarkDB::createInitialData() const
{
QSqlQuery query =
prepare(QString("CREATE TABLE IF NOT EXISTS "
"Bookmarks (id INTEGER PRIMARY KEY AUTOINCREMENT, "
"title TEXT NOT NULL, "
"url TEXT NOT NULL);"));
execute(query);
}
void BookmarkDB::addBookmark(const QString &title, const QUrl &url) const
{
QSqlQuery query;
query = prepare("INSERT INTO Bookmarks "
"(title, url) "
"VALUES (:title, :url);");
query.bindValue(":title", title);
query.bindValue(":url", url.toString());
execute(query);
}
QMap<QString, QUrl> BookmarkDB::getBookmarks() const
{
QSqlQuery query = prepare(QString("SELECT title, url FROM Bookmarks;"));
QMap<QString, QUrl> bookmarks;
if (!execute(query))
return bookmarks;
while (query.next()) {
if (query.value(0) != Invalid && query.value(1) != Invalid) {
bookmarks[query.value(0).toString()] = query.value(1).toUrl();
}
}
return bookmarks;
}