Esempio n. 1
0
void ZealDocsetsRegistry::addDocset(const QString& path) {
    auto dir = QDir(path);
    auto name = dir.dirName().replace(".docset", "");
    auto db = QSqlDatabase::addDatabase("QSQLITE", name);
    if(QFile::exists(dir.filePath("index.sqlite"))) {
        db.setDatabaseName(dir.filePath("index.sqlite"));
        db.open();
        types.insert(name, ZEAL);
    } else {
        auto dashFile = QDir(QDir(dir.filePath("Contents")).filePath("Resources")).filePath("docSet.dsidx");
        db.setDatabaseName(dashFile);
        db.open();
        auto q = db.exec("select name from sqlite_master where type='table'");
        QStringList tables;
        while(q.next()) {
            tables.append(q.value(0).toString());
        }
        if(tables.contains("searchIndex")) {
            types.insert(name, DASH);
        } else {
            types.insert(name, ZDASH);
        }
    }
    dbs.insert(name, db);
    dirs.insert(name, dir);
}
mapbox::util::variant<Database, Exception> Database::tryOpen(const std::string &filename, int flags) {
    if (!QSqlDatabase::drivers().contains("QSQLITE")) {
        return Exception { ResultCode::CantOpen, "SQLite driver not found." };
    }

    QString connectionName = QString::number(uint64_t(QThread::currentThread())) + incrementCounter();

    assert(!QSqlDatabase::contains(connectionName));
    auto db = QSqlDatabase::addDatabase("QSQLITE", connectionName);

    QString connectOptions = db.connectOptions();
    if (flags & OpenFlag::ReadOnly) {
        if (!connectOptions.isEmpty()) connectOptions.append(';');
        connectOptions.append("QSQLITE_OPEN_READONLY");
    }
    if (flags & OpenFlag::SharedCache) {
        if (!connectOptions.isEmpty()) connectOptions.append(';');
        connectOptions.append("QSQLITE_ENABLE_SHARED_CACHE");
    }

    db.setConnectOptions(connectOptions);
    db.setDatabaseName(QString(filename.c_str()));

    if (!db.open()) {
        // Assume every error when opening the data as CANTOPEN. Qt
        // always returns -1 for `nativeErrorCode()` on database errors.
        return Exception { ResultCode::CantOpen, "Error opening the database." };
    }

    return Database(std::make_unique<DatabaseImpl>(connectionName));
}
Esempio n. 3
0
void CDatabaseItem::init(const QString &dbname)
{
#ifdef DEBUG
  qDebug("CDatabaseItem::init('%s')", debug_string(dbname));
#endif

  setText(0,dbname);
  setDatabaseName(dbname);
  widgetData.setAutoDelete(true);
  if (databaseDisconnectedIcon.isNull())
    databaseDisconnectedIcon = getPixmapIcon("databaseDisconnectedIcon");

  if (databaseConnectedIcon.isNull())
    databaseConnectedIcon = getPixmapIcon("databaseConnectedIcon");

  databaseConnectIcon = getPixmapIcon("databaseConnectIcon");
  databaseDisconnectIcon = getPixmapIcon("databaseDisconnectIcon");
  sqlIcon = getPixmapIcon("sqlIcon");
  deleteIcon = getPixmapIcon("deleteIcon");
  newWindowIcon = getPixmapIcon("newWindowIcon");
  if (is_connected)
    setConnected(is_connected);
  else
    setPixmap(0, databaseDisconnectedIcon);
}
Esempio n. 4
0
void
TestBook::testInitDatabaseNoPresentTables() {
    // create a database with no data, then init the database and ensure that the tables are present
    auto dbPath = PublicBook::databasePath();

    QFileInfo fi(dbPath);
    QVERIFY(!fi.exists());

    auto db = com::chancho::system::DatabaseFactory::instance()->addDatabase("QSQLITE", "TESTS");
    db->setDatabaseName(dbPath);

    auto opened = db->open();
    QVERIFY(opened);

    db->close();
    QVERIFY(fi.exists());

    PublicBook::initDatabse();

    // assert that the tables have been created
    opened = db->open();
    QVERIFY(opened);

    // once the db has been created we need to check that it has the correct version and the required tables
    auto tables = db->tables();
    QCOMPARE(tables.count(), 4);
    QVERIFY(tables.contains("Accounts", Qt::CaseInsensitive));
    QVERIFY(tables.contains("Categories", Qt::CaseInsensitive));
    QVERIFY(tables.contains("Transactions", Qt::CaseInsensitive));
    QVERIFY(tables.contains("RecurrentTransactions", Qt::CaseInsensitive));
    db->close();
}
Esempio n. 5
0
/*!
 * \brief Database::Database
 * \param path path to sql database file
 */
Database::Database(QString path, QString driver) : QSqlDatabase(addDatabase(driver))
{
  setHostName("localhost");
  setDatabaseName(path);
  Q_ASSERT(open());
  query = QSqlQuery(*this);
}
Esempio n. 6
0
void
TestBook::testInitDatabasePresentTables() {
    // simply call init twice and make sure everything goes ok
    auto dbPath = PublicBook::databasePath();

    PublicBook::initDatabse();
    PublicBook::initDatabse();

    QFileInfo fi(dbPath);
    QVERIFY(fi.exists());

    // use qsql to ensure that the tables are there
    auto db = com::chancho::system::DatabaseFactory::instance()->addDatabase("QSQLITE", "TESTS");
    db->setDatabaseName(dbPath);

    auto opened = db->open();
    QVERIFY(opened);

    // once the db has been created we need to check that it has the correct version and the required tables
    auto tables = db->tables();
    QCOMPARE(tables.count(), 4);
    QVERIFY(tables.contains("Accounts", Qt::CaseInsensitive));
    QVERIFY(tables.contains("Categories", Qt::CaseInsensitive));
    QVERIFY(tables.contains("Transactions", Qt::CaseInsensitive));
    QVERIFY(tables.contains("RecurrentTransactions", Qt::CaseInsensitive));
    db->close();
}
Esempio n. 7
0
    // todo: remove or add clone support
    ConnectionSettings::ConnectionSettings(const mongo::MongoURI& uri, bool isClone)  
        : _connectionName(defaultNameConnection),
        _host(defaultServerHost),
        _port(port),
        _imported(false),
        _sshSettings(new SshSettings()),
        _sslSettings(new SslSettings()),
        _isReplicaSet((uri.type() == mongo::ConnectionString::ConnectionType::SET)),
        _replicaSetSettings(new ReplicaSetSettings(uri)),
        _clone(isClone),
        _uuid(QUuid::createUuid().toString())   // todo
    {
        if (!uri.getServers().empty()) {
            _host = uri.getServers().front().host();
            _port = uri.getServers().front().port();
        }

        auto str = std::string(uri.getOptions().getStringField("ssl"));
        auto sslEnabled = ("true" == str);
        if (sslEnabled) {
            _sslSettings->enableSSL(true);
            _sslSettings->setAllowInvalidCertificates(true);
        }

        auto credential = new CredentialSettings();
        credential->setUserName(uri.getUser());
        credential->setUserPassword(uri.getPassword());
        credential->setDatabaseName(uri.getDatabase());
        if (!credential->userName().empty() && !credential->userPassword().empty()) {   // todo:
            credential->setEnabled(true);
        }
        addCredential(credential);
    }
Esempio n. 8
0
void
TestBookCategory::testRemoveParentCategory() {
    // create two cats with the same parent, remove the parent and ensure that the cats have been removed
    // remove the category with a parent and ensure that the parent is left there
    auto parentName = QString("Parent");

    // create the parent category and store it
    auto parent = std::make_shared<PublicCategory>(parentName, chancho::Category::Type::INCOME);
    auto first = std::make_shared<PublicCategory>("Salary", chancho::Category::Type::INCOME, parent);
    auto second = std::make_shared<PublicCategory>("Bonus", chancho::Category::Type::INCOME, parent);

    PublicBook book;
    book.store(first);
    book.store(second);

    // assert that both the parent and the category are added
    QVERIFY(parent->wasStoredInDb());
    QVERIFY(first->wasStoredInDb());

    book.remove(parent);

    QVERIFY(!parent->wasStoredInDb());

    // assert that the db is present in the db
    auto dbPath = PublicBook::databasePath();

    auto db = sys::DatabaseFactory::instance()->addDatabase("QSQLITE", QTest::currentTestFunction());
    db->setDatabaseName(dbPath);

    auto opened = db->open();
    QVERIFY(opened);

    // create the required tables and indexes
    auto query = db->createQuery();
    query->prepare(SELECT_CATEGORY_QUERY);
    query->bindValue(":uuid", first->_dbId.toString());
    auto success = query->exec();

    QVERIFY(success);
    QVERIFY(!query->next());

    query->prepare(SELECT_CATEGORY_QUERY);
    query->bindValue(":uuid", second->_dbId.toString());
    success = query->exec();

    QVERIFY(success);
    QVERIFY(!query->next());

    // ensure that the parent is not pressent
    query->prepare(SELECT_CATEGORY_QUERY);
    query->bindValue(":uuid", parent->_dbId.toString());
    success = query->exec();

    QVERIFY(success);
    QVERIFY(!query->next());

    db->close();
}
Esempio n. 9
0
void
TestBookCategory::testStoreCategoryParentPresent() {
    QFETCH(QString, name);
    QFETCH(chancho::Category::Type, type);
    QFETCH(QString, color);

    auto parentName = QString("Parent");

    // create the parent category and store it
    auto parent = std::make_shared<PublicCategory>(parentName, chancho::Category::Type::INCOME, color);
    auto category = std::make_shared<PublicCategory>(name, type, parent);

    PublicBook book;
    book.store(category);

    // assert that both the parent and the category are added
    QVERIFY(parent->wasStoredInDb());
    QVERIFY(category->wasStoredInDb());

    // assert that the db is present in the db
    auto dbPath = PublicBook::databasePath();

    auto db = sys::DatabaseFactory::instance()->addDatabase("QSQLITE", QTest::currentTestFunction());
    db->setDatabaseName(dbPath);

    auto opened = db->open();
    QVERIFY(opened);

    // create the required tables and indexes
    auto query = db->createQuery();
    query->prepare(SELECT_CATEGORY_QUERY);
    query->bindValue(":uuid", category->_dbId.toString());
    auto success = query->exec();

    QVERIFY(success);
    QVERIFY(query->next());
    QCOMPARE(query->value("name").toString(), category->name);
    QCOMPARE(query->value("color").toString(), category->color);
    QCOMPARE(query->value("type").toInt(), static_cast<int>(category->type));
    QCOMPARE(query->value("parent").toString(), parent->_dbId.toString());

    // ensure that the parent is pressent
    query->prepare(SELECT_CATEGORY_QUERY);
    query->bindValue(":uuid", parent->_dbId.toString());
    success = query->exec();

    QVERIFY(success);
    QVERIFY(query->next());
    QCOMPARE(query->value("name").toString(), parent->name);
    QCOMPARE(query->value("type").toInt(), static_cast<int>(parent->type));
    QVERIFY(query->value("parent").isNull());

    db->close();
}
Esempio n. 10
0
KexiProjectData::KexiProjectData(
    const KexiDB::ConnectionData &cdata, const QString& dbname, const QString& caption)
        : QObject(0)
        , KexiDB::SchemaData()
        , formatVersion(0)
        , d(new KexiProjectDataPrivate())
{
    setObjectName("KexiProjectData");
    d->connData = cdata;
    setDatabaseName(cdata.dbFileName().isEmpty() ? dbname : cdata.dbFileName());
    setCaption(caption);
}
Esempio n. 11
0
		void
		DBImpl::
		setConnectionInfo(std::string& server,
		                  uint32_t port,
		                  std::string& user,
		                  std::string& pw,
		                  std::string& db)
		{
			setServerURL(server);
			setServerPort(port);
			setUserName(user);
			setUserPassword(pw);
			setDatabaseName(db);
		}
Esempio n. 12
0
DbSQLiteWidget::DbSQLiteWidget(DatabaseDialog *parent):
    StepWidget(parent),
    fileDialog(nullptr),
    ui(new Ui::DbSQLiteWidget())
{
    ui->setupUi(this);

    DatabaseSQLite *db = dynamic_cast<DatabaseSQLite*>(dialog->db.data());
    if(db){
        setDatabaseName(db->getDatabaseName());
    }

    dialog->setButtonState(DatabaseDialog::BUTTON_BACK, true);
    dialog->setButtonState(DatabaseDialog::BUTTON_NEXT, true);
    dialog->setButtonState(DatabaseDialog::BUTTON_FINISH, false);
    dialog->setDefaultButton(DatabaseDialog::BUTTON_NEXT);
}
Esempio n. 13
0
/*!
 * \brief Database::Database
 * \param path Path to SQL Database file
 * \param driver QString identifier for the specific flavor of SQL we are using.
 */
Database::Database(QString path, QString driver) : QSqlDatabase(addDatabase(driver))
{
    setHostName("localhost");
    setDatabaseName(path);

    // If the database successfully opens
    if(open())
    {
        qDebug() << "Database opened successfully";
    }
    else
    {
        // Output the last error message from the database
        qDebug() << this->lastError().text();
    }

    //  This is for activating foreign key support.
    QSqlQuery query;
    query.exec("PRAGMA foreign_keys = ON;");
}
SqlDatabase::SqlDatabase()
	: QSqlDatabase("QSQLITE")
{
	QString path = QStandardPaths::writableLocation(QStandardPaths::DataLocation);
	QString dbPath = QDir::toNativeSeparators(path + "/mmmmp.db");
	QDir userDataPath(path);
	// Init a new database file for settings
	QFile db(dbPath);
	if (!userDataPath.exists(path)) {
		userDataPath.mkpath(path);
	}
	db.open(QIODevice::ReadWrite);
	db.close();
	setDatabaseName(dbPath);

	if (open()) {
		exec("CREATE TABLE IF NOT EXISTS playlists (absPath varchar(255), name varchar(255), hash varchar(255))");
		exec("CREATE INDEX indexPlaylists ON playlists (absPath)");
		close();
	}
}
Esempio n. 15
0
void
TestBook::testUpgradeNoRecurrence() {
    // create a database with the basic tables (just the names, no need to add the exact fields)  and make sure it
    // is added
    auto dbPath = PublicBook::databasePath();

    auto db = sys::DatabaseFactory::instance()->addDatabase("QSQLITE", QTest::currentTestFunction());
    db->setDatabaseName(dbPath);

    auto opened = db->open();
    QVERIFY(opened);

    // create the required tables and indexes
    auto query = db->createQuery();

    auto success = query->exec("CREATE TABLE IF NOT EXISTS Accounts(id INT)");
    QVERIFY(success);

    success &= query->exec("CREATE TABLE IF NOT EXISTS Categories(id INT)");
    QVERIFY(success);

    success &= query->exec("CREATE TABLE IF NOT EXISTS Transactions(id INT)");
    QVERIFY(success);
    db->close();

    //init the db and test that the recurrence is added
    PublicBook::initDatabse();

    opened = db->open();
    QVERIFY(opened);

    // once the db has been created we need to check that it has the correct version and the required tables
    auto tables = db->tables();
    QCOMPARE(tables.count(), 4);
    QVERIFY(tables.contains("Accounts", Qt::CaseInsensitive));
    QVERIFY(tables.contains("Categories", Qt::CaseInsensitive));
    QVERIFY(tables.contains("Transactions", Qt::CaseInsensitive));
    QVERIFY(tables.contains("RecurrentTransactions", Qt::CaseInsensitive));
    db->close();
}
Esempio n. 16
0
void
TestBookCategory::testRemoveCategoryNoParent() {
    QString name = "Salary";
    auto type = chancho::Category::Type::INCOME;

    auto category = std::make_shared<PublicCategory>(name, type);

    PublicBook book;
    book.store(category);

    // assert that both the parent and the category are added
    QVERIFY(category->wasStoredInDb());

    // method under test
    book.remove(category);

    QVERIFY(!category->wasStoredInDb());

    // assert that the db is present in the db
    auto dbPath = PublicBook::databasePath();

    auto db = sys::DatabaseFactory::instance()->addDatabase("QSQLITE", QTest::currentTestFunction());
    db->setDatabaseName(dbPath);

    auto opened = db->open();
    QVERIFY(opened);

    // create the required tables and indexes
    auto query = db->createQuery();
    query->prepare(SELECT_CATEGORY_QUERY);
    query->bindValue(":uuid", category->_dbId.toString());
    auto success = query->exec();

    QVERIFY(success);
    QVERIFY(!query->next());

    db->close();
}
Esempio n. 17
0
bool LogMonitorFileModel::saveModel(AbstractLogModel *model, const QString& fileName)
{
    auto db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName(fileName);
    auto success = db.open();
    if (!success)
    {
        return false;
    }

    auto check = [&](bool result)
    {
        if (!result)
        {
            auto e = db.lastError();
            qDebug() << "Query failed: " << e.text() << e.nativeErrorCode();
        }
    };

    check(QSqlQuery(db).exec("CREATE TABLE lsw(version INT)"));
    check(QSqlQuery(db).exec("CREATE TABLE messages(time REAL, host INT, pid INT, level INT, channel INT, message TEXT)"));
    check(QSqlQuery(db).exec("CREATE TABLE hosts(id INT,name TEXT)"));
    check(QSqlQuery(db).exec("CREATE TABLE processes(id INT, module TEXT, process TEXT, host INT)"));
    check(QSqlQuery(db).exec("CREATE TABLE channels(id INT,facility TEXT,object TEXT)"));
    check(QSqlQuery(db).exec("CREATE VIEW log as "
              "select m.rowid, '' as timestamp, m.time, h.name as host, m.pid, m.level, m.level as type, p.module, c.facility || '-' || c.object as channel, m.message, p.process "
                  "from messages as m, hosts as h, processes as p, channels as c "
                  "where h.id = m.host and p.id = m.pid and c.id = m.channel"));



    check(QSqlQuery(db).exec("INSERT INTO lsw VALUES (3)"));

    int count = model->rowCount();
    QMap<QString, int> hosts;
    QMap<quint64, QString> processes;
    QMap<QPair<QString, QString>, int> channels;

    for (int i = 0; i < count; ++i)
    {
        auto message = model->message(i);
        if (!message || message->isMultilineContinuation)
        {
            continue;
        }
        if (hosts.find(message->machineName) == hosts.end())
        {
            hosts[message->machineName] = hosts.size() + 1;
        }
        processes[message->pid] = message->executablePath;
        if (channels.find(QPair<QString, QString>(message->module, message->channel)) == channels.end())
        {
            channels[QPair<QString, QString>(message->module, message->channel)] = channels.size() + 1;
        }
    }

    check(QSqlQuery(db).exec("BEGIN TRANSACTION"));
    {
        QSqlQuery q(db);
        q.prepare("INSERT INTO hosts VALUES (?, ?)");

        QVariantList ids;
        QVariantList names;
        for (auto it = hosts.begin(); it != hosts.end(); ++it)
        {
            ids << it.value();
            names << it.key();
        }
        q.addBindValue(ids);
        q.addBindValue(names);
        check(q.execBatch());
    }
    {
        QSqlQuery q(db);
        q.prepare("INSERT INTO processes VALUES (?, ?, ?, ?)");

        QVariantList ids;
        QVariantList modules;
        QVariantList process;
        QVariantList hosts;
        for (auto it = processes.begin(); it != processes.end(); ++it)
        {
            ids << it.key();
            modules << "";
            process << it.value();
            hosts << 0;
        }
        q.addBindValue(ids);
        q.addBindValue(modules);
        q.addBindValue(process);
        q.addBindValue(hosts);
        check(q.execBatch());
    }
    {
        QSqlQuery q(db);
        q.prepare("INSERT INTO channels VALUES (?, ?, ?)");

        QVariantList ids;
        QVariantList facilities;
        QVariantList objects;
        for (auto it = channels.begin(); it != channels.end(); ++it)
        {
            ids << it.value();
            facilities << it.key().first;
            objects << it.key().second;
        }
        q.addBindValue(ids);
        q.addBindValue(facilities);
        q.addBindValue(objects);
        check(q.execBatch());
    }
    {
        QSqlQuery q(db);
        q.prepare("INSERT INTO messages VALUES (?, ?, ?, ?, ?, ?)");

        QVariantList time;
        QVariantList host;
        QVariantList pid;
        QVariantList level;
        QVariantList channel;
        QVariantList message;
        for (int i = 0; i < count; ++i)
        {
            auto msg = model->message(i);
            if (!msg || msg->isMultilineContinuation)
            {
                continue;
            }
            time << double(msg->timestamp.toMSecsSinceEpoch()) / 1000;
            host << hosts[msg->machineName];
            pid << msg->pid;
            level << msg->severity;
            channel << channels[QPair<QString, QString>(msg->module, msg->channel)];
            message << msg->originalMessage;
        }
        q.addBindValue(time);
        q.addBindValue(host);
        q.addBindValue(pid);
        q.addBindValue(level);
        q.addBindValue(channel);
        q.addBindValue(message);
        check(q.execBatch());
    }
    check(QSqlQuery(db).exec("END TRANSACTION"));
    db.close();
    return true;
}