Example #1
0
	void SQLStorageBackend::InitializeTables ()
	{
		QSqlQuery query (DB_);

		if (!DB_.tables ().contains ("history"))
		{
			if (!query.exec ("CREATE TABLE history ("
						"date TIMESTAMP PRIMARY KEY, "
						"title TEXT, "
						"url TEXT"
						");"))
			{
				LeechCraft::Util::DBLock::DumpError (query);
				return;
			}

			if (!query.exec ("CREATE INDEX idx_history_title_url "
						"ON history (title, url)"))
				LeechCraft::Util::DBLock::DumpError (query);
		}

		if (!DB_.tables ().contains ("favorites"))
		{
			if (!query.exec ("CREATE TABLE favorites ("
						"title TEXT PRIMARY KEY, "
						"url TEXT, "
						"tags TEXT"
						");"))
			{
				LeechCraft::Util::DBLock::DumpError (query);
				return;
			}
		}

		if (!DB_.tables ().contains ("storage_settings"))
		{
			if (!query.exec ("CREATE TABLE storage_settings ("
						"key TEXT PRIMARY KEY, "
						"value TEXT"
						");"))
			{
				LeechCraft::Util::DBLock::DumpError (query);
				return;
			}

			if (Type_ == SBPostgres)
			{
				if (!query.exec ("CREATE RULE \"replace_storage_settings\" AS "
									"ON INSERT TO \"storage_settings\" "
									"WHERE "
										"EXISTS (SELECT 1 FROM storage_settings "
											"WHERE key = NEW.key) "
									"DO INSTEAD "
										"(UPDATE storage_settings "
											"SET value = NEW.value "
											"WHERE key = NEW.key)"))
				{
					LeechCraft::Util::DBLock::DumpError (query);
					return;
				}
			}

			SetSetting ("historyversion", "1");
			SetSetting ("favoritesversion", "1");
			SetSetting ("storagesettingsversion", "1");
		}

		if (!DB_.tables ().contains ("forms"))
		{
			QString binary = "BLOB";
			if (Type_ == SBPostgres)
				binary = "BYTEA";

			if (!query.exec (QString ("CREATE TABLE forms ("
							"url TEXT, "
							"form_index INTEGER, "
							"name TEXT, "
							"type TEXT, "
							"value %1"
							");").arg (binary)))
			{
				LeechCraft::Util::DBLock::DumpError (query);
				return;
			}
		}

		if (!DB_.tables ().contains ("forms_never"))
		{
			if (!query.exec ("CREATE TABLE forms_never ("
						"url TEXT PRIMARY KEY"
						");"))
			{
				LeechCraft::Util::DBLock::DumpError (query);
				return;
			}
		}
	}
void UserManager::clearOptions(const QString& user)
{
    QSqlQuery query;
    query.exec( QString("DELETE FROM options WHERE jid='%1'").arg(user) );
}
Example #3
0
AddRecipients::AddRecipients(QLineEdit & listRecipients,QWidget *parent) :
    QDialog(parent)
{
    setFixedWidth(300);
    setWindowTitle("Ajouter un destinataire");

    currentListRecipients = &listRecipients;

    db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("database.db");

    if (!db.open())
    {
        qDebug() << "Impossible de se connecter à la base de données." << endl;
        return;
    }

    listView_users = new QListView();
    listView_users->setEditTriggers(0);

    QSqlQuery query;
    query.exec("SELECT * FROM Contacts");

    modelListUsers = new QStandardItemModel();

    int index = 0;
    while(query.next())
    {
        User user(query.value(1).toInt(),QString(query.value(2).toString()));

        QStandardItem *item = new QStandardItem();
        item->setText(user.address());

        QVariant data;
        data.setValue(user);
        item->setData(data);

        modelListUsers->setItem(index,item);
        index++;
    }

    listView_users->setModel(modelListUsers);

    QVBoxLayout *layout_add_users = new QVBoxLayout();
    layout_add_users->addWidget(listView_users);

    btn_add_user = new QPushButton("Ajouter le contact");

    QVBoxLayout *layout_btn_add_users = new QVBoxLayout();
    layout_btn_add_users->addWidget(btn_add_user);

    list_users = new QGroupBox("Contacts");
    form_list_users = new QFormLayout();
    form_list_users->addRow("Liste des contacts : ", listView_users);
    form_list_users->addRow("", layout_btn_add_users);

    list_users->setLayout(form_list_users);

    QVBoxLayout *layout_main = new QVBoxLayout;
    layout_main->addWidget(list_users);

    setLayout(layout_main);

    connect(btn_add_user, SIGNAL(clicked()), this, SLOT(addUser()));
    show();
}
Example #4
0
//missing the year restriction
bool DbManager::helperAllLicensesYear(        const QString& first_name,
                                              const QString& last_name,
                                              const QString& municipality,
                                              const QString& zip,
                                              const QString& province,
                                              const QString& job,
                                              bool           is_valid,
                                              bool           is_expired)
{
    QSqlQuery query;
    QString query_string = "SELECT  "
                                                "people.id, "
                                                "people.last_name, "
                                                "people.first_name, "
                                                "address.street_name, "
                                                "address.zip, "
                                                "address.municipality, "
                                                "address.province, "
                                                "people.personal_code, "
                                                "people.job, "
                                                "people.email, "
                                                "people.phone, "
                                                "license.license_name, "
                                                "people_license.is_valid, "
                                                "people_license.date_of_issue,"
                                                "people_license.last_notification "
                            "FROM                people "
                            "INNER JOIN          address             ON people.id = address.person "
                            "INNER JOIN          people_license      ON people_license.id_person = people.id "
                            "INNER JOIN          license             ON license.id = people_license.id_license ";

    query_string += " AND people.last_name LIKE :last_name";
    query_string += " AND people.first_name LIKE :first_name";
    query_string += " AND address.municipality LIKE :municipality";
    query_string += " AND address.zip LIKE :zip";
    query_string += " AND address.province LIKE :province";
    query_string += " AND people.job LIKE :job";
    if(is_valid) {
        query_string += " AND people_license.is_valid = 'true'";
    } else if(is_expired) {
        query_string += " AND people_license.is_valid = 'false'";
    }

    query.prepare(query_string);

    query.bindValue(":last_name",       QVariant('%' + last_name + '%'));
    query.bindValue(":first_name",      QVariant('%' + first_name + '%'));
    query.bindValue(":municipality",    QVariant('%' + municipality + '%'));
    query.bindValue(":zip",             QVariant('%' + zip + '%'));
    query.bindValue(":province",        QVariant('%' + province + '%'));
    query.bindValue(":job",             QVariant('%' + job + '%'));

    search_results_table_model = new SqlQueryModel();
    if(query.exec()) {
        search_results_table_model->setQuery(query);
        last_show_query = query;
        return true;
    } else {
        search_results_table_model->setQuery(query);
        qDebug() << "query failed: " << query.lastError();
        return false;
    }
}
void UserManager::setOption(const QString& user, const QString& option, const QVariant& value)
{
    QSqlQuery query;
    query.exec( QString("REPLACE INTO options (jid,option,value) VALUES('%1', '%2', '%3')").arg(user,option, value.toString()) );
}
void addOtherOrders::on_roomNo_currentIndexChanged()
{
    QString roomno = ui->roomNo->currentText();
    qDebug() << roomno;

    if(roomno==":: select one ::")
    {
        ui->okButton->setEnabled(0);
        ui->name->setEnabled(0);
        ui->price->setEnabled(0);
        ui->nameLabel->setText("-");
        return;
    }

    QSqlDatabase db = QSqlDatabase::addDatabase( "QSQLITE" );

    db.setDatabaseName( "./innovativedb.db" );

    if( !db.open() )
    {
        qDebug() << db.lastError();
        qFatal( "Failed to connect." );
    }

    qDebug( "Connected!" );

    QSqlQuery qry;
    qry.prepare("CREATE TABLE IF NOT EXISTS roomlist (id INTEGET PRIMARY KEY, roomno VARCHAR(5), cat INTEGER, occupied INTEGER)");
    if(!qry.exec())
        qDebug() << qry.lastError();
    else
        qDebug( "Room Table Validated..." );

    qry.prepare("SELECT occupied FROM roomlist WHERE roomno=:room");
    qry.bindValue(":room",roomno);
    if(!qry.exec())
        qDebug() << qry.lastError();
    else
        qDebug( "Room Table Validated..." );

    QString guestID = "";
    while(qry.next())
    {
        guestID = qry.value(0).toString();
    }
    qDebug()<<guestID;
    qry.prepare("CREATE TABLE IF NOT EXISTS guestlist ( id INTEGET PRIMARY KEY, name VARCHAR(30),address VARCHAR(30), nationality VARCHAR(15), phone VARCHAR(15), occupation VARCHAR(15),purpose VARCHAR(20), occupant INTEGER, room VARCHAR(8), intime VARCHAR(30), outtime VARCHAR(30) )");
    if(!qry.exec())
        qDebug() << qry.lastError();
    else
        qDebug( "Table Created!" );

    qry.prepare("SELECT name FROM guestlist WHERE id=:guestID");
    qry.bindValue(":guestID",guestID);

    if(!qry.exec())
    {
       qDebug() << qry.lastError();
    }
    else
        qDebug( "Table Selected!" );

    while (qry.next())
    {
        QString cur_item = qry.value(0).toString();
        ui->nameLabel->setText(cur_item);
        ui->name->setEnabled(1);
        ui->price->setEnabled(1);
    }

}
Example #7
0
bool DbManager::createNewDatabase()
{
    bool success_1;
    bool success_2;
    bool success_3;
    bool success_4;
    bool success_5;
    bool success_6;
    bool success_7;
    bool success_8;
    bool success_9;
    bool success_10;
    bool success_11;
    bool success_12;
    bool success_13;

    *db_link = QSqlDatabase::addDatabase("QSQLITE");
    path_ += "/new_database.db";
    db_link->setDatabaseName(path_);
    db_link->open();
    //Table: license
    QSqlQuery query;
    QString query_string = "CREATE TABLE license (id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE NOT NULL, license_name UNIQUE NOT NULL, validity INTEGER)";
    query.prepare(query_string);
    success_1 = query.exec();

    //Table: address
    query_string = "CREATE TABLE address (id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE NOT NULL, person INTEGER REFERENCES people (id) ON DELETE CASCADE ON UPDATE CASCADE NOT NULL, street_name VARCHAR (100), municipality VARCHAR (50), zip VARCHAR (5), province VARCHAR (2), state VARCHAR (2))";
    query.prepare(query_string);
    success_2 = query.exec();

    //Table: people
    query_string = "CREATE TABLE people (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE, first_name VARCHAR (50) NOT NULL, last_name VARCHAR (50) NOT NULL, personal_code VARCHAR (16) UNIQUE NOT NULL, job VARCHAR (50), email VARCHAR (100), phone VARCHAR)";
    query.prepare(query_string);
    success_3 = query.exec();

    //Table: people_license
    query_string = "CREATE TABLE people_license (id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE NOT NULL, id_person REFERENCES people (id) ON DELETE CASCADE ON UPDATE CASCADE NOT NULL, id_license INTEGER REFERENCES license (id) ON DELETE CASCADE ON UPDATE CASCADE NOT NULL, date_of_issue INTEGER, is_valid BOOLEAN DEFAULT false, last_notification INTEGER DEFAULT (- 1))";
    query.prepare(query_string);
    success_4 = query.exec();

    //license population
    query_string = "INSERT INTO license (id, license_name, validity) VALUES (1, 'Bagnino di Salvataggio per Piscine', 3)";
    query.prepare(query_string);
    success_5 = query.exec();

    query_string = "INSERT INTO license (id, license_name, validity) VALUES (2, 'Bagnino di Salvataggio per Piscine e Acque Libere', 3)";
    query.prepare(query_string);
    success_6 = query.exec();

    query_string = "INSERT INTO license (id, license_name, validity) VALUES (3, 'Istruttore di Nuoto', 3)";
    query.prepare(query_string);
    success_7 = query.exec();

    query_string = "INSERT INTO license (id, license_name, validity) VALUES (4, 'Istruttore di Acquafitness e Hydrobike', 3)";
    query.prepare(query_string);
    success_8 = query.exec();

    query_string = "INSERT INTO license (id, license_name, validity) VALUES (5, 'Istruttore di Nuoto per Disabili', 3)";
    query.prepare(query_string);
    success_9 = query.exec();

    query_string = "INSERT INTO license (id, license_name, validity) VALUES (6, 'BLSD', 2)";
    query.prepare(query_string);
    success_10 = query.exec();

    query_string = "INSERT INTO license (id, license_name, validity) VALUES (7, 'Istruttore di Arti Marinaresche', 3)";
    query.prepare(query_string);
    success_11 = query.exec();

    query_string = "INSERT INTO license (id, license_name, validity) VALUES (8, 'Docente Formatore per Istruttori di Nuoto', 3)";
    query.prepare(query_string);
    success_12 = query.exec();

    query_string = "INSERT INTO license (id, license_name, validity) VALUES (9, 'Scienze Motorie', 0)";
    query.prepare(query_string);
    success_13 = query.exec();

    if(success_1 && success_2 && success_3 && success_4 && success_5 && success_6 && success_7 && success_8 && success_9 && success_10 && success_11 && success_12 && success_13) {
        return true;
    } else {
        return false;
    }
}
Example #8
0
// =====================================================================
// DUMP alle Tabellen oder eine einzelne Tabelle
// ---------------------------------------------
void admin::dbDump()
{
    if(SavePathEdit->text().count() == 0) {       // ist ein Path gewaehlt ?
      QMessageBox::information( this,
        tr("INFO"),
        tr("\nBitte DUMP-Ordner waehlen !!"),
        QMessageBox::Ok);
      return;
    }
        QString pathToMysql="";
#ifdef Q_WS_WIN
    pathToMysql=settings.value("mySQLPath","").toString();
#endif
    if(checkBoxDb->isChecked() == TRUE ) {     // gesetzt - Alle Tabellen Dumpen
        QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
        s = pathToMysql+"mysqldump -u"+settings.value("dbuser").toString()+" -p";
        s += settings.value("dbpasswd").toString();
        s += " --opt "+settings.value("dbname").toString()+" > "+SavePathEdit->text()+"backup-db.sql"; 
        StartProcess(s.toAscii());
        QApplication::restoreOverrideCursor();
    }
    else {                                   // LOG_tabelle dumpen
       QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
       if(lItem) {
         s = pathToMysql+"mysqldump -u"+settings.value("dbuser").toString()+" -p"+settings.value("dbpasswd").toString()+" --opt "+settings.value("dbname").toString()+" ";
          s += lItem->text(0)+" ";          // fun
          s += lItem->text(0)+"qsl ";       // fun_qsl
          s += lItem->text(0)+"om ";        // fun_om
          s += lItem->text(0)+"awd ";       // fun_awd
          s += lItem->text(0)+"card ";      // fun_qslcard
          s += lItem->text(0)+"dx ";        // fun_dx
          s += "wawdlist > ";               
          s+= SavePathEdit->text()+"backup-"+lItem->text(0)+".sql";
          StartProcess(s.toAscii());         // DUMP
	  
          QString tag, monat, jahr, dform;
          QDate d = QDate::currentDate();   // Datum von heute
          tag = s.setNum(d.day());
          monat = s.setNum(d.month());
          jahr = s.setNum(d.year());
	  
          if(tag.count() < 2) tag = "0"+tag;
          if(monat.count() < 2) monat = "0"+monat;
	  
          // Datum_Datensicherung
          qy = "UPDATE dblogs SET saved='"+jahr+"-"+monat+"-"+tag;
          qy += "' WHERE logname='"+lItem->text(0)+"'";
          QSqlQuery query;
          query.exec(qy);
          s = jahr+"-"+monat+"-"+tag;
          lItem->setText(3,s);
       }
       else
         if(sItem) {                          // System_tabelle dumpen
            s = pathToMysql + "mysqldump -u"+settings.value("dbuser").toString()+" -p"+settings.value("dbpasswd").toString()+" --opt "+settings.value("dbname").toString();
            s += " "+sItem->text(0)+" > ";
            s+= SavePathEdit->text()+"backup-"+sItem->text(0)+".sql";
            StartProcess(s.toAscii());        // DUMP
         }
       else {
          QApplication::restoreOverrideCursor();
          QMessageBox::information( this,
          tr("INFO"),
          tr("\nErst eine Tabelle im Logbook- oder QtLog-Ordner waehlen"),
          QMessageBox::Ok);
          return;
       }
    }
    
    s = "cp "+QDir::homePath();             // sichere immer auch qtlog.ini
    s += "/.config/QtLog/qtlog.ini "+SavePathEdit->text();
    StartProcess(s.toAscii());
    
    QApplication::restoreOverrideCursor();
}
Example #9
0
// ======================================================================
// RESTORE database kompl. oder eine einzelne Tabelle
// --------------------------------------------------------
void admin::dbRestore()
{
  int i;
  QString p;
  QFile file;
     i = 0;
     QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
     QString pathToMysql="";
#ifdef Q_WS_WIN
    pathToMysql=settings.value("mySQLPath","").toString();
#endif
     if(checkBoxDb->isChecked() == TRUE ) {          // gesetzt, RESTORE alle Tabellen
        p += SavePathEdit->text()+"backup-db.sql";
        if(!file.exists(p)) {
           QApplication::restoreOverrideCursor();
           QMessageBox::information( this,
           tr("INFO"),
           tr("\nRESTORE nicht moeglich - Datei nicht vorhanden !"),
           QMessageBox::Ok);
          return;
        }
        QSqlQuery query;
        // hier müsste noch pathToMysql rein ! ?
        qy = "DROP DATABASE IF EXISTS "+settings.value("dbname").toString(); 
        query.exec(qy);
         // auch hier müsste noch pathToMysql rein ! ?
        qy = "CREATE DATABASE logdb";                                        
        query.exec(qy);
        qy = "USE logdb";
        query.exec(qy);
 
        // Windows: dbuser hinzugefuegt, sollte unter Linux auch gehen
        s = pathToMysql + "mysql -u"+settings.value("dbuser").toString()+" -p"+settings.value("dbpasswd").toString();
        s += " "+ settings.value("dbname").toString()+" < ";
        s += p;
        StartProcess(s.toAscii());
        i = 1;
     }
     else {                                              // RESTORE eine log_Tabelle
        if( lItem) {
          p = SavePathEdit->text()+"backup-"+lItem->text(0)+".sql";
          if(!file.exists(p)) {
             QApplication::restoreOverrideCursor();
             QMessageBox::information( this,
             tr("INFO"),
             tr("\nRESTORE nicht moeglich - Datei nicht vorhanden !"),
             QMessageBox::Ok);
            return;
          }
         // fun, funqsl, funom, funawd, funcard, fundx, wawdlist
          s = pathToMysql + "mysql -u"+settings.value("dbuser").toString()+" -p"+settings.value("dbpasswd").toString()+" "+settings.value("dbname").toString()+" < ";
          s+= p;
          StartProcess(s.toAscii());
          QSqlQuery query;
          qy = "SELECT COUNT(*) FROM "+lItem->text(0);
          query.exec(qy);
          query.next();
          s = query.value(0).toString();
          qy = "UPDATE dblogs SET qsocnt='"+s+"' WHERE logname='"+lItem->text(0)+"'";
          query.exec(qy);
          i = 0;
       }
       else
          if( sItem ) {                                  // eine system_tabelle 
             p = SavePathEdit->text()+"backup-"+sItem->text(0)+".sql";
             if(!file.exists(p)) {
                QApplication::restoreOverrideCursor();
                QMessageBox::information( this,
                tr("INFO"),
                tr("\nRESTORE nicht moeglich - Datei nicht vorhanden !"),
                QMessageBox::Ok);
               return;
             }
             s = pathToMysql + "mysql -u"+settings.value("dbuser").toString()+" -p"+settings.value("dbpasswd").toString()+" "+settings.value("dbname").toString()+" < ";
             s += p;
             StartProcess(s.toAscii());
             i = 0;
          }
        else {
          QApplication::restoreOverrideCursor();
          QMessageBox::information( this,
          tr("INFO"),
          tr("\nErst eine Tabelle im Logbook- oder QtLog-Ordner waehlen"),
          QMessageBox::Ok);
          return;
       }
     }
     logList->clear();
     sysList->clear();
     showTables(i);                               // Ergebnis in logList und sysList anzeigen.
     QApplication::restoreOverrideCursor();
}
Example #10
0
bool pgiticlog::save_config()
{
    QSqlQuery qry;

    std::string command;

    std::string _joyx = (joyx)?"1":"0";
    std::string _joyy = (joyy)?"1":"0";
    std::string _rememberme = (rememberme)?"1":"0";
    std::string _logout_idle = (logout_idle)?"1":"0";
    std::string _cmdloop = (cmd_loop)?"1":"0";
    std::string _loopvalue = QString::number(loop_value).toStdString().c_str();
    std::string _remoteip = "'" + remote_ip + "'";
    std::string _remoteport = "'" + remote_port + "'";
    std::string _admin_pass = "'" + admin_pass + "'";
    std::string _user_pass = "'" + user_pass + "'";
    std::string _controller_model = "'" + controller_model + "'";
    std::string _camera_model = "'" + camera_model + "'";
    std::string _camera_speed =  QString::number(camera_speed).toStdString().c_str();
    std::string _speaker_volume =  QString::number(speaker_volume).toStdString().c_str();

    std::string _serial1_name = "'" + serial1_name + "'";
    std::string _serial2_name = "'" + serial2_name + "'";
    std::string _serial3_name = "'" + serial3_name + "'";

    std::string _serial1_baud = QString::number(serial1_baud).toStdString().c_str();
    std::string _serial2_baud = QString::number(serial2_baud).toStdString().c_str();
    std::string _serial3_baud = QString::number(serial3_baud).toStdString().c_str();


    command = "UPDATE config SET";
    command.append("  joyx = ")              ; command.append(_joyx);
    command.append(", joyy = ")              ; command.append(_joyy);
    command.append(", cmd_loop = ")          ; command.append(_cmdloop);
    command.append(", logout_idle= ")        ; command.append(_logout_idle);
    command.append(", loop_value = ")        ; command.append(_loopvalue);
    command.append(", remote_ip = ")         ; command.append(_remoteip );
    command.append(", remote_port = ")       ; command.append(_remoteport);
    command.append(", admin_pass = ")        ; command.append(_admin_pass);
    command.append(", user_pass = ")         ; command.append(_user_pass);
    command.append(", controller_model = ")  ; command.append(_controller_model);
    command.append(", camera_model = ")      ; command.append(_camera_model);
    command.append(", cameraspeed = ")       ; command.append(_camera_speed);
    command.append(", volume = ")            ; command.append(_speaker_volume);
    command.append(", rememberme = ")        ; command.append(_rememberme);
    command.append(", serial1name = ")        ; command.append(_serial1_name);
    command.append(", serial2name = ")        ; command.append(_serial2_name);
    command.append(", serial3name = ")        ; command.append(_serial3_name);
    command.append(", serial1baudrate = ")    ; command.append(_serial1_baud);
    command.append(", serial2baudrate = ")    ; command.append(_serial2_baud);
    command.append(", serial3baudrate = ")    ; command.append(_serial3_baud);

    command.append(" WHERE id = 1" );

    std::cout<<command<<std::endl;

    // mtlog->insert_log("pgiticlog",command.c_str(),"DEBUG");

    qry.prepare(command.c_str());


    if( !qry.exec() )
    {
        mtlog->insert_log("pgiticlog",qry.lastError().text(),"ERROR"); return false;
    }
    else
    {
        mtlog->insert_log("pgiticlog","Updated","DEBUG"); return true;
    }

}
Example #11
0
QWidget* RelationDelegate::createEditor(QWidget *parent,
										const QStyleOptionViewItem &option,
										const QModelIndex &index) const
{
	QWidget* e;

	switch (index.column()) {
		case COLUMN_CATEGORY:
		{
			QComboBox *editor = new QComboBox(parent);
			editor->setFrame(false);

			QSqlQuery query;
			query.exec("SELECT id, name FROM category ORDER BY name ASC");
			while (query.next()) {
				int id = query.value(0).toInt();
				QString name = query.value(1).toString();
				editor->addItem(name, QVariant(id));
			}
			e = editor;
			break;
		}
		case COLUMN_FOOTPRINT:
		{
			QComboBox *editor = new QComboBox(parent);
			editor->setFrame(false);

			QSqlQuery query;
			query.exec("SELECT id, name FROM footprint ORDER BY name ASC");
			while (query.next()) {
				int id = query.value(0).toInt();
				QString name = query.value(1).toString();
				editor->addItem(name, QVariant(id));
			}
			e = editor;
			break;
		}
		case COLUMN_TEMP:
		{
			QComboBox *editor = new QComboBox(parent);
			editor->setFrame(false);

			QSqlQuery query;
			query.exec("SELECT id, name FROM temp ORDER BY name ASC");
			while (query.next()) {
				int id = query.value(0).toInt();
				QString name = query.value(1).toString();
				editor->addItem(name, QVariant(id));
			}
			e = editor;
			break;
		}
		case COLUMN_SUPPL:
		{
			QComboBox *editor = new QComboBox(parent);
			editor->setFrame(false);

			QSqlQuery query;
			query.exec("SELECT id, name FROM suppl ORDER BY name ASC");
			while (query.next()) {
				int id = query.value(0).toInt();
				QString name = query.value(1).toString();
				editor->addItem(name, QVariant(id));
			}
			e = editor;
			break;
		}
		case COLUMN_COUNT:
		case COLUMN_PRICE_VOL:
		{
			QSpinBox *editor = new QSpinBox(parent);
			editor->setFrame(false);
			editor->setRange(-1000000, 1000000);
			e = editor;
			break;
		}
		case COLUMN_PRICE:
		{
			QDoubleSpinBox *editor = new QDoubleSpinBox(parent);
			editor->setFrame(false);
			editor->setRange(-1000000.0, 1000000.0);
			editor->setSingleStep(0.1);
			editor->setDecimals(6);
			e = editor;
			break;
		}
		default:
			e = QStyledItemDelegate::createEditor(parent, option, index);
	}

	return e;
}
Example #12
0
void pgiticlog::load_licenses()
{
    _key  = "pgitickeyabcdefg";
    QSqlQuery query;
    if(query.exec("SELECT * FROM license"))
    {
        if(query.next())
        {
            int id = query.value(0).toInt();
            QString _id = QString::number(id);

            _license1 = query.value(1).toString();
            _license2 = query.value(2).toString();
            _license3 = query.value(3).toString();
            _license4 = query.value(4).toString();

            if ( _license1 != "none")
            {
            _license1 = decodeText(_license1,_key);

                            if ( _license1 == (HID + "a").c_str())
                            {
                               _lic1 = true;
                            }
                            else
                            {
                               _lic1 = false;
                            }
            }

            if ( _license2 != "none")
            {
            _license2 = decodeText(_license2,_key);

                            if ( _license2 == (HID + "b").c_str())
                            {
                                 _lic2 = true;
                            }
                            else
                            {
                                  _lic2 = false;
                            }
            }

            if ( _license3 != "none")
            {
            _license3 = decodeText(_license3,_key);

                            if ( _license3 == (HID + "c").c_str())
                            {
                                _lic3 = true;
                            }
                            else
                            {
                               _lic3 = false;
                            }
            }

            if ( _license4 != "none")
            {
            _license4 = decodeText(_license4,_key);

                            if ( _license4 == (HID + "d").c_str())
                            {
                                  _lic4 = true;
                            }
                            else
                            {
                                  _lic4 = false;
                            }
            }


           mtlog->insert_log("pgiticlog","Licenses loaded done","DEBUG");
        }

    }
    else
    {
    }



}
Example #13
0
int PkgSchema::create(QString &errMsg)
{
  if (DEBUG)
    qDebug("PkgSchema::create(&errMsg)");

  if (_name.isEmpty())
  {
    errMsg = QString("Cannot create a schema for this package without a name.");
    return -1;
  }

  int namespaceoid = -1;
  int i = 0;
  do {
    QSqlQuery select;
    select.prepare("SELECT oid "
                   "FROM pg_namespace "
                   "WHERE (LOWER(nspname)=LOWER(:name));");
    select.bindValue(":name", _name);
    select.exec();
    if (select.first())
      namespaceoid = select.value(0).toInt();
    else if (select.lastError().type() != QSqlError::NoError)
    {
      errMsg = _sqlerrtxt.arg(_name)
                        .arg(select.lastError().databaseText())
                        .arg(select.lastError().driverText());
      return -2;
    }
    else
    {
      QSqlQuery create;
      create.exec(QString("CREATE SCHEMA %1;").arg(_name.toLower()));
      if (create.lastError().type() != QSqlError::NoError)
      {
        errMsg = _sqlerrtxt.arg(_name)
                          .arg(create.lastError().databaseText())
                          .arg(create.lastError().driverText());
        return -3;
      }
      create.exec(QString("GRANT ALL ON SCHEMA %1 TO GROUP openmfg;")
                    .arg(_name.toLower()));
      if (create.lastError().type() != QSqlError::NoError)
      {
        errMsg = _sqlerrtxt.arg(_name)
                          .arg(create.lastError().databaseText())
                          .arg(create.lastError().driverText());
        return -4;
      }

    }
  } while (namespaceoid < 0 && ++i < 2);

  int patherr = setPath(errMsg);
  if (patherr < 0)
    return patherr;

  QStringList childTable;
  childTable  << "cmd"
              << "cmdarg"
              << "image"
              << "metasql"
              << "priv"
              << "report"
              << "script"
              << "uiform"
              ;

  for (int i = 0; i < childTable.size(); i++)
  {
    QSqlQuery select;
    select.prepare("SELECT oid "
                   "FROM pg_class "
                   "WHERE ((relname=:child) AND (relnamespace=:schemaid));");
    select.bindValue(":child", "pkg" + childTable.at(i));
    select.bindValue(":schemaid", namespaceoid);
    select.exec();
    if (select.first())
      continue; // nothing to do for this child
    else if (select.lastError().type() != QSqlError::NoError)
    {
      errMsg = _sqlerrtxt.arg(_name)
                        .arg(select.lastError().databaseText())
                        .arg(select.lastError().driverText());
      return -5;
    }

    QSqlQuery create;
    create.prepare(QString("CREATE TABLE pkg%1 () INHERITS (%2);")
                   .arg(childTable.at(i)).arg(childTable.at(i)));
    create.exec();
    if (create.lastError().type() != QSqlError::NoError)
    {
      errMsg = _sqlerrtxt.arg(_name)
                        .arg(create.lastError().databaseText())
                        .arg(create.lastError().driverText());
      return -6;
    }

    QSqlQuery alt;
    alt.prepare(QString("ALTER TABLE pkg%1 "
                        "ALTER %2_id SET NOT NULL, "
                        "ADD PRIMARY KEY (%3_id), "
                        "ALTER %4_id SET DEFAULT NEXTVAL('%5_%6_id_seq');")
                   .arg(childTable.at(i)).arg(childTable.at(i))
                   .arg(childTable.at(i)).arg(childTable.at(i))
                   .arg(childTable.at(i)).arg(childTable.at(i))
                   );
    alt.exec();
    if (alt.lastError().type() != QSqlError::NoError)
    {
      errMsg = _sqlerrtxt.arg(_name)
                        .arg(alt.lastError().databaseText())
                        .arg(alt.lastError().driverText());
      return -7;
    }

    alt.prepare(QString("REVOKE ALL ON pkg%1 FROM PUBLIC; "
                        "GRANT  ALL ON pkg%2 TO GROUP openmfg; ")
                   .arg(childTable.at(i)).arg(childTable.at(i))
                   );
    alt.exec();
    if (alt.lastError().type() != QSqlError::NoError)
    {
      errMsg = _sqlerrtxt.arg(_name)
                        .arg(alt.lastError().databaseText())
                        .arg(alt.lastError().driverText());
      return -7;
    }

    if (childTable.at(i) == "cmdarg")
    {
      alt.exec(QString("ALTER TABLE pkgcmdarg "
                       "ADD FOREIGN KEY (cmdarg_cmd_id) "
                       "REFERENCES pkgcmd(cmd_id);"));
      if (alt.lastError().type() != QSqlError::NoError)
      {
        errMsg = _sqlerrtxt.arg(_name)
                          .arg(alt.lastError().databaseText())
                          .arg(alt.lastError().driverText());
        return -8;
      }
    }

    QSqlQuery triggerq;
    triggerq.exec(QString(
                  "SELECT dropIfExists('TRIGGER', 'pkg%1beforetrigger', '%2');"
                  "CREATE TRIGGER pkg%3beforetrigger "
                  "BEFORE INSERT OR UPDATE OR DELETE "
                  "ON pkg%4 FOR EACH ROW "
                  "EXECUTE PROCEDURE _pkg%5beforetrigger();")
                  .arg(childTable.at(i)) .arg(_name)
                  .arg(childTable.at(i)) .arg(childTable.at(i))
                  .arg(childTable.at(i))
                  );
    if (triggerq.lastError().type() != QSqlError::NoError)
    {
      errMsg = _sqlerrtxt.arg(_name)
                        .arg(triggerq.lastError().databaseText())
                        .arg(triggerq.lastError().driverText());
      return -9;
    }

    triggerq.exec(QString(
                  "SELECT dropIfExists('TRIGGER', 'pkg%1altertrigger', '%2');"
                  "CREATE TRIGGER pkg%3altertrigger "
                  "BEFORE INSERT OR UPDATE OR DELETE "
                  "ON pkg%4 FOR EACH ROW "
                  "EXECUTE PROCEDURE _pkg%5altertrigger();")
                  .arg(childTable.at(i)) .arg(_name)
                  .arg(childTable.at(i)) .arg(childTable.at(i))
                  .arg(childTable.at(i))
                  );
    if (triggerq.lastError().type() != QSqlError::NoError)
    {
      errMsg = _sqlerrtxt.arg(_name)
                        .arg(triggerq.lastError().databaseText())
                        .arg(triggerq.lastError().driverText());
      return -10;
    }

  }

  int tmp = upsertPkgItem(namespaceoid, errMsg);
  if (tmp < 0)
    return tmp;

  return 0;
}
Example #14
0
int PkgSchema::upsertPkgItem(const int itemid,
                               QString &errMsg)
{
  int pkgheadid = -1;
  int pkgitemid = -1;

  QSqlQuery select;
  select.prepare("SELECT pkghead_id, COALESCE(pkgitem_id, -1) "
                 "FROM pkghead LEFT OUTER JOIN"
                 "     pkgitem ON ((pkgitem_name=pkghead_name)"
                 "             AND (pkgitem_pkghead_id=pkghead_id)"
                 "             AND (pkgitem_type='S'))"
                 "WHERE (LOWER(pkghead_name)=LOWER(:name));");
  select.bindValue(":name",  _name);
  select.exec();
  if (select.first())
  {
    pkgheadid = select.value(0).toInt();
    pkgitemid = select.value(1).toInt();
  }
  else if (select.lastError().type() != QSqlError::NoError)
  {
    errMsg = _sqlerrtxt.arg(_name)
                      .arg(select.lastError().databaseText())
                      .arg(select.lastError().driverText());
    return -20;
  }
  else
  {
    errMsg = TR("Could not find pkghead record for package %1.").arg(_name);
    return -21;
  }

  QSqlQuery upsert;

  if (pkgitemid >= 0)
    upsert.prepare("UPDATE pkgitem SET pkgitem_descrip=:descrip,"
                   "       pkgitem_item_id=:itemid "
                   "WHERE (pkgitem_id=:id);");
  else
  {
    upsert.prepare("SELECT NEXTVAL('pkgitem_pkgitem_id_seq');");
    upsert.exec();
    if (upsert.first())
      pkgitemid = upsert.value(0).toInt();
    else if (upsert.lastError().type() != QSqlError::NoError)
    {
      QSqlError err = upsert.lastError();
      errMsg = _sqlerrtxt.arg(_name)
                        .arg(err.driverText()).arg(err.databaseText());
      return -22;
    }
    upsert.prepare("INSERT INTO pkgitem ("
                   "    pkgitem_id, pkgitem_pkghead_id, pkgitem_type,"
                   "    pkgitem_item_id, pkgitem_name, pkgitem_descrip"
                   ") VALUES ("
                   "    :id, :headid, 'S',"
                   "    :itemid, :name, :descrip);");
  }

  upsert.bindValue(":id",      pkgitemid);
  upsert.bindValue(":headid",  pkgheadid);
  upsert.bindValue(":itemid",  itemid);
  upsert.bindValue(":name",    _name);
  upsert.bindValue(":descrip", _comment);

  if (!upsert.exec())
  {
    QSqlError err = upsert.lastError();
    errMsg = _sqlerrtxt.arg(_name)
                      .arg(err.driverText()).arg(err.databaseText());
    return -23;
  }

  return pkgitemid;
}
void StreamMonitor::monitorDBStatus()
{
    LOG(INFO,"monitoring DB status");
    if(!isProcessAlived((char*)QReadConfig::getInstance()->getProcDogConf().strProcName.toStdString().c_str()))
        {
        qInfo()<<"HbMedia is not alived";
        clearAll();
        return ;
    }
    dbStatusInfos.clear();
    for(int i=0; i<camerasInfo.size(); i++)
    {
        QString dbPath = "/usr/local/"+camerasInfo[i].cmareId+"_Video.db";
        DBStatusInfo dbStaInfo;
        dbStaInfo.CameraID = camerasInfo[i].cmareId;
        dbStaInfo.DBState = DBStatusInfo::NORMAL;

        if(!QFile::exists(dbPath))
        {
            dbStaInfo.DBState = DBStatusInfo::DB_LOST_DB_FILE;
            LOG(WARNING, (QString("丢失数据库文件:")+dbPath).toStdString().c_str());
        }else
        {
            //1.判断能否打开数据库
                QSqlDatabase db;
                if(QSqlDatabase::contains("qt_sql_default_connection"))
                  db = QSqlDatabase::database("qt_sql_default_connection");
                else
                  db = QSqlDatabase::addDatabase("QSQLITE");

//                if(db.isOpen())
//                {
//                    LOG(WARNING, "db already opened");
//                    return;
//                }

                 db.setDatabaseName(dbPath); // 数据库名与路径, 此时是放在同目录下
                 db.setUserName("");
                 db.setPassword("");
                 if(db.open())
                 {
                     qInfo()<<"db opened";
                     QSqlQuery queryWrite;
                     QString insertSql = "insert into VIDEO_RECORD (CAMID,FILENAME) VALUES(11111,\"testInsert\")";
                     if(!queryWrite.exec(insertSql))
                     {
                          dbStaInfo.DBState = DBStatusInfo::DB_TABLE_LOCKED;
                          QString querys = queryWrite.lastError().text();
                          cout<<querys.toStdString();
                          LOG(WARNING, (QString("插入数据失败:") + querys).toStdString().c_str());
                     }else
                     {
                         qInfo()<<"插入数据到数据库"<<dbPath<<"成功";
                         //delete the rec insertted.
                         QSqlQuery queryDelete;
                         QString delSql = "delete from VIDEO_RECORD  where CAMID=11111 and FILENAME=\"testInsert\"";
                         if(!queryDelete.exec(delSql))
                         {
                             dbStaInfo.DBState = DBStatusInfo::DB_TABLE_LOCKED;
                             QString querys = queryDelete.lastError().text();
                             cout<<querys.toStdString();
                             LOG(WARNING, (QString("删除数据失败:") + querys).toStdString().c_str());
                         }else
                             qInfo()<<"删除数据到数据库"<<dbPath<<"成功";
                     }
                     db.close();
                 }else
                 {
                     dbStaInfo.DBState = DBStatusInfo::DB_OPEN_FAIL;
                     LOG(WARNING, (QString("打开失败的数据库文件:")+dbPath).toStdString().c_str());
                     qWarning()<<db.lastError();
                 }
        }

        dbStatusInfos.append(dbStaInfo);
    }

       //send to stream
    if(dbStatusInfos.size()>0)
       sendDbStatus();
}
Example #16
0
// -----------------------------
void admin::setupAction()
{
   readSettings();
   logList->setColumnWidth(0,60);          // Log_name
   logList->setColumnWidth(1,60);          // Einträge
   logList->setColumnWidth(2,40);          // Rel
   
   sysList->setColumnWidth(0,120);
   
   RefTable->setColumnWidth(0,100);        // sys.Name
   RefTable->setColumnWidth(1,100);        // User.Name
   RefTable->setColumnWidth(2,100);        // User_en
   RefTable->setColumnWidth(3,135);        // Adif.Name
   
   //RefTable->setColumnWidth(4,60);
   //RefTable->setColumnWidth(5,60);
   
   customsTable->setColumnWidth(0,80);
   customsTable->setColumnWidth(1,190);
   
   if(settings.value("dbconf").toInt() == 0) {      // liegt ein Fehler vor ?
     s = tr("\nDas Runtime-Flag 'dbconf' steht auf Null.\nDas Flag ist beschaedigt, ");
     s += tr("oder QtLog ist nicht initialisiert\n");
     s += tr("Das Programm schaltet ab");
     QMessageBox::information( this,
         tr("QtLog INFO"),
         tr(s.toAscii()),
         QMessageBox::Ok | QMessageBox::Default,
         QMessageBox::NoButton, QMessageBox::NoButton);
     exit(0);                                       // Abbruch       
   }
   else {
     openDatabase();                                // normaler db_connect   
     showTables(1);                                 // Log + SysTabellen zeigen
   }
   if(settings.value("Val").toInt() == 1) {         // ADIF_Export
       dirsel = 0;                                  // dirselector auf Pfad stellen
       adifExpCb();
   }
   else
    if(settings.value("Val").toInt() == 2) {       // ADIF_Import
       dirsel = 1;                                 // dirselector auf Datei waehlen stellen
       adifImpCb();
    }
   QSqlQuery query;
   qy = "SELECT rigtype FROM wrig";
   query.exec(qy);
   while(query.next()) {
       n = 0;
       comboBoxRig->addItem(query.value(n++).toString());
   }
   qy = "SELECT lid,logging FROM tlocation WHERE logging != ''";
   query.exec(qy);
   while(query.next()) {
       i = 0;
       n = 0;
       i = query.value(n++).toInt();                       // id   
       comboBoxHome->addItem(query.value(n++).toString()); // logging_text
   }
   
   comboBoxHome->setCurrentIndex(1);                          
   SavePathEdit->setText(settings.value("dumpPath").toString());
}
void addOtherOrders::on_okButton_clicked()
{
    QString text = ui->name->text();
    QString price = ui->price->text();
    QString roomno = ui->roomNo->currentText();

    QSqlDatabase db = QSqlDatabase::addDatabase( "QSQLITE" );

    db.setDatabaseName( "./innovativedb.db" );

    if( !db.open() )
    {
        qDebug() << db.lastError();
        qFatal( "Failed to connect." );
    }

    qDebug( "Connected!" );

    QSqlQuery qry;
    qry.prepare("CREATE TABLE IF NOT EXISTS roomlist (id INTEGET PRIMARY KEY, roomno VARCHAR(5), cat INTEGER, occupied INTEGER)");
    if(!qry.exec())
        qDebug() << qry.lastError();
    else
        qDebug( "Room Table Validated..." );

    qry.prepare("SELECT occupied FROM roomlist WHERE roomno=:room");
    qry.bindValue(":room",roomno);
    if(!qry.exec())
        qDebug() << qry.lastError();
    else
        qDebug( "Room Table Validated..." );

    QString guestID = "";
    while(qry.next())
    {
        guestID = qry.value(0).toString();
    }

    qry.prepare("CREATE TABLE IF NOT EXISTS otherorders (id INTEGER PRIMARY KEY, time VARCHAR(30), text VARCHAR(40), price INTEGER, guestid INTEGER)");
    if(!qry.exec())
        qDebug() << qry.lastError();
    else
        qDebug( "Room Table Validated..." );


    int id=0;
    qry.prepare("SELECT id FROM otherorders");
    if(!qry.exec())
        qDebug() << qry.lastError();
    else
        qDebug( "Room Table Validated..." );
    while (qry.next()) {
        int cur_item = qry.value(0).toInt();
        if(cur_item > id)
        {
            id=cur_item;
        }
    }
    id++;

    QDateTime QDTime = QDateTime::currentDateTime();
    QString QDTStr = QDTime.toString();


    qDebug() << id << text << price << guestID;
    qry.prepare("INSERT INTO otherorders (id,time,text,price,guestid) VALUES (:id,:time,:text,:price,:guestid)");
    qry.bindValue(":id",id);
    qry.bindValue(":time",QDTStr);
    qry.bindValue(":text",text);
    qry.bindValue(":price",price);
    qry.bindValue(":guestid",guestID);
    if(!qry.exec())
        qDebug() << qry.lastError();
    else
        qDebug( "Room Table Validated..." );


    this->close();
}
Example #18
0
//* Create the NoteModel table.
void NoteModel::createTable() {
    QLOG_TRACE() << "Entering NoteModel::createTable()";

    QLOG_DEBUG() << "Creating table NoteTable";
    QSqlQuery sql;
    QString command("Create table if not exists NoteTable (" +
                  QString("lid integer primary key,") +
                  QString("dateCreated real default null,") +
                  QString("dateUpdated real default null,") +
                  QString("title text default null collate nocase,") +
                  QString("notebookLid integer default null,") +
                  QString("notebook text default null collate nocase,") +
                  QString("tags text default null collate nocase,") +

                  QString("author text default null collate nocase,") +
                  QString("dateSubject real default null,") +
                  QString("dateDeleted real default null,") +

                  QString("source text default null collate nocase,") +
                  QString("sourceUrl text default null collate nocase,") +
                  QString("sourceApplication text default null collate nocase,") +
                  QString("latitude real default null,") +
                  QString("longitude real default null,") +
                  QString("altitude real default null,") +
                  QString("hasEncryption integer default null,") +
                  QString("hasTodo integer default null,") +
                  QString("isDirty integer default null,") +
                  QString("size integer default null") +
                  QString(")"));
    if (!sql.exec(command) ||
            !sql.exec("CREATE INDEX NoteTable_Title_Index on NoteTable (lid)") ||
            !sql.exec("CREATE INDEX NoteTable_Author_Index on NoteTable (lid)") ||
            !sql.exec("CREATE INDEX NoteTable_Notebook_Index on NoteTable (lid)") ||
            !sql.exec("CREATE INDEX NoteTable_Notebook_Lid_Index on NoteTable (lid)") ||
            !sql.exec("CREATE INDEX NoteTable_DateCreated_Index on NoteTable (lid)") ||
            !sql.exec("CREATE INDEX NoteTable_DateUpdated_Index on NoteTable (lid)") ||
            !sql.exec("CREATE INDEX NoteTable_Date_Subject_Index on NoteTable (lid)") ||
            !sql.exec("CREATE INDEX NoteTable_Date_Deleted_Index on NoteTable (lid)") ||
            !sql.exec("CREATE INDEX NoteTable_Source_Index on NoteTable (lid)") ||
            !sql.exec("CREATE INDEX NoteTable_Source_Url_Index on NoteTable (lid)") ||
            !sql.exec("CREATE INDEX NoteTable_Source_Application_Index on NoteTable (lid)") ||
            !sql.exec("CREATE INDEX NoteTable_Latitude_Index on NoteTable (lid)") ||
            !sql.exec("CREATE INDEX NoteTable_Longitude_Index on NoteTable (lid)") ||
            !sql.exec("CREATE INDEX NoteTable_Altitude_Index on NoteTable (lid)") ||
            !sql.exec("CREATE INDEX NoteTable_Has_Encryption_Index on NoteTable (lid)") ||
            !sql.exec("CREATE INDEX NoteTable_Has_Todo_Index on NoteTable (lid)") ||
            !sql.exec("CREATE INDEX NoteTable_Is_Dirty_Index on NoteTable (lid)")
       ) {
        QLOG_ERROR() << "Creation of NoteTable table failed: " << sql.lastError();
    }
}
Example #19
0
void DbManager::fillPersonField(const int id_person, const Person *person) const
{
    if(id_person > 0 && person) {
        QSqlQuery query;
        QSqlQuery update_query;
        QString query_string;
        QString update_query_string;
        query_string =     "SELECT   people.job, "
                                    "people.email, "
                                    "people.phone, "
                                    "address.street_name, "
                                    "address.municipality, "
                                    "address.zip, "
                                    "address.province, "
                                    "address.state "
                           "FROM people "
                           "INNER JOIN address ON   people.id = :id_person AND "
                                                    "people.id = address.person";
        query.prepare(query_string);
        query.bindValue(":id_person", id_person);
        if(query.exec()) {
            if(query.isActive()) {
                if(query.first()) {
                    if(query.value(0) == "" && person->getJob() != "") {
                        update_query_string = "UPDATE people SET job = :job WHERE id = :id_person";
                        update_query.prepare(update_query_string);
                        update_query.bindValue(":job", person->getJob());
                        update_query.bindValue(":id_person", id_person);
                        update_query.exec();
                    }
                    if(query.value(1) == "" && person->getEmail() != "") {
                        update_query_string = "UPDATE people SET email = :email WHERE id = :id_person";
                        update_query.prepare(update_query_string);
                        update_query.bindValue(":email", person->getEmail());
                        update_query.bindValue(":id_person", id_person);
                        update_query.exec();
                    }
                    if(query.value(2) == "" && person->getPhone() != "") {
                        update_query_string = "UPDATE people SET phone = :phone WHERE id = :id_person";
                        update_query.prepare(update_query_string);
                        update_query.bindValue(":phone", person->getPhone());
                        update_query.bindValue(":id_person", id_person);
                        update_query.exec();
                    }
                    if(query.value(3) == "" && person->getAddress()->getStreet() != "") {
                        update_query_string = "UPDATE address SET street_name = :street WHERE person = :id_person";
                        update_query.prepare(update_query_string);
                        update_query.bindValue(":street", person->getAddress()->getStreet());
                        update_query.bindValue(":id_person", id_person);
                        update_query.exec();
                    }
                    if(query.value(4) == "" && person->getAddress()->getMunicipality() != "") {
                        update_query_string = "UPDATE address SET municipality = :municipality WHERE person = :id_person";
                        update_query.prepare(update_query_string);
                        update_query.bindValue(":municipality", person->getAddress()->getMunicipality());
                        update_query.bindValue(":id_person", id_person);
                        update_query.exec();
                    }
                    if(query.value(5) == "" && person->getAddress()->getZip() != "") {
                        update_query_string = "UPDATE address SET zip = :zip WHERE person = :id_person";
                        update_query.prepare(update_query_string);
                        update_query.bindValue(":zip", person->getAddress()->getZip());
                        update_query.bindValue(":id_person", id_person);
                        update_query.exec();
                    }
                    if(query.value(6) == "" && person->getAddress()->getProvince() != "") {
                        update_query_string = "UPDATE address SET province = :province WHERE person = :id_person";
                        update_query.prepare(update_query_string);
                        update_query.bindValue(":province", person->getAddress()->getProvince());
                        update_query.bindValue(":id_person", id_person);
                        update_query.exec();
                    }
                    if(query.value(7) == "" && person->getAddress()->getState() != "") {
                        update_query_string = "UPDATE address SET state = :state WHERE person = :id_person";
                        update_query.prepare(update_query_string);
                        update_query.bindValue(":state", person->getAddress()->getState());
                        update_query.bindValue(":id_person", id_person);
                        update_query.exec();
                    }
                }
            }
        }
    }
}
Example #20
0
void Database::SaverLoader::save()
{
    qDebug()<<"Save : init() Debut";
    init();
    qDebug()<<"Save : init() Fin";
    qDebug()<<"Save : UV() Debut";
    vector<UV>::const_iterator it=tUV.getIterator();
    //sauvegarde des UVs
    for(unsigned int i=0; i<tUV.size(); i++)
    {
        QSqlQuery query;
        query.prepare("INSERT INTO UV (code, titre, automne, printemps) VALUES (:code, :titre, :automne,:printemps)");
        query.bindValue(":code", QString::fromStdString(it[i].getCode()));
        query.bindValue(":titre", QString::fromStdString(it[i].getTitre()));
        query.bindValue(":automne", QString::fromStdString(to_string(int(it[i].ouvertureAutomne()))));
        query.bindValue(":printemps", QString::fromStdString(to_string(int(it[i].ouverturePrintemps()))));
        query.exec();


        map<Categorie, unsigned int> creditsUvI=it[i].getCredits();
        typedef map<Categorie, unsigned int>::iterator iteratorCat;

        for(iteratorCat itCat=creditsUvI.begin(); itCat!=creditsUvI.end(); itCat++)
        {
            QSqlQuery query;
            query.prepare("INSERT INTO CreditsUV (code, categorie, nbCredits) VALUES (:code, :categorie, :nbCredits)");
            query.bindValue(":code", QString::fromStdString(it[i].getCode()));
            query.bindValue(":categorie", QString::fromStdString(itCat->first.getCodeStdString()));
            query.bindValue(":nbCredits", QString::fromStdString(std::to_string(itCat->second)));
            query.exec();
        }
    }
    qDebug()<<"Save : UV() Fin";
    qDebug()<<"Save : Etudiant() Debut";
    //sauvegarde des étudiants, inscription et formations par étudiants
    vector<Etudiant>::const_iterator itEtu=tEtudiant.getIterator();
    for(unsigned int i=0; i<tEtudiant.size(); i++)
    {
        qDebug()<<"Etudiant : INSERT INTO Etudiant";
        QSqlQuery query;
        query.prepare("INSERT INTO Etudiant (ine, login, nom, prenom, dateNaissance) VALUES (:ine, :login, :nom,:prenom,:dateNaissance)");
        query.bindValue(":ine", QString::fromStdString(to_string(itEtu[i].getIne())));
        query.bindValue(":login", itEtu[i].getLogin());
        query.bindValue(":nom", QString::fromStdString(itEtu[i].getNom().toStdString()));
        query.bindValue(":prenom", QString::fromStdString(itEtu[i].getPrenom().toStdString()));
        query.bindValue(":dateNaissance", itEtu[i].getDateNaissance().toString(QString("yyyy-MM-dd")));
        query.exec();

        vector<Inscription> it2=itEtu[i].getDossier().getInscription();
        for(unsigned int j=0; j<itEtu[i].getDossier().getInscription().size(); j++)
        {
            QSqlQuery query;
            query.prepare("INSERT INTO Inscription (login, code, saison, annee, resultat) VALUES (:login, :code, :saison,:annee,:resultat)");
            query.bindValue(":login",itEtu[i].getLogin());
            query.bindValue(":code", QString::fromStdString(it2[j].getUV().getCode()));
            query.bindValue(":saison", it2[j].getSemestre().getSaison().getNom());
            query.bindValue(":annee", QString::number(it2[j].getSemestre().getAnnee()));
            query.bindValue(":resultat", it2[j].getResultat().getNote());
            query.exec();
        }
        qDebug()<<"Etudiant : INSERT INTO Inscription";

        vector<Formation*> it3=itEtu[i].getDossier().getFormation();
        //qDebug()<<"TEst";
        for(unsigned int j=0; j<itEtu[i].getDossier().getFormation().size(); j++)
        {
            //qDebug()<<"TEst";
//           std::string q="INSERT INTO FormationEtudiant (login, formation) VALUES ('"+itEtu[i].getLogin().toStdString()+"', '"+it3[j]->getNom().toStdString()+"');";
//            db.query(q);

            QSqlQuery query;
            query.prepare("INSERT INTO FormationEtudiant (login, formation) VALUES (:login, :formation)");
            query.bindValue(":login",itEtu[i].getLogin());
            query.bindValue(":formation", it3[j]->getNom());
            query.exec();
        }
        qDebug()<<"Etudiant : INSERT INTO FormationEtudiant";
    }
    qDebug()<<"Save : Etudiant() Fin";
    qDebug()<<"Save : Formations() Debut";
    //Sauvegarde des formations
    vector<Formation>::const_iterator itForm=tFormation.getIterator();
    for(unsigned int i=0; i<tFormation.size(); i++)
    {
//        string q="INSERT INTO Formation (nom, description) VALUES ('"+itForm[i].getNom().toStdString()+"', '"+itForm[i].getDescription().toStdString()+"');";
//        db.query(q);
        QSqlQuery query;
        query.prepare("INSERT INTO Formation (nom, description) VALUES (:nom, :description)");
        query.bindValue(":nom",itForm[i].getNom());
        query.bindValue(":description", itForm[i].getDescription());
        query.exec();

        map<UV*, bool> uvs=itForm[i].getUVs();
        for( map <UV*,bool>::const_iterator it2 = uvs.begin(); it2!=uvs.end(); it2++)
        {
//            q="INSERT INTO FormationUV (formation, uv, obligatoire) VALUES ('"+itForm[i].getNom().toStdString()+"', '"+it2->first->getCode()+"', '"+to_string(int(it2->second))+"');";
//            db.query(q);
            QSqlQuery query;
            query.prepare("INSERT INTO FormationUV (formation, uv, obligatoire) VALUES (:formation, :uv, :obligatoire)");
            query.bindValue(":formation",itForm[i].getNom());
            query.bindValue(":uv", QString::fromStdString(it2->first->getCode()));
            query.bindValue(":obligatoire", QString::fromStdString(to_string(int(it2->second))));
            query.exec();
        }
        map<Categorie, unsigned int> creditsFormationI=itForm[i].getNbCreditsByCat();
        typedef map<Categorie, unsigned int>::iterator iteratorCat;

        for(iteratorCat itCat=creditsFormationI.begin(); itCat!=creditsFormationI.end(); itCat++)
        {
//            q="INSERT INTO CreditsFormation (formation, categorie, nbCredits) VALUES ('"+itForm[i].getNom().toStdString()+"', '"+itCat->first.getCodeStdString()+"', '"+std::to_string(itCat->second)+"');";
//            db.query(q);
            QSqlQuery query;
            query.prepare("INSERT INTO CreditsFormation (formation, categorie, nbCredits) VALUES (:formation, :categorie, :nbCredits)");
            query.bindValue(":formation",itForm[i].getNom());
            query.bindValue(":categorie", itCat->first.getCode());
            query.bindValue(":nbCredits", QString::number(itCat->second));
            query.exec();
        }

        std::vector<Condition> conditionFormation=itForm[i].getConditions();
        for( std::vector<Condition>::iterator it3 = conditionFormation.begin(); it3!=conditionFormation.end(); it3++)
        {
//            q="INSERT INTO ConditionsFormation (formation, condition) VALUES ('"+itForm[i].getNom().toStdString()+"', '"+it3->getCond().toStdString()+"');";
//            db.query(q);
            QSqlQuery query;
            query.prepare("INSERT INTO ConditionsFormation (formation, condition) VALUES (:formation, :condition)");
            query.bindValue(":formation",itForm[i].getNom());
            query.bindValue(":condition", it3->getCond());
            query.exec();
        }
    }
    qDebug()<<"Save : Formations() Fin";
    qDebug()<<"Save : Catégories() Debut";

    //Sauvegarde des Catégories
    vector<Categorie>::iterator itCat = tCategorie.getIterator();
    for(; itCat != tCategorie.end(); itCat++)
    {
//        string q="INSERT INTO Categorie (code, description) VALUES ('"+itCat->getCodeStdString()+"', '"+itCat->getDescriptionStdString()+"');";
//        db.query(q);

        QSqlQuery query;
        query.prepare("INSERT INTO Categorie (code, description) VALUES (:code, :description)");
        query.bindValue(":code",itCat->getCode());
        query.bindValue(":description", itCat->getDescription());
        query.exec();

        vector<Categorie> temp=itCat->getSousCategorie();

        for(vector<Categorie>::iterator itCat2 = temp.begin(); itCat2 != temp.end(); itCat2++)
        {
//            string q="INSERT INTO SousCategorie (codeParent, codeFille) VALUES ('"+itCat->getCode().toStdString()+"', '"+itCat2->getCode().toStdString()+"');";
//            db.query(q);

            QSqlQuery query;
            query.prepare("INSERT INTO SousCategorie (codeParent, codeFille) VALUES (:codeParent, :codeFille)");
            query.bindValue(":codeParent",itCat->getCode());
            query.bindValue(":codeFille", itCat2->getCode());
            query.exec();
        }
    }
    qDebug()<<"Save : Catégories() Fin";
    qDebug()<<"Save : Saisons() Debut";


    //Sauvegarde des Saisons
    vector<Saison>::iterator itSaison = tSaison.getIterator();
    for(; itSaison != tSaison.end(); itSaison++)
    {
//        string q="INSERT INTO Saison (nom, description) VALUES ('"+itSaison->getNomStdString()+"', '"+itSaison->getDescriptionStdString()+"');";
//        db.query(q);

        QSqlQuery query;
        query.prepare("INSERT INTO Saison (nom, description) VALUES (:nom, :description)");
        query.bindValue(":nom",itSaison->getNom());
        query.bindValue(":description", itSaison->getDescription());
        query.exec();
    }

    qDebug()<<"Save : Saisons() Fin";
    qDebug()<<"Save : Notes() Debut";

    //Sauvegarde des Notes
    vector<Note>::iterator itNote = tNote.getIterator();
    for(; itNote != tNote.end(); itNote++)
    {
        int boo=itNote->getEliminatoire();
//        string q="INSERT INTO Note (note, description,rang, eliminatoire ) VALUES ('"+itNote->getNoteStdString()+"', '"+itNote->getDescriptionStdString()+"','"+std::to_string(itNote->getRang())+"','"+std::to_string(boo)+"');";
//        db.query(q);

        QSqlQuery query;
        query.prepare("INSERT INTO Note (note, description,rang, eliminatoire ) VALUES (:note, :description, :rang ,:eliminatoire)");
        query.bindValue(":note",itNote->getNote());
        query.bindValue(":description", itNote->getDescription());
        query.bindValue(":rang", QString::number(itNote->getRang()));
        query.bindValue(":eliminatoire", QString::number(boo));
        query.exec();
    }

    qDebug()<<"Save : Notes() Fin";
    qDebug()<<"Save : Semestres() Debut";

    //Sauvegarde des Semestre
    vector<Semestre>::iterator itSemestre = tSemestre.getIterator();
    for(; itSemestre != tSemestre.end(); itSemestre++)
    {
        int temp=itSemestre->getAnnee();
//        string q="INSERT INTO Semestre (code, saison, year) VALUES ('"+itSemestre->getCode().toStdString() +"', '"+itSemestre->getSaison().getNomStdString()+"', '"+ std::to_string(temp)+"');";
//        db.query(q);

        QSqlQuery query;
        query.prepare("INSERT INTO Semestre (code, saison, year) VALUES (:code, :saison, :year)");
        query.bindValue(":code",itSemestre->getCode());
        query.bindValue(":saison", itSemestre->getSaison().getNom());
        query.bindValue(":year", QString::number(temp));
        query.exec();
    }
    qDebug()<<"Save : Semestres() Fin";


    qDebug()<<"fin save";
}
Example #21
0
bool DbManager::helperOneLicenseYear(         const QString& first_name,
                                              const QString& last_name,
                                              const QString& municipality,
                                              const QString& zip,
                                              const QString& province,
                                              const QString& job,
                                              const QString& license,
                                              bool           is_valid,
                                              bool           is_expired)
{
    int license_validity = getLicenseValidity(getIdLicense(license));
    if(license_validity != -1) {
        QDate date_of_issue;
        date_of_issue = QDate::currentDate().addYears(-license_validity + 1);

        date_of_issue = QDate(date_of_issue.year(), 12, 31);

        QSqlQuery query;
        QString query_string;
        query_string =          "SELECT  "
                                                    "people.id, "
                                                    "people.last_name, "
                                                    "people.first_name, "
                                                    "address.street_name, "
                                                    "address.zip, "
                                                    "address.municipality, "
                                                    "address.province, "
                                                    "people.personal_code, "
                                                    "people.job, "
                                                    "people.email, "
                                                    "people.phone, "
                                                    "license.license_name, "
                                                    "people_license.is_valid, "
                                                    "people_license.date_of_issue,"
                                                    "people_license.last_notification "
                                "FROM                people "
                                "INNER JOIN          address             ON people.id = address.person "
                                "INNER JOIN          people_license      ON people_license.id_person = people.id "
                                "INNER JOIN          license             ON license.id = people_license.id_license ";

        query_string += " AND people.last_name LIKE :last_name";
        query_string += " AND people.first_name LIKE :first_name";
        query_string += " AND address.municipality LIKE :municipality";
        query_string += " AND address.zip LIKE :zip";
        query_string += " AND address.province LIKE :province";
        query_string += " AND people.job LIKE :job";
        query_string += " AND license.license_name = :license";
        query_string += " AND people_license.is_valid = 'true'";
        query_string += " AND people_license.date_of_issue <= :date_of_issue";


        query.prepare(query_string);

        query.bindValue(":last_name",       QVariant('%' + last_name + '%'));
        query.bindValue(":first_name",      QVariant('%' + first_name + '%'));
        query.bindValue(":municipality",    QVariant('%' + municipality + '%'));
        query.bindValue(":zip",             QVariant('%' + zip + '%'));
        query.bindValue(":province",        QVariant('%' + province + '%'));
        query.bindValue(":job",             QVariant('%' + job + '%'));
        query.bindValue(":license",         QVariant(license));
        query.bindValue(":date_of_issue",   QVariant(date_of_issue.toJulianDay()));

        search_results_table_model = new SqlQueryModel();
        if(query.exec()) {
            search_results_table_model->setQuery(query);
            last_show_query = query;
            return true;
        } else {
            search_results_table_model->setQuery(query);
            qDebug() << "query failed: " << query.lastError();
            return false;
        }
    } else {
        return false;
    }
}
Example #22
0
bool Prerequisite::met(QString &errMsg)
{
  if (DEBUG)
    qDebug("Prerequisite::met() name %s, type %d (%s), message %s, "
           "dependency %p (%s %s %s), query %s",
           qPrintable(_name), _type, qPrintable(typeToName(_type)),
           qPrintable(_message), _dependency,
           qPrintable(/*_dependency ? _dependency->name()     :*/ QString()),
           qPrintable(/*_dependency ? _dependency->version()  :*/ QString()),
           qPrintable(/*_dependency ? _dependency->developer():*/ QString()),
           qPrintable(_query));

  bool returnVal = false;

  switch (_type)
  {
    case Query:
      {
      QSqlQuery query;
      query.exec(_query);
      if (query.first())
      {
        returnVal = query.value(0).toBool();
        errMsg    = _message;
      }
      else if (query.lastError().type() != QSqlError::NoError)
        errMsg = _sqlerrtxt.arg(_name).arg(query.lastError().databaseText())
                           .arg(query.lastError().driverText());
      else
      {
        returnVal = false;
        errMsg    = _message;
      }
      break;
      }

    case License:
      {
      LicenseWindow newdlg(_message);
      returnVal = (newdlg.exec() == QDialog::Accepted);
      if (! returnVal)
        errMsg = TR("The user declined to accept the usage license.");
      break;
      }

    case Dependency:
      {
      QString sql = "SELECT * FROM pkghead WHERE ((pkghead_name=:name) ";
      if (! _dependency->version().isEmpty())
        sql += "AND (pkghead_version=:version) ";
      if (! _dependency->developer().isEmpty())
        sql += "AND (pkghead_developer=:developer) ";
      sql += ");";

      QSqlQuery query;
      query.prepare(sql);
      query.bindValue(":name",      _dependency->name());
      query.bindValue(":version",   _dependency->version());
      query.bindValue(":developer", _dependency->developer());
      query.exec();
      if (query.first())
        returnVal = true;
      else if (query.lastError().type() != QSqlError::NoError)
        errMsg = _sqlerrtxt.arg(_name).arg(query.lastError().databaseText())
                           .arg(query.lastError().driverText());
      else
        errMsg = TR("%1<br>The prerequisite %2 has not been met. It "
                             "requires that the package %3 (version %4, "
                             "developer %5) be installed first.")
                    .arg(_message).arg(_name).arg(_dependency->name())
                    .arg(_dependency->version().isEmpty() ?
                         TR("Unspecified") : _dependency->version())
                    .arg(_dependency->developer().isEmpty() ?
                         TR("Unspecified") : _dependency->developer());
      break;
      }

    default:
      errMsg = TR("Encountered an unknown Prerequisite type. "
                           "Prerequisite '%1' has not been validated.")
                        .arg(_name);
      break;
  }

  return returnVal;
}
Example #23
0
int main(int argc, char* argv[])
{
  QSqlDatabase db;
  QString dbName;
  QString hostName;
  QString passwd;
  QString pkgfile;
  QString port;
  QString username;
  XAbstractMessageHandler *handler;
  bool    autoRunArg      = false;
  bool    autoRunCheck    = false;
  bool    debugpkg        = false;
  bool    haveDatabaseURL = false;
  bool    acceptDefaults  = false;

  QApplication app(argc, argv);
  app.addLibraryPath(".");
#ifndef Q_OS_MAC
  app.setWindowIcon(QIcon(":/images/updater-32x32.png"));
#endif

  if (argc > 1)
  {
    for (int intCounter = 1; intCounter < argc; intCounter++)
    {
      QString argument(argv[intCounter]);

      if (argument.startsWith("-help", Qt::CaseInsensitive))
      {
        qWarning("%s [ -databaseURL=PSQL7://hostname:port/databasename ]"
                 " [ -h hostname ]"
                 " [ -p port ]"
                 " [ -d databasename ]"
                 " [ -U username | -username=username ]"
                 " [ -passwd=databasePassword ]"
                 " [ -debug ]"
                 " [ -file=updaterFile.gz | -f updaterFile.gz ]"
                 " [ -autorun [ -D ] ]",
                 argv[0]);
        return 0;
      }
      else if (argument.startsWith("-databaseURL=", Qt::CaseInsensitive))
      {
        QString protocol;
        haveDatabaseURL = true;
        _databaseURL    = argument.right(argument.length() - 13);
        parseDatabaseURL(_databaseURL, protocol, hostName, dbName, port);
      }
      else if (argument == "-h")
      {
        hostName = argv[++intCounter];
      }
      else if (argument == "-p")
      {
        port = argv[++intCounter];
      }
      else if (argument == "-d")
      {
        dbName = argv[++intCounter];
      }
      else if (argument == "-U")
      {
        username = argv[++intCounter];
      }
      else if (argument.startsWith("-username=", Qt::CaseInsensitive))
      {
        username = argument.right(argument.length() - 10);
      }
      else if (argument.startsWith("-passwd=", Qt::CaseInsensitive))
      {
        passwd = argument.right(argument.length() - 8);
      }
      else if (argument.toLower() == "-debug")
      {
        debugpkg = true;
      }
      else if (argument == "-f")
      {
        pkgfile = argv[++intCounter];
      }
      else if (argument.startsWith("-file=", Qt::CaseInsensitive))
      {
        pkgfile = argument.right(argument.size() - argument.indexOf("=") - 1);
      }
      else if (argument.toLower() == "-autorun")
      {
        autoRunArg = true;
      }
      else if (argument == "-D")
      {
        acceptDefaults = true;
      }
    }
  }

  LoaderWindow * mainwin = new LoaderWindow();
  mainwin->setDebugPkg(debugpkg);
  mainwin->setCmdline(autoRunArg);
  handler = mainwin->handler();
  handler->setAcceptDefaults(autoRunArg && acceptDefaults);

  db = QSqlDatabase::addDatabase("QPSQL7");
  if (!db.isValid())
  {
    handler->message(QtFatalMsg,
                     QObject::tr("Unable to load the database driver. "
                                 "Please contact your systems administrator."));
    return 1;
  }

  db.setDatabaseName(dbName);
  db.setUserName(username);
  db.setPassword(passwd);
  db.setHostName(hostName);
  db.setPort(port.toInt());

  if (!db.open() && autoRunArg)
  {
    handler->message(QtFatalMsg,
                     QObject::tr("Unable to connect to the database "
                                 "with the given information."));
    return 1;
  }

  if (!db.open())
  {
    ParameterList params;
    params.append("name",      Updater::name);
    params.append("copyright", Updater::copyright);
    params.append("version",   Updater::version);
    params.append("build",     Updater::build);
    params.append("username",  username);

    if (haveDatabaseURL)
      params.append("databaseURL", _databaseURL.toLatin1().data());

    login2 newdlg(0, "", true);
    newdlg.set(params, 0);

    if (newdlg.exec() == QDialog::Rejected)
      return 2;

    _databaseURL = newdlg._databaseURL;
    username     = newdlg._user;
    Updater::loggedIn = true;
    mainwin->setWindowTitle();

    QSqlQuery set("SET standard_conforming_strings TO true;");
    if (set.lastError().type() != QSqlError::NoError)
      handler->message(QtWarningMsg,
                       QObject::tr("Unable to set standard_conforming_strings. "
                                   "Updates may fail with unexpected errors."));

    QSqlQuery su;
    su.prepare("SELECT rolsuper FROM pg_roles WHERE (rolname=:user);");
    su.bindValue(":user", username);
    su.exec();
    if (su.first())
    {
      if (! su.value(0).toBool() &&
          handler->question(QObject::tr("You are not logged in as a "
                                        "database super user. The update "
                                        "may fail. Are you sure you want "
                                        "to continue?"),
                            QMessageBox::Yes | QMessageBox::No,
                            QMessageBox::No) == QMessageBox::No)
        return 3;
    }
    else if (su.lastError().type() != QSqlError::NoError &&
             handler->question(QObject::tr("<p>The application received a database "
                                           "error while trying to check the user "
                                           "status of %1. Would you like to try to "
                                           "update anyway?</p><pre>%2</pre>")
                            .arg(username, su.lastError().databaseText()),
                            QMessageBox::Yes | QMessageBox::No,
                            QMessageBox::No) == QMessageBox::No)
      return 4;
  }

  if (! pkgfile.isEmpty())
  {
    autoRunCheck = mainwin->openFile(pkgfile);
  }

  if (autoRunArg)
  {
    bool successful = autoRunCheck && ! pkgfile.isEmpty();
    if (successful)
    {
      successful = mainwin->sStart();
    }
    if (successful)     // not else if
      return 0;
    else
    {
#ifdef Q_OS_WIN32
      mainwin->show();
#else
      qWarning("%s", qPrintable(mainwin->_text->toPlainText()));
      return 5;
#endif
    }
  }
  else
    mainwin->show();

  return app.exec();
}
Example #24
0
int Prerequisite::writeToDB(const QString pkgname, QString &errMsg)
{
  if (DEBUG)
    qDebug("Prerequisite::writeToDB(%s, &errMsg)", qPrintable(pkgname));

  if (! pkgname.isEmpty() && _dependency)
  {
    QSqlQuery select;
    int pkgheadid = -1;
    select.prepare("SELECT pkghead_id FROM pkghead WHERE (pkghead_name=:name);");
    select.bindValue(":name", pkgname);
    select.exec();
    if (select.first())
      pkgheadid = select.value(0).toInt();
    else if (select.lastError().type() != QSqlError::NoError)
    {
      errMsg = _sqlerrtxt.arg(_name)
                         .arg(select.lastError().databaseText())
                         .arg(select.lastError().driverText());
      return -1;
    }

    int parentid = -1;
    QString sql = "SELECT * FROM pkghead WHERE ((pkghead_name=:name) ";
    if (! _dependency->version().isEmpty())
      sql += "AND (pkghead_version=:version) ";
    if (! _dependency->developer().isEmpty())
      sql += "AND (pkghead_developer=:developer) ";
    sql += ") ORDER BY pkghead_version DESC LIMIT 1;";

    select.prepare(sql);
    select.bindValue(":name",      _dependency->name());
    select.bindValue(":version",   _dependency->version());
    select.bindValue(":developer", _dependency->developer());
    select.exec();
    if (select.first())
      parentid = select.value(0).toInt();
    else if (select.lastError().type() != QSqlError::NoError)
    {
      errMsg = _sqlerrtxt.arg(_name)
                         .arg(select.lastError().databaseText())
                         .arg(select.lastError().driverText());
      return -2;
    }
    else
    {
      errMsg = TR("Could not record the dependency %1 of package %2 "
                           "on package %3 (version %4, developer %5) because "
                           "the record for %6 was not found.")
                    .arg(_name).arg(pkgname).arg(_dependency->name())
                    .arg(_dependency->version().isEmpty() ?
                         TR("Unspecified") : _dependency->version())
                    .arg(_dependency->developer().isEmpty() ?
                         TR("Unspecified") : _dependency->developer())
                    .arg(_dependency->name());
      return -3;
    }

    int pkgdepid = -1;
    select.prepare("SELECT * FROM pkgdep "
                   "WHERE ((pkgdep_pkghead_id=:pkgheadid)"
                   "  AND  (pkgdep_parent_pkghead_id=:parentid));");
    select.bindValue(":pkgheadid", pkgheadid);
    select.bindValue(":parentid",  parentid);
    select.exec();
    if (select.first())
      pkgdepid=select.value(0).toInt();
    else if (select.lastError().type() != QSqlError::NoError)
    {
      errMsg = _sqlerrtxt.arg(_name)
                         .arg(select.lastError().databaseText())
                         .arg(select.lastError().driverText());
      return -4;
    }

    QSqlQuery upsert;
    if (pkgdepid > 0)
      upsert.prepare("UPDATE pkgdep "
                     "SET pkgdep_pkghead_id=:pkgheadid,"
                     "    pkgdep_parent_pkghead_id=:parentid "
                     "WHERE (pkgdep_id=:pkgdepid);");
    else
    {
      upsert.exec("SELECT NEXTVAL('pkgdep_pkgdep_id_seq');");
      if (upsert.first())
        pkgdepid = upsert.value(0).toInt();
      else if (upsert.lastError().type() != QSqlError::NoError)
      {
        QSqlError err = upsert.lastError();
        errMsg = _sqlerrtxt.arg(_name).arg(err.driverText()).arg(err.databaseText());
        return -5;
      }
      upsert.prepare("INSERT INTO pkgdep ("
                     "   pkgdep_id, pkgdep_pkghead_id, pkgdep_parent_pkghead_id"
                     ") VALUES ("
                     "    :pkgdepid, :pkgheadid, :parentid);");
    }

    upsert.bindValue(":pkgdepid",   pkgdepid);
    upsert.bindValue(":pkgheadid",  pkgheadid);
    upsert.bindValue(":parentid",   parentid);

    if (! upsert.exec())
    {
      QSqlError err = upsert.lastError();
      errMsg = _sqlerrtxt.arg(_name).arg(err.driverText()).arg(err.databaseText());
      return -6;
    }

    return pkgdepid;
  }

  return 0;
}
bool UserManager::hasOption(const QString& user, const QString& option) const
{
    QSqlQuery query;
    query.exec( QString("SELECT value from options WHERE jid = '%1' AND option='%2'").arg(user,option) );
    return query.first();
}
Example #26
0
void Busybook::on_pushButton_give_clicked()
{
    QString busyname , busygenre , busyauthor , busyyear , result , s = "1";
    QString n = "0";
 // busyreg.open();
    busyname = ui->lineEdit_n->text();
    busygenre = ui->lineEdit_g->text();
    busyauthor = ui->lineEdit_a->text();
    busyyear = ui->lineEdit_y->text();

    busyreg_click = QSqlDatabase::addDatabase("QSQLITE");
    busyreg_click.setDatabaseName("D:/Kyrs/Kyrs/Reg.db");
    busyreg_click.open();
     if(!busyreg_click.open()){

         qDebug() << busyreg_click.lastError().text();
          return;
      }
      else {

         qDebug() << "otkrilo database reg!";

    }



     QSqlQuery qrybusyreg("SELECT * FROM Reg where Sign = '"+s+"'");
     while(qrybusyreg.next()){

         result  = qrybusyreg.value(4).toString();

     }
     busyreg_click.close();

     busybd_click = QSqlDatabase::addDatabase("QSQLITE");
     busybd_click.setDatabaseName("D:/Kyrs/Kyrs/Book.db");
     busybd_click.open();
     if(!busybd_click.open()){

         qDebug() <<"problema ";
          return;
      }
      else {

         qDebug() << "Success snova!";

    }


    QSqlQuery b;
    b.prepare ("update Book set Status  = '"+n+"' where Status = '"+result+"' and Name = '"+busyname+"' and Genre = '"+busygenre+"' and Author = '"+busyauthor+"' and Year = '"+busyyear+"'");


    if(!busybd_click.isOpen()){

        puts("bd ne otkrito s knigami");
    }

    else {
        puts ("ads");
    }
    if(b.exec()){
        QMessageBox::information(0,"Otdal" , "Vce ok!");
        ui->lineEdit_a->clear();
        ui->lineEdit_g->clear();
        ui->lineEdit_n->clear();
        ui->lineEdit_y->clear();
       // busybd_click.close();
        ////////////////****ќбновление базы*****\\\\\\\\\\\\\\\\\\






       QSqlQueryModel * modalbusy = new QSqlQueryModel();
       QSqlQuery * qrybusy = new QSqlQuery(busybd_click);
       qrybusy->prepare("select Genre ,Name , Author , Year from Book where  Status = '"+result+"'");
       qrybusy->exec();

       modalbusy->setQuery(*qrybusy);
       ui->tableView->setModel(modalbusy);


    }
    busybd_click.close();
}
bool UserManager::isRegistered(const QString& user) const
{
    QSqlQuery query;
    query.exec( QString("SELECT jid FROM users WHERE jid = '%1'").arg(user) );
    return query.first();
}
Example #28
0
int main(int argc, char* argv[])
{
  QString username  = "";
  bool    haveUsername    = FALSE;
  bool    haveDatabaseURL = FALSE;
  _loggedIn        = FALSE;
  bool multitrans = false;
  bool debugpkg   = false;
  bool autoRunArg   = false;
  bool autoRunCheck = false;
  QString pkgfile = "";

  QApplication app(argc, argv);
  app.addLibraryPath(".");
#ifndef Q_WS_MACX
  app.setWindowIcon(QIcon(":/images/updater-32x32.png"));
#endif

  if (argc > 1)
  {
    haveUsername        = FALSE;
    bool    havePasswd          = FALSE;
    QString passwd              = "";

    for (int intCounter = 1; intCounter < argc; intCounter++)
    {
      QString argument(argv[intCounter]);

      if (argument.startsWith("-help", Qt::CaseInsensitive))
      {
        qWarning("%s [ -databaseURL=PSQL7://hostname:port/databasename |"
                 " -username=databaseUserName -passwd=databasePassword |"
                 " -noauth ]"
                 " [ -multitrans ]"
                 " [ -debug ]"
                 " [ -file=updaterFile.gz ]"
                 " [ -autorun ]",
                 argv[0]);
        return 0;
      }
      else if (argument.startsWith("-databaseURL=", Qt::CaseInsensitive))
      {
        haveDatabaseURL = TRUE;
        _databaseURL    = argument.right(argument.length() - 13);
      }
      else if (argument.startsWith("-username=", Qt::CaseInsensitive))
      {
        haveUsername = TRUE;
        username     = argument.right(argument.length() - 10);
      }
      else if (argument.startsWith("-passwd=", Qt::CaseInsensitive))
      {
        havePasswd = TRUE;
        passwd     = argument.right(argument.length() - 8);
      }
      else if (argument.toLower() == "-noauth")
      {
        haveUsername = TRUE;
        havePasswd   = TRUE;
      }
      else if (argument.toLower() == "-multitrans")
        multitrans = true;
      else if (argument.toLower() == "-debug")
        debugpkg = true;
      else if (argument.startsWith("-file=", Qt::CaseInsensitive))
        pkgfile = argument.right(argument.size() - argument.indexOf("=") - 1);
      else if (argument.toLower() == "-autorun")
        autoRunArg = true;
    }

    if ( (haveDatabaseURL) && (haveUsername) && (havePasswd) )
    {
      QSqlDatabase db;
      QString      protocol;
      QString      hostName;
      QString      dbName;
      QString      port;

      db = QSqlDatabase::addDatabase("QPSQL7");
      if (!db.isValid())
      {
        QMessageBox::critical(0, QObject::tr("Can not load database driver"), QObject::tr("Unable to load the databse driver. Please contact your systems adminstrator."));
        QApplication::exit(-1);
      }

      parseDatabaseURL(_databaseURL, protocol, hostName, dbName, port);
      db.setDatabaseName(dbName);
      db.setUserName(username);
      db.setPassword(passwd);
      db.setHostName(hostName);
      db.setPort(port.toInt());

      if (!db.open())
      {
        QMessageBox::critical(0, QObject::tr("Unable to connect to database"), QObject::tr("Unable to connect to the database with the given information."));
        QApplication::exit(-1);
      }
      else
        _loggedIn = TRUE;
    }

  }

  if(!_loggedIn)
  {
    ParameterList params;
    params.append("name", _name);
    params.append("copyright", _copyright.toAscii().data());
    params.append("version",   _version.toAscii().data());
    params.append("build", __DATE__ " " __TIME__); // use C++ string concat

    if (haveUsername)
      params.append("username", _user);

    if (haveDatabaseURL)
      params.append("databaseURL", _databaseURL.toAscii().data());

    if (_evaluation)
      params.append("evaluation");

    login2 newdlg(0, "", TRUE);
    newdlg.set(params, 0);

    if (newdlg.exec() == QDialog::Rejected)
      return -1;
    else
    {
      _databaseURL = newdlg._databaseURL;
      _user = newdlg._user;
      _loggedIn = TRUE;
    }

    QSqlQuery su;
    su.prepare("SELECT rolsuper FROM pg_roles WHERE (rolname=:user);");
    su.bindValue(":user", _user);
    su.exec();
    if (su.first())
    {
      if (! su.value(0).toBool() &&
          QMessageBox::question(0, QObject::tr("Not Super User"),
                                QObject::tr("You are not logged in as a "
                                            "database super user. The update "
                                            "may fail. Are you sure you want "
                                            "to continue?"),
                                QMessageBox::Yes,
                                QMessageBox::No | QMessageBox::Default) == QMessageBox::No)
        return -2;
    }
    else if (su.lastError().type() != QSqlError::NoError &&
             QMessageBox::question(0, QObject::tr("System Error"),
                            QObject::tr("<p>The application received a database "
                                        "error while trying to check the user "
                                        "status of %1. Would you like to try to "
                                        "update anyway?<br><pre>%2")
                            .arg(_user)
                            .arg(su.lastError().databaseText()),
                            QMessageBox::Yes,
                            QMessageBox::No | QMessageBox::Default) == QMessageBox::No)
      return -3;
  }

  LoaderWindow * mainwin = new LoaderWindow();
  mainwin->setMultipleTransactions(multitrans);
  mainwin->setDebugPkg(debugpkg);
  if (! pkgfile.isEmpty())
  {
    autoRunCheck = mainwin->openFile(pkgfile);
  }

  // Start the upgrade if the -autoRun argument is used and file prereqs pass.
  if (autoRunArg)
  {
    bool successful = autoRunCheck && ! pkgfile.isEmpty();
    if (successful)
    {
      _autoRun = true;
      successful = mainwin->sStart();
    }
    if (successful)     // not else if
      return 0;
    else
    {
#ifdef Q_OS_WIN32
      mainwin->show();
#else
      qWarning("%s", qPrintable(mainwin->_text->toPlainText()));
      return 1;
#endif
    }
  }
  else
    mainwin->show();

  return app.exec();
}
Example #29
0
bool QCatDataModuleClass::createDB(const QString fileName, bool overwrite)
{
	bool fileExist = QFileInfo(fileName).exists();
	if (!overwrite && fileExist)
		return false;
     
	QSqlQuery *wq;
    
	QString dropIconsTable = "DROP TABLE IF EXISTS Icons";
	QString crIconsTable = "CREATE TABLE Icons (id INTEGER PRIMARY KEY AUTOINCREMENT, catId INTEGER(2), name TEXT(255), fileName TEXT(255), iconData BLOB)";    
    
	QString dropNodeTypes = "DROP TABLE IF EXISTS nodeTypes";
	QString crNodeTypes = "CREATE TABLE NodeTypes (id INTEGER(4), nodeName TEXT(255), nodeIcon INT(4), PRIMARY KEY(id))";
    
	QString dropCatalogsTable = "DROP TABLE IF EXISTS Catalogs";
	QString crCatalogsTable = "CREATE TABLE Catalogs(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT(255), description TEXT(512), iconId INT, catSize INT, numFiles INT, numDirs INT, numGroups INT, numCD INT, numDVD INT, numNetDrives INT, numFlash INT, numHDD INT, numFDD INT, flags INT, readPass TEXT, writePass TEXT, datetime INT)";
    
	QString dropDiskNumbersTable = "DROP TABLE IF EXISTS DiskNumbers";
	QString crDiskNumbersTable = "CREATE TABLE DiskNumbers(id INTERGER, seq INTEGER)";
    
//	QSqlDatabase _db;
     //db = QSqlDatabase::addDatabase(DBTYPE, "AA");
	db.setDatabaseName(fileName);
	printQS(fileName);
	db.open();
    
	wq = new QSqlQuery(db);
	if (!wq->exec(dropIconsTable))
	{
		delete wq;
		return false;
	}
	if (!wq->exec(crIconsTable))
	{
		delete wq;
		return false;
	}
    if (!wq->exec(dropNodeTypes))
	{
		delete wq;
		return false;
	}
    if (!wq->exec(crNodeTypes))
	{
		delete wq;
		return false;
	}
	if (!wq->exec(dropCatalogsTable))
	{
		delete wq;
		return false;
	}
	if (!wq->exec(crCatalogsTable))
	{
		delete wq;
		return false;
	}
	if (!wq->exec(dropDiskNumbersTable))
	{
		delete wq;
		return false;
	}
	if (!wq->exec(crDiskNumbersTable))
	{
		delete wq;
		return false;
	}
	delete wq;
    
   // IconManager im(_db);
    //im.fillDefaultIcons();
    
	db.close();
	return true;
}
Example #30
0
	void SQLStorageBackend::Prepare ()
	{
		if (Type_ == SBSQLite)
		{
			QSqlQuery pragma (DB_);
			if (!pragma.exec (QString ("PRAGMA journal_mode = %1;")
						.arg (XmlSettingsManager::Instance ()->
							property ("SQLiteJournalMode").toString ())))
				LeechCraft::Util::DBLock::DumpError (pragma);
			if (!pragma.exec (QString ("PRAGMA synchronous = %1;")
						.arg (XmlSettingsManager::Instance ()->
							property ("SQLiteSynchronous").toString ())))
				LeechCraft::Util::DBLock::DumpError (pragma);
			if (!pragma.exec (QString ("PRAGMA temp_store = %1;")
						.arg (XmlSettingsManager::Instance ()->
							property ("SQLiteTempStore").toString ())))
				LeechCraft::Util::DBLock::DumpError (pragma);
		}

		HistoryLoader_ = QSqlQuery (DB_);
		HistoryLoader_.prepare ("SELECT "
				"title, "
				"date, "
				"url "
				"FROM history "
				"ORDER BY date DESC");

		HistoryRatedLoader_ = QSqlQuery (DB_);
		switch (Type_)
		{
			case SBSQLite:
				HistoryRatedLoader_.prepare ("SELECT "
						"SUM (julianday (date)) - julianday (MIN (date)) * COUNT (date) AS rating, "
						"title, "
						"url "
						"FROM history "
						"WHERE ( title LIKE :titlebase ) "
						"OR ( url LIKE :urlbase ) "
						"GROUP BY url "
						"ORDER BY rating DESC "
						"LIMIT 100");
				break;
			case SBPostgres:
				HistoryRatedLoader_.prepare ("SELECT "
						"SUM (AGE (date)) - AGE (MIN (date)) * COUNT (date) AS rating, "
						"MAX (title) AS title, "
						"url "
						"FROM history "
						"WHERE ( title LIKE :titlebase ) "
						"OR ( url LIKE :urlbase ) "
						"GROUP BY url "
						"ORDER BY rating ASC "
						"LIMIT 100");
				break;
			case SBMysql:
				qWarning () << Q_FUNC_INFO
						<< "it's not MySQL";
				break;
		}

		HistoryAdder_ = QSqlQuery (DB_);
		HistoryAdder_.prepare ("INSERT INTO history ("
				"date, "
				"title, "
				"url"
				") VALUES ("
				":date, "
				":title, "
				":url"
				")");

		HistoryEraser_ = QSqlQuery (DB_);
		switch (Type_)
		{
			case SBSQLite:
				HistoryEraser_.prepare ("DELETE FROM history "
						"WHERE "
						"(julianday ('now') - julianday (date) > :age)");
				break;
			case SBPostgres:
				HistoryEraser_.prepare ("DELETE FROM history "
						"WHERE "
						"(date - now () > :age * interval '1 day')");
				break;
			case SBMysql:
				qWarning () << Q_FUNC_INFO
						<< "it's not MySQL";
				break;
		}

		HistoryTruncater_ = QSqlQuery (DB_);
		switch (Type_)
		{
			case SBSQLite:
				HistoryTruncater_.prepare ("DELETE FROM history "
						"WHERE date IN "
						"(SELECT date FROM history ORDER BY date DESC "
						"LIMIT 10000 OFFSET :num)");
				break;
			case SBPostgres:
				HistoryTruncater_.prepare ("DELETE FROM history "
						"WHERE date IN "
						"	(SELECT date FROM history ORDER BY date DESC OFFSET :num)");
				break;
			case SBMysql:
				qWarning () << Q_FUNC_INFO
						<< "it's not MySQL";
				break;
		}

		FavoritesLoader_ = QSqlQuery (DB_);
		switch (Type_)
		{
			case SBSQLite:
				FavoritesLoader_.prepare ("SELECT "
						"title, "
						"url, "
						"tags "
						"FROM favorites "
						"ORDER BY ROWID DESC");
				break;
			case SBPostgres:
				FavoritesLoader_.prepare ("SELECT "
						"title, "
						"url, "
						"tags "
						"FROM favorites "
						"ORDER BY CTID DESC");
				break;
			case SBMysql:
				qWarning () << Q_FUNC_INFO
						<< "it's not MySQL";
				break;
		}

		FavoritesAdder_ = QSqlQuery (DB_);
		FavoritesAdder_.prepare ("INSERT INTO favorites ("
				"title, "
				"url, "
				"tags"
				") VALUES ("
				":title, "
				":url, "
				":tags"
				")");

		FavoritesUpdater_ = QSqlQuery (DB_);
		FavoritesUpdater_.prepare ("UPDATE favorites SET "
				"title = :title, "
				"tags = :tags "
				"WHERE url = :url");

		FavoritesRemover_ = QSqlQuery (DB_);
		FavoritesRemover_.prepare ("DELETE FROM favorites "
				"WHERE url = :url");

		FormsIgnoreSetter_ = QSqlQuery (DB_);
		FormsIgnoreSetter_.prepare ("INSERT INTO forms_never ("
				"url"
				") VALUES ("
				":url"
				")");

		FormsIgnoreGetter_ = QSqlQuery (DB_);
		FormsIgnoreGetter_.prepare ("SELECT COUNT (url) AS num "
				"FROM forms_never "
				"WHERE url = :url");

		FormsIgnoreClearer_ = QSqlQuery (DB_);
		FormsIgnoreClearer_.prepare ("DELETE FROM forms_never ("
				"WHERE url = :url");
	}