void DatabaseSync::runTransaction(PassOwnPtr<SQLTransactionSyncCallback> callback, bool readOnly, ExceptionState& exceptionState) { ASSERT(m_executionContext->isContextThread()); if (sqliteDatabase().transactionInProgress()) { setLastErrorMessage("unable to start a transaction from within a transaction"); exceptionState.throwUninformativeAndGenericDOMException(SQLDatabaseError); return; } RefPtr<SQLTransactionSync> transaction = SQLTransactionSync::create(this, callback, readOnly); transaction->begin(exceptionState); if (exceptionState.hadException()) { rollbackTransaction(transaction); return; } transaction->execute(exceptionState); if (exceptionState.hadException()) { rollbackTransaction(transaction); return; } transaction->commit(exceptionState); if (exceptionState.hadException()) { rollbackTransaction(transaction); return; } setLastErrorMessage(""); }
bool LocalyticsDatabase::incrementLastSessionNumber(int *sessionNumber) { QString t(QLatin1String("increment_session_number")); bool success = true; success = beginTransaction(t); QSqlQuery q(_databaseConnection); if (success) { // Increment value success = q.exec(QLatin1String("UPDATE localytics_info " "SET last_session_number = (last_session_number + 1)")); } if (success) { // Retrieve new value success = q.exec(QLatin1String("SELECT last_session_number FROM localytics_info")); if (q.next()) { *sessionNumber = q.value(0).toInt(); } } if (success) { releaseTransaction(t); } else { rollbackTransaction(t); } return success; }
//---------------------------------------------------------------------------- void ctkPluginStorageSQL::cleanupDB() { QSqlDatabase database = getConnection(); QSqlQuery query(database); beginTransaction(&query, Write); try { // remove all plug-ins marked as UNINSTALLED QString statement = "DELETE FROM " PLUGINS_TABLE " WHERE StartLevel==-2"; executeQuery(&query, statement); // remove all old plug-in generations statement = "DELETE FROM " PLUGINS_TABLE " WHERE K NOT IN (SELECT K FROM (SELECT K, MAX(Generation) FROM " PLUGINS_TABLE " GROUP BY ID))"; } catch (...) { rollbackTransaction(&query); throw; } commitTransaction(&query); }
bool QgsTransaction::rollback( QString& errorMsg ) { if ( !mTransactionActive ) { return false; } Q_FOREACH ( QgsVectorLayer* l, mLayers ) { if ( l->isEditable() ) { return false; } } if ( !rollbackTransaction( errorMsg ) ) { return false; } setLayerTransactionIds( 0 ); mTransactionActive = false; emit afterRollback(); return true; }
bool LocalyticsDatabase::resetAnalyticsData() { // Delete or zero all analytics data. // Reset: headers, events, session number, upload number, last session start, last close event, and last flow event. // Unaffected: schema version, opt out status, install ID (deprecated), and app key. QString t(QLatin1String("reset_analytics_data")); bool success = beginTransaction(t); QSqlQuery q(_databaseConnection); success &= q.exec(QLatin1String("DELETE FROM events")); success &= q.exec(QLatin1String("DELETE FROM upload_headers")); success &= q.exec(QLatin1String("DELETE FROM localytics_amp_rule")); success &= q.exec(QLatin1String("DELETE FROM localytics_amp_ruleevent")); success &= q.exec(QLatin1String("UPDATE localytics_info SET " " last_session_number = 0, last_upload_number = 0," " last_close_event = null, last_flow_event = null, last_session_start = null, " " custom_d0 = null, custom_d1 = null, custom_d2 = null, custom_d3 = null, " " customer_id = null, queued_close_event_blob = null ")); if (success) { releaseTransaction(t); } else { rollbackTransaction(t); } return success; }
bool LocalyticsDatabase::addCloseEventWithBlobString(QString blob) { QString t(QLatin1String("add_close_event")); bool success = beginTransaction(t); int event_id; // Add close event. if (success) { success = addEventWithBlobString(blob, &event_id); } // Record row id to localytics_info so that it can be removed if the session resumes. if (success) { QSqlQuery q(_databaseConnection); q.prepare(QLatin1String("UPDATE localytics_info SET last_close_event = (SELECT event_id FROM events WHERE rowid = :rowid)")); q.bindValue(QLatin1String(":rowid"), event_id); success = q.exec(); } if (success) { releaseTransaction(t); } else { rollbackTransaction(t); } return success; }
bool IncrementalParser::runStaticInitOnTransaction(Transaction* T) const { // run the static initializers that came from codegenning bool success = m_Interpreter->runStaticInitializersOnce() < Interpreter::kExeFirstError; if (!success) rollbackTransaction(T); return success; }
static void deleteNodeFromCountry(LCountry* country, OsmId id) { beginTransaction(country->db); if(deleteFromDbById(country->db, country->deleteNodeTagsStatement, id) && deleteFromDbById(country->db, country->deleteNodeStatement, id)) { commitTransaction(country->db); } else { rollbackTransaction(country->db); } }
bool IncrementalParser::transformTransactionIR(Transaction* T) const { // Transform IR bool success = true; for (size_t i = 0; success && i < m_IRTransformers.size(); ++i) success = m_IRTransformers[i]->TransformTransaction(*T); if (!success) rollbackTransaction(T); return success; }
bool IncrementalParser::transformTransactionAST(Transaction* T) const { bool success = true; // We are sure it's safe to pipe it through the transformers for (size_t i = 0; success && i < m_ASTTransformers.size(); ++i) success = m_ASTTransformers[i]->TransformTransaction(*T); m_CI->getDiagnostics().Reset(); // FIXME: Should be in rollback transaction. if (!success) rollbackTransaction(T); return success; }
bool QgsTransaction::rollback( QString& errorMsg ) { if ( !mTransactionActive ) return false; if ( !rollbackTransaction( errorMsg ) ) return false; setLayerTransactionIds( nullptr ); mTransactionActive = false; emit afterRollback(); return true; }
// Call Trade Order Frame 5 void CTradeOrderDB::DoTradeOrderFrame5(TTradeOrderFrame5Output *pOut) { #ifdef DEBUG cout << "<<< TOF5" << endl; #endif // rollback the transaction we are inside rollbackTransaction(); pOut->status = CBaseTxnErr::ROLLBACK; #ifdef DEBUG cout << "- Trade Order Frame 5 (output)" << endl << "-- status: " << pOut->status << endl; cout << ">>> TOF5" << endl; #endif }
bool LocalyticsDatabase::deleteUploadedData() { // Delete all headers and staged events. QString t(QLatin1String("delete_upload_data")); bool success = beginTransaction(t); QSqlQuery q(_databaseConnection); success &= q.exec(QLatin1String("DELETE FROM events WHERE upload_header IS NOT NULL")); success &= q.exec(QLatin1String("DELETE FROM upload_headers")); if (success) { releaseTransaction(t); } else { rollbackTransaction(t); } return success; }
void BaseDatabaseUnitImpl::runTransaction(std::vector<CppSQLite3Statement> & statements) { if (beginTransaction()) { try { for (auto it = statements.begin(); it != statements.end(); ++it) { it->execDML(); } commitTransaction(); } catch (CppSQLite3Exception e) { LOG_ERR_R(DATABASE_MANAGER_LOG_TAG, _T("Failed to run transaction, error: %u"), e.errorCode()); LOG_ERR_D_A(DATABASE_MANAGER_LOG_TAG_A, "Message: %s", e.errorMessage()); rollbackTransaction(); } } }
bool MySqlDataBase::insertWithManyValues(const QString &tableDescr, const QList<QVariantList> &data) { if(data.count() == 0 || tableDescr.isEmpty()) { return false; } QSqlQuery query(db_); const int bufferSizeMax = 2000; int counter = 0; const int dataSize = data.at(0).count(); QString valuesRequet("("); for(int i = 0; i < data.count(); i++) { valuesRequet += "?, "; } valuesRequet = valuesRequet.left(valuesRequet.length()-2); valuesRequet += "),"; beginTransaction(); while(counter < dataSize) { int delta = 0; if(counter + bufferSizeMax <= dataSize) { delta = bufferSizeMax; } else { delta = dataSize - counter; } QString request("insert into " + tableDescr + " values"); for(int j = counter; j < counter + delta ; j++) { request += valuesRequet; } request = request.left(request.length() - 1); request += ";"; query.prepare(request); for(int k = counter; k < counter + delta; k++) { foreach (const QVariantList &list, data) { query.addBindValue(list.at(k)); } } if(!query.exec()) { qInfo() << query.lastError().text(); qInfo() << query.lastQuery(); rollbackTransaction(); return false; } counter += delta; }
//---------------------------------------------------------------------------- void ctkPluginStorageSQL::updateDB() { QSqlDatabase database = getConnection(); QSqlQuery query(database); beginTransaction(&query, Write); // 1. Get the state information of all plug-ins (it is assumed that // plug-ins marked as UNINSTALLED (startlevel == -2) are already removed QString statement = "SELECT ID,MAX(Generation),Location,LocalPath,Timestamp,StartLevel,AutoStart,K " "FROM " PLUGINS_TABLE " GROUP BY ID"; QList<int> outdatedIds; QList<QSharedPointer<ctkPluginArchiveSQL> > updatedPluginArchives; try { executeQuery(&query, statement); // 2. Check the timestamp for each plug-in while (query.next()) { QFileInfo pluginInfo(query.value(EBindIndex3).toString()); QDateTime pluginLastModified = pluginInfo.lastModified(); // Make sure the QDateTime has the same accuracy as the one in the database pluginLastModified = getQDateTimeFromString(getStringFromQDateTime(pluginLastModified)); if (pluginLastModified > getQDateTimeFromString(query.value(EBindIndex4).toString())) { QSharedPointer<ctkPluginArchiveSQL> updatedPA( new ctkPluginArchiveSQL(this, query.value(EBindIndex2).toUrl(), // plug-in location url query.value(EBindIndex3).toString(), // plugin local path query.value(EBindIndex).toInt(), // plugin id query.value(EBindIndex5).toInt(), // start level QDateTime(), // last modififed query.value(EBindIndex6).toInt()) // auto start setting ); updatedPA->key = query.value(EBindIndex7).toInt(); updatedPluginArchives << updatedPA; // remember the plug-in ids for deletion outdatedIds << query.value(EBindIndex).toInt(); } } } catch (...) { rollbackTransaction(&query); throw; } query.finish(); query.clear(); if (!outdatedIds.isEmpty()) { // 3. Remove all traces from outdated plug-in data. Due to cascaded delete, // it is sufficient to remove the records from the main table statement = "DELETE FROM " PLUGINS_TABLE " WHERE ID IN (%1)"; QString idStr; foreach(int id, outdatedIds) { idStr += QString::number(id) + ","; }
void IncrementalParser::commitTransaction(Transaction* T) { //Transaction* CurT = m_Consumer->getTransaction(); assert(T->isCompleted() && "Transaction not ended!?"); assert(T->getState() != Transaction::kCommitted && "Committing an already committed transaction."); // Check for errors... if (T->getIssuedDiags() == Transaction::kErrors) { rollbackTransaction(T); return; } if (T->hasNestedTransactions()) { for(Transaction::const_nested_iterator I = T->nested_begin(), E = T->nested_end(); I != E; ++I) if ((*I)->getState() != Transaction::kCommitted) commitTransaction(*I); } // We are sure it's safe to pipe it through the transformers bool success = true; for (size_t i = 0; i < m_TTransformers.size(); ++i) { success = m_TTransformers[i]->TransformTransaction(*T); if (!success) { break; } } m_CI->getDiagnostics().Reset(); // FIXME: Should be in rollback transaction. if (!success) { // Roll back on error in a transformer rollbackTransaction(T); return; } // Pull all template instantiations in that came from the consumers. getCI()->getSema().PerformPendingInstantiations(); m_Consumer->HandleTranslationUnit(getCI()->getASTContext()); if (T->getCompilationOpts().CodeGeneration && hasCodeGenerator()) { // codegen the transaction for (size_t Idx = 0; Idx < T->size() /*can change in the loop!*/; ++Idx) { // Copy DCI; it might get relocated below. Transaction::DelayCallInfo I = (*T)[Idx]; if (I.m_Call == Transaction::kCCIHandleTopLevelDecl) getCodeGenerator()->HandleTopLevelDecl(I.m_DGR); else if (I.m_Call == Transaction::kCCIHandleInterestingDecl) { // Usually through BackendConsumer which doesn't implement // HandleInterestingDecl() and thus calls // ASTConsumer::HandleInterestingDecl() getCodeGenerator()->HandleTopLevelDecl(I.m_DGR); } else if(I.m_Call == Transaction::kCCIHandleTagDeclDefinition) { TagDecl* TD = cast<TagDecl>(I.m_DGR.getSingleDecl()); getCodeGenerator()->HandleTagDeclDefinition(TD); } else if (I.m_Call == Transaction::kCCIHandleVTable) { CXXRecordDecl* CXXRD = cast<CXXRecordDecl>(I.m_DGR.getSingleDecl()); getCodeGenerator()->HandleVTable(CXXRD, /*isRequired*/true); } else if (I.m_Call == Transaction::kCCIHandleCXXImplicitFunctionInstantiation) { FunctionDecl* FD = cast<FunctionDecl>(I.m_DGR.getSingleDecl()); getCodeGenerator()->HandleCXXImplicitFunctionInstantiation(FD); } else if (I.m_Call == Transaction::kCCIHandleCXXStaticMemberVarInstantiation) { VarDecl* VD = cast<VarDecl>(I.m_DGR.getSingleDecl()); getCodeGenerator()->HandleCXXStaticMemberVarInstantiation(VD); } else if (I.m_Call == Transaction::kCCINone) ; // We use that internally as delimiter in the Transaction. else llvm_unreachable("We shouldn't have decl without call info."); } getCodeGenerator()->HandleTranslationUnit(getCI()->getASTContext()); T->setModule(getCodeGenerator()->GetModule()); // The static initializers might run anything and can thus cause more // decls that need to end up in a transaction. But this one is done // with CodeGen... T->setState(Transaction::kCommitting); // run the static initializers that came from codegenning if (m_Interpreter->runStaticInitializersOnce() >= Interpreter::kExeFirstError) { // Roll back on error in a transformer rollbackTransaction(T); return; } } else T->setState(Transaction::kCommitting); InterpreterCallbacks* callbacks = m_Interpreter->getCallbacks(); if (callbacks) { callbacks->TransactionCommitted(*T); } if (T->hasNestedTransactions()) { Transaction* SubTransactionWhileCommitting = *T->rnested_begin(); if (SubTransactionWhileCommitting->getState() == Transaction::kCollecting) { // A nested transaction was created while committing this // transaction; commit it now. SubTransactionWhileCommitting->setState(Transaction::kCompleted); commitTransaction(SubTransactionWhileCommitting); } } T->setState(Transaction::kCommitted); // If the transaction is empty do nothing. // Except it was nested transaction and we want to reuse it later on. if (T->empty() && T->isNestedTransaction()) { // We need to remove the marker from its parent. Transaction* ParentT = T->getParent(); for (size_t i = 0; i < ParentT->size(); ++i) if ((*ParentT)[i].m_DGR.isNull()) ParentT->erase(i); } if (T->isNestedTransaction()) { // TODO: Add proper logic in the case where there are multiple nested // transaction. This now won't handle the case where there are more than // one level 1 nested transactions. m_Consumer->setTransaction(T->getParent()); } }
void IncrementalParser::commitTransaction(Transaction* T) { //Transaction* CurT = m_Consumer->getTransaction(); assert(T->isCompleted() && "Transaction not ended!?"); assert(T->getState() != Transaction::kCommitted && "Committing an already committed transaction."); // If committing a nested transaction the active one should be its parent // from now on. if (T->isNestedTransaction()) m_Consumer->setTransaction(T->getParent()); // Check for errors... if (T->getIssuedDiags() == Transaction::kErrors) { rollbackTransaction(T); return; } if (T->hasNestedTransactions()) { for(Transaction::const_nested_iterator I = T->nested_begin(), E = T->nested_end(); I != E; ++I) if ((*I)->getState() != Transaction::kCommitted) commitTransaction(*I); } if (!transformTransactionAST(T)) return; // Here we expect a template instantiation. We need to open the transaction // that we are currently work with. Transaction::State oldState = T->getState(); T->setState(Transaction::kCollecting); // Pull all template instantiations in that came from the consumers. getCI()->getSema().PerformPendingInstantiations(); T->setState(oldState); m_Consumer->HandleTranslationUnit(getCI()->getASTContext()); if (T->getCompilationOpts().CodeGeneration && hasCodeGenerator()) { codeGenTransaction(T); transformTransactionIR(T); } // The static initializers might run anything and can thus cause more // decls that need to end up in a transaction. But this one is done // with CodeGen... T->setState(Transaction::kCommitted); if (T->getCompilationOpts().CodeGeneration && hasCodeGenerator()) { runStaticInitOnTransaction(T); } InterpreterCallbacks* callbacks = m_Interpreter->getCallbacks(); if (callbacks) callbacks->TransactionCommitted(*T); // If the transaction is empty do nothing. // Except it was nested transaction and we want to reuse it later on. if (T->empty() && T->isNestedTransaction()) { // We need to remove the marker from its parent. Transaction* ParentT = T->getParent(); for (size_t i = 0; i < ParentT->size(); ++i) if ((*ParentT)[i].m_DGR.isNull()) ParentT->erase(i); } }