Exemplo n.º 1
0
QStringList SqliteDriver::tables(const QString &typeName) const
{
  QStringList res;
  if (!isOpen() || !dataBase_)
    return res;
  int type = typeName.toInt();

  QSqlQuery q = createQuery();
  q.setForwardOnly(TRUE);
#if (QT_VERSION-0 >= 0x030000)
  if ((type & (int)QSql::Tables) && (type & (int)QSql::Views))
    q.exec("SELECT name FROM sqlite_master WHERE type='table' OR type='view'");
  else if (typeName.isEmpty() || (type & (int)QSql::Tables))
    q.exec("SELECT name FROM sqlite_master WHERE type='table'");
  else if (type & (int)QSql::Views)
    q.exec("SELECT name FROM sqlite_master WHERE type='view'");
#else
  q.exec("SELECT name FROM sqlite_master WHERE type='table' OR type='view'");
#endif


  if (q.isActive()) {
    while (q.next())
      res.append(q.value(0).toString());
  }

#if (QT_VERSION-0 >= 0x030000)
  if (type & (int)QSql::SystemTables) {
    // there are no internal tables beside this one:
    res.append("sqlite_master");
  }
#endif

  return res;
}
Exemplo n.º 2
0
QSqlIndex SqliteDriver::primaryIndex2(const QString &tblname) const
{
  QSqlRecordInfo rec(recordInfo(tblname));     // expensive :(

  if (!isOpen() || !dataBase_)
    return QSqlIndex();

  QSqlQuery q = createQuery();
  q.setForwardOnly(TRUE);
  // finrst find a UNIQUE INDEX
  q.exec("PRAGMA index_list('" + tblname + "');");
  QString indexname;
  while (q.next()) {
    if (q.value(2).toInt() == 1) {
      indexname = q.value(1).toString();
      break;
    }
  }
  if (indexname.isEmpty())
    return QSqlIndex();

  q.exec("PRAGMA index_info('" + indexname + "');");

  QSqlIndex index(tblname, indexname);
  while (q.next()) {
    QString name = q.value(2).toString();
    QSqlVariant::Type type = QSqlVariant::Invalid;
    if (rec.contains(name))
      type = rec.find(name).type();
    index.append(QSqlField(name, type));
  }
  return index;
}
Exemplo n.º 3
0
bool AbstractQueryItem::load()
{
    if (m_account == nullptr || !isQueryValid() || m_status == Loading) {
        return false;
    }

    QNetworkReply *reply = createQuery();
    setStatusAndErrorMessage(Loading, QString());

    connect(reply, &QNetworkReply::finished, this, [this, reply]() {
        QObjectPtr<QNetworkReply> replyPtr {reply};
        const QByteArray &data {replyPtr->readAll()};
        handleReply(data, replyPtr->error(), replyPtr->errorString());
        if (m_status == Loading) {
            if (replyPtr->error() != QNetworkReply::NoError) {
                qCWarning(QLoggingCategory("query-item")) << "Error happened during query";
                qCWarning(QLoggingCategory("query-item")) << "Error code:" << replyPtr->error();
                qCWarning(QLoggingCategory("query-item")) << "Error message (Qt):" << replyPtr->errorString();
                qCWarning(QLoggingCategory("query-item")) << "Error message (Twitter):" << data;
                setStatusAndErrorMessage(Error, tr("Network error. Please try again later."));
            } else {
                setStatusAndErrorMessage(Idle, QString());
            }
        }
    });

    return true;
}
Exemplo n.º 4
0
// Called due to cefQuery execution in binding.html.
bool QueryHandler::OnQuery(CefRefPtr<CefBrowser> browser,
                           CefRefPtr<CefFrame> frame,
                           int64 query_id,
                           const CefString& request,
                           bool persistent,
                           CefRefPtr<Callback> callback) {
  try {
    auto query = createQuery(browser, frame, request.ToString());

    if (!query)
      return false;

    CefPostTask(TID_FILE, base::Bind(&Query::execute, query, callback));
  } catch (std::exception& e) {
    auto logger = lootState_.getLogger();
    if (logger) {
      logger->error("Failed to parse CEF query request \"{}\": {}",
        request.ToString(),
        e.what());
    }
    callback->Failure(-1, e.what());
  }

  return true;
}
Exemplo n.º 5
0
QVariant SqliteDriver::nextSerialVal(const QString &table, const QString &field)
{
  QSqlQuery query = createQuery();
  query.exec("SELECT max(" + field + ") FROM " + table + ";");
  query.next();
  return query.value(0).toInt() + 1;
}
Exemplo n.º 6
0
	D3D9TimerQuery::D3D9TimerQuery()
		:mFinalized(false), mBeginQuery(nullptr), mFreqQuery(nullptr), mQueryIssued(false),
		mEndQuery(nullptr), mDisjointQuery(nullptr), mTimeDelta(0.0f), mDevice(nullptr)
	{
		createQuery();

		BS_INC_RENDER_STAT_CAT(ResCreated, RenderStatObject_Query);
	}
Exemplo n.º 7
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();
}
Exemplo n.º 8
0
QSqlRecordInfo SqliteDriver::recordInfo2(const QString &tbl) const
{
  if (!isOpen() || !dataBase_)
    return QSqlRecordInfo();

  QSqlQuery q = createQuery();
  q.setForwardOnly(TRUE);
  q.exec("SELECT * FROM " + tbl + " LIMIT 1");
  return recordInfo(q);
}
Exemplo 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();
}
Exemplo n.º 10
0
VERITAS::VSDBStatement* 
VERITAS::VSDatabase::createSelectQuery(const std::string& table, 
				       const std::string& condition,
				       const std::string& columns, 
				       uint32_t flags) throw()
{
  std::ostringstream qstream;
  qstream << "SELECT ";
  if(!columns.empty())qstream << columns;
  else qstream << "*";
  qstream << " FROM " << table;
  if(!condition.empty())qstream << " WHERE " << condition;
  return createQuery(qstream.str(), flags);
}
bool guFolderInspector::initDb()
{
    QSqlQuery createQuery(db);
    QFile file(":/sql/sql/createDb.sql");
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
        return false;
    QString queryText = file.readAll();
    //qDebug() << queryText;
    QStringList queryList = queryText.split("|");
    for ( int i = 0 ; i < queryList.count() ; i++)
    {
        //qDebug() << queryList.at(i);
        createQuery.exec( queryList.at(i));
    }
    file.close();
    return true;
}
Exemplo n.º 12
0
QSqlIndex QMYSQLDriver::primaryIndex( const QString& tablename ) const
{
    QSqlIndex idx;
    if ( !isOpen() )
	return idx;
    QSqlQuery i = createQuery();
    QString stmt( "show index from %1;" );
    QSqlRecord fil = record( tablename );
    i.exec( stmt.arg( tablename ) );
    while ( i.isActive() && i.next() ) {
	if ( i.value(2).toString() == "PRIMARY" ) {
	    idx.append( *fil.field( i.value(4).toString() ) );
	    idx.setCursorName( i.value(0).toString() );
	    idx.setName( i.value(2).toString() );
	}
    }
    return idx;
}
Exemplo n.º 13
0
QTM_BEGIN_NAMESPACE

QMDEGalleryQueryResultSet::QMDEGalleryQueryResultSet(QMdeSession *session, QObject *parent)
:QMDEGalleryResultSet(parent)
{
    m_request = static_cast<QGalleryQueryRequest *>(parent);
    m_live = m_request->autoUpdate();
    m_session = session;
    m_query = NULL;
    m_launchUpdateQuery = false;
    m_query_running = false;
    m_cleaned = false;

    if (m_session)
        m_session->AddTrackedResultSet( this );

    createQuery();
}
Exemplo n.º 14
0
void Donations::loadData() {
	dateFrom->setDate(QDate::currentDate().addMonths(-4));
	dateUntil->setDate(QDate::currentDate());
	
	QSqlQuery query = createQuery();
	query.exec();
	tableModel->setQuery(query);
	
	tableModel->setHeaderData(0, Qt::Horizontal, tr("Person"));
	tableModel->setHeaderData(1, Qt::Horizontal, tr("Amount"));
	tableModel->setHeaderData(2, Qt::Horizontal, tr("City"));
	tableModel->setHeaderData(3, Qt::Horizontal, tr("Section"));
	tableModel->setHeaderData(4, Qt::Horizontal, tr("Date"));
	tableModel->setHeaderData(5, Qt::Horizontal, tr("Objective"));
	
	tableView->setSortingEnabled(false);
	tableView->setModel(tableModel);
}
	//------------------------------------------------------------------
	// Occlusion query functions (see base class documentation for this)
	//--
	void D3D9HardwareOcclusionQuery::beginOcclusionQuery() 
	{	
		IDirect3DDevice9* pCurDevice  = D3D9RenderSystem::getActiveD3D9Device();				
		DeviceToQueryIterator it      = mMapDeviceToQuery.find(pCurDevice);

		// No resource exits for current device -> create it.
		if (it == mMapDeviceToQuery.end() || it->second == NULL)		
			createQuery(pCurDevice);			
		

		// Grab the query of the current device.
		IDirect3DQuery9* pOccQuery = mMapDeviceToQuery[pCurDevice];

		
		if (pOccQuery != NULL)
		{
			pOccQuery->Issue(D3DISSUE_BEGIN); 
			mIsQueryResultStillOutstanding = true;
			mPixelCount = 0;
		}		
	}
Exemplo n.º 16
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();
}
Exemplo n.º 17
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();
}
Exemplo n.º 18
0
// Called due to cefQuery execution in binding.html.
bool QueryHandler::OnQuery(CefRefPtr<CefBrowser> browser,
                           CefRefPtr<CefFrame> frame,
                           int64 query_id,
                           const CefString& request,
                           bool persistent,
                           CefRefPtr<Callback> callback) {
  YAML::Node parsedRequest;
  try {
    parsedRequest = JSON::parse(request.ToString());
  } catch (exception &e) {
    BOOST_LOG_TRIVIAL(error) << "Failed to parse CEF query request \"" << request.ToString() << "\": " << e.what();
    callback->Failure(-1, e.what());
    return true;
  }

  auto query = createQuery(browser, frame, parsedRequest);

  if (!query)
    return false;

  CefPostTask(TID_FILE, base::Bind(&Query::execute, query, callback));

  return true;
}
Exemplo n.º 19
0
void Donations::searchData() {
	QSqlQuery query = createQuery();
	query.exec();
	tableModel->setQuery(query);
	showOverview();
}
Exemplo n.º 20
0
void mysqlQuery::execute(QString const& sql)
{
    Query = createQuery(sql);
    checkQuery();
}
Exemplo n.º 21
0
void mysqlQuery::execute(void)
{
    Query = createQuery(query()->sql());
    checkQuery();
}
Exemplo n.º 22
0
void LocationCompleterModel::refreshCompletions(const QString &string)
{
    if (m_lastCompletion == string) {
        refreshTabPositions();
        return;
    }

    m_lastCompletion = string;

    if (string.isEmpty()) {
        showMostVisited();
        return;
    }

    clear();

    Type showType = (Type) qzSettings->showLocationSuggestions;

    int limit = string.size() < 3 ? 25 : 15;
    QList<QUrl> urlList;
    QList<QStandardItem*> itemList;

    if (showType == HistoryAndBookmarks || showType == Bookmarks) {
        QSqlQuery query = createQuery(string, "history.count DESC", urlList, limit, true);
        query.exec();

        while (query.next()) {
            QStandardItem* item = new QStandardItem();
            const QUrl &url = query.value(1).toUrl();

            item->setIcon(qIconProvider->iconFromImage(QImage::fromData(query.value(4).toByteArray())));
            item->setText(url.toEncoded());
            item->setData(query.value(0), IdRole);
            item->setData(query.value(2), TitleRole);
            item->setData(query.value(3), CountRole);
            item->setData(QVariant(true), BookmarkRole);
            item->setData(string, SearchStringRole);
            if (qzSettings->showSwitchTab) {
                item->setData(QVariant::fromValue<TabPosition>(tabPositionForUrl(url)), TabPositionRole);
            }

            urlList.append(url);
            itemList.append(item);
        }

        limit -= query.size();
    }

    if (showType == HistoryAndBookmarks || showType == History) {
        QSqlQuery query = createQuery(string, "count DESC", urlList, limit);
        query.exec();

        while (query.next()) {
            QStandardItem* item = new QStandardItem();
            const QUrl &url = query.value(1).toUrl();

            item->setIcon(_iconForUrl(url));
            item->setText(url.toEncoded());
            item->setData(query.value(0), IdRole);
            item->setData(query.value(2), TitleRole);
            item->setData(query.value(3), CountRole);
            item->setData(QVariant(false), BookmarkRole);
            item->setData(string, SearchStringRole);
            if (qzSettings->showSwitchTab) {
                item->setData(QVariant::fromValue<TabPosition>(tabPositionForUrl(url)), TabPositionRole);
            }

            itemList.append(item);
        }
    }

    // Sort by count
    qSort(itemList.begin(), itemList.end(), countBiggerThan);

    appendColumn(itemList);
}
Exemplo n.º 23
0
	void D3D9TimerQuery::notifyOnDeviceReset(IDirect3DDevice9* d3d9Device)
	{
		if (d3d9Device == mDevice)
			createQuery();
	}
void TimeTrackerConfigurationWidget::on_btnNewCompany_clicked()
{
  QString fileName = QFileDialog::getSaveFileName(this, "Database File", "", "Image Files (*.sqlite)");

  if(fileName.toStdString().empty())
    {
    std::cout << "Filename was empty." << std::endl;
    return;
    }

  if(QFile::exists(fileName))
    {
    QMessageBox::warning(this, "Time Tracker Configuration",
                               "This company database already exists. Please choose a different file.",
                                QMessageBox::Ok);
    return;
    }

  if(this->CompanyDatabase)
    {
    delete this->CompanyDatabase;
    this->CompanyDatabase = NULL;
    }

  QSqlDatabase::removeDatabase("CompanyDatabase");

  this->CompanyDatabase = new QSqlDatabase(QSqlDatabase::addDatabase("QSQLITE"));
  this->CompanyDatabase->setDatabaseName(fileName);
  if (this->CompanyDatabase->open())
    {
    std::cout << "Opened." << std::endl;
    }
  else
    {
    std::cerr << "Could not open database" << std::endl;
    std::cerr << this->CompanyDatabase->lastError().text().toStdString() << std::endl;
    }

  QSqlQuery createQuery(*(this->CompanyDatabase));
  bool createSuccess = createQuery.exec("create table CompanyTable "
              "(id integer primary key, "
              "CompanyName TEXT, "
              "PayrollClientNumber TEXT, "
              "PayDay TEXT, "
              "PayrollFaxNumber TEXT, "
              "MOTD TEXT, "
              "PayrollContact TEXT, "
              "OwnerName TEXT, "
              "CompanyPhone TEXT, "
              "PayrollSubmission TEXT)");

  if(!createSuccess)
    {
    std::cerr << "Could not create table!" << std::endl;
    std::cerr << createQuery.lastError().text().toStdString() << std::endl;
    return;
    }

  // Populate the table with default values
  QSqlQuery insertQuery(*(this->CompanyDatabase));
  insertQuery.prepare("INSERT INTO CompanyTable (id, CompanyName, PayrollClientNumber, PayDay, PayrollFaxNumber, MOTD, PayrollContact, OwnerName, CompanyPhone, PayrollSubmission) "
                "VALUES (:id, :CompanyName, :PayrollClientNumber, :PayDay, :PayrollFaxNumber, :MOTD, :PayrollContact, :OwnerName, :CompanyPhone, :PayrollSubmission)");
  insertQuery.bindValue(":id", 0);
  insertQuery.bindValue(":CompanyName", "CompanyName");
  insertQuery.bindValue(":PayrollClientNumber", "PayrollClientNumber");
  insertQuery.bindValue(":PayDay", "PayDay");
  insertQuery.bindValue(":PayrollFaxNumber", "PayrollFaxNumber");
  insertQuery.bindValue(":MOTD", "MOTD");
  insertQuery.bindValue(":PayrollContact", "PayrollContact");
  insertQuery.bindValue(":OwnerName", "OwnerName");
  insertQuery.bindValue(":CompanyPhone", "CompanyPhone");
  insertQuery.bindValue(":PayrollSubmission", "PayrollSubmission");
  bool insertSuccess = insertQuery.exec();
  if(!insertSuccess)
    {
    std::cerr << "Could not insert values!" << std::endl;
    std::cerr << "insertQuery last error: " << insertQuery.lastError().text().toStdString() << std::endl;
    return;
    }
  
  EditCompanyWidget* editCompanyWidget = new EditCompanyWidget(this->CompanyDatabase);
  editCompanyWidget->exec();
}
Exemplo n.º 25
0
bool SyncJournalDb::checkConnect()
{
    if( _db.isOpen() ) {
        return true;
    }

    if( _dbFile.isEmpty()) {
        qDebug() << "Database filename" + _dbFile + " is empty";
        return false;
    }

    bool isNewDb = !QFile::exists(_dbFile);

    // The database file is created by this call (SQLITE_OPEN_CREATE)
    if( !_db.openOrCreateReadWrite(_dbFile) ) {
        QString error = _db.error();
        qDebug() << "Error opening the db: " << error;
        return false;
    }

    if( !QFile::exists(_dbFile) ) {
        qDebug() << "Database file" + _dbFile + " does not exist";
        return false;
    }

    SqlQuery pragma1(_db);
    pragma1.prepare("SELECT sqlite_version();");
    if (!pragma1.exec()) {
        return sqlFail("SELECT sqlite_version()", pragma1);
    } else {
        pragma1.next();
        qDebug() << "sqlite3 version" << pragma1.stringValue(0);
    }

    // Allow forcing the journal mode for debugging
    static QString env_journal_mode = QString::fromLocal8Bit(qgetenv("OWNCLOUD_SQLITE_JOURNAL_MODE"));
    QString journal_mode = env_journal_mode;
    if (journal_mode.isEmpty()) {
        journal_mode = defaultJournalMode(_dbFile);
    }
    pragma1.prepare(QString("PRAGMA journal_mode=%1;").arg(journal_mode));
    if (!pragma1.exec()) {
        return sqlFail("Set PRAGMA journal_mode", pragma1);
    } else {
        pragma1.next();
        qDebug() << "sqlite3 journal_mode=" << pragma1.stringValue(0);
    }

    // For debugging purposes, allow temp_store to be set
    static QString env_temp_store = QString::fromLocal8Bit(qgetenv("OWNCLOUD_SQLITE_TEMP_STORE"));
    if (!env_temp_store.isEmpty()) {
        pragma1.prepare(QString("PRAGMA temp_store = %1;").arg(env_temp_store));
        if (!pragma1.exec()) {
            return sqlFail("Set PRAGMA temp_store", pragma1);
        }
        qDebug() << "sqlite3 with temp_store =" << env_temp_store;
    }

    pragma1.prepare("PRAGMA synchronous = 1;");
    if (!pragma1.exec()) {
        return sqlFail("Set PRAGMA synchronous", pragma1);
    }
    pragma1.prepare("PRAGMA case_sensitive_like = ON;");
    if (!pragma1.exec()) {
        return sqlFail("Set PRAGMA case_sensitivity", pragma1);
    }

    /* Because insert is so slow, we do everything in a transaction, and only need one call to commit */
    startTransaction();

    SqlQuery createQuery(_db);
    createQuery.prepare("CREATE TABLE IF NOT EXISTS metadata("
                         "phash INTEGER(8),"
                         "pathlen INTEGER,"
                         "path VARCHAR(4096),"
                         "inode INTEGER,"
                         "uid INTEGER,"
                         "gid INTEGER,"
                         "mode INTEGER,"
                         "modtime INTEGER(8),"
                         "type INTEGER,"
                         "md5 VARCHAR(32)," /* This is the etag.  Called md5 for compatibility */
                        // updateDatabaseStructure() will add a fileid column
                        // updateDatabaseStructure() will add a remotePerm column
                         "PRIMARY KEY(phash)"
                         ");");

    if (!createQuery.exec()) {
        return sqlFail("Create table metadata", createQuery);
    }

    createQuery.prepare("CREATE TABLE IF NOT EXISTS downloadinfo("
                         "path VARCHAR(4096),"
                         "tmpfile VARCHAR(4096),"
                         "etag VARCHAR(32),"
                         "errorcount INTEGER,"
                         "PRIMARY KEY(path)"
                         ");");

    if (!createQuery.exec()) {
        return sqlFail("Create table downloadinfo", createQuery);
    }

    createQuery.prepare("CREATE TABLE IF NOT EXISTS uploadinfo("
                           "path VARCHAR(4096),"
                           "chunk INTEGER,"
                           "transferid INTEGER,"
                           "errorcount INTEGER,"
                           "size INTEGER(8),"
                           "modtime INTEGER(8),"
                           "PRIMARY KEY(path)"
                           ");");

    if (!createQuery.exec()) {
        return sqlFail("Create table uploadinfo", createQuery);
    }

    // create the blacklist table.
    createQuery.prepare("CREATE TABLE IF NOT EXISTS blacklist ("
                        "path VARCHAR(4096),"
                        "lastTryEtag VARCHAR[32],"
                        "lastTryModtime INTEGER[8],"
                        "retrycount INTEGER,"
                        "errorstring VARCHAR[4096],"
                        "PRIMARY KEY(path)"
                        ");");

    if (!createQuery.exec()) {
        return sqlFail("Create table blacklist", createQuery);
    }

    createQuery.prepare("CREATE TABLE IF NOT EXISTS poll("
                           "path VARCHAR(4096),"
                           "modtime INTEGER(8),"
                           "pollpath VARCHAR(4096));");
    if (!createQuery.exec()) {
        return sqlFail("Create table poll", createQuery);
    }

    // create the selectivesync table.
    createQuery.prepare("CREATE TABLE IF NOT EXISTS selectivesync ("
                        "path VARCHAR(4096),"
                        "type INTEGER"
                        ");");

    if (!createQuery.exec()) {
        return sqlFail("Create table selectivesync", createQuery);
    }



    createQuery.prepare("CREATE TABLE IF NOT EXISTS version("
                               "major INTEGER(8),"
                               "minor INTEGER(8),"
                               "patch INTEGER(8),"
                               "custom VARCHAR(256)"
                               ");");
    if (!createQuery.exec()) {
        return sqlFail("Create table version", createQuery);
    }

    bool forceRemoteDiscovery = false;

    SqlQuery versionQuery("SELECT major, minor, patch FROM version;", _db);
    if (!versionQuery.next()) {
        // If there was no entry in the table, it means we are likely upgrading from 1.5
        if (!isNewDb) {
            qDebug() << Q_FUNC_INFO << "possibleUpgradeFromMirall_1_5 detected!";
            forceRemoteDiscovery = true;
        }
        createQuery.prepare("INSERT INTO version VALUES (?1, ?2, ?3, ?4);");
        createQuery.bindValue(1, MIRALL_VERSION_MAJOR);
        createQuery.bindValue(2, MIRALL_VERSION_MINOR);
        createQuery.bindValue(3, MIRALL_VERSION_PATCH);
        createQuery.bindValue(4, MIRALL_VERSION_BUILD);
        createQuery.exec();

    } else {
        int major = versionQuery.intValue(0);
        int minor = versionQuery.intValue(1);
        int patch = versionQuery.intValue(2);

        if( major == 1 && minor == 8 && (patch == 0 || patch == 1) ) {
            qDebug() << Q_FUNC_INFO << "possibleUpgradeFromMirall_1_8_0_or_1 detected!";
            forceRemoteDiscovery = true;
        }
        // Not comparing the BUILD id here, correct?
        if( !(major == MIRALL_VERSION_MAJOR && minor == MIRALL_VERSION_MINOR && patch == MIRALL_VERSION_PATCH) ) {
            createQuery.prepare("UPDATE version SET major=?1, minor=?2, patch =?3, custom=?4 "
                                "WHERE major=?5 AND minor=?6 AND patch=?7;");
            createQuery.bindValue(1, MIRALL_VERSION_MAJOR);
            createQuery.bindValue(2, MIRALL_VERSION_MINOR);
            createQuery.bindValue(3, MIRALL_VERSION_PATCH);
            createQuery.bindValue(4, MIRALL_VERSION_BUILD);
            createQuery.bindValue(5, major);
            createQuery.bindValue(6, minor);
            createQuery.bindValue(7, patch);
            if (!createQuery.exec()) {
                return sqlFail("Update version", createQuery);
            }

        }
    }

    commitInternal("checkConnect");

    bool rc = updateDatabaseStructure();
    if( !rc ) {
        qDebug() << "WARN: Failed to update the database structure!";
    }

    /*
     * If we are upgrading from a client version older than 1.5,
     * we cannot read from the database because we need to fetch the files id and etags.
     *
     *  If 1.8.0 caused missing data in the local tree, so we also don't read from DB
     *  to get back the files that were gone.
     *  In 1.8.1 we had a fix to re-get the data, but this one here is better
     */
    if (forceRemoteDiscovery) {
        forceRemoteDiscoveryNextSyncLocked();
    }

    _getFileRecordQuery.reset(new SqlQuery(_db));
    _getFileRecordQuery->prepare("SELECT path, inode, uid, gid, mode, modtime, type, md5, fileid, remotePerm, filesize, ignoredChildrenRemote FROM "
                                 "metadata WHERE phash=?1" );

    _setFileRecordQuery.reset(new SqlQuery(_db) );
    _setFileRecordQuery->prepare("INSERT OR REPLACE INTO metadata "
                                 "(phash, pathlen, path, inode, uid, gid, mode, modtime, type, md5, fileid, remotePerm, filesize, ignoredChildrenRemote) "
                                 "VALUES (?1 , ?2, ?3 , ?4 , ?5 , ?6 , ?7,  ?8 , ?9 , ?10, ?11, ?12, ?13, ?14);" );

    _getDownloadInfoQuery.reset(new SqlQuery(_db) );
    _getDownloadInfoQuery->prepare( "SELECT tmpfile, etag, errorcount FROM "
                                    "downloadinfo WHERE path=?1" );

    _setDownloadInfoQuery.reset(new SqlQuery(_db) );
    _setDownloadInfoQuery->prepare( "INSERT OR REPLACE INTO downloadinfo "
                                    "(path, tmpfile, etag, errorcount) "
                                    "VALUES ( ?1 , ?2, ?3, ?4 )" );

    _deleteDownloadInfoQuery.reset(new SqlQuery(_db) );
    _deleteDownloadInfoQuery->prepare( "DELETE FROM downloadinfo WHERE path=?1" );

    _getUploadInfoQuery.reset(new SqlQuery(_db));
    _getUploadInfoQuery->prepare( "SELECT chunk, transferid, errorcount, size, modtime FROM "
                                  "uploadinfo WHERE path=?1" );

    _setUploadInfoQuery.reset(new SqlQuery(_db));
    _setUploadInfoQuery->prepare( "INSERT OR REPLACE INTO uploadinfo "
                                  "(path, chunk, transferid, errorcount, size, modtime) "
                                  "VALUES ( ?1 , ?2, ?3 , ?4 ,  ?5, ?6 )");

    _deleteUploadInfoQuery.reset(new SqlQuery(_db));
    _deleteUploadInfoQuery->prepare("DELETE FROM uploadinfo WHERE path=?1" );


    _deleteFileRecordPhash.reset(new SqlQuery(_db));
    _deleteFileRecordPhash->prepare("DELETE FROM metadata WHERE phash=?1");

    _deleteFileRecordRecursively.reset(new SqlQuery(_db));
    _deleteFileRecordRecursively->prepare("DELETE FROM metadata WHERE path LIKE(?||'/%')");

    QString sql( "SELECT lastTryEtag, lastTryModtime, retrycount, errorstring, lastTryTime, ignoreDuration "
                 "FROM blacklist WHERE path=?1");
    if( Utility::fsCasePreserving() ) {
        // if the file system is case preserving we have to check the blacklist
        // case insensitively
        sql += QLatin1String(" COLLATE NOCASE");
    }
    _getErrorBlacklistQuery.reset(new SqlQuery(_db));
    _getErrorBlacklistQuery->prepare(sql);

    _setErrorBlacklistQuery.reset(new SqlQuery(_db));
    _setErrorBlacklistQuery->prepare("INSERT OR REPLACE INTO blacklist "
                                "(path, lastTryEtag, lastTryModtime, retrycount, errorstring, lastTryTime, ignoreDuration) "
                                "VALUES ( ?1, ?2, ?3, ?4, ?5, ?6, ?7)");

    _getSelectiveSyncListQuery.reset(new SqlQuery(_db));
    _getSelectiveSyncListQuery->prepare("SELECT path FROM selectivesync WHERE type=?1");

    // don't start a new transaction now
    commitInternal(QString("checkConnect End"), false);

    // Hide 'em all!
    FileSystem::setFileHidden(databaseFilePath(), true);
    FileSystem::setFileHidden(databaseFilePath() + "-wal", true);
    FileSystem::setFileHidden(databaseFilePath() + "-shm", true);
    FileSystem::setFileHidden(databaseFilePath() + "-journal", true);

    return rc;
}
Exemplo n.º 26
0
bool SyncJournalDb::checkConnect()
{
    if( _db.isOpen() ) {
        return true;
    }

    if( _dbFile.isEmpty() || !QFile::exists(_dbFile) ) {
        qDebug() << "Database " + _dbFile + " is empty or does not exist";
        return false;
    }

    QStringList list = QSqlDatabase::drivers();
    if( list.size() == 0 ) {
        qDebug() << "Database Drivers could not be loaded.";
        return false ;
    } else {
        if( list.indexOf( QSQLITE ) == -1 ) {
            qDebug() << "Database Driver QSQLITE could not be loaded!";
            return false;
        }
    }

    // Add the connection
    _db = QSqlDatabase::addDatabase( QSQLITE,  _dbFile);

    // Open the file
    _db.setDatabaseName(_dbFile);

    if (!_db.isOpen()) {
        if( !_db.open() ) {
            QSqlError error = _db.lastError();
            qDebug() << "Error opening the db: " << error.text();
            return false;
        }
    }

    QSqlQuery pragma1(_db);
    pragma1.prepare("PRAGMA synchronous = 1;");
    if (!pragma1.exec()) {
        return sqlFail("Set PRAGMA synchronous", pragma1);
    }
    pragma1.prepare("PRAGMA case_sensitive_like = ON;");
    if (!pragma1.exec()) {
        return sqlFail("Set PRAGMA case_sensitivity", pragma1);
    }

    /* Because insert are so slow, e do everything in a transaction, and one need to call commit */
    startTransaction();

    QSqlQuery createQuery(_db);
    createQuery.prepare("CREATE TABLE IF NOT EXISTS metadata("
                         "phash INTEGER(8),"
                         "pathlen INTEGER,"
                         "path VARCHAR(4096),"
                         "inode INTEGER,"
                         "uid INTEGER,"
                         "gid INTEGER,"
                         "mode INTEGER,"
                         "modtime INTEGER(8),"
                         "type INTEGER,"
                         "md5 VARCHAR(32)," /* This is the etag.  Called md5 for compatibility */
                        // updateDatabaseStructure() will add a fileid column
                        // updateDatabaseStructure() will add a remotePerm column
                         "PRIMARY KEY(phash)"
                         ");");

    if (!createQuery.exec()) {
        return sqlFail("Create table metadata", createQuery);
    }

    createQuery.prepare("CREATE TABLE IF NOT EXISTS downloadinfo("
                         "path VARCHAR(4096),"
                         "tmpfile VARCHAR(4096),"
                         "etag VARCHAR(32),"
                         "errorcount INTEGER,"
                         "PRIMARY KEY(path)"
                         ");");

    if (!createQuery.exec()) {
        return sqlFail("Create table downloadinfo", createQuery);
    }

    createQuery.prepare("CREATE TABLE IF NOT EXISTS uploadinfo("
                           "path VARCHAR(4096),"
                           "chunk INTEGER,"
                           "transferid INTEGER,"
                           "errorcount INTEGER,"
                           "size INTEGER(8),"
                           "modtime INTEGER(8),"
                           "PRIMARY KEY(path)"
                           ");");

    if (!createQuery.exec()) {
        return sqlFail("Create table uploadinfo", createQuery);
    }

    // create the blacklist table.
    createQuery.prepare("CREATE TABLE IF NOT EXISTS blacklist ("
                        "path VARCHAR(4096),"
                        "lastTryEtag VARCHAR[32],"
                        "lastTryModtime INTEGER[8],"
                        "retrycount INTEGER,"
                        "errorstring VARCHAR[4096],"
                        "PRIMARY KEY(path)"
                        ");");

    if (!createQuery.exec()) {
        return sqlFail("Create table blacklist", createQuery);
    }

    createQuery.prepare("CREATE TABLE IF NOT EXISTS version("
                               "major INTEGER(8),"
                               "minor INTEGER(8),"
                               "patch INTEGER(8),"
                               "custom VARCHAR(256)"
                               ");");
    if (!createQuery.exec()) {
        return sqlFail("Create table blacklist", createQuery);
    }

    QSqlQuery versionQuery("SELECT major, minor FROM version;", _db);
    if (!versionQuery.next()) {
        // If there was no entry in the table, it means we are likely upgrading from 1.5
        _possibleUpgradeFromMirall_1_5 = true;
    } else {
        // Delete the existing entry so we can replace it by the new one
        createQuery.prepare("DELETE FROM version;");
        if (!createQuery.exec()) {
            return sqlFail("Remove version", createQuery);
        }
    }
    createQuery.prepare("INSERT INTO version (major, minor, patch) VALUES ( ? , ? , ? );");
    createQuery.bindValue(0, MIRALL_VERSION_MAJOR);
    createQuery.bindValue(1, MIRALL_VERSION_MINOR);
    createQuery.bindValue(2, MIRALL_VERSION_PATCH);
    if (!createQuery.exec()) {
        return sqlFail("Insert Version", createQuery);
    }

    commitInternal("checkConnect");

    bool rc = updateDatabaseStructure();
    if( !rc ) {
        qDebug() << "WARN: Failed to update the database structure!";
    }

    _getFileRecordQuery.reset(new QSqlQuery(_db));
    _getFileRecordQuery->prepare("SELECT path, inode, uid, gid, mode, modtime, type, md5, fileid, remotePerm FROM "
                                 "metadata WHERE phash=:ph" );

    _setFileRecordQuery.reset(new QSqlQuery(_db) );
    _setFileRecordQuery->prepare("INSERT OR REPLACE INTO metadata "
                                 "(phash, pathlen, path, inode, uid, gid, mode, modtime, type, md5, fileid, remotePerm) "
                                 "VALUES ( ? , ?, ? , ? , ? , ? , ?,  ? , ? , ?, ?, ? )" );

    _getDownloadInfoQuery.reset(new QSqlQuery(_db) );
    _getDownloadInfoQuery->prepare( "SELECT tmpfile, etag, errorcount FROM "
                                    "downloadinfo WHERE path=:pa" );

    _setDownloadInfoQuery.reset(new QSqlQuery(_db) );
    _setDownloadInfoQuery->prepare( "INSERT OR REPLACE INTO downloadinfo "
                                    "(path, tmpfile, etag, errorcount) "
                                    "VALUES ( ? , ?, ? , ? )" );

    _deleteDownloadInfoQuery.reset(new QSqlQuery(_db) );
    _deleteDownloadInfoQuery->prepare( "DELETE FROM downloadinfo WHERE path=?" );

    _getUploadInfoQuery.reset(new QSqlQuery(_db));
    _getUploadInfoQuery->prepare( "SELECT chunk, transferid, errorcount, size, modtime FROM "
                                  "uploadinfo WHERE path=:pa" );

    _setUploadInfoQuery.reset(new QSqlQuery(_db));
    _setUploadInfoQuery->prepare( "INSERT OR REPLACE INTO uploadinfo "
                                  "(path, chunk, transferid, errorcount, size, modtime) "
                                  "VALUES ( ? , ?, ? , ? ,  ? , ? )");

    _deleteUploadInfoQuery.reset(new QSqlQuery(_db));
    _deleteUploadInfoQuery->prepare("DELETE FROM uploadinfo WHERE path=?" );


    _deleteFileRecordPhash.reset(new QSqlQuery(_db));
    _deleteFileRecordPhash->prepare("DELETE FROM metadata WHERE phash=?");

    _deleteFileRecordRecursively.reset(new QSqlQuery(_db));
    _deleteFileRecordRecursively->prepare("DELETE FROM metadata WHERE path LIKE(?||'/%')");

    _blacklistQuery.reset(new QSqlQuery(_db));
    _blacklistQuery->prepare("SELECT lastTryEtag, lastTryModtime, retrycount, errorstring "
                             "FROM blacklist WHERE path=:path");

    return rc;
}
/**
  * Default object constructor
  * 
  */
GLES2HardwareOcclusionQuery::GLES2HardwareOcclusionQuery() 
{ 
    createQuery();
}
Exemplo n.º 28
0
bool SyncJournalDb::checkConnect()
{
    if( _db.isOpen() ) {
        return true;
    }

    if( _dbFile.isEmpty() || !QFile::exists(_dbFile) ) {
        return false;
    }

    QStringList list = QSqlDatabase::drivers();
    if( list.size() == 0 ) {
        qDebug() << "Database Drivers could not be loaded.";
        return false ;
    } else {
        if( list.indexOf( QSQLITE ) == -1 ) {
            qDebug() << "Database Driver QSQLITE could not be loaded!";
            return false;
        }
    }

    // Add the connection
    _db = QSqlDatabase::addDatabase( QSQLITE,  _dbFile);

    // Open the file
    _db.setDatabaseName(_dbFile);

    if (!_db.isOpen()) {
        if( !_db.open() ) {
            QSqlError error = _db.lastError();
            qDebug() << "Error opening the db: " << error.text();
            return false;
        }
    }

    QSqlQuery pragma1(_db);
    pragma1.prepare("PRAGMA synchronous = 1;");
    if (!pragma1.exec()) {
        return sqlFail("Set PRAGMA synchronous", pragma1);
    }
    pragma1.prepare("PRAGMA case_sensitive_like = ON;");
    if (!pragma1.exec()) {
        return sqlFail("Set PRAGMA case_sensitivity", pragma1);
    }

    /* Because insert are so slow, e do everything in a transaction, and one need to call commit */
    startTransaction();

    QSqlQuery createQuery(_db);
    createQuery.prepare("CREATE TABLE IF NOT EXISTS metadata("
                         "phash INTEGER(8),"
                         "pathlen INTEGER,"
                         "path VARCHAR(4096),"
                         "inode INTEGER,"
                         "uid INTEGER,"
                         "gid INTEGER,"
                         "mode INTEGER,"
                         "modtime INTEGER(8),"
                         "type INTEGER,"
                         "md5 VARCHAR(32)," /* This is the etag.  Called md5 for compatibility */
                         "PRIMARY KEY(phash)"
                         ");");

    if (!createQuery.exec()) {
        return sqlFail("Create table metadata", createQuery);
    }

    createQuery.prepare("CREATE TABLE IF NOT EXISTS downloadinfo("
                         "path VARCHAR(4096),"
                         "tmpfile VARCHAR(4096),"
                         "etag VARCHAR(32),"
                         "errorcount INTEGER,"
                         "PRIMARY KEY(path)"
                         ");");

    if (!createQuery.exec()) {
        return sqlFail("Create table downloadinfo", createQuery);
    }

    createQuery.prepare("CREATE TABLE IF NOT EXISTS uploadinfo("
                           "path VARCHAR(4096),"
                           "chunk INTEGER,"
                           "transferid INTEGER,"
                           "errorcount INTEGER,"
                           "size INTEGER(8),"
                           "modtime INTEGER(8),"
                           "PRIMARY KEY(path)"
                           ");");

    if (!createQuery.exec()) {
        return sqlFail("Create table uploadinfo", createQuery);
    }

    // create the blacklist table.
    createQuery.prepare("CREATE TABLE IF NOT EXISTS blacklist ("
                        "path VARCHAR(4096),"
                        "lastTryEtag VARCHAR[32],"
                        "lastTryModtime INTEGER[8],"
                        "retrycount INTEGER,"
                        "errorstring VARCHAR[4096],"
                        "PRIMARY KEY(path)"
                        ");");

    if (!createQuery.exec()) {
        return sqlFail("Create table blacklist", createQuery);
    }

    commitInternal("checkConnect");

    bool rc = updateDatabaseStructure();
    if( rc ) {
        _getFileRecordQuery.reset(new QSqlQuery(_db));
        _getFileRecordQuery->prepare("SELECT path, inode, uid, gid, mode, modtime, type, md5, fileid FROM "
                                     "metadata WHERE phash=:ph" );

        _setFileRecordQuery.reset(new QSqlQuery(_db) );
        _setFileRecordQuery->prepare("INSERT OR REPLACE INTO metadata "
                                     "(phash, pathlen, path, inode, uid, gid, mode, modtime, type, md5, fileid) "
                                     "VALUES ( ? , ?, ? , ? , ? , ? , ?,  ? , ? , ?, ? )" );

        _getDownloadInfoQuery.reset(new QSqlQuery(_db) );
        _getDownloadInfoQuery->prepare( "SELECT tmpfile, etag, errorcount FROM "
                                        "downloadinfo WHERE path=:pa" );

        _setDownloadInfoQuery.reset(new QSqlQuery(_db) );
        _setDownloadInfoQuery->prepare( "INSERT OR REPLACE INTO downloadinfo "
                                        "(path, tmpfile, etag, errorcount) "
                                        "VALUES ( ? , ?, ? , ? )" );

        _deleteDownloadInfoQuery.reset(new QSqlQuery(_db) );
        _deleteDownloadInfoQuery->prepare( "DELETE FROM downloadinfo WHERE path=?" );

        _getUploadInfoQuery.reset(new QSqlQuery(_db));
        _getUploadInfoQuery->prepare( "SELECT chunk, transferid, errorcount, size, modtime FROM "
                                      "uploadinfo WHERE path=:pa" );

        _setUploadInfoQuery.reset(new QSqlQuery(_db));
        _setUploadInfoQuery->prepare( "INSERT OR REPLACE INTO uploadinfo "
                                      "(path, chunk, transferid, errorcount, size, modtime) "
                                      "VALUES ( ? , ?, ? , ? ,  ? , ? )");

        _deleteUploadInfoQuery.reset(new QSqlQuery(_db));
        _deleteUploadInfoQuery->prepare("DELETE FROM uploadinfo WHERE path=?" );


        _deleteFileRecordPhash.reset(new QSqlQuery(_db));
        _deleteFileRecordPhash->prepare("DELETE FROM metadata WHERE phash=?");

        _deleteFileRecordRecursively.reset(new QSqlQuery(_db));
        _deleteFileRecordRecursively->prepare("DELETE FROM metadata WHERE path LIKE(?||'/%')");

        _blacklistQuery.reset(new QSqlQuery(_db));
        _blacklistQuery->prepare("SELECT lastTryEtag, lastTryModtime, retrycount, errorstring "
                                 "FROM blacklist WHERE path=:path");
    }
    return rc;
}
//------------------------------------------------------------------
void GLES2HardwareOcclusionQuery::notifyOnContextReset()
{
    createQuery();
}