Store connection configuration as key value pairs

Add migration for the sqlite database.
Because the Qt SQL library is a bit hard to work with use sqlite through custom wrapper.
This commit is contained in:
eelke 2025-02-22 19:59:24 +01:00
parent 4caccf1000
commit aac55b0ed1
17 changed files with 276439 additions and 384 deletions

View file

@ -5,7 +5,6 @@
#------------------------------------------------- #-------------------------------------------------
QT -= gui QT -= gui
QT += sql
TARGET = core TARGET = core
TEMPLATE = lib TEMPLATE = lib
@ -21,16 +20,13 @@ error( "Couldn't find the common.pri file!" )
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
SOURCES += my_boost_assert_handler.cpp \ SOURCES += my_boost_assert_handler.cpp \
KeyStrengthener.cpp \
SqlLexer.cpp \ SqlLexer.cpp \
PasswordManager.cpp \
CsvWriter.cpp \ CsvWriter.cpp \
BackupFormatModel.cpp \ BackupFormatModel.cpp \
ExplainTreeModelItem.cpp \ ExplainTreeModelItem.cpp \
jsoncpp.cpp jsoncpp.cpp
HEADERS += PasswordManager.h \ HEADERS += \
KeyStrengthener.h \
SqlLexer.h \ SqlLexer.h \
ScopeGuard.h \ ScopeGuard.h \
CsvWriter.h \ CsvWriter.h \

View file

@ -2,11 +2,10 @@
#include "MasterController.h" #include "MasterController.h"
#include "ConnectionManagerWindow.h" #include "ConnectionManagerWindow.h"
#include "ConnectionListModel.h" #include "ConnectionListModel.h"
#include "PasswordManager.h" #include "utils/PasswordManager.h"
#include "DatabaseWindow.h" #include "DatabaseWindow.h"
#include "BackupDialog.h" #include "BackupDialog.h"
#include "PasswordPromptDialog.h" #include "PasswordPromptDialog.h"
#include "ScopeGuard.h"
#include "ConnectionConfigurationWidget.h" #include "ConnectionConfigurationWidget.h"
#include <QSqlQuery> #include <QSqlQuery>
#include <QInputDialog> #include <QInputDialog>
@ -133,11 +132,14 @@ void ConnectionController::addGroup()
auto result = QInputDialog::getText(nullptr, tr("Add new connection group"), auto result = QInputDialog::getText(nullptr, tr("Add new connection group"),
tr("Group name")); tr("Group name"));
if (!result.isEmpty()) { if (!result.isEmpty()) {
auto res = m_connectionTreeModel->addGroup(result); try
if (std::holds_alternative<QSqlError>(res)) { {
m_connectionTreeModel->addGroup(result);
}
catch (const SQLiteException &ex) {
QMessageBox::critical(nullptr, tr("Add group failed"), QMessageBox::critical(nullptr, tr("Add group failed"),
tr("Failed to add group.\n") + tr("Failed to add group.\n") +
std::get<QSqlError>(res).text()); QString(ex.what()));
} }
} }
} }
@ -236,19 +238,11 @@ bool ConnectionController::decodeConnectionPassword(QUuid id, QByteArray encoded
void ConnectionController::resetPasswordManager() void ConnectionController::resetPasswordManager()
{ {
auto&& user_cfg_db = m_masterController->userConfigDatabase(); SQLiteConnection& user_cfg_db = m_masterController->userConfigDatabase();
user_cfg_db.transaction(); SQLiteTransaction tx(user_cfg_db);
try m_passwordManager->resetMasterPassword(user_cfg_db);
{ m_connectionTreeModel->clearAllPasswords();
m_passwordManager->resetMasterPassword(user_cfg_db); tx.Commit();
m_connectionTreeModel->clearAllPasswords();
user_cfg_db.commit();
}
catch (...)
{
user_cfg_db.rollback();
throw;
}
} }
bool ConnectionController::UnlockPasswordManagerIfNeeded() bool ConnectionController::UnlockPasswordManagerIfNeeded()

View file

@ -56,19 +56,12 @@ SELECT migration_id
FROM _migration;)__"; FROM _migration;)__";
const char * const q_insert_or_replace_into_connection =
R"__(INSERT OR REPLACE INTO connection
VALUES (:uuid, :name, :conngroup_id, :host, :hostaddr, :port, :user, :dbname,
:sslmode, :sslcert, :sslkey, :sslrootcert, :sslcrl, :password);
)__" ;
// Keeping migration function name and id DRY // Keeping migration function name and id DRY
#define APPLY_MIGRATION(id) ApplyMigration(#id, &MigrationDirector::id) #define APPLY_MIGRATION(id) ApplyMigration(#id, &MigrationDirector::id)
class MigrationDirector { class MigrationDirector {
public: public:
explicit MigrationDirector(QSqlDatabase &db) explicit MigrationDirector(SQLiteConnection &db)
: db(db) : db(db)
{ {
} }
@ -81,12 +74,12 @@ R"__(INSERT OR REPLACE INTO connection
} }
private: private:
QSqlDatabase &db; SQLiteConnection &db;
std::unordered_set<QString> present; std::unordered_set<QString> present;
void M20250215_0933_Parameters() void M20250215_0933_Parameters()
{ {
Exec(R"__( db.Exec(R"__(
CREATE TABLE connection_parameter ( CREATE TABLE connection_parameter (
connection_uuid TEXT, connection_uuid TEXT,
pname TEXT, pname TEXT,
@ -95,16 +88,29 @@ CREATE TABLE connection_parameter (
PRIMARY KEY(connection_uuid, pname) PRIMARY KEY(connection_uuid, pname)
);)__"); );)__");
db.Exec(R"__(
INSERT INTO connection_parameter (connection_uuid, pname, pvalue)
SELECT uuid, 'sslmode' AS pname, CASE
WHEN sslmode = '0' THEN 'disable'
WHEN sslmode = '1' THEN 'allow'
WHEN sslmode = '2' THEN 'prefer'
WHEN sslmode = '3' THEN 'require'
WHEN sslmode = '4' THEN 'verify_ca'
WHEN sslmode = '5' THEN 'verify_full'
END AS pvalue
FROM connection
WHERE sslmode is not null and sslmode between 0 and 5)__");
for (QString key : { "host", "hostaddr", "user", "dbname", "sslmode", "sslcert", "sslkey", "sslrootcert", "sslcrl" })
for (QString key : { "host", "hostaddr", "user", "dbname", "sslcert", "sslkey", "sslrootcert", "sslcrl" })
{ {
Exec( db.Exec(
"INSERT INTO connection_parameter (connection_uuid, pname, pvalue)" "INSERT INTO connection_parameter (connection_uuid, pname, pvalue)"
" SELECT uuid, '" % key % "', " % key % "\n" " SELECT uuid, '" % key % "', " % key % "\n"
" FROM connection\n" " FROM connection\n"
" WHERE " % key % " IS NOT NULL and " % key % " <> '';"); " WHERE " % key % " IS NOT NULL and " % key % " <> '';");
} }
Exec(R"__( db.Exec(R"__(
INSERT INTO connection_parameter (connection_uuid, pname, pvalue) INSERT INTO connection_parameter (connection_uuid, pname, pvalue)
SELECT uuid, 'port', port SELECT uuid, 'port', port
FROM connection FROM connection
@ -114,118 +120,76 @@ INSERT INTO connection_parameter (connection_uuid, pname, pvalue)
for (QString column : { "host", "hostaddr", "user", "dbname", "sslmode", "sslcert", "sslkey", "sslrootcert", "sslcrl", "port" }) for (QString column : { "host", "hostaddr", "user", "dbname", "sslmode", "sslcert", "sslkey", "sslrootcert", "sslcrl", "port" })
{ {
// sqlite does not seem to support dropping more then one column per alter table // sqlite does not seem to support dropping more then one column per alter table
Exec("ALTER TABLE connection DROP COLUMN " % column % ";"); db.Exec("ALTER TABLE connection DROP COLUMN " % column % ";");
} }
} }
void Exec(QString query)
{
QSqlQuery q(query, db);
Verify(q);
}
void ApplyMigration(QString migration_id, void (MigrationDirector::*func)()) void ApplyMigration(QString migration_id, void (MigrationDirector::*func)())
{ {
if (!present.contains(migration_id)) if (!present.contains(migration_id))
{ {
if (!db.transaction()) SQLiteTransaction tx(db);
{
throw std::runtime_error("Failed to start transaction on user configuration database");
}
(this->*func)(); (this->*func)();
RegisterMigration(migration_id); RegisterMigration(migration_id);
if (!db.commit()) tx.Commit();
{
db.rollback();
throw std::runtime_error("Failed to commit transaction on user configuration database");
}
} }
} }
std::unordered_set<QString> LoadMigrations() std::unordered_set<QString> LoadMigrations()
{ {
std::unordered_set<QString> result; std::unordered_set<QString> result;
QSqlQuery q(q_load_migrations_present, db);
Verify(q); auto stmt = db.Prepare(q_load_migrations_present);
while (q.next()) while (stmt.Step())
{ {
result.insert(q.value(0).toString()); result.insert(stmt.ColumnText(0));
} }
return result; return result;
} }
void RegisterMigration(QString migrationId) void RegisterMigration(QString migrationId)
{ {
const char * const q_register_migration = auto stmt = db.Prepare("INSERT INTO _migration VALUES (?1);");
R"__(INSERT INTO _migration VALUES (:id);)__" ; stmt.Bind(1, migrationId);
stmt.Step();
QSqlQuery q(db);
q.prepare(q_register_migration);
q.bindValue(":id", migrationId);
if (!q.exec()) {
Verify(q);
}
}
void Verify(QSqlQuery &q)
{
auto err = q.lastError();
if (err.type() == QSqlError::NoError)
return;
db.rollback();
QString errString = err.text();
throw std::runtime_error(errString.toStdString());
} }
void InitConnectionTables() void InitConnectionTables()
{ {
// Original schema // Original schema
QSqlQuery q_create_table(db); db.Exec(q_create_table_conngroup);
q_create_table.exec(q_create_table_conngroup); db.Exec(q_create_table_connection);
Verify(q_create_table);
q_create_table.exec(q_create_table_connection);
Verify(q_create_table);
// Start using migrations // Start using migrations
q_create_table.exec(q_create_table_migrations); db.Exec(q_create_table_migrations);
Verify(q_create_table);
} }
}; };
std::optional<QSqlError> SaveConnectionConfig(QSqlDatabase &db, const ConnectionConfig &cc, int conngroup_id) void SaveConnectionConfig(SQLiteConnection &db, const ConnectionConfig &cc, int conngroup_id)
{ {
QSqlQuery q(db); const char * const q_insert_or_replace_into_connection =
q.prepare(q_insert_or_replace_into_connection); R"__(INSERT OR REPLACE INTO connection
q.bindValue(":uuid", cc.uuid().toString()); VALUES (?1, ?2, ?3, ?4);
q.bindValue(":name", cc.name()); )__" ;
q.bindValue(":conngroup_id", conngroup_id);
q.bindValue(":host", cc.host());
q.bindValue(":hostaddr", cc.hostAddr());
q.bindValue(":port", (int)cc.port());
q.bindValue(":user", cc.user());
q.bindValue(":dbname", cc.dbname());
q.bindValue(":sslmode", static_cast<int>(cc.sslMode()));
q.bindValue(":sslcert", cc.sslCert());
q.bindValue(":sslkey", cc.sslKey());
q.bindValue(":sslrootcert", cc.sslRootCert());
q.bindValue(":sslcrl", cc.sslCrl());
auto& encodedPassword = cc.encodedPassword();
if (encodedPassword.isEmpty())
q.bindValue(":password", QVariant());
else
q.bindValue(":password", encodedPassword);
if (!q.exec()) { QByteArray b64; // needs to stay in scope until query is executed
auto sql_error = q.lastError(); SQLiteTransaction tx(db);
return { sql_error }; SQLitePreparedStatement stmt = db.Prepare(q_insert_or_replace_into_connection);
} stmt.Bind(1, cc.uuid().toString());
return {}; stmt.Bind(2, cc.name());
stmt.Bind(3, conngroup_id);
auto& encodedPassword = cc.encodedPassword();
if (!encodedPassword.isEmpty())
{
b64 = encodedPassword.toBase64(QByteArray::Base64Encoding);
stmt.Bind(4, b64.data(), b64.length());
}
stmt.Step();
} }
} // end of unnamed namespace } // end of unnamed namespace
ConnectionTreeModel::ConnectionTreeModel(QObject *parent, QSqlDatabase &db) ConnectionTreeModel::ConnectionTreeModel(QObject *parent, SQLiteConnection &db)
: QAbstractItemModel(parent) : QAbstractItemModel(parent)
, m_db(db) , m_db(db)
{ {
@ -237,56 +201,61 @@ void ConnectionTreeModel::load()
MigrationDirector md(m_db); MigrationDirector md(m_db);
md.Execute(); md.Execute();
QSqlQuery q(m_db); loadGroups();
q.prepare("SELECT conngroup_id, gname FROM conngroup;"); loadConnections();
if (!q.exec()) { }
// auto err = q_create_table.lastError();
// return { false, err };
throw std::runtime_error("Loading groups failed");
}
while (q.next()) {
int id = q.value(0).toInt();
QString name = q.value(1).toString();
auto g = std::make_shared<ConnectionGroup>(); void ConnectionTreeModel::loadGroups()
g->conngroup_id = id; {
g->name = name; auto stmt = m_db.Prepare("SELECT conngroup_id, gname FROM conngroup;");
m_groups.push_back(g); while (stmt.Step())
} {
auto g = std::make_shared<ConnectionGroup>();
g->conngroup_id = stmt.ColumnInteger(0);
g->name = stmt.ColumnText(1);
m_groups.push_back(g);
}
}
q.prepare("SELECT uuid, cname, conngroup_id, password " void ConnectionTreeModel::loadConnections()
"FROM connection ORDER BY conngroup_id, cname;"); {
if (!q.exec()) { auto stmt = m_db.Prepare(
// auto err = q_create_table.lastError(); "SELECT uuid, cname, conngroup_id, password "
// return { false, err }; "FROM connection ORDER BY conngroup_id, cname;");
throw std::runtime_error("Loading groups failed");
}
while (q.next()) {
auto cc = std::make_shared<ConnectionConfig>();
cc->setUuid(q.value(0).toUuid());
cc->setName(q.value(1).toString());
cc->setHost(q.value(3).toString());
cc->setHostAddr(q.value(4).toString());
cc->setPort(static_cast<uint16_t>(q.value(5).toInt()));
cc->setUser(q.value(6).toString());
cc->setDbname(q.value(7).toString());
cc->setSslMode(static_cast<SslMode>(q.value(8).toInt()));
cc->setSslCert(q.value(9).toString());
cc->setSslKey(q.value(10).toString());
cc->setSslRootCert(q.value(11).toString());
cc->setSslCrl(q.value(12).toString());
cc->setEncodedPassword(q.value(13).toByteArray());
int group_id = q.value(2).toInt(); while (stmt.Step()) {
auto find_res = std::find_if(m_groups.begin(), m_groups.end(), auto cc = std::make_shared<ConnectionConfig>();
[group_id] (auto item) { return item->conngroup_id == group_id; }); cc->setUuid(QUuid::fromString(stmt.ColumnText(0)));
if (find_res != m_groups.end()) { cc->setName(stmt.ColumnText(1));
(*find_res)->add(cc); cc->setEncodedPassword(QByteArray::fromBase64(stmt.ColumnCharPtr(3), QByteArray::Base64Encoding));
} loadConnectionParameters(*cc);
else {
throw std::runtime_error("conngroup missing"); int group_id = stmt.ColumnInteger(2);
} auto find_res = std::find_if(m_groups.begin(), m_groups.end(),
} [group_id] (auto item) { return item->conngroup_id == group_id; });
if (find_res != m_groups.end()) {
(*find_res)->add(cc);
}
else {
throw std::runtime_error("conngroup missing");
}
}
}
void ConnectionTreeModel::loadConnectionParameters(ConnectionConfig &cc)
{
auto stmt = m_db.Prepare(
"SELECT pname, pvalue \n"
"FROM connection_parameter\n"
"WHERE connection_uuid=?1");
stmt.Bind(1, cc.uuid().toString());
while (stmt.Step())
{
cc.setParameter(
stmt.ColumnText(0),
stmt.ColumnText(1)
);
}
} }
QVariant ConnectionTreeModel::data(const QModelIndex &index, int role) const QVariant ConnectionTreeModel::data(const QModelIndex &index, int role) const
@ -408,15 +377,11 @@ bool ConnectionTreeModel::removeRows(int row, int count, const QModelIndex &pare
auto grp = m_groups[parent.row()]; auto grp = m_groups[parent.row()];
for (int i = 0; i < count; ++i) { for (int i = 0; i < count; ++i) {
QUuid uuid = grp->connections().at(row + i)->uuid(); QUuid uuid = grp->connections().at(row + i)->uuid();
QSqlQuery q(m_db); auto stmt = m_db.Prepare(
q.prepare(
"DELETE FROM connection " "DELETE FROM connection "
" WHERE uuid=:uuid"); " WHERE uuid=?0");
q.bindValue(":uuid", uuid); stmt.Bind(0, uuid.toString());
if (!q.exec()) { stmt.Step();
auto err = q.lastError();
throw std::runtime_error("QqlError");
}
} }
beginRemoveRows(parent, row, row + count - 1); beginRemoveRows(parent, row, row + count - 1);
SCOPE_EXIT { endRemoveRows(); }; SCOPE_EXIT { endRemoveRows(); };
@ -454,14 +419,8 @@ void ConnectionTreeModel::save(const QString &group_name, const ConnectionConfig
// We assume the model is in sync with the DB as the DB should not be shared! // We assume the model is in sync with the DB as the DB should not be shared!
int new_grp_idx = findGroup(group_name); int new_grp_idx = findGroup(group_name);
if (new_grp_idx < 0) { if (new_grp_idx < 0) {
// Group not found we are g // Group not found we are g
auto add_grp_res = addGroup(group_name); new_grp_idx = addGroup(group_name);
if (std::holds_alternative<int>(add_grp_res)) {
new_grp_idx = std::get<int>(add_grp_res);
}
else {
throw std::runtime_error("SqlError1");
}
} }
auto new_grp = m_groups[new_grp_idx]; auto new_grp = m_groups[new_grp_idx];
@ -470,15 +429,8 @@ void ConnectionTreeModel::save(const QString &group_name, const ConnectionConfig
beginInsertRows(parent, idx, idx); beginInsertRows(parent, idx, idx);
SCOPE_EXIT { endInsertRows(); }; SCOPE_EXIT { endInsertRows(); };
auto node = std::make_shared<ConnectionConfig>(cc); auto node = std::make_shared<ConnectionConfig>(cc);
new_grp->add(node); new_grp->add(node);
auto save_res = saveToDb(*node); saveToDb(*node);
if (save_res) {
QString msg = save_res->text()
% "\n" % save_res->driverText()
% "\n" % save_res->databaseText();
throw std::runtime_error(msg.toUtf8().data());
}
} }
void ConnectionTreeModel::save(const ConnectionConfig &cc) void ConnectionTreeModel::save(const ConnectionConfig &cc)
@ -523,17 +475,13 @@ int ConnectionTreeModel::findGroup(const QString &name) const
return -1; return -1;
} }
std::variant<int, QSqlError> ConnectionTreeModel::addGroup(const QString &group_name) int ConnectionTreeModel::addGroup(const QString &group_name)
{ {
QSqlQuery q(m_db); auto stmt = m_db.Prepare("INSERT INTO conngroup (gname) VALUES (?1)");
q.prepare("INSERT INTO conngroup (gname) VALUES (:name)"); stmt.Bind(1, group_name);
q.bindValue(":name", group_name);
if (!q.exec()) { auto cg = std::make_shared<ConnectionGroup>();
auto err = q.lastError(); cg->conngroup_id = m_db.LastInsertRowId();
return { err };
}
auto cg = std::make_shared<ConnectionGroup>();
cg->conngroup_id = q.lastInsertId().toInt();
cg->name = group_name; cg->name = group_name;
int row = m_groups.size(); int row = m_groups.size();
@ -543,27 +491,21 @@ std::variant<int, QSqlError> ConnectionTreeModel::addGroup(const QString &group_
return row; return row;
} }
std::optional<QSqlError> ConnectionTreeModel::removeGroup(int row) void ConnectionTreeModel::removeGroup(int row)
{ {
beginRemoveRows({}, row, row); beginRemoveRows({}, row, row);
SCOPE_EXIT { endRemoveRows(); }; SCOPE_EXIT { endRemoveRows(); };
auto id = m_groups[row]->conngroup_id; auto id = m_groups[row]->conngroup_id;
QSqlQuery q(m_db);
q.prepare("DELETE FROM connection WHERE conngroup_id=:id"); auto stmt = m_db.Prepare("DELETE FROM connection WHERE conngroup_id=?1");
q.bindValue(":id", id); stmt.Bind(1, id);
if (!q.exec()) { stmt.Step();
auto err = q.lastError();
return { err }; stmt = m_db.Prepare("DELETE FROM conngroup WHERE conngroup_id=?1");
} stmt.Bind(1, id);
q.prepare("DELETE FROM conngroup WHERE conngroup_id=:id"); stmt.Step();
q.bindValue(":id", id);
if (!q.exec()) {
auto err = q.lastError();
return { err };
}
m_groups.remove(row); m_groups.remove(row);
return {};
} }
int ConnectionTreeModel::findGroup(int conngroup_id) const int ConnectionTreeModel::findGroup(int conngroup_id) const
@ -591,9 +533,9 @@ ConnectionGroup *ConnectionTreeModel::getGroupFromModelIndex(QModelIndex index)
return dynamic_cast<ConnectionGroup*>(node); return dynamic_cast<ConnectionGroup*>(node);
} }
std::optional<QSqlError> ConnectionTreeModel::saveToDb(const ConnectionConfig &cc) void ConnectionTreeModel::saveToDb(const ConnectionConfig &cc)
{ {
return SaveConnectionConfig(m_db, cc, cc.parent()->conngroup_id); SaveConnectionConfig(m_db, cc, cc.parent()->conngroup_id);
} }

View file

@ -11,8 +11,7 @@
#include <variant> #include <variant>
#include <QVector> #include <QVector>
#include <QSqlError> #include "sqlite/SQLiteConnection.h"
class QSqlDatabase;
class ConnectionTreeModel : public QAbstractItemModel { class ConnectionTreeModel : public QAbstractItemModel {
Q_OBJECT Q_OBJECT
@ -27,7 +26,7 @@ public:
ColCount ColCount
}; };
ConnectionTreeModel(QObject *parent, QSqlDatabase &db); ConnectionTreeModel(QObject *parent, SQLiteConnection &db);
void load(); void load();
@ -61,8 +60,8 @@ public:
void save(const ConnectionConfig &cc); void save(const ConnectionConfig &cc);
void clearAllPasswords(); void clearAllPasswords();
/// Create a new group in the DB and place in the tree /// Create a new group in the DB and place in the tree
std::variant<int, QSqlError> addGroup(const QString &group_name); int addGroup(const QString &group_name);
std::optional<QSqlError> removeGroup(int row); void removeGroup(int row);
int findGroup(int conngroup_id) const; int findGroup(int conngroup_id) const;
static ConnectionConfig* getConfigFromModelIndex(QModelIndex index); static ConnectionConfig* getConfigFromModelIndex(QModelIndex index);
@ -71,7 +70,7 @@ public:
private: private:
using Groups = QVector<std::shared_ptr<ConnectionGroup>>; using Groups = QVector<std::shared_ptr<ConnectionGroup>>;
QSqlDatabase &m_db; SQLiteConnection &m_db;
Groups m_groups; Groups m_groups;
/// Finds the connection with the specified uuid and returns /// Finds the connection with the specified uuid and returns
@ -79,8 +78,11 @@ private:
std::tuple<int, int> findConfig(const QUuid uuid) const; std::tuple<int, int> findConfig(const QUuid uuid) const;
int findGroup(const QString &name) const; int findGroup(const QString &name) const;
std::optional<QSqlError> saveToDb(const ConnectionConfig &cc); void saveToDb(const ConnectionConfig &cc);
void loadGroups();
void loadConnections();
void loadConnectionParameters(ConnectionConfig &cc);
// QAbstractItemModel interface // QAbstractItemModel interface
public: public:
virtual Qt::DropActions supportedDropActions() const override; virtual Qt::DropActions supportedDropActions() const override;

View file

@ -30,15 +30,7 @@ MasterController::~MasterController()
void MasterController::init() void MasterController::init()
{ {
m_userConfigDatabase = QSqlDatabase::addDatabase("QSQLITE"); m_userConfigDatabase.Open(GetUserConfigDatabaseName());
m_userConfigDatabase.setDatabaseName(GetUserConfigDatabaseName());
if (!m_userConfigDatabase.open()) {
qDebug() << "Error: connection with database fail";
}
else {
qDebug() << "Database: connection ok";
}
m_connectionController = new ConnectionController(this); m_connectionController = new ConnectionController(this);
m_connectionController->init(); m_connectionController->init();
@ -62,7 +54,7 @@ ConnectionController *MasterController::connectionController()
return m_connectionController; return m_connectionController;
} }
QSqlDatabase& MasterController::userConfigDatabase() SQLiteConnection& MasterController::userConfigDatabase()
{ {
return m_userConfigDatabase; return m_userConfigDatabase;
} }

View file

@ -2,11 +2,11 @@
#define MASTERCONTROLLER_H #define MASTERCONTROLLER_H
#include <QObject> #include <QObject>
#include <QSqlDatabase>
#include <atomic> #include <atomic>
#include <future> #include <future>
#include <map> #include <map>
#include <memory> #include <memory>
#include "sqlite/SQLiteConnection.h"
class ConnectionController; class ConnectionController;
@ -23,14 +23,14 @@ public:
void init(); void init();
ConnectionController* connectionController(); ConnectionController* connectionController();
QSqlDatabase& userConfigDatabase(); SQLiteConnection& userConfigDatabase();
signals: signals:
public slots: public slots:
private: private:
QSqlDatabase m_userConfigDatabase; SQLiteConnection m_userConfigDatabase;
ConnectionController* m_connectionController = nullptr; ConnectionController* m_connectionController = nullptr;
}; };

View file

@ -19,10 +19,10 @@ namespace {
{ SslMode::verify_full, "verify-full" } { SslMode::verify_full, "verify-full" }
}; };
inline const char *valuePtr(const std::string &v) // inline const char *valuePtr(const std::string &v)
{ // {
return v.empty() ? nullptr : v.c_str(); // return v.empty() ? nullptr : v.c_str();
} // }
struct { struct {
const char * host = "host"; const char * host = "host";
@ -46,17 +46,16 @@ QString SslModeToString(SslMode sm)
if (e.mode == sm) if (e.mode == sm)
return QString::fromUtf8(e.string); return QString::fromUtf8(e.string);
return {}; return {};
} }
SslMode StringToSslMode(QString s) SslMode StringToSslMode(QString s)
{ {
SslMode result = SslMode::allow;
for (auto e : SslModeStringTable) for (auto e : SslModeStringTable)
if (e.string == s) if (e.string == s)
result = e.mode; return e.mode;
return {}; return SslMode::allow;
} }
ConnectionConfig::ConnectionConfig() ConnectionConfig::ConnectionConfig()
@ -297,46 +296,11 @@ QString ConnectionConfig::connectionString() const
// maybe we should prevent empty parameters from staying in the map? // maybe we should prevent empty parameters from staying in the map?
if (!param.second.isEmpty()) if (!param.second.isEmpty())
{ {
if (!s.isEmpty())
s += " ";
s += param.first % "=" % escapeConnectionStringValue(param.second); s += param.first % "=" % escapeConnectionStringValue(param.second);
} }
} }
// s += "host="
// % escapeConnectionStringValue(m_host)
// % " port="
// % QString::number(m_port)
// % " user="
// % escapeConnectionStringValue(m_user);
// s += " password=";
// s += escapeConnectionStringValue(m_password);
// s += " dbname=";
// s += escapeConnectionStringValue(m_dbname);
// s += " sslmode=";
// s += SslModeToString(m_sslMode);
// if (!m_sslCert.isEmpty())
// {
// s += " sslcert=";
// s += escapeConnectionStringValue(m_sslCert);
// }
// if (!m_sslKey.isEmpty())
// {
// s += " sslkey=";
// s += escapeConnectionStringValue(m_sslKey);
// }
// if (!m_sslRootCert.isEmpty())
// {
// s += " sslrootcrt=";
// s += escapeConnectionStringValue(m_sslRootCert);
// }
// if (!m_sslCrl.isEmpty())
// {
// s += " sslCrl=";
// s += escapeConnectionStringValue(m_sslCrl);
// }
// s += " client_encoding=utf8";
// s += " application_name=";
// s += escapeConnectionStringValue(m_applicationName);
return s; return s;
} }

View file

@ -45,6 +45,8 @@ SOURCES += \
catalog/PgConstraintContainer.cpp \ catalog/PgConstraintContainer.cpp \
ParamListJson.cpp \ ParamListJson.cpp \
ParamListModel.cpp \ ParamListModel.cpp \
sqlite/SQLiteConnection.cpp \
sqlite/sqlite3.c \
ui/catalog/tables/TableNode.cpp \ ui/catalog/tables/TableNode.cpp \
ui/catalog/tables/TableSize.cpp \ ui/catalog/tables/TableSize.cpp \
ui/catalog/tables/TableTreeBuilder.cpp \ ui/catalog/tables/TableTreeBuilder.cpp \
@ -89,6 +91,8 @@ SOURCES += \
catalog/PgSequence.cpp \ catalog/PgSequence.cpp \
catalog/PgSequenceContainer.cpp \ catalog/PgSequenceContainer.cpp \
utils/HumanReadableBytes.cpp \ utils/HumanReadableBytes.cpp \
utils/KeyStrengthener.cpp \
utils/PasswordManager.cpp \
utils/PostgresqlUrlParser.cpp utils/PostgresqlUrlParser.cpp
HEADERS += \ HEADERS += \
@ -118,6 +122,9 @@ HEADERS += \
catalog/PgConstraintContainer.h \ catalog/PgConstraintContainer.h \
ParamListJson.h \ ParamListJson.h \
ParamListModel.h \ ParamListModel.h \
sqlite/SQLiteConnection.h \
sqlite/sqlite3.h \
sqlite/sqlite3ext.h \
ui/catalog/tables/TableNode.h \ ui/catalog/tables/TableNode.h \
ui/catalog/tables/TableSize.h \ ui/catalog/tables/TableSize.h \
ui/catalog/tables/TableTreeBuilder.h \ ui/catalog/tables/TableTreeBuilder.h \
@ -166,6 +173,8 @@ HEADERS += \
catalog/PgSequence.h \ catalog/PgSequence.h \
catalog/PgSequenceContainer.h \ catalog/PgSequenceContainer.h \
utils/HumanReadableBytes.h \ utils/HumanReadableBytes.h \
utils/KeyStrengthener.h \
utils/PasswordManager.h \
utils/PostgresqlUrlParser.h utils/PostgresqlUrlParser.h
unix { unix {

View file

@ -0,0 +1,159 @@
#include "SQLiteConnection.h"
SQLitePreparedStatement::SQLitePreparedStatement(SQLitePreparedStatement &&rhs)
: pStatement(rhs.pStatement)
{
rhs.pStatement = nullptr;
}
SQLitePreparedStatement &SQLitePreparedStatement::operator=(SQLitePreparedStatement &&rhs)
{
Free();
pStatement = rhs.pStatement;
rhs.pStatement = nullptr;
return *this;
}
SQLitePreparedStatement::~SQLitePreparedStatement()
{
Free();
}
void SQLitePreparedStatement::Open(SQLiteConnection &db, const char *query)
{
int result = sqlite3_prepare_v2(
db.pDb,
query,
-1,
&pStatement,
nullptr);
db.CheckResult(result);
}
void SQLitePreparedStatement::Open(SQLiteConnection &db, const QString &query)
{
Open(db, query.toUtf8().constData());
}
void SQLitePreparedStatement::Bind(int index, const char *s, int length)
{
int result = sqlite3_bind_text(pStatement, index, s, length, SQLITE_STATIC);
if (result != SQLITE_OK)
throw SQLiteException("failed to bind");
}
void SQLitePreparedStatement::Bind(int index, const QString &s)
{
int result = sqlite3_bind_text16(pStatement, index, s.constData(), -1, SQLITE_TRANSIENT);
if (result != SQLITE_OK)
throw SQLiteException("failed to bind");
}
void SQLitePreparedStatement::Bind(int index, int v)
{
int result = sqlite3_bind_int(pStatement, index, v);
if (result != SQLITE_OK)
throw SQLiteException("failed to bind");
}
const char *SQLitePreparedStatement::ColumnCharPtr(int col)
{
return (const char*)sqlite3_column_text(pStatement, col);
}
QString SQLitePreparedStatement::ColumnText(int col)
{
const unsigned char *val = sqlite3_column_text(pStatement, col);
if (val != nullptr)
{
return QString::fromUtf8(val);
}
return {};
}
int SQLitePreparedStatement::ColumnInteger(int col)
{
return sqlite3_column_int(pStatement, col);
}
bool SQLitePreparedStatement::Step()
{
int result = sqlite3_step(pStatement);
switch (result)
{
case SQLITE_ROW:
return true;
case SQLITE_DONE:
return false;
default:
throw std::runtime_error("Error in step");
}
}
SQLiteConnection::SQLiteConnection(SQLiteConnection &&rhs)
: pDb(rhs.pDb)
{
rhs.pDb = nullptr;
}
SQLiteConnection &SQLiteConnection::operator=(SQLiteConnection &&rhs)
{
if (pDb != nullptr)
{
sqlite3_close(pDb);
}
pDb = rhs.pDb;
rhs.pDb = nullptr;
return *this;
}
SQLiteTransaction::SQLiteTransaction(SQLiteConnection &db)
: db(db)
{
SQLitePreparedStatement stmt = db.Prepare("BEGIN TRANSACTION;");
stmt.Step();
inTransaction = true;
}
SQLiteTransaction::~SQLiteTransaction()
{
if (inTransaction)
{
UncheckedRollback();
}
}
void SQLiteTransaction::Commit()
{
if (inTransaction)
{
SQLitePreparedStatement stmt = db.Prepare("COMMIT TRANSACTION;");
stmt.Step();
inTransaction = false;
}
else
{
throw SQLiteException("Transaction already ended or never started");
}
}
void SQLiteTransaction::Rollback()
{
if (inTransaction)
{
UncheckedRollback();
}
else
{
throw SQLiteException("Transaction already ended or never started");
}
}
void SQLiteTransaction::UncheckedRollback()
{
SQLitePreparedStatement stmt = db.Prepare("ROLLBACK TRANSACTION;");
stmt.Step();
inTransaction = false;
}

View file

@ -0,0 +1,156 @@
#pragma once
#include "sqlite3.h"
#include <qstring.h>
#include <stdexcept>
class SQLiteException : public std::runtime_error
{
public:
explicit SQLiteException(const char* msg)
: std::runtime_error(msg)
{}
};
class SQLiteConnection;
class SQLitePreparedStatement
{
public:
SQLitePreparedStatement() = default;
SQLitePreparedStatement(const SQLitePreparedStatement &) = delete;
SQLitePreparedStatement(SQLitePreparedStatement&& rhs);
SQLitePreparedStatement &operator=(SQLitePreparedStatement&& rhs);
~SQLitePreparedStatement();
void Open(SQLiteConnection &db, const char *query);
void Open(SQLiteConnection &db, const QString &query);
void Bind(int index, const char *s, int length = 0);
void Bind(int index, const QString &s);
void Bind(int index, int v);
const char* ColumnCharPtr(int col);
QString ColumnText(int col);
int ColumnInteger(int col);
bool Step();
void Reset()
{
sqlite3_reset(pStatement);
}
private:
sqlite3_stmt *pStatement = nullptr;
void Free()
{
if (pStatement != nullptr)
{
sqlite3_finalize(pStatement);
pStatement = nullptr;
}
}
};
class SQLiteTransaction
{
public:
explicit SQLiteTransaction(SQLiteConnection &db);
SQLiteTransaction(const SQLiteTransaction&&) = delete;
~SQLiteTransaction();
void Commit();
void Rollback();
private:
SQLiteConnection &db;
bool inTransaction = false;
void UncheckedRollback();
};
class SQLiteConnection
{
public:
SQLiteConnection() = default;
SQLiteConnection(const SQLiteConnection&) = delete;
SQLiteConnection(SQLiteConnection&& rhs);
SQLiteConnection& operator=(const SQLiteConnection &) = delete;
SQLiteConnection& operator=(SQLiteConnection && rhs);
~SQLiteConnection()
{
if (pDb)
{
sqlite3_close(pDb);
}
}
void Open(const char *filename)
{
int result = sqlite3_open(filename, &pDb);
CheckResult(result);
}
void Open(QString filename)
{
int result = sqlite3_open16((void*)filename.data(), &pDb);
CheckResult(result);
}
void CheckResult(int result)
{
if (result == SQLITE_OK)
return;
if (pDb == nullptr)
{
const char * msg = sqlite3_errstr(result);
throw SQLiteException(msg);
}
const char * msg = sqlite3_errmsg(pDb);
throw SQLiteException(msg);
}
SQLitePreparedStatement Prepare(const char* query)
{
SQLitePreparedStatement stmt;
stmt.Open(*this, query);
return stmt;
}
SQLitePreparedStatement Prepare(const QString &query)
{
SQLitePreparedStatement stmt;
stmt.Open(*this, query);
return stmt;
}
void Exec(const char* query)
{
SQLitePreparedStatement stmt = Prepare(query);
stmt.Step();
}
void Exec(QString query)
{
SQLitePreparedStatement stmt = Prepare(query.toUtf8().constData());
stmt.Step();
}
int64_t LastInsertRowId()
{
return sqlite3_last_insert_rowid(pDb);
}
private:
sqlite3 *pDb = nullptr;
friend class SQLitePreparedStatement;
};

261452
pglablib/sqlite/sqlite3.c Normal file

File diff suppressed because it is too large Load diff

13715
pglablib/sqlite/sqlite3.h Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,719 @@
/*
** 2006 June 7
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** This header file defines the SQLite interface for use by
** shared libraries that want to be imported as extensions into
** an SQLite instance. Shared libraries that intend to be loaded
** as extensions by SQLite should #include this file instead of
** sqlite3.h.
*/
#ifndef SQLITE3EXT_H
#define SQLITE3EXT_H
#include "sqlite3.h"
/*
** The following structure holds pointers to all of the SQLite API
** routines.
**
** WARNING: In order to maintain backwards compatibility, add new
** interfaces to the end of this structure only. If you insert new
** interfaces in the middle of this structure, then older different
** versions of SQLite will not be able to load each other's shared
** libraries!
*/
struct sqlite3_api_routines {
void * (*aggregate_context)(sqlite3_context*,int nBytes);
int (*aggregate_count)(sqlite3_context*);
int (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
int (*bind_double)(sqlite3_stmt*,int,double);
int (*bind_int)(sqlite3_stmt*,int,int);
int (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
int (*bind_null)(sqlite3_stmt*,int);
int (*bind_parameter_count)(sqlite3_stmt*);
int (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
const char * (*bind_parameter_name)(sqlite3_stmt*,int);
int (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
int (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
int (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
int (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
int (*busy_timeout)(sqlite3*,int ms);
int (*changes)(sqlite3*);
int (*close)(sqlite3*);
int (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
int eTextRep,const char*));
int (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
int eTextRep,const void*));
const void * (*column_blob)(sqlite3_stmt*,int iCol);
int (*column_bytes)(sqlite3_stmt*,int iCol);
int (*column_bytes16)(sqlite3_stmt*,int iCol);
int (*column_count)(sqlite3_stmt*pStmt);
const char * (*column_database_name)(sqlite3_stmt*,int);
const void * (*column_database_name16)(sqlite3_stmt*,int);
const char * (*column_decltype)(sqlite3_stmt*,int i);
const void * (*column_decltype16)(sqlite3_stmt*,int);
double (*column_double)(sqlite3_stmt*,int iCol);
int (*column_int)(sqlite3_stmt*,int iCol);
sqlite_int64 (*column_int64)(sqlite3_stmt*,int iCol);
const char * (*column_name)(sqlite3_stmt*,int);
const void * (*column_name16)(sqlite3_stmt*,int);
const char * (*column_origin_name)(sqlite3_stmt*,int);
const void * (*column_origin_name16)(sqlite3_stmt*,int);
const char * (*column_table_name)(sqlite3_stmt*,int);
const void * (*column_table_name16)(sqlite3_stmt*,int);
const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
const void * (*column_text16)(sqlite3_stmt*,int iCol);
int (*column_type)(sqlite3_stmt*,int iCol);
sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
int (*complete)(const char*sql);
int (*complete16)(const void*sql);
int (*create_collation)(sqlite3*,const char*,int,void*,
int(*)(void*,int,const void*,int,const void*));
int (*create_collation16)(sqlite3*,const void*,int,void*,
int(*)(void*,int,const void*,int,const void*));
int (*create_function)(sqlite3*,const char*,int,int,void*,
void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
void (*xStep)(sqlite3_context*,int,sqlite3_value**),
void (*xFinal)(sqlite3_context*));
int (*create_function16)(sqlite3*,const void*,int,int,void*,
void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
void (*xStep)(sqlite3_context*,int,sqlite3_value**),
void (*xFinal)(sqlite3_context*));
int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
int (*data_count)(sqlite3_stmt*pStmt);
sqlite3 * (*db_handle)(sqlite3_stmt*);
int (*declare_vtab)(sqlite3*,const char*);
int (*enable_shared_cache)(int);
int (*errcode)(sqlite3*db);
const char * (*errmsg)(sqlite3*);
const void * (*errmsg16)(sqlite3*);
int (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
int (*expired)(sqlite3_stmt*);
int (*finalize)(sqlite3_stmt*pStmt);
void (*free)(void*);
void (*free_table)(char**result);
int (*get_autocommit)(sqlite3*);
void * (*get_auxdata)(sqlite3_context*,int);
int (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
int (*global_recover)(void);
void (*interruptx)(sqlite3*);
sqlite_int64 (*last_insert_rowid)(sqlite3*);
const char * (*libversion)(void);
int (*libversion_number)(void);
void *(*malloc)(int);
char * (*mprintf)(const char*,...);
int (*open)(const char*,sqlite3**);
int (*open16)(const void*,sqlite3**);
int (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
int (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
void (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
void *(*realloc)(void*,int);
int (*reset)(sqlite3_stmt*pStmt);
void (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
void (*result_double)(sqlite3_context*,double);
void (*result_error)(sqlite3_context*,const char*,int);
void (*result_error16)(sqlite3_context*,const void*,int);
void (*result_int)(sqlite3_context*,int);
void (*result_int64)(sqlite3_context*,sqlite_int64);
void (*result_null)(sqlite3_context*);
void (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
void (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
void (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
void (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
void (*result_value)(sqlite3_context*,sqlite3_value*);
void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
int (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
const char*,const char*),void*);
void (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
char * (*xsnprintf)(int,char*,const char*,...);
int (*step)(sqlite3_stmt*);
int (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
char const**,char const**,int*,int*,int*);
void (*thread_cleanup)(void);
int (*total_changes)(sqlite3*);
void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
int (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
sqlite_int64),void*);
void * (*user_data)(sqlite3_context*);
const void * (*value_blob)(sqlite3_value*);
int (*value_bytes)(sqlite3_value*);
int (*value_bytes16)(sqlite3_value*);
double (*value_double)(sqlite3_value*);
int (*value_int)(sqlite3_value*);
sqlite_int64 (*value_int64)(sqlite3_value*);
int (*value_numeric_type)(sqlite3_value*);
const unsigned char * (*value_text)(sqlite3_value*);
const void * (*value_text16)(sqlite3_value*);
const void * (*value_text16be)(sqlite3_value*);
const void * (*value_text16le)(sqlite3_value*);
int (*value_type)(sqlite3_value*);
char *(*vmprintf)(const char*,va_list);
/* Added ??? */
int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
/* Added by 3.3.13 */
int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
int (*clear_bindings)(sqlite3_stmt*);
/* Added by 3.4.1 */
int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
void (*xDestroy)(void *));
/* Added by 3.5.0 */
int (*bind_zeroblob)(sqlite3_stmt*,int,int);
int (*blob_bytes)(sqlite3_blob*);
int (*blob_close)(sqlite3_blob*);
int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
int,sqlite3_blob**);
int (*blob_read)(sqlite3_blob*,void*,int,int);
int (*blob_write)(sqlite3_blob*,const void*,int,int);
int (*create_collation_v2)(sqlite3*,const char*,int,void*,
int(*)(void*,int,const void*,int,const void*),
void(*)(void*));
int (*file_control)(sqlite3*,const char*,int,void*);
sqlite3_int64 (*memory_highwater)(int);
sqlite3_int64 (*memory_used)(void);
sqlite3_mutex *(*mutex_alloc)(int);
void (*mutex_enter)(sqlite3_mutex*);
void (*mutex_free)(sqlite3_mutex*);
void (*mutex_leave)(sqlite3_mutex*);
int (*mutex_try)(sqlite3_mutex*);
int (*open_v2)(const char*,sqlite3**,int,const char*);
int (*release_memory)(int);
void (*result_error_nomem)(sqlite3_context*);
void (*result_error_toobig)(sqlite3_context*);
int (*sleep)(int);
void (*soft_heap_limit)(int);
sqlite3_vfs *(*vfs_find)(const char*);
int (*vfs_register)(sqlite3_vfs*,int);
int (*vfs_unregister)(sqlite3_vfs*);
int (*xthreadsafe)(void);
void (*result_zeroblob)(sqlite3_context*,int);
void (*result_error_code)(sqlite3_context*,int);
int (*test_control)(int, ...);
void (*randomness)(int,void*);
sqlite3 *(*context_db_handle)(sqlite3_context*);
int (*extended_result_codes)(sqlite3*,int);
int (*limit)(sqlite3*,int,int);
sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
const char *(*sql)(sqlite3_stmt*);
int (*status)(int,int*,int*,int);
int (*backup_finish)(sqlite3_backup*);
sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
int (*backup_pagecount)(sqlite3_backup*);
int (*backup_remaining)(sqlite3_backup*);
int (*backup_step)(sqlite3_backup*,int);
const char *(*compileoption_get)(int);
int (*compileoption_used)(const char*);
int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
void (*xStep)(sqlite3_context*,int,sqlite3_value**),
void (*xFinal)(sqlite3_context*),
void(*xDestroy)(void*));
int (*db_config)(sqlite3*,int,...);
sqlite3_mutex *(*db_mutex)(sqlite3*);
int (*db_status)(sqlite3*,int,int*,int*,int);
int (*extended_errcode)(sqlite3*);
void (*log)(int,const char*,...);
sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
const char *(*sourceid)(void);
int (*stmt_status)(sqlite3_stmt*,int,int);
int (*strnicmp)(const char*,const char*,int);
int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
int (*wal_autocheckpoint)(sqlite3*,int);
int (*wal_checkpoint)(sqlite3*,const char*);
void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
int (*vtab_config)(sqlite3*,int op,...);
int (*vtab_on_conflict)(sqlite3*);
/* Version 3.7.16 and later */
int (*close_v2)(sqlite3*);
const char *(*db_filename)(sqlite3*,const char*);
int (*db_readonly)(sqlite3*,const char*);
int (*db_release_memory)(sqlite3*);
const char *(*errstr)(int);
int (*stmt_busy)(sqlite3_stmt*);
int (*stmt_readonly)(sqlite3_stmt*);
int (*stricmp)(const char*,const char*);
int (*uri_boolean)(const char*,const char*,int);
sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64);
const char *(*uri_parameter)(const char*,const char*);
char *(*xvsnprintf)(int,char*,const char*,va_list);
int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*);
/* Version 3.8.7 and later */
int (*auto_extension)(void(*)(void));
int (*bind_blob64)(sqlite3_stmt*,int,const void*,sqlite3_uint64,
void(*)(void*));
int (*bind_text64)(sqlite3_stmt*,int,const char*,sqlite3_uint64,
void(*)(void*),unsigned char);
int (*cancel_auto_extension)(void(*)(void));
int (*load_extension)(sqlite3*,const char*,const char*,char**);
void *(*malloc64)(sqlite3_uint64);
sqlite3_uint64 (*msize)(void*);
void *(*realloc64)(void*,sqlite3_uint64);
void (*reset_auto_extension)(void);
void (*result_blob64)(sqlite3_context*,const void*,sqlite3_uint64,
void(*)(void*));
void (*result_text64)(sqlite3_context*,const char*,sqlite3_uint64,
void(*)(void*), unsigned char);
int (*strglob)(const char*,const char*);
/* Version 3.8.11 and later */
sqlite3_value *(*value_dup)(const sqlite3_value*);
void (*value_free)(sqlite3_value*);
int (*result_zeroblob64)(sqlite3_context*,sqlite3_uint64);
int (*bind_zeroblob64)(sqlite3_stmt*, int, sqlite3_uint64);
/* Version 3.9.0 and later */
unsigned int (*value_subtype)(sqlite3_value*);
void (*result_subtype)(sqlite3_context*,unsigned int);
/* Version 3.10.0 and later */
int (*status64)(int,sqlite3_int64*,sqlite3_int64*,int);
int (*strlike)(const char*,const char*,unsigned int);
int (*db_cacheflush)(sqlite3*);
/* Version 3.12.0 and later */
int (*system_errno)(sqlite3*);
/* Version 3.14.0 and later */
int (*trace_v2)(sqlite3*,unsigned,int(*)(unsigned,void*,void*,void*),void*);
char *(*expanded_sql)(sqlite3_stmt*);
/* Version 3.18.0 and later */
void (*set_last_insert_rowid)(sqlite3*,sqlite3_int64);
/* Version 3.20.0 and later */
int (*prepare_v3)(sqlite3*,const char*,int,unsigned int,
sqlite3_stmt**,const char**);
int (*prepare16_v3)(sqlite3*,const void*,int,unsigned int,
sqlite3_stmt**,const void**);
int (*bind_pointer)(sqlite3_stmt*,int,void*,const char*,void(*)(void*));
void (*result_pointer)(sqlite3_context*,void*,const char*,void(*)(void*));
void *(*value_pointer)(sqlite3_value*,const char*);
int (*vtab_nochange)(sqlite3_context*);
int (*value_nochange)(sqlite3_value*);
const char *(*vtab_collation)(sqlite3_index_info*,int);
/* Version 3.24.0 and later */
int (*keyword_count)(void);
int (*keyword_name)(int,const char**,int*);
int (*keyword_check)(const char*,int);
sqlite3_str *(*str_new)(sqlite3*);
char *(*str_finish)(sqlite3_str*);
void (*str_appendf)(sqlite3_str*, const char *zFormat, ...);
void (*str_vappendf)(sqlite3_str*, const char *zFormat, va_list);
void (*str_append)(sqlite3_str*, const char *zIn, int N);
void (*str_appendall)(sqlite3_str*, const char *zIn);
void (*str_appendchar)(sqlite3_str*, int N, char C);
void (*str_reset)(sqlite3_str*);
int (*str_errcode)(sqlite3_str*);
int (*str_length)(sqlite3_str*);
char *(*str_value)(sqlite3_str*);
/* Version 3.25.0 and later */
int (*create_window_function)(sqlite3*,const char*,int,int,void*,
void (*xStep)(sqlite3_context*,int,sqlite3_value**),
void (*xFinal)(sqlite3_context*),
void (*xValue)(sqlite3_context*),
void (*xInv)(sqlite3_context*,int,sqlite3_value**),
void(*xDestroy)(void*));
/* Version 3.26.0 and later */
const char *(*normalized_sql)(sqlite3_stmt*);
/* Version 3.28.0 and later */
int (*stmt_isexplain)(sqlite3_stmt*);
int (*value_frombind)(sqlite3_value*);
/* Version 3.30.0 and later */
int (*drop_modules)(sqlite3*,const char**);
/* Version 3.31.0 and later */
sqlite3_int64 (*hard_heap_limit64)(sqlite3_int64);
const char *(*uri_key)(const char*,int);
const char *(*filename_database)(const char*);
const char *(*filename_journal)(const char*);
const char *(*filename_wal)(const char*);
/* Version 3.32.0 and later */
const char *(*create_filename)(const char*,const char*,const char*,
int,const char**);
void (*free_filename)(const char*);
sqlite3_file *(*database_file_object)(const char*);
/* Version 3.34.0 and later */
int (*txn_state)(sqlite3*,const char*);
/* Version 3.36.1 and later */
sqlite3_int64 (*changes64)(sqlite3*);
sqlite3_int64 (*total_changes64)(sqlite3*);
/* Version 3.37.0 and later */
int (*autovacuum_pages)(sqlite3*,
unsigned int(*)(void*,const char*,unsigned int,unsigned int,unsigned int),
void*, void(*)(void*));
/* Version 3.38.0 and later */
int (*error_offset)(sqlite3*);
int (*vtab_rhs_value)(sqlite3_index_info*,int,sqlite3_value**);
int (*vtab_distinct)(sqlite3_index_info*);
int (*vtab_in)(sqlite3_index_info*,int,int);
int (*vtab_in_first)(sqlite3_value*,sqlite3_value**);
int (*vtab_in_next)(sqlite3_value*,sqlite3_value**);
/* Version 3.39.0 and later */
int (*deserialize)(sqlite3*,const char*,unsigned char*,
sqlite3_int64,sqlite3_int64,unsigned);
unsigned char *(*serialize)(sqlite3*,const char *,sqlite3_int64*,
unsigned int);
const char *(*db_name)(sqlite3*,int);
/* Version 3.40.0 and later */
int (*value_encoding)(sqlite3_value*);
/* Version 3.41.0 and later */
int (*is_interrupted)(sqlite3*);
/* Version 3.43.0 and later */
int (*stmt_explain)(sqlite3_stmt*,int);
/* Version 3.44.0 and later */
void *(*get_clientdata)(sqlite3*,const char*);
int (*set_clientdata)(sqlite3*, const char*, void*, void(*)(void*));
};
/*
** This is the function signature used for all extension entry points. It
** is also defined in the file "loadext.c".
*/
typedef int (*sqlite3_loadext_entry)(
sqlite3 *db, /* Handle to the database. */
char **pzErrMsg, /* Used to set error string on failure. */
const sqlite3_api_routines *pThunk /* Extension API function pointers. */
);
/*
** The following macros redefine the API routines so that they are
** redirected through the global sqlite3_api structure.
**
** This header file is also used by the loadext.c source file
** (part of the main SQLite library - not an extension) so that
** it can get access to the sqlite3_api_routines structure
** definition. But the main library does not want to redefine
** the API. So the redefinition macros are only valid if the
** SQLITE_CORE macros is undefined.
*/
#if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
#define sqlite3_aggregate_context sqlite3_api->aggregate_context
#ifndef SQLITE_OMIT_DEPRECATED
#define sqlite3_aggregate_count sqlite3_api->aggregate_count
#endif
#define sqlite3_bind_blob sqlite3_api->bind_blob
#define sqlite3_bind_double sqlite3_api->bind_double
#define sqlite3_bind_int sqlite3_api->bind_int
#define sqlite3_bind_int64 sqlite3_api->bind_int64
#define sqlite3_bind_null sqlite3_api->bind_null
#define sqlite3_bind_parameter_count sqlite3_api->bind_parameter_count
#define sqlite3_bind_parameter_index sqlite3_api->bind_parameter_index
#define sqlite3_bind_parameter_name sqlite3_api->bind_parameter_name
#define sqlite3_bind_text sqlite3_api->bind_text
#define sqlite3_bind_text16 sqlite3_api->bind_text16
#define sqlite3_bind_value sqlite3_api->bind_value
#define sqlite3_busy_handler sqlite3_api->busy_handler
#define sqlite3_busy_timeout sqlite3_api->busy_timeout
#define sqlite3_changes sqlite3_api->changes
#define sqlite3_close sqlite3_api->close
#define sqlite3_collation_needed sqlite3_api->collation_needed
#define sqlite3_collation_needed16 sqlite3_api->collation_needed16
#define sqlite3_column_blob sqlite3_api->column_blob
#define sqlite3_column_bytes sqlite3_api->column_bytes
#define sqlite3_column_bytes16 sqlite3_api->column_bytes16
#define sqlite3_column_count sqlite3_api->column_count
#define sqlite3_column_database_name sqlite3_api->column_database_name
#define sqlite3_column_database_name16 sqlite3_api->column_database_name16
#define sqlite3_column_decltype sqlite3_api->column_decltype
#define sqlite3_column_decltype16 sqlite3_api->column_decltype16
#define sqlite3_column_double sqlite3_api->column_double
#define sqlite3_column_int sqlite3_api->column_int
#define sqlite3_column_int64 sqlite3_api->column_int64
#define sqlite3_column_name sqlite3_api->column_name
#define sqlite3_column_name16 sqlite3_api->column_name16
#define sqlite3_column_origin_name sqlite3_api->column_origin_name
#define sqlite3_column_origin_name16 sqlite3_api->column_origin_name16
#define sqlite3_column_table_name sqlite3_api->column_table_name
#define sqlite3_column_table_name16 sqlite3_api->column_table_name16
#define sqlite3_column_text sqlite3_api->column_text
#define sqlite3_column_text16 sqlite3_api->column_text16
#define sqlite3_column_type sqlite3_api->column_type
#define sqlite3_column_value sqlite3_api->column_value
#define sqlite3_commit_hook sqlite3_api->commit_hook
#define sqlite3_complete sqlite3_api->complete
#define sqlite3_complete16 sqlite3_api->complete16
#define sqlite3_create_collation sqlite3_api->create_collation
#define sqlite3_create_collation16 sqlite3_api->create_collation16
#define sqlite3_create_function sqlite3_api->create_function
#define sqlite3_create_function16 sqlite3_api->create_function16
#define sqlite3_create_module sqlite3_api->create_module
#define sqlite3_create_module_v2 sqlite3_api->create_module_v2
#define sqlite3_data_count sqlite3_api->data_count
#define sqlite3_db_handle sqlite3_api->db_handle
#define sqlite3_declare_vtab sqlite3_api->declare_vtab
#define sqlite3_enable_shared_cache sqlite3_api->enable_shared_cache
#define sqlite3_errcode sqlite3_api->errcode
#define sqlite3_errmsg sqlite3_api->errmsg
#define sqlite3_errmsg16 sqlite3_api->errmsg16
#define sqlite3_exec sqlite3_api->exec
#ifndef SQLITE_OMIT_DEPRECATED
#define sqlite3_expired sqlite3_api->expired
#endif
#define sqlite3_finalize sqlite3_api->finalize
#define sqlite3_free sqlite3_api->free
#define sqlite3_free_table sqlite3_api->free_table
#define sqlite3_get_autocommit sqlite3_api->get_autocommit
#define sqlite3_get_auxdata sqlite3_api->get_auxdata
#define sqlite3_get_table sqlite3_api->get_table
#ifndef SQLITE_OMIT_DEPRECATED
#define sqlite3_global_recover sqlite3_api->global_recover
#endif
#define sqlite3_interrupt sqlite3_api->interruptx
#define sqlite3_last_insert_rowid sqlite3_api->last_insert_rowid
#define sqlite3_libversion sqlite3_api->libversion
#define sqlite3_libversion_number sqlite3_api->libversion_number
#define sqlite3_malloc sqlite3_api->malloc
#define sqlite3_mprintf sqlite3_api->mprintf
#define sqlite3_open sqlite3_api->open
#define sqlite3_open16 sqlite3_api->open16
#define sqlite3_prepare sqlite3_api->prepare
#define sqlite3_prepare16 sqlite3_api->prepare16
#define sqlite3_prepare_v2 sqlite3_api->prepare_v2
#define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
#define sqlite3_profile sqlite3_api->profile
#define sqlite3_progress_handler sqlite3_api->progress_handler
#define sqlite3_realloc sqlite3_api->realloc
#define sqlite3_reset sqlite3_api->reset
#define sqlite3_result_blob sqlite3_api->result_blob
#define sqlite3_result_double sqlite3_api->result_double
#define sqlite3_result_error sqlite3_api->result_error
#define sqlite3_result_error16 sqlite3_api->result_error16
#define sqlite3_result_int sqlite3_api->result_int
#define sqlite3_result_int64 sqlite3_api->result_int64
#define sqlite3_result_null sqlite3_api->result_null
#define sqlite3_result_text sqlite3_api->result_text
#define sqlite3_result_text16 sqlite3_api->result_text16
#define sqlite3_result_text16be sqlite3_api->result_text16be
#define sqlite3_result_text16le sqlite3_api->result_text16le
#define sqlite3_result_value sqlite3_api->result_value
#define sqlite3_rollback_hook sqlite3_api->rollback_hook
#define sqlite3_set_authorizer sqlite3_api->set_authorizer
#define sqlite3_set_auxdata sqlite3_api->set_auxdata
#define sqlite3_snprintf sqlite3_api->xsnprintf
#define sqlite3_step sqlite3_api->step
#define sqlite3_table_column_metadata sqlite3_api->table_column_metadata
#define sqlite3_thread_cleanup sqlite3_api->thread_cleanup
#define sqlite3_total_changes sqlite3_api->total_changes
#define sqlite3_trace sqlite3_api->trace
#ifndef SQLITE_OMIT_DEPRECATED
#define sqlite3_transfer_bindings sqlite3_api->transfer_bindings
#endif
#define sqlite3_update_hook sqlite3_api->update_hook
#define sqlite3_user_data sqlite3_api->user_data
#define sqlite3_value_blob sqlite3_api->value_blob
#define sqlite3_value_bytes sqlite3_api->value_bytes
#define sqlite3_value_bytes16 sqlite3_api->value_bytes16
#define sqlite3_value_double sqlite3_api->value_double
#define sqlite3_value_int sqlite3_api->value_int
#define sqlite3_value_int64 sqlite3_api->value_int64
#define sqlite3_value_numeric_type sqlite3_api->value_numeric_type
#define sqlite3_value_text sqlite3_api->value_text
#define sqlite3_value_text16 sqlite3_api->value_text16
#define sqlite3_value_text16be sqlite3_api->value_text16be
#define sqlite3_value_text16le sqlite3_api->value_text16le
#define sqlite3_value_type sqlite3_api->value_type
#define sqlite3_vmprintf sqlite3_api->vmprintf
#define sqlite3_vsnprintf sqlite3_api->xvsnprintf
#define sqlite3_overload_function sqlite3_api->overload_function
#define sqlite3_prepare_v2 sqlite3_api->prepare_v2
#define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
#define sqlite3_clear_bindings sqlite3_api->clear_bindings
#define sqlite3_bind_zeroblob sqlite3_api->bind_zeroblob
#define sqlite3_blob_bytes sqlite3_api->blob_bytes
#define sqlite3_blob_close sqlite3_api->blob_close
#define sqlite3_blob_open sqlite3_api->blob_open
#define sqlite3_blob_read sqlite3_api->blob_read
#define sqlite3_blob_write sqlite3_api->blob_write
#define sqlite3_create_collation_v2 sqlite3_api->create_collation_v2
#define sqlite3_file_control sqlite3_api->file_control
#define sqlite3_memory_highwater sqlite3_api->memory_highwater
#define sqlite3_memory_used sqlite3_api->memory_used
#define sqlite3_mutex_alloc sqlite3_api->mutex_alloc
#define sqlite3_mutex_enter sqlite3_api->mutex_enter
#define sqlite3_mutex_free sqlite3_api->mutex_free
#define sqlite3_mutex_leave sqlite3_api->mutex_leave
#define sqlite3_mutex_try sqlite3_api->mutex_try
#define sqlite3_open_v2 sqlite3_api->open_v2
#define sqlite3_release_memory sqlite3_api->release_memory
#define sqlite3_result_error_nomem sqlite3_api->result_error_nomem
#define sqlite3_result_error_toobig sqlite3_api->result_error_toobig
#define sqlite3_sleep sqlite3_api->sleep
#define sqlite3_soft_heap_limit sqlite3_api->soft_heap_limit
#define sqlite3_vfs_find sqlite3_api->vfs_find
#define sqlite3_vfs_register sqlite3_api->vfs_register
#define sqlite3_vfs_unregister sqlite3_api->vfs_unregister
#define sqlite3_threadsafe sqlite3_api->xthreadsafe
#define sqlite3_result_zeroblob sqlite3_api->result_zeroblob
#define sqlite3_result_error_code sqlite3_api->result_error_code
#define sqlite3_test_control sqlite3_api->test_control
#define sqlite3_randomness sqlite3_api->randomness
#define sqlite3_context_db_handle sqlite3_api->context_db_handle
#define sqlite3_extended_result_codes sqlite3_api->extended_result_codes
#define sqlite3_limit sqlite3_api->limit
#define sqlite3_next_stmt sqlite3_api->next_stmt
#define sqlite3_sql sqlite3_api->sql
#define sqlite3_status sqlite3_api->status
#define sqlite3_backup_finish sqlite3_api->backup_finish
#define sqlite3_backup_init sqlite3_api->backup_init
#define sqlite3_backup_pagecount sqlite3_api->backup_pagecount
#define sqlite3_backup_remaining sqlite3_api->backup_remaining
#define sqlite3_backup_step sqlite3_api->backup_step
#define sqlite3_compileoption_get sqlite3_api->compileoption_get
#define sqlite3_compileoption_used sqlite3_api->compileoption_used
#define sqlite3_create_function_v2 sqlite3_api->create_function_v2
#define sqlite3_db_config sqlite3_api->db_config
#define sqlite3_db_mutex sqlite3_api->db_mutex
#define sqlite3_db_status sqlite3_api->db_status
#define sqlite3_extended_errcode sqlite3_api->extended_errcode
#define sqlite3_log sqlite3_api->log
#define sqlite3_soft_heap_limit64 sqlite3_api->soft_heap_limit64
#define sqlite3_sourceid sqlite3_api->sourceid
#define sqlite3_stmt_status sqlite3_api->stmt_status
#define sqlite3_strnicmp sqlite3_api->strnicmp
#define sqlite3_unlock_notify sqlite3_api->unlock_notify
#define sqlite3_wal_autocheckpoint sqlite3_api->wal_autocheckpoint
#define sqlite3_wal_checkpoint sqlite3_api->wal_checkpoint
#define sqlite3_wal_hook sqlite3_api->wal_hook
#define sqlite3_blob_reopen sqlite3_api->blob_reopen
#define sqlite3_vtab_config sqlite3_api->vtab_config
#define sqlite3_vtab_on_conflict sqlite3_api->vtab_on_conflict
/* Version 3.7.16 and later */
#define sqlite3_close_v2 sqlite3_api->close_v2
#define sqlite3_db_filename sqlite3_api->db_filename
#define sqlite3_db_readonly sqlite3_api->db_readonly
#define sqlite3_db_release_memory sqlite3_api->db_release_memory
#define sqlite3_errstr sqlite3_api->errstr
#define sqlite3_stmt_busy sqlite3_api->stmt_busy
#define sqlite3_stmt_readonly sqlite3_api->stmt_readonly
#define sqlite3_stricmp sqlite3_api->stricmp
#define sqlite3_uri_boolean sqlite3_api->uri_boolean
#define sqlite3_uri_int64 sqlite3_api->uri_int64
#define sqlite3_uri_parameter sqlite3_api->uri_parameter
#define sqlite3_uri_vsnprintf sqlite3_api->xvsnprintf
#define sqlite3_wal_checkpoint_v2 sqlite3_api->wal_checkpoint_v2
/* Version 3.8.7 and later */
#define sqlite3_auto_extension sqlite3_api->auto_extension
#define sqlite3_bind_blob64 sqlite3_api->bind_blob64
#define sqlite3_bind_text64 sqlite3_api->bind_text64
#define sqlite3_cancel_auto_extension sqlite3_api->cancel_auto_extension
#define sqlite3_load_extension sqlite3_api->load_extension
#define sqlite3_malloc64 sqlite3_api->malloc64
#define sqlite3_msize sqlite3_api->msize
#define sqlite3_realloc64 sqlite3_api->realloc64
#define sqlite3_reset_auto_extension sqlite3_api->reset_auto_extension
#define sqlite3_result_blob64 sqlite3_api->result_blob64
#define sqlite3_result_text64 sqlite3_api->result_text64
#define sqlite3_strglob sqlite3_api->strglob
/* Version 3.8.11 and later */
#define sqlite3_value_dup sqlite3_api->value_dup
#define sqlite3_value_free sqlite3_api->value_free
#define sqlite3_result_zeroblob64 sqlite3_api->result_zeroblob64
#define sqlite3_bind_zeroblob64 sqlite3_api->bind_zeroblob64
/* Version 3.9.0 and later */
#define sqlite3_value_subtype sqlite3_api->value_subtype
#define sqlite3_result_subtype sqlite3_api->result_subtype
/* Version 3.10.0 and later */
#define sqlite3_status64 sqlite3_api->status64
#define sqlite3_strlike sqlite3_api->strlike
#define sqlite3_db_cacheflush sqlite3_api->db_cacheflush
/* Version 3.12.0 and later */
#define sqlite3_system_errno sqlite3_api->system_errno
/* Version 3.14.0 and later */
#define sqlite3_trace_v2 sqlite3_api->trace_v2
#define sqlite3_expanded_sql sqlite3_api->expanded_sql
/* Version 3.18.0 and later */
#define sqlite3_set_last_insert_rowid sqlite3_api->set_last_insert_rowid
/* Version 3.20.0 and later */
#define sqlite3_prepare_v3 sqlite3_api->prepare_v3
#define sqlite3_prepare16_v3 sqlite3_api->prepare16_v3
#define sqlite3_bind_pointer sqlite3_api->bind_pointer
#define sqlite3_result_pointer sqlite3_api->result_pointer
#define sqlite3_value_pointer sqlite3_api->value_pointer
/* Version 3.22.0 and later */
#define sqlite3_vtab_nochange sqlite3_api->vtab_nochange
#define sqlite3_value_nochange sqlite3_api->value_nochange
#define sqlite3_vtab_collation sqlite3_api->vtab_collation
/* Version 3.24.0 and later */
#define sqlite3_keyword_count sqlite3_api->keyword_count
#define sqlite3_keyword_name sqlite3_api->keyword_name
#define sqlite3_keyword_check sqlite3_api->keyword_check
#define sqlite3_str_new sqlite3_api->str_new
#define sqlite3_str_finish sqlite3_api->str_finish
#define sqlite3_str_appendf sqlite3_api->str_appendf
#define sqlite3_str_vappendf sqlite3_api->str_vappendf
#define sqlite3_str_append sqlite3_api->str_append
#define sqlite3_str_appendall sqlite3_api->str_appendall
#define sqlite3_str_appendchar sqlite3_api->str_appendchar
#define sqlite3_str_reset sqlite3_api->str_reset
#define sqlite3_str_errcode sqlite3_api->str_errcode
#define sqlite3_str_length sqlite3_api->str_length
#define sqlite3_str_value sqlite3_api->str_value
/* Version 3.25.0 and later */
#define sqlite3_create_window_function sqlite3_api->create_window_function
/* Version 3.26.0 and later */
#define sqlite3_normalized_sql sqlite3_api->normalized_sql
/* Version 3.28.0 and later */
#define sqlite3_stmt_isexplain sqlite3_api->stmt_isexplain
#define sqlite3_value_frombind sqlite3_api->value_frombind
/* Version 3.30.0 and later */
#define sqlite3_drop_modules sqlite3_api->drop_modules
/* Version 3.31.0 and later */
#define sqlite3_hard_heap_limit64 sqlite3_api->hard_heap_limit64
#define sqlite3_uri_key sqlite3_api->uri_key
#define sqlite3_filename_database sqlite3_api->filename_database
#define sqlite3_filename_journal sqlite3_api->filename_journal
#define sqlite3_filename_wal sqlite3_api->filename_wal
/* Version 3.32.0 and later */
#define sqlite3_create_filename sqlite3_api->create_filename
#define sqlite3_free_filename sqlite3_api->free_filename
#define sqlite3_database_file_object sqlite3_api->database_file_object
/* Version 3.34.0 and later */
#define sqlite3_txn_state sqlite3_api->txn_state
/* Version 3.36.1 and later */
#define sqlite3_changes64 sqlite3_api->changes64
#define sqlite3_total_changes64 sqlite3_api->total_changes64
/* Version 3.37.0 and later */
#define sqlite3_autovacuum_pages sqlite3_api->autovacuum_pages
/* Version 3.38.0 and later */
#define sqlite3_error_offset sqlite3_api->error_offset
#define sqlite3_vtab_rhs_value sqlite3_api->vtab_rhs_value
#define sqlite3_vtab_distinct sqlite3_api->vtab_distinct
#define sqlite3_vtab_in sqlite3_api->vtab_in
#define sqlite3_vtab_in_first sqlite3_api->vtab_in_first
#define sqlite3_vtab_in_next sqlite3_api->vtab_in_next
/* Version 3.39.0 and later */
#ifndef SQLITE_OMIT_DESERIALIZE
#define sqlite3_deserialize sqlite3_api->deserialize
#define sqlite3_serialize sqlite3_api->serialize
#endif
#define sqlite3_db_name sqlite3_api->db_name
/* Version 3.40.0 and later */
#define sqlite3_value_encoding sqlite3_api->value_encoding
/* Version 3.41.0 and later */
#define sqlite3_is_interrupted sqlite3_api->is_interrupted
/* Version 3.43.0 and later */
#define sqlite3_stmt_explain sqlite3_api->stmt_explain
/* Version 3.44.0 and later */
#define sqlite3_get_clientdata sqlite3_api->get_clientdata
#define sqlite3_set_clientdata sqlite3_api->set_clientdata
#endif /* !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) */
#if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
/* This case when the file really is being compiled as a loadable
** extension */
# define SQLITE_EXTENSION_INIT1 const sqlite3_api_routines *sqlite3_api=0;
# define SQLITE_EXTENSION_INIT2(v) sqlite3_api=v;
# define SQLITE_EXTENSION_INIT3 \
extern const sqlite3_api_routines *sqlite3_api;
#else
/* This case when the file is being statically linked into the
** application */
# define SQLITE_EXTENSION_INIT1 /*no-op*/
# define SQLITE_EXTENSION_INIT2(v) (void)v; /* unused parameter */
# define SQLITE_EXTENSION_INIT3 /*no-op*/
#endif
#endif /* SQLITE3EXT_H */

View file

@ -1,9 +1,5 @@
#include "KeyStrengthener.h" #include "KeyStrengthener.h"
#include <botan/base64.h> #include <botan/base64.h>
#include <QSqlError>
#include <QSqlQuery>
#include <QVariant>
#include <stdexcept>
KeyStrengthener::KeyStrengthener(std::unique_ptr<Botan::PasswordHash> hasher, Botan::secure_vector<uint8_t> salt, size_t keysize) KeyStrengthener::KeyStrengthener(std::unique_ptr<Botan::PasswordHash> hasher, Botan::secure_vector<uint8_t> salt, size_t keysize)
: m_hasher (std::move(hasher)) : m_hasher (std::move(hasher))
@ -35,7 +31,7 @@ Botan::secure_vector<uint8_t> KeyStrengthener::derive(const std::string &passphr
return master_key; return master_key;
} }
void KeyStrengthener::saveParams(QSqlDatabase &db, const QString &table_name) void KeyStrengthener::saveParams(SQLiteConnection &db, const QString &table_name)
{ {
size_t i1 = m_hasher->memory_param(); size_t i1 = m_hasher->memory_param();
size_t i2 = m_hasher->iterations(); size_t i2 = m_hasher->iterations();
@ -43,18 +39,15 @@ void KeyStrengthener::saveParams(QSqlDatabase &db, const QString &table_name)
auto salt_str = QString::fromUtf8(Botan::base64_encode(m_salt).c_str()); auto salt_str = QString::fromUtf8(Botan::base64_encode(m_salt).c_str());
// SAVE parameters in database // SAVE parameters in database
QSqlQuery insert_statement(db);
insert_statement.prepare("INSERT OR REPLACE INTO " + table_name + "(id, algo, i1, i2, i3, ks, salt) " auto stmt = db.Prepare("INSERT OR REPLACE INTO " + table_name + "(id, algo, i1, i2, i3, ks, salt) "
+ "VALUES(:id, :algo, :i1, :i2, :i3, :ks, :salt)"); + "VALUES(?1, ?2, ?3, ?4, ?5, ?6, ?7)");
insert_statement.bindValue(":id", 1); stmt.Bind(1, 1);
insert_statement.bindValue(":algo", "Scrypt"); stmt.Bind(2, "Scrypt");
insert_statement.bindValue(":i1", i1); stmt.Bind(3, i1);
insert_statement.bindValue(":i2", i2); stmt.Bind(4, i2);
insert_statement.bindValue(":i3", i3); stmt.Bind(5, i3);
insert_statement.bindValue(":ks", m_keySize); stmt.Bind(6, m_keySize);
insert_statement.bindValue(":salt", salt_str); stmt.Bind(7, salt_str);
if (!insert_statement.exec()) { stmt.Step();
throw std::runtime_error("PasswordManager::KeyStrengthener::saveParams failed");
// auto err = insert_statement.lastError();
}
} }

View file

@ -1,10 +1,10 @@
#ifndef KEYSTRENGTHENER_H #ifndef KEYSTRENGTHENER_H
#define KEYSTRENGTHENER_H #define KEYSTRENGTHENER_H
#include <QSqlDatabase>
#include <botan/pwdhash.h> #include <botan/pwdhash.h>
#include <botan/secmem.h> #include <botan/secmem.h>
#include <memory> #include <memory>
#include "sqlite/SQLiteConnection.h"
class KeyStrengthener { class KeyStrengthener {
public: public:
@ -19,7 +19,7 @@ public:
KeyStrengthener& operator=(KeyStrengthener &&rhs); KeyStrengthener& operator=(KeyStrengthener &&rhs);
Botan::secure_vector<uint8_t> derive(const std::string &passphrase); Botan::secure_vector<uint8_t> derive(const std::string &passphrase);
void saveParams(QSqlDatabase &db, const QString &table_name); void saveParams(SQLiteConnection &db, const QString &table_name);
private: private:
std::unique_ptr<Botan::PasswordHash> m_hasher; std::unique_ptr<Botan::PasswordHash> m_hasher;
Botan::secure_vector<uint8_t> m_salt; Botan::secure_vector<uint8_t> m_salt;

View file

@ -1,7 +1,5 @@
#include "PasswordManager.h" #include "PasswordManager.h"
#include <QSqlQuery>
#include <QSqlError>
#include <QDebug> #include <QDebug>
#include <QVariant> #include <QVariant>
#include <botan/hash.h> #include <botan/hash.h>
@ -13,20 +11,6 @@
#include <botan/block_cipher.h> #include <botan/block_cipher.h>
#include <boost/lexical_cast.hpp> #include <boost/lexical_cast.hpp>
namespace {
class SqlException : public std::runtime_error {
public:
QSqlError error;
SqlException(const QSqlError &err)
: std::runtime_error(err.text().toUtf8().data())
, error(err)
{}
};
}
using namespace Botan; using namespace Botan;
class PasswordCryptoEngine { class PasswordCryptoEngine {
@ -85,7 +69,7 @@ PasswordManager::PasswordManager() = default;
PasswordManager::~PasswordManager() = default; PasswordManager::~PasswordManager() = default;
bool PasswordManager::initialized(QSqlDatabase& db) bool PasswordManager::initialized(SQLiteConnection& db)
{ {
return isPskStoreInitialized(db); return isPskStoreInitialized(db);
} }
@ -101,7 +85,7 @@ PasswordManager::deriveKey(KeyStrengthener &ks, QString passphrase)
return { master_key, mkh }; return { master_key, mkh };
} }
bool PasswordManager::createDatabase(QSqlDatabase &db, QString passphrase) bool PasswordManager::createDatabase(SQLiteConnection &db, QString passphrase)
{ {
m_cryptoEngine.reset(); m_cryptoEngine.reset();
if (!isPskStoreInitialized(db)) { if (!isPskStoreInitialized(db)) {
@ -112,15 +96,11 @@ bool PasswordManager::createDatabase(QSqlDatabase &db, QString passphrase)
auto [master_key, mkh_bin] = deriveKey(ks, passphrase); auto [master_key, mkh_bin] = deriveKey(ks, passphrase);
auto mkh = QString::fromUtf8(Botan::base64_encode(mkh_bin).c_str()); auto mkh = QString::fromUtf8(Botan::base64_encode(mkh_bin).c_str());
QSqlQuery q_ins_hash(db); auto q_ins_hash = db.Prepare(
q_ins_hash.prepare("INSERT INTO " + m_secretHashTableName + "(id, hash) VALUES(:id, :hash)"); "INSERT INTO " + m_secretHashTableName + "(id, hash) VALUES(?1, ?2)");
q_ins_hash.bindValue(":id", 1); q_ins_hash.Bind(1, 1);
q_ins_hash.bindValue(":hash", mkh); q_ins_hash.Bind(2, mkh);
if (!q_ins_hash.exec()) { q_ins_hash.Step();
auto err = q_ins_hash.lastError();
qDebug() << err.text();
throw SqlException(err);
}
m_cryptoEngine = std::make_unique<PasswordCryptoEngine>(master_key); m_cryptoEngine = std::make_unique<PasswordCryptoEngine>(master_key);
return true; return true;
@ -128,16 +108,16 @@ bool PasswordManager::createDatabase(QSqlDatabase &db, QString passphrase)
return false; return false;
} }
bool PasswordManager::openDatabase(QSqlDatabase &db, QString passphrase) bool PasswordManager::openDatabase(SQLiteConnection &db, QString passphrase)
{ {
m_cryptoEngine.reset(); m_cryptoEngine.reset();
if (isPskStoreInitialized(db)) { if (isPskStoreInitialized(db)) {
auto ks = getKeyStrengthener(db); auto ks = getKeyStrengthener(db);
auto [master_key, mkh_bin] = deriveKey(ks, passphrase); auto [master_key, mkh_bin] = deriveKey(ks, passphrase);
QSqlQuery q("SELECT hash FROM " + m_secretHashTableName + " WHERE id=1", db); auto q = db.Prepare("SELECT hash FROM " + m_secretHashTableName + " WHERE id=1");
if (q.next()) { if (q.Step()) {
auto hash_b64 = q.value(0).toString().toUtf8(); QByteArray hash_b64 = q.ColumnCharPtr(0);
auto hash_bin = Botan::base64_decode(hash_b64.data(), static_cast<size_t>(hash_b64.size())); auto hash_bin = Botan::base64_decode(hash_b64.data(), static_cast<size_t>(hash_b64.size()));
if (hash_bin == mkh_bin) { if (hash_bin == mkh_bin) {
m_cryptoEngine = std::make_unique<PasswordCryptoEngine>(master_key); m_cryptoEngine = std::make_unique<PasswordCryptoEngine>(master_key);
@ -158,16 +138,16 @@ bool PasswordManager::locked() const
return m_cryptoEngine == nullptr; return m_cryptoEngine == nullptr;
} }
void PasswordManager::resetMasterPassword(QSqlDatabase &db) void PasswordManager::resetMasterPassword(SQLiteConnection &db)
{ {
if (!isPskStoreInitialized(db)) if (!isPskStoreInitialized(db))
return; return;
closeDatabase(); closeDatabase();
QSqlQuery del_algo("DELETE FROM " + m_secretAlgoTableName + " WHERE id=1", db); auto del_algo = db.Prepare("DELETE FROM " + m_secretAlgoTableName + " WHERE id=1");
del_algo.exec(); del_algo.Step();
QSqlQuery del_hash("DELETE FROM " + m_secretHashTableName + " WHERE id=1", db); auto del_hash = db.Prepare("DELETE FROM " + m_secretHashTableName + " WHERE id=1");
del_hash.exec(); del_hash.Step();
} }
std::string PasswordManager::encrypt(const std::string &name, const std::string &passwd) std::string PasswordManager::encrypt(const std::string &name, const std::string &passwd)
@ -199,14 +179,13 @@ std::string PasswordManager::decrypt(const std::string &id, const std::string_vi
} }
} }
void PasswordManager::initializeNewPskStore(QSqlDatabase &db) void PasswordManager::initializeNewPskStore(SQLiteConnection &db)
{ {
// // Create tables // // Create tables
// // - psk_masterkey_algo // // - psk_masterkey_algo
// // - psk_passwd // // - psk_passwd
{ {
QSqlQuery create_tbl(db); auto create_tbl = db.Prepare(
create_tbl.prepare(
"CREATE TABLE IF NOT EXISTS " + m_secretAlgoTableName + "( \n" "CREATE TABLE IF NOT EXISTS " + m_secretAlgoTableName + "( \n"
" id INTEGER PRIMARY KEY, \n" " id INTEGER PRIMARY KEY, \n"
" algo TEXT, \n" " algo TEXT, \n"
@ -216,70 +195,55 @@ void PasswordManager::initializeNewPskStore(QSqlDatabase &db)
" ks INTEGER, \n" " ks INTEGER, \n"
" salt TEXT \n" " salt TEXT \n"
");"); ");");
if (!create_tbl.exec()) { create_tbl.Step();
auto err = create_tbl.lastError();
throw SqlException(err);
}
} }
QSqlQuery create_tbl(db); auto create_tbl = db.Prepare(
create_tbl.prepare(
"CREATE TABLE IF NOT EXISTS " + m_secretHashTableName + "( \n" "CREATE TABLE IF NOT EXISTS " + m_secretHashTableName + "( \n"
" id INTEGER PRIMARY KEY, \n" " id INTEGER PRIMARY KEY, \n"
" hash TEXT \n" " hash TEXT \n"
");"); ");");
if (!create_tbl.exec()) { create_tbl.Step();
auto err = create_tbl.lastError();
throw SqlException(err);
}
} }
bool PasswordManager::isPskStoreInitialized(QSqlDatabase& db) bool PasswordManager::isPskStoreInitialized(SQLiteConnection& db)
{ {
// Is the table with the secret data present and filled? // Is the table with the secret data present and filled?
QSqlQuery query(db); auto query = db.Prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=?1");
query.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=:name"); query.Bind(1, m_secretAlgoTableName);
query.bindValue(":name", m_secretAlgoTableName); if (!query.Step()) {
if (!query.exec()) {
auto err = query.lastError();
throw SqlException(err);
}
if (!query.next()) {
return false; return false;
} }
query.bindValue(":name", m_secretHashTableName); query.Reset();
if (!query.exec()) { query.Bind(1, m_secretHashTableName);
auto err = query.lastError(); if (!query.Step()) {
throw SqlException(err);
}
if (!query.next()) {
return false; return false;
} }
QSqlQuery sel_algo("SELECT algo FROM " + m_secretAlgoTableName + " WHERE id=1", db); auto sel_algo = db.Prepare("SELECT algo FROM " + m_secretAlgoTableName + " WHERE id=1");
if (!sel_algo.next()) { if (!sel_algo.Step()) {
return false; return false;
} }
QSqlQuery sel_hash("SELECT hash FROM " + m_secretHashTableName + " WHERE id=1", db); auto sel_hash = db.Prepare("SELECT hash FROM " + m_secretHashTableName + " WHERE id=1");
if (!sel_hash.next()) { if (!sel_hash.Step()) {
return false; return false;
} }
return true; return true;
} }
KeyStrengthener PasswordManager::getKeyStrengthener(QSqlDatabase &db) KeyStrengthener PasswordManager::getKeyStrengthener(SQLiteConnection &db)
{ {
QSqlQuery query("SELECT algo, i1, i2, i3, ks, salt FROM " + m_secretAlgoTableName + " WHERE id=1", db); auto query = db.Prepare("SELECT algo, i1, i2, i3, ks, salt FROM " + m_secretAlgoTableName + " WHERE id=1");
if (query.next()) { if (query.Step()) {
std::string algo = query.value(0).toString().toUtf8().data(); std::string algo = query.ColumnCharPtr(0);
size_t i1 = query.value(1).toUInt(); size_t i1 = query.ColumnInteger(1);
size_t i2 = query.value(2).toUInt(); size_t i2 = query.ColumnInteger(2);
size_t i3 = query.value(3).toUInt(); size_t i3 = query.ColumnInteger(3);
size_t ks = query.value(4).toUInt(); size_t ks = query.ColumnInteger(4);
auto salt = query.value(5).toString().toUtf8(); QByteArray salt = query.ColumnCharPtr(5);
auto pwh_fam = Botan::PasswordHashFamily::create(algo); auto pwh_fam = Botan::PasswordHashFamily::create(algo);
return KeyStrengthener( return KeyStrengthener(

View file

@ -1,8 +1,7 @@
#ifndef PASSWORDMANAGER_H #ifndef PASSWORDMANAGER_H
#define PASSWORDMANAGER_H #define PASSWORDMANAGER_H
#include "KeyStrengthener.h" #include "utils/KeyStrengthener.h"
#include <QSqlDatabase>
#include <botan/secmem.h> #include <botan/secmem.h>
#include <string> #include <string>
#include <string_view> #include <string_view>
@ -10,7 +9,6 @@
#include <memory> #include <memory>
#include <botan/pwdhash.h> #include <botan/pwdhash.h>
#include <map>
namespace Botan { namespace Botan {
@ -47,13 +45,13 @@ public:
* If returns false then use createDatabase to set it up * If returns false then use createDatabase to set it up
* else use openDatabase to get access. * else use openDatabase to get access.
*/ */
bool initialized(QSqlDatabase &db); bool initialized(SQLiteConnection &db);
bool createDatabase(QSqlDatabase &db, QString passphrase); bool createDatabase(SQLiteConnection &db, QString passphrase);
/// Opens the PSK database /// Opens the PSK database
bool openDatabase(QSqlDatabase &db, QString passphrase); bool openDatabase(SQLiteConnection &db, QString passphrase);
void closeDatabase(); void closeDatabase();
bool locked() const; bool locked() const;
void resetMasterPassword(QSqlDatabase &db); void resetMasterPassword(SQLiteConnection &db);
std::string encrypt(const std::string &id, const std::string &passwd); std::string encrypt(const std::string &id, const std::string &passwd);
@ -65,11 +63,11 @@ private:
QString m_secretHashTableName = "psk_masterkey_hash"; QString m_secretHashTableName = "psk_masterkey_hash";
std::unique_ptr<PasswordCryptoEngine> m_cryptoEngine; std::unique_ptr<PasswordCryptoEngine> m_cryptoEngine;
bool isPskStoreInitialized(QSqlDatabase& db); bool isPskStoreInitialized(SQLiteConnection& db);
void initializeNewPskStore(QSqlDatabase &db); void initializeNewPskStore(SQLiteConnection &db);
/// Get PasswordHash from parameters in database /// Get PasswordHash from parameters in database
KeyStrengthener getKeyStrengthener(QSqlDatabase &db); KeyStrengthener getKeyStrengthener(SQLiteConnection &db);
KeyStrengthener createKeyStrengthener(); KeyStrengthener createKeyStrengthener();
std::tuple<Botan::secure_vector<uint8_t>, Botan::secure_vector<uint8_t>> std::tuple<Botan::secure_vector<uint8_t>, Botan::secure_vector<uint8_t>>