Пример #1
0
void SitesDatabaseInterface::deleteSite(int id)
{
    qDebug() << "db: " << this->dbPath;
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName(this->dbPath);

    if(false == db.open())
    {
        qDebug() << "can not open database";
    }

    QSqlQuery query;
    query.prepare("DELETE FROM sites WHERE ID = :id;");
    query.bindValue(":id", id);
    if(false == query.exec())
    {
       qDebug() << "SQL ERROR : " << query.lastError();
    }
    db.commit();

    //We have also to delete the associated weather data to this site
    query.prepare("DELETE FROM meteo WHERE id_site = :id;");
    query.bindValue(":id", id);
    if(false == query.exec())
    {
       qDebug() << "SQL ERROR : " << query.lastError();
    }

    db.commit();
    db.close();
}
Пример #2
0
QModelIndex ListModel::moveItemHorizontal(const QModelIndex& index, int direction)
{
    ListItem* item = itemFromIndex(index);
    if (!item)
        return index;

    ListItem* parent = item->parent();
    int row = item->row();

    if (direction == App::Left) { // reparent as child of parent's parent
        if (!parent || parent->isRoot()) // already top level item
            return index;

        ListItem* newParent = parent->parent();
        int newRow = parent->row() + 1;

        QSqlDatabase db = QSqlDatabase::database();
        db.transaction();
        if (parent->takeChildDb(row) &&
            item->setParentDb(newParent, newRow)) {
            db.commit();
            if (beginMoveRows(indexFromItem(parent), row, row, indexFromItem(newParent), newRow)) {
                newParent->insertChild(newRow, parent->takeChild(row));
                endMoveRows();
            }
            return indexFromItem(item);
        } else {
            db.rollback();
            return index;
        }
    } else { // move as child of previous sibling
        ListItem* newParent = parent->child(row - 1);
        if (!newParent)
            return index;

        QSqlDatabase db = QSqlDatabase::database();
        db.transaction();
        if (parent->takeChildDb(row) &&
            item->setParentDb(newParent, newParent->childCount())) {
            db.commit();
            if (beginMoveRows(indexFromItem(parent), row, row, indexFromItem(newParent), newParent->childCount())) {
                newParent->appendChild(parent->takeChild(row));
                endMoveRows();
            }
            newParent->setExpanded(true);
            return indexFromItem(item);
        } else {
            db.rollback();
            return index;
        }
    }
}
Пример #3
0
bool Migration::run(bool forward)
{
    QSqlDatabase db = QSqlDatabase::database();
    qDebug() << db.databaseName();
    try {
        db.transaction();
        if (forward)
        {
            qDebug() << "DB::Migration [" << name() << "] run up";
            up();
        }
        else
        {
            qDebug() << "DB::Migration [" << name() << "] run down";
            down();
        }
        qDebug() << "commit " << name() << " " << db.lastError().text();
        db.commit();
        return true;
    } catch (...) {
        qDebug() << "DB::Migration [" << name() << "] failed: " << db.lastError().text();
        db.rollback();
        throw(QObject::tr("Can't update your database !"));
        return false;
    }
}
Пример #4
0
int main(int argc, char *argv[])
{
	QCoreApplication app(argc, argv);

	QSqlDatabase db1();

	{
		QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", "connection_name");
		db.setDatabaseName(":memory:");
		db.open();
		db.transaction();
		QSqlQuery q("CREATE TABLE t (i INTEGER)", db);
		q.prepare("INSERT INTO t (i) VALUES(?)");
		q.addBindValue(42);
		q.exec();
		db.commit();

		db.transaction();
		q.setForwardOnly(true);
		q.setForwardOnly(false);
		q.exec("SELECT * FROM t");
		q.first();
		int value = q.value(0).toInt();
		Q_ASSERT(value == 42);
		q.last();
		q.finish();
	}
	QSqlDatabase::removeDatabase("connection_name");

	QTimer::singleShot(500, qApp, SLOT(quit()));
	return app.exec();
}
Пример #5
0
void ListModel::removeItem(const QModelIndex& index)
{
    if (!index.isValid())
        return;

    ListItem* item = itemFromIndex(index);
    if (!item)
        return;

    bool isProject = item->isProject();

    ListItem* parent = item->parent();

    // disable removing the last child
    if (parent == root() && root()->childCount() == 1)
        return;

    int row = item->row();

    beginRemoveRows(indexFromItem(parent), row, row);
    QSqlDatabase db = QSqlDatabase::database();
    db.transaction();
    if (_removeItem(item)) {
        db.commit();
        if (isProject)
            emit projectRemoved();
    } else {
        db.rollback();
    }
    endRemoveRows();
}
Пример #6
0
void NetworkQueue::appendToLibrary(Scraper::ScraperData *data)
{
    qCDebug(phxLibrary) << "Game received: " << data->title << " On Platform: " << data->platform << " And artwork: " << data->front_boxart << " and: " << data->back_boxart;
    counter++;
    if (counter == 1) {
        emit progress(0.0);
        emit label("Attaching Artwork");
    }

    QSqlDatabase database = db_manager.handle();
    database.transaction();
    QSqlQuery q(database);

    q.prepare("UPDATE " + LibraryDbManager::table_games + " SET artwork = ? WHERE id = ?");

    q.addBindValue(data->front_boxart);
    q.addBindValue(data->libraryId);

    q.exec();

    delete data;

    emit ((qreal)counter / m_request_count * 100.0);

    if (counter == m_request_count) {
        database.commit();
        QMetaObject::invokeMethod(m_game_model, "select");

        emit label("");
        emit finished();
        m_request_count = 0;
        counter = 0;
    }

}
Пример #7
0
/**
 * Constructeur qui initialise le client par rapport au info contenu dans la BDD
 * @param identifiant, identifiant du client au sein de la BDD
 */
Customer::Customer(int identifiant){

    QSqlDatabase base = QSqlDatabase::database();
    QSqlQuery query;
    query.prepare("SELECT * FROM customer WHERE idCustomer=:id");
    query.bindValue(":id",identifiant);
    query.exec();

    query.next();
    QSqlRecord rec = query.record();

    m_name=rec.value("name").toString();
    m_adress=rec.value("adress").toString();
    m_adress2=rec.value("adress2").toString();
    m_city=rec.value("city").toString();
    m_country=rec.value("country").toString();
    m_email=rec.value("email").toString();
    m_phone=rec.value("phone").toString();
    m_postalCode=rec.value("postalCode").toInt();
    this->id=identifiant;

    query.finish();
    base.commit();

}
Пример #8
0
bool ContentCategory::removeCategory(QSqlDatabase &database,
                                     ContentCategory &category)
{
    // Use transaction.
    database.transaction();

    // Step1: Remove from category_category table.
    QSqlQuery query(database);
    query.prepare( "delete from category_category where "
                   "child_category_id = ?" );
    query.addBindValue(category.id());
    query.exec();

    query.prepare( "delete from category_category where "
                   "parent_category_id = ?" );
    query.addBindValue(category.id());
    query.exec();

    // Step2: Remove from content_category table
    query.prepare( "delete from content_category where "
                   "category_id = ?" );
    query.addBindValue(category.id());
    query.exec();

    // Step3: Remove from category table
    query.prepare( "delete from category where "
                   "id = ?" );
    query.addBindValue(category.id());
    query.exec();

    database.commit();
    category.clear();
    return true;
}
static bool prepareDatabase(QSqlDatabase &database)
{
    if (!database.transaction())
        return false;

    bool error = false;
    for (int i = 0; i < db_schema_count; ++i) {
        QSqlQuery query(database);

        if (!query.exec(QLatin1String(db_schema[i]))) {
            qWarning() << "Table creation failed";
            qWarning() << query.lastError();
            qWarning() << db_schema[i];
            error = true;
            break;
        }
    }

    if (error) {
        database.rollback();
        return false;
    } else {
        return database.commit();
    }
}
Пример #10
0
bool ValidDocument::createEntry(){
    QSqlDatabase base = QSqlDatabase::database();
    bool retour=false;

    QSqlQuery query;
    query.prepare("INSERT INTO DocumentValide (idCustomer,price,type,payment,date,view,tva) VALUES (:idCustomer,:price,:type,:payment,:date,:view,:tva )");
    query.bindValue(":idCustomer",idCustomer);
    query.bindValue(":price",price);
    query.bindValue(":type",docType);
    query.bindValue(":payment",payment);
    query.bindValue(":date",mdate.toString("yyyy-MM-dd"));
    query.bindValue(":view",view);
    query.bindValue(":tva",tva);

    retour=query.exec();

    if(retour)
        id=query.lastInsertId().toInt();

    query.finish();
    base.commit();


    Document d(idDocument);
    d.remove();


    return retour;

}
Пример #11
0
bool DlgEditPeoples::sqlUpdateField(
    const QString &sField,
    const T &vUi,
    T &vCp)
{
    if (vCp != vUi)
    {
        QSqlDatabase db = QSqlDatabase::database("mega");
        db.transaction();
        QSqlQuery q(db);
        q.prepare(QString("UPDATE peoples SET %1=? WHERE id=?").arg(sField));
        q.bindValue(1, m_id);
        q.bindValue(0, vUi);
        if (! q.exec())
        {
            QString se = tr("Update query error");
            qDebug() << se << ": " << q.lastError().text();
            QMessageBox::warning(this, se, q.lastError().text());
            db.rollback();
            qDebug() << q.executedQuery();
            q.clear();
            return false;
        }
        vCp = vUi;
        db.commit();
        q.clear();
    }
    return true;
}
Пример #12
0
bool Library::createUserDatabaseSchema( QSqlDatabase db ) {
    qCDebug( phxLibrary, "Initializing database schema" );
    db.transaction();

    qCDebug( phxLibrary ) << db;

    QSqlQuery q( db );
    q.exec( "CREATE TABLE schema_version (version INTEGER NOT NULL)" );
    q.exec( QStringLiteral( "INSERT INTO schema_version (version) VALUES (0)" ) );
    q.exec( QStringLiteral( "CREATE TABLE games (\n" )
            % QStringLiteral( "   rowIndex INTEGER PRIMARY KEY AUTOINCREMENT,\n" )

            % QStringLiteral( "   \n/* game info */\n" )
            % QStringLiteral( "   title TEXT NOT NULL,\n" )
            % QStringLiteral( "   system TEXT,\n" )
            % QStringLiteral( "   region TEXT,\n" )
            % QStringLiteral( "   goodtoolsCode TEXT,\n" )
            % QStringLiteral( "   timePlayed DATETIME,\n" )
            % QStringLiteral( "   artworkUrl TEXT,\n" )
            % QStringLiteral( "   coreFilePath TEXT,\n" )

            % QStringLiteral( "   /* file info */" )
            % QStringLiteral( "   absolutePath TEXT,\n" )
            % QStringLiteral( "   absoluteFilePath TEXT UNIQUE NOT NULL,\n" )
            % QStringLiteral( "   crc32Checksum TEXT\n" )
            % QStringLiteral( ")" ) );

    q.exec( QStringLiteral( "CREATE INDEX title_index ON games (title)" ) );
    q.exec( QStringLiteral( "CREATE INDEX favorite_index ON games (is_favorite)" ) );


    // Create Collections Mapping Table
    q.exec( QStringLiteral( "CREATE TABLE collections (\n" )
            % QStringLiteral( " collectionID INTEGER PRIMARY KEY AUTOINCREMENT,\n" )
            % QStringLiteral( " collectionName TEXT UNIQUE NOT NULL\n" )
            % QStringLiteral( ")" ) );

    // Create Collections Table
    q.exec( QStringLiteral( "CREATE TABLE collectionMappings (\n" )
            % QStringLiteral( " collectionID INTEGER,\n" )
            % QStringLiteral( " rowIndex INTEGER,\n" )
            % QStringLiteral( " FOREIGN KEY (collectionID) REFERENCES collections " )
            % QStringLiteral( "(collectionID) ON DELETE CASCADE ON UPDATE CASCADE\n" )
            % QStringLiteral( " FOREIGN KEY (rowIndex) REFERENCES games " )
            % QStringLiteral( "(rowIndex) ON DELETE CASCADE ON UPDATE CASCADE\n" )
            % QStringLiteral( ")" ) );

    q.exec( QStringLiteral( "INSERT INTO collections " )
            % QStringLiteral( "(collectionID, collectionName) VALUES (0, 'All')" ) );

    // Create default core table
    q.exec( QStringLiteral( "CREATE TABLE defaultCores (\n" )
            % QStringLiteral( " system TEXT UNIQUE NOT NULL," )
            % QStringLiteral( " defaultCore TEXT" )
            % QStringLiteral( ")" ) );

    db.commit();

    return true;
}
Пример #13
0
bool QSqlDatabaseProto::commit()
{
  QSqlDatabase *item = qscriptvalue_cast<QSqlDatabase*>(thisObject());
  if (item)
    return item->commit();
  return false;
}
Пример #14
0
static v8::Handle<v8::Value> qmlsqldatabase_changeVersion(const v8::Arguments& args)
{
    if (args.Length() < 2)
        return v8::Undefined();

    QV8SqlDatabaseResource *r = v8_resource_cast<QV8SqlDatabaseResource>(args.This());
    if (!r || r->type != QV8SqlDatabaseResource::Database)
        V8THROW_REFERENCE("Not a SQLDatabase object");

    QV8Engine *engine = r->engine;

    QSqlDatabase db = r->database;
    QString from_version = engine->toString(args[0]);
    QString to_version = engine->toString(args[1]);
    v8::Handle<v8::Value> callback = args[2];

    if (from_version != r->version)
        V8THROW_SQL(SQLEXCEPTION_VERSION_ERR, QQmlEngine::tr("Version mismatch: expected %1, found %2").arg(from_version).arg(r->version));

    v8::Local<v8::Object> instance = databaseData(engine)->queryConstructor->NewInstance();
    QV8SqlDatabaseResource *r2 = new QV8SqlDatabaseResource(engine);
    r2->type = QV8SqlDatabaseResource::Query;
    r2->database = db;
    r2->version = r->version;
    r2->inTransaction = true;
    instance->SetExternalResource(r2);

    bool ok = true;
    if (callback->IsFunction()) {
        ok = false;
        db.transaction();

        v8::TryCatch tc;
        v8::Handle<v8::Value> callbackArgs[] = { instance };
        v8::Handle<v8::Function>::Cast(callback)->Call(engine->global(), 1, callbackArgs);

        if (tc.HasCaught()) {
            db.rollback();
            tc.ReThrow();
            return v8::Handle<v8::Value>();
        } else if (!db.commit()) {
            db.rollback();
            V8THROW_SQL(SQLEXCEPTION_UNKNOWN_ERR,QQmlEngine::tr("SQL transaction failed"));
        } else {
            ok = true;
        }
    }

    r2->inTransaction = false;

    if (ok) {
        r2->version = to_version;
#ifndef QT_NO_SETTINGS
        QSettings ini(qmlsqldatabase_databaseFile(db.connectionName(),engine) + QLatin1String(".ini"), QSettings::IniFormat);
        ini.setValue(QLatin1String("Version"), to_version);
#endif
    }

    return v8::Undefined();
}
Пример #15
0
QModelIndex ListModel::moveItemVertical(const QModelIndex& index, App::Direction direction)
{
    ListItem* item = itemFromIndex(index);
    if (!item)
        return index;

    int row = item->row();
    if (direction == App::Up && row == 0)
        return index;

    ListItem* parent = item->parent();
    if (direction == App::Down && row == (parent->childCount() - 1))
        return index;

    ListItem* otherItem = parent->child(direction == App::Up ? row - 1 : row + 1);
    int downRow = direction == App::Down ? row : row - 1; // the row that is being moved down

    QSqlDatabase db = QSqlDatabase::database();
    db.transaction();

    if (item->setRow(direction == App::Down ? row + 1 : row - 1) &&
        otherItem->setRow(row)) {
        db.commit();
        if (beginMoveRows(index.parent(), downRow, downRow, index.parent(), downRow + 2)) {
            parent->moveChild(downRow);
            endMoveRows();
            return indexFromItem(item);
        }
    } else
        db.rollback();
    return index;
}
Пример #16
0
bool QSqlDatabaseProto::commit()
{
  QSqlDatabase *item = qscriptvalue_cast<QSqlDatabase*>(thisObject());
  if (item)
    return item->commit();
  else if (! thisObject().isNull())
    return thisObject().toVariant().value<QSqlDatabase>().commit();
  return false;
}
Пример #17
0
void FileCache::allocFileSpace( int size )
{
    QSqlDatabase database = QSqlDatabase::database( "FileCache" );
    database.transaction();

    bool ok = allocFileSpace( size, database );
    if ( ok )
        ok = database.commit();

    if ( !ok )
        database.rollback();
}
Пример #18
0
void CollectionFieldCleaner::cleanField(int collectionId, int fieldId)
{
    switch (m_metadataEngine->getFieldType(fieldId, collectionId)) {
    case MetadataEngine::ImageType:
    case MetadataEngine::FilesType:
    {
        //delete all files
        QSqlDatabase db = DatabaseManager::getInstance().getDatabase();
        QSqlQuery query(db);

        //start transaction to speed up writes
        db.transaction();

        //get all file ids
        QStringList fileIdList;
        QString tableName = m_metadataEngine->getTableName(collectionId);
        QString sql = QString("SELECT \"%1\" FROM \"%2\"")
                             .arg(QString::number(fieldId)).arg(tableName);
        query.exec(sql);

        while (query.next()) {
            QString rawData = query.value(0).toString();
            if (!rawData.isEmpty()) {
                if (rawData.contains(",")) { //file list type has comma separated ids
                    fileIdList.append(rawData.split(',',
                                                    QString::SkipEmptyParts));
                } else {
                    fileIdList.append(rawData); //img type has only one id
                }
            }
        }

        //rm files
        sql = QString("DELETE FROM files WHERE _id IN (%1)")
                .arg(fileIdList.join(","));
        query.exec(sql);

        //commit transaction
        db.commit();
    }
        break;
    case MetadataEngine::DateType:
    {
        //delete all alarm triggers if any
        AlarmManager a(this);
        a.removeAllAlarms(collectionId, fieldId);
    }
        break;
    default:
        //no special action needed
        break;
    }
}
Пример #19
0
// Перехватываем закрытие окна -------------
void DSPWindow::closeEvent( QCloseEvent *e )
{
  //if (maybeSave())
  // Подключение к базе данных ---------------------------------
  QSqlDatabase db = QSqlDatabase::database("DSP"); 

  db.commit();		// Подтверждаем транзакцию
  
  e->accept();
  //else
  //    e->ignore();
}
Пример #20
0
bool UserDataAccess::deleteCourse(Course* course)
{
    QSqlDatabase db = database();

    if (!db.isOpen())
        return false;

    if (!db.transaction())
    {
        kWarning() <<  db.lastError().text();
        raiseError(db.lastError());
        return false;
    }

    QSqlQuery deleteCourseQuery(db);

    deleteCourseQuery.prepare("DELETE FROM courses WHERE id = ?");
    deleteCourseQuery.bindValue(0, course->id());
    deleteCourseQuery.exec();

    if (deleteCourseQuery.lastError().isValid())
    {
        kWarning() << deleteCourseQuery.lastError().text();
        raiseError(deleteCourseQuery.lastError());
        db.rollback();
        return false;
    }

    QSqlQuery deleteLessonsQuery(db);

    deleteLessonsQuery.prepare("DELETE FROM course_lessons WHERE course_id = ?");
    deleteLessonsQuery.bindValue(0, course->id());
    deleteLessonsQuery.exec();

    if (deleteLessonsQuery.lastError().isValid())
    {
        kWarning() << deleteLessonsQuery.lastError().text();
        raiseError(deleteLessonsQuery.lastError());
        db.rollback();
        return false;
    }

    if(!db.commit())
    {
        kWarning() <<  db.lastError().text();
        raiseError(db.lastError());
        db.rollback();
        return false;
    }

    return true;
}
Пример #21
0
void MainWindow::savetabletodb()
{
    QSqlDatabase db;
    db=QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("bullware.dat");
    if (db.open())
    {
        qDebug() << "db open: success";
        QSqlQuery query;
        query.exec("drop table transactions");
        if (query.exec("create table if not exists transactions(stock varchar(20), type int, date date, amount float, price float, currency char(3), sum float, sumcurrency char(3))"))
        {
            qDebug() << "create query successful";
            for (int y=0; y<ui->tableWidget->rowCount()-1; ++y)
            {
                if (ui->tableWidget->item(y,0))
                {
                    QString line="'";
                    line.append(ui->tableWidget->item(y,0)->text()); // stock
                    line.append("',");
                    line.append(type(ui->tableWidget->item(y,1)->text())); // type
                    line.append(",'");
                    line.append(ui->tableWidget->item(y,2)->text()); // date
                    line.append("',");
                    line.append(ui->tableWidget->item(y,3)->text()); // amount
                    line.append(",");
                    line.append(ui->tableWidget->item(y,4)->text()); // price
                    line.append(",'");
                    line.append(ui->tableWidget->item(y,5)->text()); // price currency
                    line.append("',");
                    line.append(ui->tableWidget->item(y,6)->text()); // sum
                    line.append(",'");
                    line.append(ui->tableWidget->item(y,7)->text()); // sum currency
                    if (!query.exec(QString("insert into transactions VALUES (").append(line).append("')")))
                    {
                        qDebug() << "insert query failed" << line;
                    }
                    else qDebug() << "insert query ok" << line;
                }
            }
        }
        else
        {
            qDebug() << "create query failed";
        }
    }
    else
        qDebug() << "db open failed";
    db.commit();
    db.close();
}
Пример #22
0
//-----------------------------------------------------------------------------------------
// 题目列表
// Add questions
int ddmAddQuestions(QList<CQuestion> &quesList)
{
	QSqlQuery q;
	QString sql;

	db.transaction();
    for (int i = 0; i < quesList.length(); i++) {
        CQuestion ques = quesList[i];

        switch (ques.type) {
        case EQUES_TYPE_SIGOPTION:
        case EQUES_TYPE_MULOPTION:
            sql = QObject::tr("INSERT INTO "
                    "questions (paperId, title, optionA, optionB, optionC, optionD, answer, type) "
                    "VALUES (%1, '%2', '%3', '%4', '%5', '%6', '%7', %8)")
                    .arg(ques.paper_id).arg(ques.title).arg(ques.options[0])
                    .arg(ques.options[1]).arg(ques.options[2]).arg(ques.options[3])
                    .arg(ques.proper_ans).arg(ques.type);
			break;
        case EQUES_TYPE_JUDGE:
        case EQUES_TYPE_CALC_ANALYSIS:
        case EQUES_TYPE_CASE_ANALYSIS:
        case EQUES_TYPE_UNCONFIRM_OPTION:
			sql = QObject::tr("INSERT INTO "
					"questions (paperId, title, answer, type) "
                    "VALUES (%1, '%2', '%3', %4)").arg(ques.paper_id)
                    .arg(ques.title).arg(ques.proper_ans).arg(ques.type);
			break;
        case EQUES_TYPE_ACTUAL_PRACTICE:
            sql = QObject::tr("INSERT INTO "
                    "questions (paperId, title, type) VALUES (%1, '%2', %3)")
                    .arg(ques.paper_id).arg(ques.title).arg(ques.type);
			break;
		}

		if (sql.isEmpty())
			continue;
        if (!q.exec(sql)) {
			QMessageBox::warning(0, QObject::tr("错误"), q.lastError().text());
			db.rollback();
			return -1;
		}
		sql.clear();
	}

    if (!db.commit()) {
		db.rollback();
		return -1;
	}
	return 0;
}
Пример #23
0
/**
 * Methode qui sauvegarde un document valider dans la base de données
 * @return true si l'enregistrement n'a pas poser de probleme, false sinon
 */
bool ValidDocument::save(){
    QSqlDatabase base = QSqlDatabase::database();
    bool retour=false;

    if(id==-1){
        retour=createEntry();
    }
    else{
        retour=updateEntry();
    }

    base.commit();
    return retour;
}
Пример #24
0
QSqlDatabase DatabaseFactory::sqliteInitializeInMemoryDatabase() {
  QSqlDatabase database = QSqlDatabase::addDatabase(APP_DB_SQLITE_DRIVER);

  database.setDatabaseName(QSL(":memory:"));

  if (!database.open()) {
    qFatal("In-memory SQLite database was NOT opened. Delivered error message: '%s'", qPrintable(database.lastError().text()));
  }
  else {
    QSqlQuery query_db(database);

    query_db.setForwardOnly(true);
    query_db.exec(QSL("PRAGMA encoding = \"UTF-8\""));
    query_db.exec(QSL("PRAGMA synchronous = OFF"));
    query_db.exec(QSL("PRAGMA journal_mode = MEMORY"));
    query_db.exec(QSL("PRAGMA page_size = 4096"));
    query_db.exec(QSL("PRAGMA cache_size = 16384"));
    query_db.exec(QSL("PRAGMA count_changes = OFF"));
    query_db.exec(QSL("PRAGMA temp_store = MEMORY"));

    // Sample query which checks for existence of tables.
    query_db.exec(QSL("SELECT inf_value FROM Information WHERE inf_key = 'schema_version'"));

    if (query_db.lastError().isValid()) {
      qWarning("Error occurred. In-memory SQLite database is not initialized. Initializing now.");

      QFile file_init(APP_MISC_PATH + QDir::separator() + APP_DB_SQLITE_INIT);

      if (!file_init.open(QIODevice::ReadOnly | QIODevice::Text)) {
        // Database initialization file not opened. HUGE problem.
        qFatal("In-memory SQLite database initialization file '%s' from directory '%s' was not found. In-memory database is uninitialized.",
               APP_DB_SQLITE_INIT,
               qPrintable(APP_MISC_PATH));
      }

      const QStringList statements = QString(file_init.readAll()).split(APP_DB_COMMENT_SPLIT, QString::SkipEmptyParts);
      database.transaction();

      foreach(const QString &statement, statements) {
        query_db.exec(statement);

        if (query_db.lastError().isValid()) {
          qFatal("In-memory SQLite database initialization failed. Initialization script '%s' is not correct.", APP_DB_SQLITE_INIT);
        }
      }

      database.commit();
      qDebug("In-memory SQLite database backend should be ready now.");
    }
Пример #25
0
void PropertiesDialog::updateComics()
{
	QSqlDatabase db = DataBaseManagement::loadDatabase(databasePath);
	db.open();
	db.transaction();
	QList<ComicDB>::iterator itr;
	for(itr = comics.begin();itr!=comics.end();itr++)
	{
		if(itr->info.edited)
			DBHelper::update(&(itr->info),db);
	}
	db.commit();
	db.close();
	QSqlDatabase::removeDatabase(databasePath);
}
Пример #26
0
QList<Product> Product::getAllProduct(){
    QList<Product> list;

    QSqlDatabase base = QSqlDatabase::database();
    QSqlQuery query;
    query.exec("SELECT idProduct FROM product ORDER BY idProduct");

    while(query.next()){
        Product p(query.record().value("idProduct").toInt());
        list.append(p);
    }

    query.finish();
    base.commit();
    return list;
}
Пример #27
0
/*! \brief Same as qttools::execSqlCode() but execution performs inside a transaction
 *  \note Any SqlQueryError exceptions thrown by qttools::execSqlCode() is catched (transaction
 *        is rolled back then)
 */
QSqlQuery execSqlCodeInTransaction(const QString& sqlCode, QSqlDatabase db)
{
  db.transaction();

  QSqlQuery sqlQry;
  try {
    sqlQry = qttools::execSqlCode(sqlCode, db);
    db.commit();
  }
  catch (const SqlQueryError& err) {
    Q_UNUSED(err);
    db.rollback();
    throw;
  }
  return sqlQry;
}
Пример #28
0
bool MappeurAppareils::ecrire(const Appareil* appareil, const QString &commande)
{
    QSqlDatabase bd = *Application::bd;
    bd.transaction();
    QSqlQuery* requete = preparerRequete(appareil, commande);
    const bool succes = requete->exec();
    if (succes) {
        bd.commit();
        AideMappeurs::noterModification();
    } else {
        Application::erreurEcriture(requete->lastError().text());
        bd.rollback();
    }
    delete requete;
    return succes;
}
Пример #29
0
QList<Customer> Customer::getAllCustomer(){
    QList<Customer> list;

    QSqlDatabase base = QSqlDatabase::database();
    QSqlQuery query;
    query.exec("SELECT idCustomer FROM customer ORDER BY idCustomer");

    while(query.next()){
        Customer c(query.record().value("idCustomer").toInt());
        list.append(c);
    }

    query.finish();
    base.commit();
    return list;
}
Пример #30
0
static QScriptValue qmlsqldatabase_change_version(QScriptContext *context, QScriptEngine *engine)
{
    if (context->argumentCount() < 2)
        return engine->undefinedValue();

    QSqlDatabase db = qscriptvalue_cast<QSqlDatabase>(context->thisObject());
    QString from_version = context->argument(0).toString();
    QString to_version = context->argument(1).toString();
    QScriptValue callback = context->argument(2);

    QScriptValue instance = engine->newObject();
    instance.setProperty(QLatin1String("executeSql"), engine->newFunction(qmlsqldatabase_executeSql,1));
    QScriptValue tx = engine->newVariant(instance,QVariant::fromValue(db));

    QString foundvers = context->thisObject().property(QLatin1String("version")).toString();
    if (from_version!=foundvers) {
        THROW_SQL(VERSION_ERR,QDeclarativeEngine::tr("Version mismatch: expected %1, found %2").arg(from_version).arg(foundvers));
        return engine->undefinedValue();
    }

    bool ok = true;
    if (callback.isFunction()) {
        ok = false;
        db.transaction();
        callback.call(QScriptValue(), QScriptValueList() << tx);
        if (engine->hasUncaughtException()) {
            db.rollback();
        } else {
            if (!db.commit()) {
                db.rollback();
                THROW_SQL(UNKNOWN_ERR,QDeclarativeEngine::tr("SQL transaction failed"));
            } else {
                ok = true;
            }
        }
    }

    if (ok) {
        context->thisObject().setProperty(QLatin1String("version"), to_version, QScriptValue::ReadOnly);
#ifndef QT_NO_SETTINGS
        QSettings ini(qmlsqldatabase_databaseFile(db.connectionName(),engine) + QLatin1String(".ini"), QSettings::IniFormat);
        ini.setValue(QLatin1String("Version"), to_version);
#endif
    }

    return engine->undefinedValue();
}