bool League::finished() { //calculate games count // int max; if (clubs.count() %2 == 0) { max = ((clubs.count()-1)*2)*(clubs.count() /2); } else { int count = clubs.count() + 1; max = ((count-1)*2)*(count/2); } //смотрим максимальный сыгранный тур QSqlQuery q; q.prepare("SELECT COUNT (*) FROM Matches"); if (!q.exec()) {qDebug() << "SQL Error: " + q.lastError().text() + ", query " + q.executedQuery();} else {qDebug() << "Query done: " + q.executedQuery();} q.first(); if (max <= q.value(0).toInt()) { writeResults(); return true; } else return false; }
void Logging::clearLogs(void){ QSqlQuery query; query.exec("DELETE FROM logging"); if (!query.exec()){ qDebug()<<"clearLogs.SqlError: "<<query.lastError()<<query.executedQuery(); } query.exec("VACUUM"); if (!query.exec()){ qDebug()<<"clearLogs.SqlError: "<<query.lastError()<<query.executedQuery(); } return; }
bool AMDatabase::execQuery(QSqlQuery &query, int timeoutMs) { if (isReadOnly() && !(query.executedQuery().startsWith("SELECT", Qt::CaseInsensitive) || query.executedQuery().startsWith("PRAGMA", Qt::CaseInsensitive))){ AMErrorMon::debug(this, AMDATABASE_IS_READ_ONLY, QString("This database is read-only and the desired command would modify the contents of the database. Query: %1").arg(query.executedQuery())); return false; } QTime startTime; startTime.start(); bool success; int lastErrorNumber; QString lastErrorMessage; int attempt = 0; do { success = query.exec(); lastErrorNumber = query.lastError().number(); lastErrorMessage = query.lastError().text(); attempt++; if(lastErrorNumber == 5) usleep(5000); } while(success != true && startTime.elapsed() < timeoutMs && (lastErrorNumber == 5)); if(attempt > 1) { if(success) { AMErrorMon::debug(0, AMDATABASE_LOCK_FOR_EXECQUERY_CONTENTION_SUCCEEDED, QString("AMDatabase detected contention for database locking in execQuery(). It took %1 tries for the query to succeed.").arg(attempt) ); } else { AMErrorMon::debug(0, AMDATABASE_LOCK_FOR_EXECQUERY_CONTENTION_FAILED, QString("AMDatabase detected contention for database locking in execQuery(). After %1 attempts, the query still did not succeed. The last error is %2").arg(attempt).arg(lastErrorMessage) ); } } return success; }
void menusViewDialog::menusModify(){ getMenusID(); QSqlQuery *getMenu = new QSqlQuery(); getMenu->prepare("SELECT menu_id, name, altname, price, category_id " "FROM public.menus " "WHERE deleted='0' " "AND menu_id=:menuCurrentID"); getMenu->bindValue(":menuCurrentID",menuCurrentID); getMenu->exec(); if(getMenu->lastError().isValid()) qDebug() << trUtf8("Запрос:") << getMenu->executedQuery(); while (getMenu->next()){ menuID = getMenu->value(0).toInt(); menuName = getMenu->value(1).toString(); menuAltName = getMenu->value(2).toString(); menuPrice = getMenu->value(3).toInt(); categoryID = getMenu->value(4).toInt(); qDebug() << trUtf8("Menu ID: ") << menuID; qDebug() << trUtf8("Menu Name: ") << menuName; qDebug() << trUtf8("Menu Alt Name: ") << menuAltName; qDebug() << trUtf8("Menu Price: ") << menuPrice; qDebug() << trUtf8("Category ID: ") << categoryID; } menusChangeDialog dialog(this); dialog.menusEdit(menuID,menuName,menuAltName,menuPrice,categoryID); dialog.exec(); if(dialog.close()) getMenusList(); }
void HiddenTableModel::setTableModel(int id) { Q_UNUSED(id); QSqlQuery query; const QString tableName("hidden_songs"); QStringList columns; columns << "library." + LIBRARYTABLE_ID; QString filter("mixxx_deleted=1"); query.prepare("CREATE TEMPORARY VIEW IF NOT EXISTS " + tableName + " AS " "SELECT " + columns.join(",") + " FROM library " "INNER JOIN track_locations " "ON library.location=track_locations.id " "WHERE " + filter); if (!query.exec()) { qDebug() << query.executedQuery() << query.lastError(); } //Print out any SQL error, if there was one. if (query.lastError().isValid()) { qDebug() << __FILE__ << __LINE__ << query.lastError(); } QStringList tableColumns; tableColumns << LIBRARYTABLE_ID; setTable(tableName, LIBRARYTABLE_ID, tableColumns, m_pTrackCollection->getTrackSource()); setDefaultSort(fieldIndex("artist"), Qt::AscendingOrder); setSearch(""); }
void Logging::deleteLogs(QString prefix_name){ QSqlQuery query; query.prepare("DELETE FROM logging WHERE prefix_id=(SELECT id FROM prefix WHERE name=:prefix_name);"); query.bindValue(":prefix_name", prefix_name); if (!query.exec()){ qDebug()<<"SqlError: "<<query.lastError()<<query.executedQuery(); } return; }
void IconManager::updateIconName(int catId, int iconId, const QString &iconName) { QString sql = "UPDATE Icons SET name = '" + iconName + "' WHERE catId = " + QString::number(catId) + " AND id = " + QString::number(iconId); QSqlQuery *q = new QSqlQuery(db); q->prepare(sql); q->exec(); printQS(q->executedQuery()); delete q; }
bool Image::delImage(const QString name) const{ QSqlQuery query; query.prepare("DELETE FROM images WHERE name=:name"); query.bindValue("name", name); if (!query.exec()){ qDebug()<<"SqlError: "<<query.lastError()<<query.executedQuery(); return false; } return true; }
bool Prefix::delByName(const QString prefix_name) const{ QSqlQuery query; query.prepare("DELETE FROM prefix WHERE id=(SELECT id FROM prefix WHERE name=:prefix_name )"); query.bindValue(":prefix_name", prefix_name); if (!query.exec()){ qDebug()<<"SqlError: "<<query.lastError()<<query.executedQuery(); return false; } return true; }
bool Image::renameImage(const QString name, const QString old_name) const{ QSqlQuery query; query.prepare("UPDATE images SET name=:name WHERE name=:old_name"); query.bindValue("name", name); query.bindValue("old_name", old_name); if (!query.exec()){ qDebug()<<"SqlError: "<<query.lastError()<<query.executedQuery(); return false; } return true; }
bool Image::addImage(const QString name, const QString path) const{ QSqlQuery query; query.prepare("INSERT INTO images(name, path) VALUES(:name, :path)"); query.bindValue("name", name); query.bindValue("path", path); if (!query.exec()){ qDebug()<<"SqlError: "<<query.lastError()<<query.executedQuery(); return false; } return true; }
bool Dir::addDir(const QString prefix_name, const QString dir_name) const{ QSqlQuery query; query.prepare("INSERT INTO dir(name, prefix_id) VALUES(:name, (SELECT id FROM prefix WHERE name=:prefix_name))"); query.bindValue(":prefix_name", prefix_name); query.bindValue(":name", dir_name); if (!query.exec()){ qDebug()<<"SqlError: "<<query.lastError()<<query.executedQuery(); return false; } return true; }
void Logging::deleteLogs(QString prefix_name, QString app_name, QString date){ QSqlQuery query; query.prepare("DELETE FROM logging WHERE prefix_id=(SELECT id FROM prefix WHERE name=:prefix_name) AND name=:app_name AND date=:date;"); query.bindValue(":prefix_name", prefix_name); query.bindValue(":app_name", app_name); query.bindValue(":date", QDateTime::fromString(date, "dd.MM.yyyy hh:mm:ss").toTime_t()); if (!query.exec()){ qDebug()<<"SqlError: "<<query.lastError()<<query.executedQuery(); } return; }
QSqlQuery ClvDataAccessor::execSql(QSqlQuery query){ bool success = query.exec(); if(AppInfo::DEBUG_CLV_DATA_ACCESSOR){ qDebug() << "EXEC SQL: " << query.lastQuery(); } if(!success){ qDebug(); qDebug() << QString("SQL Error:'%1'").arg(query.executedQuery()); qDebug() << query.lastError().text(); qDebug(); } return query; }
bool Image::isExistsByName(const QString name) const{ QSqlQuery query; query.prepare("SELECT id FROM images WHERE name=:name"); query.bindValue(":name", name); if (!query.exec()){ qDebug()<<"SqlError: "<<query.lastError()<<query.executedQuery(); return false; } query.first(); if (query.isValid()){ return true; } return false; }
bool Dir::renameDir(const QString dir_name, const QString prefix_name, const QString new_dir_name) const{ QSqlQuery query; query.prepare("UPDATE dir SET name=:new_dir_name WHERE name=:dir_name AND prefix_id=(SELECT id FROM prefix WHERE name=:prefix_name)"); query.bindValue(":prefix_name", prefix_name); query.bindValue(":new_dir_name", new_dir_name); query.bindValue(":dir_name", dir_name); if (!query.exec()){ qDebug()<<"SqlError: "<<query.lastError()<<query.executedQuery(); return false; } return true; }
void residuesFilialForm::setCountDish(QString tableName,int d){ // int c; // QString tableName; // tableName = "countsp"; QSqlDatabase::database(); QString updateDishQuery; updateDishQuery = QString("%1 %2 %3 %4 %5").arg("UPDATE dish SET ").arg(tableName).arg(" = ").arg(d).arg("WHERE users=1 AND id=1"); qDebug() << updateDishQuery; QSqlQuery *updateDish = new QSqlQuery; updateDish->prepare(updateDishQuery); updateDish->exec(); if(updateDish->lastError().isValid()){ qDebug() << updateDish->lastError(); qDebug() << updateDish->executedQuery(); qDebug() << updateDish->lastQuery(); } else { qDebug() << updateDish->executedQuery(); qDebug() << "Sell Complited. " << tableName << " = " << d ; } updateResiduesFilial(); }
void Logging::addLogRecord(int prefix_id, QString program, int exit, QString stdout, uint date){ QSqlQuery query; query.prepare("INSERT INTO logging(name, exit, stdout, prefix_id, date) VALUES (:name, :exit, :stdout, :prefix_id, :date);"); query.bindValue(":name", program); query.bindValue(":exit", exit); query.bindValue(":stdout", stdout); query.bindValue(":prefix_id", prefix_id); query.bindValue(":date", date); if (!query.exec()){ qDebug()<<"SqlError: "<<query.lastError()<<query.executedQuery(); } return; }
bool Dir::delDir(const QString prefix_name, const QString dir_name) const{ QSqlQuery query; if (dir_name.isEmpty()){ query.prepare("DELETE FROM dir WHERE prefix_id=(SELECT id FROM prefix WHERE name=:prefix_name)"); } else { query.prepare("DELETE FROM dir WHERE prefix_id=(SELECT id FROM prefix WHERE name=:prefix_name) and name=:dir_name"); query.bindValue(":dir_name", dir_name); } query.bindValue(":prefix_name", prefix_name); if (!query.exec()){ qDebug()<<"SqlError: "<<query.lastError()<<query.executedQuery(); return false; } return true; }
int DatabaseManager::commitTrigger(Trigger* trig) { SDPASSERT(Logger::instancePtr()); int newID = -1; if ( !__db.isOpen() ) { Logger::instancePtr()->addMessage(Logger::CRITICAL, __func__, QString("Failed to store trigger %1. Database couldn't be opened.") .arg(trig->id())); return newID; } QByteArray buffer; QDataStream stream(&buffer, QIODevice::WriteOnly); #if (QT_VERSION >= QT_VERSION_CHECK(4, 8, 0)) stream.setVersion(QDataStream::Qt_4_8); #else stream.setVersion(QDataStream::Qt_4_6); #endif trig->toDataStream(stream); QSqlQuery query; if ( triggerExists(trig->id()) ) { query.prepare("UPDATE main.Trigger SET status=:tstatus, data=:tdata WHERE id = :tid"); query.bindValue("tstatus", static_cast<int>(trig->status())); query.bindValue("tdata", qCompress(buffer)); query.bindValue("tid", trig->id()); } else { query.prepare("INSERT INTO main.Trigger (id, status, data, detection_id) " "VALUES (:tid, :tstatus, :tdata, :jid)"); query.bindValue("tid", trig->id()); query.bindValue("tstatus", static_cast<int>(trig->status())); query.bindValue("tdata", qCompress(buffer)); query.bindValue("jid", trig->jobID()); } if ( query.exec() ) newID = query.lastInsertId().toInt(); else Logger::instancePtr()->addMessage(Logger::CRITICAL, __func__, QString("Query failed: %1").arg(query.executedQuery())); return newID; }
int DatabaseManager::commitDetection(DetectionJob* job) { SDPASSERT(Logger::instancePtr()); int newID = -1; if ( !__db.isOpen() ) { Logger::instancePtr()->addMessage(Logger::CRITICAL, __func__, QString("Failed to store detection job %1. Database couldn't be opened.") .arg(job->id())); return newID; } QByteArray buffer; QDataStream stream(&buffer, QIODevice::WriteOnly); #if (QT_VERSION >= QT_VERSION_CHECK(4, 8, 0)) stream.setVersion(QDataStream::Qt_4_8); #else stream.setVersion(QDataStream::Qt_4_6); #endif job->toDataStream(stream); QSqlQuery query; if ( detectionExists(job->id()) ) { query.prepare("UPDATE main.Detection SET return_code=:jretcode, " "data=:jdata WHERE id = :jid"); query.bindValue("jretcode", job->runExitCode()); query.bindValue("jdata", qCompress(buffer)); query.bindValue("jid", job->id()); } else { query.prepare("INSERT INTO main.Detection (id, return_code, data) " "VALUES (:jid, :jretcode, :jdata)"); query.bindValue("jid", job->id()); query.bindValue("jretcode", job->runExitCode()); query.bindValue("jdata", qCompress(buffer)); } if ( query.exec() ) newID = query.lastInsertId().toInt(); else Logger::instancePtr()->addMessage(Logger::CRITICAL, __func__, QString("Query failed: %1").arg(query.executedQuery())); return newID; }
bool Dir::isExistsByName(const QString prefix_name, const QString dir_name) const{ QSqlQuery query; query.prepare("SELECT id FROM dir WHERE prefix_id=(SELECT id FROM prefix WHERE name=:prefix_name) AND name=:dir_name"); query.bindValue(":prefix_name", prefix_name); query.bindValue(":dir_name", dir_name); if (!query.exec()){ qDebug()<<"SqlError: "<<query.lastError()<<query.executedQuery(); return false; } query.first(); if (query.isValid()){ return true; } return false; }
QStringList Last_Run_Icon::getIcons(){ QStringList list; QSqlQuery query; query.prepare("SELECT exec FROM last_run_icon ORDER BY id DESC"); if (query.exec()){ int i=0; while (query.next()) { i++; list.append(query.value(0).toString()); } } else { qDebug()<<"SqlError: "<<query.lastError()<<query.executedQuery(); list.clear(); } return list; }
QStringList Last_Run_Icon::getByExec(const QString exec) const{ QStringList valuelist; QSqlQuery query; // 0 1 2 3 4 5 6 7 query.prepare("SELECT wrkdir, override, winedebug, useconsole, display, cmdargs, desktop, nice, lang FROM last_run_icon WHERE exec=:exec"); query.bindValue(":exec", exec); if (query.exec()){ query.first(); //QStringList values; int i=0; while (query.value(i).isValid()){ valuelist.append(query.value(i).toString()); i++; } } else { qDebug()<<"SqlError: "<<query.lastError()<<query.executedQuery(); valuelist.clear(); } return valuelist; }
bool SQLManager::insertInto (const QString & table, QStringList & params) { QString stmt; QSqlQuery query; if (table == "users") { stmt = "INSERT INTO users (username, password, tags, access) " "VALUES (?, ?, ?, ?)"; } else if (table == "fingerprint") { stmt = "INSERT INTO fingerprint (tag, title, artists, duration, fingerprint) " "VALUES (?, ?, ?, ?, ?)"; } if (! query.prepare (stmt)) { qDebug () << "SQL Error: Failed to create query"; return false; } foreach (const QString & param, params) { if (param.length() == 0) { qDebug () << "SQL Error: Invalid parameters"; return false; } query.addBindValue (param); } if(! query.exec()) { qDebug () << "SQL Error: Failed to save data"; qDebug () << query.executedQuery(); return false; } qDebug () << "SQL Success: Data saved"; return true; }
void addoredir_raspisanie::on_pushButton_save_clicked() { if (ui->comboBox_sotr->currentIndex() ==-1) { QMessageBox::warning(this, tr("Ошибка"), tr("Выберите сотрудника")); return; } if (! dal_main->checkConnection()) { QMessageBox::warning(this, tr("Ошибка соединения"), tr("Соединение не установлено")); return; } QSqlQuery* insertQuery = new QSqlQuery(); insertQuery->prepare("INSERT INTO is_raspisanie(sotr_id, den_nedeli, vremya, predmet) VALUES (:sotr_id, :den_nedeli, :vremya, :predmet)"); insertQuery->bindValue(":sotr_id", ui->comboBox_sotr->model()->index(ui->comboBox_sotr->currentIndex(),0).data().toInt()); if (!this->isEdit) { for (int den = 0; den < 6; den++) { for (int i = 0; i < 7; i++) { QString vr = ui->tableWidget_rasp->item(i, 0)->text(); QString pr = ui->tableWidget_rasp->item(i, den+1)->text(); if(pr.isEmpty()) pr = "-"; insertQuery->bindValue(":den_nedeli", days.at(den)); insertQuery->bindValue(":vremya", vr); insertQuery->bindValue(":predmet", pr); insertQuery->exec(); } } QMessageBox::information(this, tr("Информация"), tr("Запись успешно добавлена")); } else { QSqlQuery* deleteQuery = new QSqlQuery; int id = ui->comboBox_sotr->model()->index(ui->comboBox_sotr->currentIndex(),0).data().toInt(); deleteQuery->prepare("DELETE FROM is_raspisanie WHERE sotr_id = " + QString::number(id)); deleteQuery->exec(); qDebug()<<ui->comboBox_sotr->model()->index(ui->comboBox_sotr->currentIndex(),0).data().toInt()<<deleteQuery->executedQuery()<<deleteQuery->lastError(); for (int den = 0; den < 6; den++) { for (int i = 0; i < 7; i++) { QString vr = ui->tableWidget_rasp->item(i, 0)->text(); QString pr = ui->tableWidget_rasp->item(i, den+1)->text(); if(pr.isEmpty()) pr = "-"; insertQuery->bindValue(":den_nedeli", days.at(den)); insertQuery->bindValue(":vremya", vr); insertQuery->bindValue(":predmet", pr); insertQuery->exec(); } } QMessageBox::information(this, tr("Информация"), tr("Данные успешно отредактированы")); } this->close(); }
void MainWindow::createCase(QString classification) { qDebug()<<classification; QSqlQuery query; QString tempTable = "tempClass" + classification.simplified().remove(" "); query.exec("DROP TEMPORARY TABLE IF EXISTS " + tempTable); // the temprary table is created as below to ensure that the index is also created query.clear(); query.exec("CREATE TEMPORARY TABLE " + tempTable + " LIKE SensorVector"); query.clear(); query.exec("INSERT INTO " + tempTable + " select * from SensorVector limit 1"); query.clear(); query.exec(" select lastUpdate, sensorId, status from Sensors where sensorId < 61 order by sensorId"); QDateTime start(QDate(2010,1,1),QTime(0,0,1)); QString lastSensorId = "-1"; QDateTime currentUpdate; // qDebug()<<".sensor loop"; while (query.next()) { QDateTime sensorLastUpdate = query.value(0).toDateTime(); QString sensorId = query.value(1).toString(); QString sensorStatus = query.value(2).toString(); if (sensorLastUpdate > start) // this gets the last update { start = sensorLastUpdate; lastSensorId = sensorId; } QSqlQuery updateQuery; QString seq; seq = "update " + tempTable + " set sensor" + sensorId + " = '" + sensorStatus + "'"; // qDebug()<<seq; // qDebug()<<"...update temp loop"; updateQuery.exec(seq); } query.clear(); //// Sensor location QSqlQuery locnQuery; QString qry; qry = "select"; qry+= " CASE WHEN L1.where = 0 and L2.where = 0 and L3.where = 0 THEN L1.name"; qry+= " WHEN L3.where = 0 and L2.where = 0 THEN L2.name"; qry+= " ELSE L3.name END,"; qry+= " CASE WHEN L1.where = 0 and L2.where = 0 and L3.where = 0 THEN L1.locationId"; qry+= " WHEN L3.where = 0 and L2.where = 0 THEN L2.locationId"; qry+= " ELSE L3.locationId END"; qry+= " FROM Locations L1, Locations L2, Locations L3"; qry+= " WHERE L2.locationId = L1.where"; qry+= " AND L3.locationId = L2.where"; qry+= " AND L1.locationId = ("; qry+= "select L.locationId from Sensors S, Locations L where S.sensorId = "; qry+= lastSensorId + " and L.locationId = S.locationId LIMIT 1)"; // qDebug()<<qry; // qDebug()<<"..locn query"; if (!locnQuery.exec(qry)) { QMessageBox msgBox; msgBox.setIcon(QMessageBox::Warning); msgBox.setText("Cannot select from location or sensor tables!"); msgBox.exec(); msgBox.setText(locnQuery.lastError().text()); msgBox.exec(); qDebug()<<locnQuery.lastError(); qDebug()<<locnQuery.executedQuery(); return; } if (!locnQuery.next()) { QMessageBox msgBox; msgBox.setIcon(QMessageBox::Warning); msgBox.setText("Cannot select row from location query!"); msgBox.exec(); msgBox.setText(locnQuery.lastError().text()); msgBox.exec(); qDebug()<<locnQuery.lastError(); qDebug()<<locnQuery.executedQuery(); return; } QString location = locnQuery.value(0).toString(); //// QSqlQuery updateQuery; QString seq; seq = "update " + tempTable + " set lastUpdate = '" + start.toString("yyyy-MM-dd hh:mm:ss") + "', sensorLocation = '" + location + "', lastSensorId = '" + lastSensorId + "', classification = '?'"; // qDebug()<<seq; // qDebug()<<"...update temp final"; updateQuery.exec(seq); // create the class file for C5.0 QString fname; fname = "/home/joe/git/accompany/ShowME/data/" + classification + ".cases"; QFile file(fname); if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) { qDebug()<<"Error opening class file"; return; } QTextStream out(&file); seq = "select * from " + tempTable; updateQuery.clear(); updateQuery.exec(seq); QSqlRecord rec = updateQuery.record(); int cols = rec.count(); while(updateQuery.next()) { for (int i=0;i<cols-1;i++) { out << updateQuery.value(i).toString() <<","; } out << updateQuery.value(cols-1).toString()<<"\n"; } file.close(); }
void Window::updateDefinition(const QModelIndex &index) { QString string = mQueryModel->record( index.row() ).value(0).toString(); if(string.isEmpty()) { ui->textEdit->setHtml("<html></html>"); return; } QString html = ""; QString list; QSqlQuery query; switch( columnNameForSearching() ) { case Window::Glassman: query.prepare("select distinct glassman,ipa,persian,did from dari where glassman=:string;"); break; case Window::IPA: query.prepare("select distinct glassman,ipa,persian,did from dari where ipa=:string;"); break; case Window::Dari: query.prepare("select distinct glassman,ipa,persian,did from dari where persian=:string;"); break; case Window::English: query.prepare("select distinct glassman,ipa,persian,dari.did from dari,english,lr where english.english=? and english.eid=lr.eid and lr.did=dari.did;"); break; } query.bindValue(0, string); if( !query.exec() ) { qWarning() << query.lastError() << string << ui->comboBox->currentIndex() << query.executedQuery(); } while(query.next()) { html += "<table style=\"margin-bottom: 10px; font-size: 14pt; font-family: Charis SIL;\">"; html += QString("<tr><td style=\"font-family: Tahoma,sans-serif; text-align: left; background-color: rgb(235,235,235); padding: 3px; padding-right: 6px; font-weight: bold;\">%1</td><td style=\"padding: 3px;\">%2</td></tr>").arg("IPA").arg(query.value(1).toString()); html += QString("<tr><td style=\"font-family: Tahoma,sans-serif; text-align: left; background-color: rgb(235,235,235); padding: 3px; padding-right: 6px; font-weight: bold;\">%1</td><td style=\"padding: 3px;\">%2</td></tr>").arg("Glassman").arg(query.value(0).toString()); list = ""; QSqlQuery query2; query2.prepare("select english from english,lr where lr.eid=english.eid and lr.did=?;"); query2.bindValue(0, query.value(3).toInt() ); if( ! query2.exec() ) { qWarning() << query.lastError(); } while(query2.next()) { list += query2.value(0).toString() + ", "; } list.chop(2); html += QString("<tr><td style=\"font-family: Tahoma,sans-serif; text-align: left; background-color: rgb(235,235,235); padding: 3px; padding-right: 6px; font-weight: bold;\">%1</td><td style=\"padding: 3px;\">%2</td></tr>").arg("English").arg(list); html += "</table>"; } ui->textEdit->setHtml(html); }
int LoadMetasql::writeToDB(const QByteArray &pdata, const QString pkgname, QString &errMsg) { if (pdata.isEmpty()) { errMsg = TR("<font color=orange>The MetaSQL statement %1 is empty.</font>") .arg(_name); return -2; } QString metasqlStr = QString(pdata); QStringList lines = metasqlStr.split("\n"); QRegExp groupRE = QRegExp("(^\\s*--\\s*GROUP:\\s*)(.*)",Qt::CaseInsensitive); QRegExp nameRE = QRegExp("(^\\s*--\\s*NAME:\\s*)(.*)", Qt::CaseInsensitive); QRegExp notesRE = QRegExp("(^\\s*--\\s*NOTES:\\s*)(.*)",Qt::CaseInsensitive); QRegExp dashdashRE = QRegExp("(^\\s*--\\s*)(.*)"); for (int i = 0; i < lines.size(); i++) { if (DEBUG) qDebug("LoadMetasql::writeToDB looking at %s", qPrintable(lines.at(i))); if (groupRE.indexIn(lines.at(i)) >= 0) { _group = groupRE.cap(2); if (DEBUG) qDebug("LoadMetasql::writeToDB() found group %s", qPrintable(_group)); } else if (nameRE.indexIn(lines.at(i)) >= 0) { _name = nameRE.cap(2); if (DEBUG) qDebug("LoadMetasql::writeToDB() found name %s", qPrintable(_name)); } else if (notesRE.indexIn(lines.at(i)) >= 0) { _comment = notesRE.cap(2); while (dashdashRE.indexIn(lines.at(++i)) >= 0) _comment += " " + dashdashRE.cap(2); if (DEBUG) qDebug("LoadMetasql::writeToDB() found notes %s", qPrintable(_comment)); } } if (DEBUG) qDebug("LoadMetasql::writeToDB(): name %s group %s notes %s\n%s", qPrintable(_name), qPrintable(_group), qPrintable(_comment), qPrintable(metasqlStr)); QSqlQuery upsert; int metasqlid = -1; upsert.prepare("SELECT saveMetasql(:group, :name, :notes, :query, :system) AS result;"); upsert.bindValue(":group", _group); upsert.bindValue(":name", _name); upsert.bindValue(":notes", _comment); upsert.bindValue(":query", metasqlStr); upsert.bindValue(":system",_system); upsert.exec(); if (upsert.first()) { metasqlid = upsert.value(0).toInt(); if (metasqlid < 0) { errMsg = TR("The %1 stored procedure failed, returning %2.") .arg("saveMetasql").arg(metasqlid); return -5; } } else if (upsert.lastError().type() != QSqlError::NoError) { QSqlError err = upsert.lastError(); errMsg = _sqlerrtxt.arg(_filename).arg(err.driverText()).arg(err.databaseText()); return -6; } else { errMsg = TR("Saving the MetaSQL statement returned 0 rows. This should " "not be possible."); return -6; } if (DEBUG) qDebug("LoadMetasql::writeToDB() executed %s and got %d in return", qPrintable(upsert.executedQuery()), metasqlid); if (! pkgname.isEmpty()) { QSqlQuery select; int pkgitemid = -1; int pkgheadid = -1; select.prepare(_pkgitemQueryStr); select.bindValue(":name", _group + "-" + _name); select.bindValue(":pkgname", pkgname); select.bindValue(":type", _pkgitemtype); select.exec(); if(select.first()) { pkgheadid = select.value(1).toInt(); pkgitemid = select.value(2).toInt(); } else if (select.lastError().type() != QSqlError::NoError) { QSqlError err = select.lastError(); errMsg = _sqlerrtxt.arg(_filename).arg(err.driverText()).arg(err.databaseText()); return -7; } QString simplename = _name; _name = _group + "-" + _name; int tmp = upsertPkgItem(pkgitemid, pkgheadid, metasqlid, errMsg); _name = simplename; if (tmp < 0) return tmp; } return metasqlid; }
/*! \fn FormActualizacion::analizarGeneral() Funcion que analiza el archivo xml de actualizaciones para comprobar las descargas */ void FormActualizacion::analizarGeneral() { QDomDocument *docxml = new QDomDocument(); int linea,columna; QString mensaje; if( !docxml->setContent( ftp->readAll(), false, &mensaje, &linea, &columna ) ) { TELog->append( "Error al cargar el contenido del archivo de actualizaciones" ); qDebug( QString( "Error: f:%1,c:%2; m=%3 " ).arg( linea ).arg(columna ).arg(mensaje ).toLocal8Bit() ); _continuar_actualizando = false; return; } else { TELog->append( "Descarga correcta." ); qDebug( "Descarga Correcta" ); } TELog->append( "Analizando actualizaciones disponibles" ); QDomElement docElem = docxml->documentElement(); qDebug( QString( "Primer hijo: %1" ).arg( docElem.tagName() ).toLocal8Bit() ); if( docElem.tagName() == "actualizacion" ) { qDebug( "Encontrado nodo de actualizacion" ); } if( docElem.attribute( "version", 0 ).toDouble() > VERSION_PROGRAMA ) { TELog->append( "No existen actualizaciones para esta version de Gestotux. Por Favor actualize el programa a una version superior" ); ftp->clearPendingCommands(); ftp->close(); _continuar_actualizando = false; return; } else { TELog->append( "No se necesita actualizar el programa general." ); //Ingreso al directorio de la version del programa ftp->cd( QString::number( docElem.attribute( "version", 0 ).toDouble() ) ); qDebug( QString( "entrando en: %1" ).arg( docElem.attribute( "version", 0 ).toDouble() ).toLocal8Bit() ); // Busco si hay algo dentro de archivos /*QDomNode nodo_archivos = docxml->elementsByTagName( "archivos" ).item(0); if( nodo_archivos.hasChildNodes() ) { qDebug( "Encontrada etiqueta de archivos generales" ); ///\todo Esto todavia no defini como lo voy a hacer }*/ qDebug( QString( "Encontrada version :%1" ).arg( docElem.attribute( "version", 0 ) ).toLocal8Bit() ); // Busco los plugins while( docElem.hasChildNodes() ) { if( !_continuar_actualizando ) { return; } QDomNode nodoA = docElem.firstChild(); if( nodoA.toElement().tagName() == "plugin" ) { // Tengo instalado el plugin?? qDebug( QString( "Encontrado plugin %1" ).arg( nodoA.toElement().attribute( "nombre" ) ).toLocal8Bit() ); QString nombre = nodoA.toElement().attribute( "nombre" ); if( ERegistroPlugins::getInstancia()->pluginsHash()->find( nombre ) == ERegistroPlugins::getInstancia()->pluginsHash()->end() ) { qDebug( QString( "El plugin %1 no se encuentra en este sistema, no se descargara ni actualizar?" ).arg( nombre ).toLocal8Bit() ); docElem.removeChild( nodoA ); continue; } // ingreso a la carpeta del plugin ftp->cd( nombre ); qDebug( QString( "Entrando en la carpeta: %1" ).arg( nombre ).toLocal8Bit() ); QMap<double,QDomNode> versiones; // Este nodo debe tener tantos nodos como versiones disponibles while( nodoA.hasChildNodes() ) { QDomNode nodoVersion = nodoA.firstChild(); if( nodoVersion.toElement().tagName() == "version" ) { //veo que numero de version es double version = nodoVersion.toElement().attribute( "numero" ).toDouble(); qDebug( QString( "Encontrada version %1" ).arg( version ).toLocal8Bit() ); if( version >= ERegistroPlugins::getInstancia()->pluginsHash()->value( nombre )->version() ) { // Lo ingreso a la lista de actualizaciones de forma ordenanda qDebug( "Version agregada" ); versiones.insert( version, nodoVersion ); nodoA.removeChild( nodoVersion ); } else { // actualizacion vieja, la elimino del arbol nodoA.removeChild( nodoVersion ); continue; } } else { // No puede haber de otro tipo, lo elimino qDebug( "Encontrado nodo que no es version" ); nodoA.removeChild( nodoVersion ); } } // Ejecuto las actualizaciones de forma ordenada qDebug( "Ordenando versiones" ); QList<double> lista = versiones.keys(); qStableSort( lista.begin(), lista.end() ); if( lista.size() == 0 ) { qDebug( "La lista de actualizaciones esta vacia" ); } while( lista.size() > 0 ) { QDomNode nodoB = versiones[lista.first()]; // Trabajo con el nodo // Busco los hijos que son archivos TELog->append( QString( "Actualizando plugin %1..." ).arg( nombre ) ); // Ingreso al directorio de la version del plugin ftp->cd( QString::number( lista.first() ) ); #ifdef Q_WS_WIN32 QString nombre_os = "windows"; #endif #ifdef Q_WS_X11 QString nombre_os = "linux"; #endif QDomNode nodo_os = nodoB.toElement().elementsByTagName( nombre_os ).item(0); qDebug( QString( "Nodo OS: %1" ).arg( nodo_os.nodeName() ).toLocal8Bit() ); QDomNodeList nodos_archivos = nodo_os.toElement().elementsByTagName( "archivo" ); unsigned int posNodo = 0; qDebug( QString( "Encontrado %1 nodos").arg( nodos_archivos.length() ).toLocal8Bit() ); while( posNodo < nodos_archivos.length() && _continuar_actualizando ) { QDomNode nodo_archivo = nodos_archivos.item(posNodo); QPair<QString,QString> tmp; tmp.first = nodo_archivo.toElement().attribute( "nombre" ); tmp.second = nodo_archivo.toElement().attribute( "directorio_destino" ); qDebug( QString( "Encontrado archivo %1, dir %2" ).arg( tmp.first ).arg( tmp.second ).toLocal8Bit() ); TELog->append( QString( "Descargando archivo %1..." ).arg( tmp.first ) ); int pos = ftp->get( tmp.first ); _arch_dest.insert( pos, tmp ); posNodo++; } //Veo si hay actualizaciones de la base de datos qDebug( "Actualizaciones de base de datos" ); QDomNodeList nodos_db = nodoB.toElement().elementsByTagName( "db" ); if( nodos_db.length() > 0 && _continuar_actualizando ) { for( unsigned int i=0; i<nodos_db.length(); i++ ) { if( !_continuar_actualizando ) { return; } QDomNode nodo = nodos_db.item(i); // Busco todos los hijos QDomNodeList nodos_colas = nodo.toElement().elementsByTagName( "cola" ); if( nodos_colas.length() > 0 && _continuar_actualizando ) { for( unsigned int j=0; j < nodos_colas.length(); j++ ) { if( !_continuar_actualizando ) { return;} QDomNode nCola = nodos_colas.item(j); if( nCola.nodeName() == "cola" ) { QSqlQuery cola; if( cola.exec( nCola.firstChild().toText().data() ) ) { qDebug( QString( "Cola ejecutada correctamente: %1" ).arg( cola.executedQuery() ).toLocal8Bit() ); } else { qWarning( QString( "La ejecucion de la actualizacion no fue correcta. Cola: %1" ).arg( cola.executedQuery() ).toLocal8Bit() ); qDebug( QString( "Error: %1.\n Cola: %2" ).arg( cola.lastError().text() ).arg( cola.executedQuery() ).toLocal8Bit() ); } } else { qDebug( QString("Nodo encontrado: %1").arg(nodo.nodeName() ).toLocal8Bit() ); } } // Fin for colas }// Fin if nodos_colas }// Fin for dbs } else { qDebug( "No hay actualizaciones para la base de datos" ); } //////////////////////// Fin de trabajar con el nodo versiones.remove(lista.first()); lista.removeFirst(); // Salgo del directorio de la version y quedo en el directorio del plugin ftp->cd(".."); } qDebug( "Fin bucle Versiones" ); // Termino de actualizar el plugin y sus versiones -> salgo al directorio de la version del programa ftp->cd(".."); docElem.removeChild( nodoA ); } else if( nodoA.toElement().tagName() == "libreria" ) { ftp->cd( "librerias" ); // Veo el numero de secuencia int num_seq = preferencias::getInstancia()->value( "Preferencias/General/"+nodoA.toElement().attribute("nombre" ) + "/numseq", 0 ).toInt(); int num_nuevo = nodoA.toElement().attribute( "numerosecuencia" ).toInt(); if( num_seq <= num_nuevo ) { ftp->cd( QString::number( num_nuevo ) ); #ifdef Q_WS_WIN32 QString nombre_os = "windows"; #endif #ifdef Q_WS_X11 QString nombre_os = "linux"; #endif QDomNode nodo_os = nodoA.toElement().elementsByTagName( nombre_os ).item(0); qDebug( QString( "Nodo OS: %1" ).arg( nodo_os.nodeName() ).toLocal8Bit() ); QDomNodeList nodos_archivos = nodo_os.toElement().elementsByTagName( "archivo" ); unsigned int posNodo = 0; qDebug( QString( "Encontrado %1 nodos").arg( nodos_archivos.length() ).toLocal8Bit() ); while( posNodo < nodos_archivos.length() && _continuar_actualizando ) { QDomNode nodo_archivo = nodos_archivos.item(posNodo); QPair<QString,QString> tmp; tmp.first = nodo_archivo.toElement().attribute( "nombre" ); tmp.second = nodo_archivo.toElement().attribute( "directorio_destino" ); qDebug( QString( "Encontrado archivo %1, dir %2" ).arg( tmp.first ).arg( tmp.second ).toLocal8Bit() ); TELog->append( QString( "Descargando archivo %1..." ).arg( tmp.first ) ); int pos = ftp->get( tmp.first ); _arch_dest.insert( pos, tmp ); posNodo++; } } else { // La libreria no necesita actualizacion } ftp->cd(".."); //Fin de actualizar la libreria -> regreso a la carpeta de version del programa } else { // El nodo no es plugin /// \todo ver que hacer aca qDebug( QString( "Tipo de nodo desconocido: %1" ).arg( nodoA.toElement().tagName() ).toLocal8Bit() ); docElem.removeChild( nodoA ); } } // fin de si actualizacion tiene nodos } ftp->close(); TELog->append( "Lista el Analisis" ); transferencia( 100, 100 ); qDebug( "Fin" ); }