Files
homehud/MataAvistas/BudgetPro/utils/dbutils.cpp
T

52 lines
2.2 KiB
C++

#include "dbutils.h"
#include <QSqlQuery>
#include <QSqlError>
#include <QDebug>
DbUtils::DbUtils()
{
// Initialize database connection (example using a default connection)
// We'll use a connection named "BudgetProUtils"
m_db = QSqlDatabase::database(QStringLiteral("BudgetProUtils"));
if (!m_db.isValid()) {
m_db = QSqlDatabase::addDatabase(QStringLiteral("QSQLITE"), QStringLiteral("BudgetProUtils"));
// Set the database name to the same as the enterprise list or a default?
// For simplicity, we'll use the same as EnterpriseListDB from MApplication
// But we don't have access to that here. Let's use a default path.
// Alternatively, we can try to use the existing EnterpriseListDB connection.
// Since we cannot access MApplication's private members, we'll create a separate connection.
// However, note that the formBudget.cpp uses m_dbUtils.isConnected() and getLastDocumentId.
// The getLastDocumentId function likely queries the current enterprise database.
// We need to know which database is currently open.
// Looking at mapplication.cpp, EnterpriseListDB is a static? Actually it's a member of MApplication.
// We can't access it from here without a singleton or global.
// Let's change approach: Instead of creating a new connection, we'll use the default connection
// that is set by MApplication when an enterprise is opened.
// But we don't have that context.
// For now, we'll leave the database unconfigured and return false for isConnected.
// This is a placeholder.
m_db.setDatabaseName(QStringLiteral(":memory:")); // fallback to in-memory
}
}
bool DbUtils::isConnected()
{
return m_db.isOpen();
}
QString DbUtils::getLastDocumentId(const QString& docType)
{
if (!m_db.isOpen()) {
return QStringLiteral("0");
}
QSqlQuery query(m_db);
query.prepare(QStringLiteral("SELECT MAX(ID) FROM ") + docType);
if (!query.exec()) {
qWarning() << "Failed to get last document id:" << query.lastError().text();
return QStringLiteral("0");
}
if (query.next()) {
return query.value(0).toString();
}
return QStringLiteral("0");
}