コード例 #1
0
ファイル: dbmanager.cpp プロジェクト: sgranfius/sns
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;
    }
}
コード例 #2
0
DetailMeeting::DetailMeeting(int _meeting_id, QWidget *parent) : QDialog(parent)
{
    global_settings = new QSettings("../Thunderlook/data/settings/settings.ini", QSettings::IniFormat);

    db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName(global_settings->value("SQL/addr_ip").toString());
    db.setPort(QString(global_settings->value("SQL/port").toString()).toInt());
    db.setDatabaseName("thunderlook");
    db.setUserName("esgi");
    db.setPassword("esgi");

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

    meeting_id = _meeting_id;

    setWindowTitle("Détails de la réunion");

    QSqlQuery *req = new QSqlQuery();
    req->prepare("SELECT * FROM Meeting m WHERE id = :meeting_id");
    req->bindValue(":meeting_id", meeting_id);
    req->exec();
    QSqlRecord rec = req->record();
    req->next();

    lb_label = new QLabel(req->value(rec.indexOf("title")).toString());

    // DATE BEGIN
    QStringList date_begin = req->value(rec.indexOf("date_begin")).toString().split(" ").at(0).split("/");
    QStringList time_begin = req->value(rec.indexOf("date_begin")).toString().split(" ").at(1).split(":");

    QDate date_begin_edit(date_begin.at(0).toInt(),date_begin.at(1).toInt(),date_begin.at(2).toInt());
    QTime time_begin_edit(time_begin.at(0).toInt(),time_begin.at(1).toInt(),0);

    QDateTime date_time_begin(date_begin_edit,time_begin_edit);

    meeting_dt_begin = new QDateTimeEdit(date_time_begin);
    meeting_dt_begin->setDisplayFormat("dd/MM/yyyy hh:mm");
    meeting_dt_begin->setMinimumTime(QTime(8,0,0,0));
    meeting_dt_begin->setMaximumTime(QTime(19,45,0,0));

    // DATE END
    QStringList date_end = req->value(rec.indexOf("date_end")).toString().split(" ").at(0).split("/");
    QStringList time_end = req->value(rec.indexOf("date_end")).toString().split(" ").at(1).split(":");

    QDate date_end_edit(date_end.at(0).toInt(),date_end.at(1).toInt(),date_end.at(2).toInt());
    QTime time_end_edit(time_end.at(0).toInt(),time_end.at(1).toInt(),0);

    QDateTime date_time_end(date_end_edit,time_end_edit);

    meeting_dt_end = new QDateTimeEdit(date_time_end);
    meeting_dt_end->setDisplayFormat("dd/MM/yyyy hh:mm");
    meeting_dt_end->setMinimumTime(QTime(8,0,0,0));
    meeting_dt_end->setMaximumTime(QTime(19,45,0,0));

    meeting_duration = new QTimeEdit();
    meeting_duration->setDisplayFormat("hh:mm");

    QTime time(0,0,0);
    meeting_duration->setTime(time.addSecs(req->value(rec.indexOf("duration")).toInt()*60));

    btn_action = new QPushButton("Mettre à jour");
    btn_cancel = new QPushButton("Annuler");
    btn_del = new QPushButton("Supprimer cette réunion");

    global_settings = new QSettings("../Thunderlook/data/settings/settings.ini", QSettings::IniFormat);

    QSqlQuery *reqOrganizer = new QSqlQuery();
    reqOrganizer->prepare("SELECT Users.address FROM Meeting,Users WHERE Meeting.id = :meeting_id AND Users.id = Meeting.organizer");
    reqOrganizer->bindValue(":meeting_id", meeting_id);
    reqOrganizer->exec();
    QSqlRecord recOrganizer = reqOrganizer->record();
    reqOrganizer->next();

    // Enable Item if user is not organizer
    if(reqOrganizer->value(recOrganizer.indexOf("address")).toString() != global_settings->value("Send/smtp_user").toString())
    {
        btn_del->setEnabled(false);
        btn_action->setEnabled(false);
        meeting_dt_end->setEnabled(false);
        meeting_dt_begin->setEnabled(false);
        meeting_duration->setEnabled(false);
    }

    cb_organizer = new QComboBox();
    cb_organizer->setEnabled(false);

    QSqlQuery *reqUser = new QSqlQuery();

    reqUser->prepare("SELECT * FROM Users WHERE id = :id_user");
    reqUser->bindValue(":id_user", req->value(rec.indexOf("organizer")).toString());
    QString organiz(req->value(rec.indexOf("organizer")).toString());
    reqUser->exec();
    QSqlRecord recUser = reqUser->record();
    while(reqUser->next())
    {
        cb_organizer->addItem(reqUser->value(recUser.indexOf("address")).toString());
    }

    cb_users = new QComboBox();

    model_users = new QStandardItemModel();
    int i = 0;

    QSqlQuery *reqUsersMeeting = new QSqlQuery();
    reqUsersMeeting->prepare("SELECT * FROM UsersMeeting usermeeting INNER JOIN Users user ON user.id = usermeeting.id_user WHERE usermeeting.id_meeting = :id_meeting and present != 0");
    reqUsersMeeting->bindValue(":id_meeting", meeting_id);
    reqUsersMeeting->exec();
    QSqlRecord recUserMeeting = reqUsersMeeting->record();
    while(reqUsersMeeting->next())
    {
        User user(reqUsersMeeting->value(recUserMeeting.indexOf("id_user")).toInt(),reqUsersMeeting->value(recUserMeeting.indexOf("address")).toString());

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

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

        model_users->setItem(i,item);
        i++;
    }

    cb_users->setModel(model_users);

    req->first();

    cb_room = new QComboBox();
    cb_room->setEnabled(false);

    QSqlQuery *reqRoom = new QSqlQuery();

    reqRoom->prepare("SELECT * FROM Room WHERE id = :id_room");
    reqRoom->bindValue(":id_room", req->value(rec.indexOf("room")).toString());
    QString room(req->value(rec.indexOf("room")).toString());
    reqRoom->exec();
    QSqlRecord recRoom = reqRoom->record();
    while(reqRoom->next())
    {
        cb_room->addItem(reqRoom->value(recRoom.indexOf("name")).toString());
    }

    id_room = req->value(rec.indexOf("id")).toInt();

    QFormLayout *fl_data = new QFormLayout;
    fl_data->addRow("Libellé:", lb_label);
    fl_data->addRow("Début:", meeting_dt_begin);
    fl_data->addRow("Fin:", meeting_dt_end);
    fl_data->addRow("Durée:", meeting_duration);
    fl_data->addRow("Organisateur:", cb_organizer);
    fl_data->addRow("Invité(s):", cb_users);
    fl_data->addRow("Salle:", cb_room);

    QHBoxLayout *layout_buttons = new QHBoxLayout;
    layout_buttons->setAlignment(Qt::AlignRight);
    layout_buttons->addWidget(btn_del);
    layout_buttons->addWidget(btn_action);
    layout_buttons->addWidget(btn_cancel);

    QVBoxLayout *layout_main = new QVBoxLayout;
    layout_main->addLayout(fl_data);
    layout_main->addLayout(layout_buttons);

    setLayout(layout_main);

    connect(btn_del, SIGNAL(clicked()), this, SLOT(deleteMeeting()));
    connect(btn_cancel, SIGNAL(clicked()), this, SLOT(close()));
    connect(btn_action, SIGNAL(clicked()), this, SLOT(updateMeeting()));
}
コード例 #3
0
void editRoom::on_addButton_clicked()
{

    QString roomno=ui->roomName->text();

    QString nameStr= ui->catList->currentText();

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

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

    if( !db.open() )
    {
        qDebug() << db.lastError();
        qFatal( "MAYDAY!!!\n\nSOMETHING IS WRONG WITH YOUR DATABASE." );
    }
    qDebug( "Database Connection Validated..." );
    QSqlQuery qry;

    qry.prepare("CREATE TABLE IF NOT EXISTS roomcat (id INTEGET PRIMARY KEY, item VARCHAR(30), price INTEGER)");
    if(!qry.exec())
        qDebug() << qry.lastError();
    else
        qDebug( "Table Created!" );


    qry.prepare("SELECT id FROM roomcat WHERE item = :name");
    qry.bindValue(":name",nameStr);
    if(!qry.exec())
    {
        qDebug() << qry.lastError();
    }
    else
        qDebug( "Table Selected!" );

    int catid=0;
    while (qry.next()) {
        catid = qry.value(0).toInt();
    }
    if(catid==0)
    {
        qFatal("MAYDAY!!! DATABASE ERROR!!!");
    }

    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..." );

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

    int roomid=0;
    while (qry.next()) {

        int item = qry.value(0).toInt();
        if(item>roomid)
        {
            roomid=item;
        }
    }
    roomid++;

    qry.prepare("INSERT INTO roomlist (id, roomno, cat, occupied) values (:id, :roomno, :roomcat, :occ)");
    qry.bindValue(":id",roomid);
    qry.bindValue(":roomno",roomno);
    qry.bindValue(":roomcat",catid);
    qry.bindValue(":occ",0);
    if(!qry.exec())
        qDebug() << qry.lastError();
    else
    {
        qDebug( "Inserted to Room Table." );
        ui->roomList->addItem(ui->roomName->text());
        ui->roomName->clear();
    }

}
コード例 #4
0
void DBWorker::deleteSetting(QString name)
{
    QSqlQuery query = prepare("DELETE FROM settings WHERE name = ?");
    query.bindValue(0, name);
    execute(query);
}
コード例 #5
0
bool TestAssistance::extQuestionByType(QUESTIONTYPE type)
{
    //clear buffer
    questionBuffer.clear();
    //open database
    if (!m_objDatabase.open()) {
        packErrorInfo(m_objDatabase.lastError().text(),
                      TA_ERROR_NOTCONNECTED);
        return false;
    }

    QSqlQuery query;
    QString sql("SELECT qtxt,qhard,qimage FROM questions "
                "WHERE qmajor=:major AND qcourse=:course "
                "AND qgrade=:grade AND qtype=:type AND qknowpoint in (");

    //pack qknowpoint
    for(size_t i = 0; i != m_objPaperInfo.kpoint.size(); ++i){
        sql += "'" + m_objPaperInfo.kpoint[i] + "'";
        if(i < m_objPaperInfo.kpoint.size()-1)
            sql += ",";
    }
    sql += ") ORDER BY RANDOM() limit 100";

    query.prepare(sql);
    query.bindValue(":major", m_objPaperInfo.major);
    query.bindValue(":course", m_objPaperInfo.strCourse);
    query.bindValue(":grade", m_objPaperInfo.nGrade);
    query.bindValue(":type", static_cast<int>(type));

    if(query.exec()){
        int maxNum = typeNum(type);
        int easy = floor(maxNum*m_objPaperInfo.fEasy);
        int normal = maxNum*m_objPaperInfo.fNormal;
        int hard = maxNum*m_objPaperInfo.fHard;

        //if sum is not equal to maxNum, set normal=normal+rest
        if(easy + normal + hard < maxNum)
            normal = maxNum - easy - hard;

        QUESTION q;
        int max = typeNum(type);
        while(query.next()){
            if(questionBuffer.size() >= max)
                break;
            int t = query.value(1).toInt();
            if(easy > 0 && t == TA_EASY){
                q.txt = query.value(0).toString();
                q.imgBytes = query.value(2).toByteArray();
                questionBuffer.push_back(q);
                easy--;maxNum--;
                continue;
            }
            if(normal > 0 && t == TA_NORMAL){
                q.txt = query.value(0).toString();
                q.imgBytes = query.value(2).toByteArray();
                questionBuffer.push_back(q);
                normal--;maxNum--;
                continue;
            }
            if(hard > 0 && t == TA_HARD){
                q.txt = query.value(0).toString();
                q.imgBytes = query.value(2).toByteArray();
                questionBuffer.push_back(q);
                hard--;maxNum--;
                continue;
            }
            if(maxNum > 0){
                q.txt = query.value(0).toString();
                q.imgBytes = query.value(2).toByteArray();
                questionBuffer.push_back(q);
                maxNum--;
            }
        }
    }
    else{
        packErrorInfo(query.lastError().text(),
                      TA_ERROR_SQLERROR);
        m_objDatabase.close();
        return false;
    }
    m_objDatabase.close();
    return true;
}
コード例 #6
0
ファイル: itunesfeature.cpp プロジェクト: MK-42/mixxx
void ITunesFeature::parsePlaylist(QXmlStreamReader &xml, QSqlQuery &query_insert_to_playlists,
                                  QSqlQuery &query_insert_to_playlist_tracks, TreeItem* root) {
    //qDebug() << "Parse Playlist";

    QString playlistname;
    int playlist_id = -1;
    int playlist_position = -1;
    int track_reference = -1;
    //indicates that we haven't found the <
    bool isSystemPlaylist = false;
    bool isPlaylistItemsStarted = false;

    QString key;


    //We process and iterate the <dict> tags holding playlist summary information here
    while (!xml.atEnd() && !m_cancelImport) {
        xml.readNext();

        if (xml.isStartElement()) {

            if (xml.name() == "key") {
                QString key = xml.readElementText();
                // The rules are processed in sequence
                // That is, XML is ordered.
                // For iTunes Playlist names are always followed by the ID.
                // Afterwars the playlist entries occur
                if (key == "Name") {
                    readNextStartElement(xml);
                    playlistname = xml.readElementText();
                    continue;
                }
                //When parsing the ID, the playlistname has already been found
                if (key == "Playlist ID") {
                    readNextStartElement(xml);
                    playlist_id = xml.readElementText().toInt();
                    playlist_position = 1;
                    continue;
                }
                //Hide playlists that are system playlists
                if (key == "Master" || key == "Movies" || key == "TV Shows" ||
                    key == "Music" || key == "Books" || key == "Purchased") {
                    isSystemPlaylist = true;
                    continue;
                }

                if (key == "Playlist Items") {
                    isPlaylistItemsStarted = true;
                    
                    //if the playlist is prebuild don't hit the database
                    if (isSystemPlaylist) continue;
                    query_insert_to_playlists.bindValue(":id", playlist_id);
                    query_insert_to_playlists.bindValue(":name", playlistname);

                    bool success = query_insert_to_playlists.exec();
                    if (!success) {
                        qDebug() << "SQL Error in ITunesTableModel.cpp: line" << __LINE__
                                 << " " << query_insert_to_playlists.lastError();
                        return;
                    }
                    //append the playlist to the child model
                    root->appendChild(playlistname);
                }
                // When processing playlist entries, playlist name and id have
                // already been processed and persisted
                if (key == "Track ID") {

                    readNextStartElement(xml);
                    track_reference = xml.readElementText().toInt();

                    query_insert_to_playlist_tracks.bindValue(":playlist_id", playlist_id);
                    query_insert_to_playlist_tracks.bindValue(":track_id", track_reference);
                    query_insert_to_playlist_tracks.bindValue(":position", playlist_position++);

                    //Insert tracks if we are not in a pre-build playlist
                    if (!isSystemPlaylist && !query_insert_to_playlist_tracks.exec()) {
                        qDebug() << "SQL Error in ITunesFeature.cpp: line" << __LINE__ << " "
                                 << query_insert_to_playlist_tracks.lastError();
                        qDebug() << "trackid" << track_reference;
                        qDebug() << "playlistname; " << playlistname;
                        qDebug() << "-----------------";
                    }
                }
            }
        }
        if (xml.isEndElement()) {
            if (xml.name() == "array") {
                //qDebug() << "exit playlist";
                break;
            }
            if (xml.name() == "dict" && !isPlaylistItemsStarted){
                // Some playlists can be empty, so we need to exit.
                break;
            }
        }
    }
}
コード例 #7
0
ファイル: EspecieView.cpp プロジェクト: skhaz/oldies
void EspecieView::deleteClicked()
{
	if (tableView->currentIndex().row() < 0)
	{
		return;
	}

	QSqlRecord record = model->record(tableView->currentIndex().row());
	int cod = record.value("cod_materialespecie").toInt();
	QString nome = record.value("nome").toString();

	QMessageBox messageBox(QMessageBox::Question, "Admin",
			QString::fromUtf8("Confirma a exclusão do registro <b>%1</b>?").arg(nome), QMessageBox::Yes | QMessageBox::No, this);

	if (messageBox.exec() == QMessageBox::Yes)
	{
		QString detailedText;

		QSqlQuery sql;
		sql.prepare("delete from materialespecie where cod_materialespecie = :cod");
		sql.bindValue(":cod", cod);

		if (!sql.exec())
		{
			QSqlQuery query1;
			query1.prepare("select nome from materiaprima where cod_materialespecie = :cod");
			query1.bindValue(":cod", cod);

			if (query1.exec())
			{
				while (query1.next()) {
					detailedText.append(query1.value(query1.record().indexOf("nome")).toString());
					detailedText.append("\n");
				}
			}

			QSqlQuery query2;
			query2.prepare("delete from materiaprima where cod_materialespecie = :cod");
			query2.bindValue(":cod", cod);

			QMessageBox messageBox;
			messageBox.setWindowTitle("Admin");
			messageBox.setText(QString::fromUtf8(
					"Existe alguma matéria prima sendo referenciada por este material (veja em detalhes)\n"
					"tentar uma exclusão em cadeia forçada?"
				));
			messageBox.setDetailedText(detailedText);
			messageBox.setIcon(QMessageBox::Critical);
			messageBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);

			switch(messageBox.exec())
			{
				case QMessageBox::Yes:
						query2.exec();
						sql.exec();
					break;

				default:
					break;
			}
		}

		model->select();
	}

}
コード例 #8
0
ファイル: mainwindow.cpp プロジェクト: stevenvergenz/milestat
void MainWindow::addCrossing()
{
	QString curState = ui->comboCurState->currentText();
	QString toState = ui->comboToState->currentText();
	quint32 odometer = ui->spinOdometer->value();
	quint32 curtime = ui->dteTime->dateTime().toTime_t();
	QSqlQuery query;
	Command entry = {"Crossings", odometer, curState};
	
	if( ui->comboCurState->currentIndex() == 0 || ui->comboToState->currentIndex() == 0 )
		return;
	
	query.exec("SELECT Odometer,Destination from Crossings ORDER BY Odometer;");
	query.last();
	QSqlRecord prevresult = query.record();

	int dist = 0;
	if( curState == prevresult.value("Destination").toString() ){
		// calculate distance traveled
		dist = odometer - prevresult.value("Odometer").toInt();

	}
	
	// add the entry to Crossings table
	query.prepare("INSERT INTO Crossings (Date, Odometer, Origin, Destination, Distance) "
				  "VALUES (:date, :odo,:orig,:dest,:dist);");
	query.bindValue(":date", curtime);
	query.bindValue(":odo", odometer);
	query.bindValue(":orig", curState);
	query.bindValue(":dest", toState);
	query.bindValue(":dist", dist);
	query.exec();

	// handle the undo entry
	undoStack.push(entry);
	
	// calculate the updated statistics
	query.prepare("UPDATE States SET "
		"Mileage= (SELECT SUM(Distance) FROM Crossings WHERE Origin=:state1), "
		"NumEntries= (SELECT COUNT(*) FROM Crossings WHERE Origin=:state2 AND Distance<>0) "
		"WHERE Abbrev=:state3;");
	query.bindValue(":state1", curState);
	query.bindValue(":state2", curState);
	query.bindValue(":state3", curState);
	query.exec();
	emit dataUpdated();
	
	// update the log
	addToLog(QString("%1 [%L2]: Crossed from %3 to %4, traveling %5 miles in %3.")
		.arg(QDateTime::fromTime_t(curtime).toString(dtFormat))
		.arg(odometer)
	        .arg(curState)
		.arg(toState)
		.arg(dist)
	);

	// update the widgets
	ui->dteTime->setTime( ui->dteTime->time().addSecs(60) );
	ui->comboCurState->setCurrentIndex(ui->comboToState->currentIndex());
	ui->comboToState->setCurrentIndex(0);
	ui->action_Undo->setEnabled(true);
}
コード例 #9
0
void PostSizTableForm::editRecord()
{
    if(checkingFill()){
        QTextStream stream(&exchangeFile);
        QString line;
        while(!stream.atEnd()){
            stream.readLine();
        }
        if(updateRecord){
            QSqlQuery query;
            query.prepare("UPDATE postsiz SET "
                          "postsizname = :postsizname "
                          "WHERE postsizid = :postsizid");
            query.bindValue(":postsizname",editPostSIZ->text().simplified());
            query.bindValue(":postsizid",indexTemp);
            query.exec();
            if(!query.isActive()){
                QMessageBox::warning(this,QObject::trUtf8("Post SIZ, UPDATE ERROR!"),query.lastError().text());
                return;
            }
            line += "UPDATE postsiz SET postsizname = '";
            line += editPostSIZ->text().toUtf8();
            line += "' WHERE postsizid = '";
            line += indexTemp.toUtf8();
            line += "'";
            line += "\r\n";
            stream<<line;
        }else{
            QSqlQuery query;
            query.prepare("SELECT * FROM postsiz WHERE postsizname = :postsizname");
            query.bindValue(":postsizname",editPostSIZ->text().simplified());
            query.exec();
            query.next();
            if(!query.isValid()){
                QSqlQuery queryInsert;
                queryInsert.prepare("INSERT INTO postsiz ("
                                    "postsizid, "
                                    "postsizname"
                                    ") VALUES(:postsizid, "
                                    ":postsizname"
                                    ");");
                queryInsert.bindValue(":postsizid",indexTemp);
                queryInsert.bindValue(":postsizname",editPostSIZ->text().simplified());
                queryInsert.exec();
                if(!queryInsert.isActive()){
                    QMessageBox::warning(this,QObject::trUtf8("Post SIZ, INSERT ERROR!"),queryInsert.lastError().text());
                    return;
                }
                line += "INSERT INTO postsiz (postsizid, postsizname) VALUES('";
                line += indexTemp.toUtf8();
                line += "', ";
                line += editPostSIZ->text().simplified().toUtf8();
                line += "'";
                line += "\r\n";
                stream<<line;
            }else{
                QString tempString = trUtf8("Документ Сиз-Нормы");
                tempString += editPostSIZ->text().toUtf8();
                tempString += QObject::trUtf8(" - существует!");
                QMessageBox::warning(this,QObject::trUtf8("Внимание!!!"),tempString);
            }
        }
    }
}
コード例 #10
0
void Servatrice_DatabaseInterface::storeGameInformation(const QString &roomName, const QStringList &roomGameTypes, const ServerInfo_Game &gameInfo, const QSet<QString> &allPlayersEver, const QSet<QString> &allSpectatorsEver, const QList<GameReplay *> &replayList)
{
    if (!checkSql())
        return;

    if (!settingsCache->value("game/store_replays", 1).toBool() )
        return;

    QVariantList gameIds1, playerNames, gameIds2, userIds, replayNames;
    QSetIterator<QString> playerIterator(allPlayersEver);
    while (playerIterator.hasNext()) {
        gameIds1.append(gameInfo.game_id());
        const QString &playerName = playerIterator.next();
        playerNames.append(playerName);
    }
    QSet<QString> allUsersInGame = allPlayersEver + allSpectatorsEver;
    QSetIterator<QString> allUsersIterator(allUsersInGame);
    while (allUsersIterator.hasNext()) {
        int id = getUserIdInDB(allUsersIterator.next());
        if (id == -1)
            continue;
        gameIds2.append(gameInfo.game_id());
        userIds.append(id);
        replayNames.append(QString::fromStdString(gameInfo.description()));
    }

    QVariantList replayIds, replayGameIds, replayDurations, replayBlobs;
    for (int i = 0; i < replayList.size(); ++i) {
        QByteArray blob;
        const unsigned int size = replayList[i]->ByteSize();
        blob.resize(size);
        replayList[i]->SerializeToArray(blob.data(), size);

        replayIds.append(QVariant((qulonglong) replayList[i]->replay_id()));
        replayGameIds.append(gameInfo.game_id());
        replayDurations.append(replayList[i]->duration_seconds());
        replayBlobs.append(blob);
    }

    {
        QSqlQuery *query = prepareQuery("update {prefix}_games set room_name=:room_name, descr=:descr, creator_name=:creator_name, password=:password, game_types=:game_types, player_count=:player_count, time_finished=now() where id=:id_game");
        query->bindValue(":room_name", roomName);
        query->bindValue(":id_game", gameInfo.game_id());
        query->bindValue(":descr", QString::fromStdString(gameInfo.description()));
        query->bindValue(":creator_name", QString::fromStdString(gameInfo.creator_info().name()));
        query->bindValue(":password", gameInfo.with_password() ? 1 : 0);
        query->bindValue(":game_types", roomGameTypes.isEmpty() ? QString("") : roomGameTypes.join(", "));
        query->bindValue(":player_count", gameInfo.max_players());
        if (!execSqlQuery(query))
            return;
    }
    {
        QSqlQuery *query = prepareQuery("insert into {prefix}_games_players (id_game, player_name) values (:id_game, :player_name)");
        query->bindValue(":id_game", gameIds1);
        query->bindValue(":player_name", playerNames);
        query->execBatch();
    }
    {
        QSqlQuery *query = prepareQuery("update {prefix}_replays set id_game=:id_game, duration=:duration, replay=:replay where id=:id_replay");
        query->bindValue(":id_replay", replayIds);
        query->bindValue(":id_game", replayGameIds);
        query->bindValue(":duration", replayDurations);
        query->bindValue(":replay", replayBlobs);
        query->execBatch();
    }
    {
        QSqlQuery *query = prepareQuery("insert into {prefix}_replays_access (id_game, id_player, replay_name) values (:id_game, :id_player, :replay_name)");
        query->bindValue(":id_game", gameIds2);
        query->bindValue(":id_player", userIds);
        query->bindValue(":replay_name", replayNames);
        query->execBatch();
    }
}
コード例 #11
0
ファイル: main.cpp プロジェクト: als5ev/updater
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="******"-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();
}
コード例 #12
0
QList<ServerInfo_ChatMessage> Servatrice_DatabaseInterface::getMessageLogHistory(const QString &user, const QString &ipaddress, const QString &gamename, const QString &gameid, const QString &message, bool &chat, bool &game, bool &room, int &range, int &maxresults)
{

    QList<ServerInfo_ChatMessage> results;
    ServerInfo_ChatMessage chatMessage;

    if (!checkSql())
        return results;

    // BUILD QUERY STRING BASED ON PASSED IN VALUES
    QString queryString = "SELECT * FROM {prefix}_log WHERE `sender_ip` IS NOT NULL";
    if (!user.isEmpty())
        queryString.append(" AND (`sender_name` = :user_name OR `target_name` = :user_name)");

    if (!ipaddress.isEmpty())
        queryString.append(" AND `sender_ip` = :ip_to_find");

    if (!gameid.isEmpty())
        queryString.append(" AND (`target_id` = :game_id AND `target_type` = 'game')");

    if (!gamename.isEmpty())
        queryString.append(" AND (`target_name` = :game_name AND `target_type` = 'game')");

    if (!message.isEmpty())
        queryString.append(" AND `log_message` LIKE :log_message");

    if (chat || game || room) {
        queryString.append(" AND (");

        if (chat)
            queryString.append("`target_type` = 'chat'");

        if (game) {
            if (chat)
                queryString.append(" OR `target_type` = 'game'");
            else
                queryString.append("`target_type` = 'game'");
        }

        if (room) {
            if (game || chat)
                queryString.append(" OR `target_type` = 'room'");
            else
                queryString.append("`target_type` = 'room'");
        }
        queryString.append(")");
    }

    if (range)
        queryString.append(" AND log_time >= DATE_SUB(now(), INTERVAL :range_time HOUR)");

    if (maxresults)
        queryString.append(" LIMIT :limit_size");

    QSqlQuery *query = prepareQuery(queryString);
    if (!user.isEmpty()) { query->bindValue(":user_name", user); }
    if (!ipaddress.isEmpty()) { query->bindValue(":ip_to_find", ipaddress); }
    if (!gameid.isEmpty()) { query->bindValue(":game_id", gameid); }
    if (!gamename.isEmpty()) { query->bindValue(":game_name", gamename); }
    if (!message.isEmpty()) { query->bindValue(":log_message", message); }
    if (range) { query->bindValue(":range_time", range); }
    if (maxresults) { query->bindValue(":limit_size", maxresults); }

    if (!execSqlQuery(query)) {
        qDebug("Failed to collect log history information: SQL Error");
        return results;
    }

    while (query->next()) {
        chatMessage.set_time(QString(query->value(0).toString()).toStdString());
        chatMessage.set_sender_id(QString(query->value(1).toString()).toStdString());
        chatMessage.set_sender_name(QString(query->value(2).toString()).toStdString());
        chatMessage.set_sender_ip(QString(query->value(3).toString()).toStdString());
        chatMessage.set_message(QString(query->value(4).toString()).toStdString());
        chatMessage.set_target_type(QString(query->value(5).toString()).toStdString());
        chatMessage.set_target_id(QString(query->value(6).toString()).toStdString());
        chatMessage.set_target_name(QString(query->value(7).toString()).toStdString());
        results << chatMessage;
    }

    return results;
}
コード例 #13
0
ファイル: item.cpp プロジェクト: RoskildeSkiklub/ssfh
void Item::db_reid( const QString &from_id, const QString &to_id ) {
    Logger log( "void Item::db_reid( const QString &from_id, const QString &to_id )" );
    // This method would have been a lot easier, if "label" was not the same as "id"...

    log.stream( debug ) << "Will try to reid from id '" << from_id << "' to '" << to_id << "'";

    // Source must exist, dest must not
    if ( ! db_exists( from_id ) ) {
        throw Exception( Errors::ItemDoesNotExist )
                << ( log.stream( error )
                    << "Item with id '" << from_id << " does not exist, so it can not get a new id." );
    }
    if ( db_exists( to_id ) ) {
        throw Exception( Errors::ItemAlreadyExists )
                << ( log.stream( error )
                    << "Item with id '" << to_id << " already exist, so item with id '" << from_id << "' can not get this as a new id." );
    }

    // Make sure that the temp table is not in the way, so drop it now.
    {
        log.stream( debug ) << "Dropping temporary table temp_item_reid if it exists";
        QSqlQuery query;
        log.stream( debug ) << "Query.isActive is " << query.isActive()
                            << ", isValid is " << query.isValid();
        query_check_prepare( query,
                            "drop table if exists temp_item_reid" );
        query_check_exec( query );
    }
    // Now, copy all from from_id to to_id in items, using a temporary table.
    // The temporary table is needed because of foreign key constraints...
    // Need a transaction for this.
    database_transaction( "Item::db_reid( const QString &from_id, const QString &to_id )" );
    try {
        QSqlQuery query;
        log.stream( debug ) << "Creating temporary table to insert data that needs id change into";
        query_check_prepare( query, "create temporary table temp_item_reid as select * from items where id = :from_id");
        query.bindValue( ":from_id", from_id );
        query_check_exec( query );
        // Change the id
        log.stream( debug ) << "Changing the id of the item in the temporary table";
        query_check_prepare( query, "update temp_item_reid set id = :to_id" );
        query.bindValue( ":to_id", to_id );
        query_check_exec( query );
        // Copy back, that is, insert it into items
        log.stream( debug ) << "Copying modified item back into the items table";
        query_check_prepare( query,
                            "insert into items select * from temp_item_reid" );
        query_check_exec( query );
        log.stream( debug ) << "Modifying contractitems to point at the new id";
        // Now, update contract items and itemevents, to point at the new row
        query_check_prepare( query, "update contractitems set item_id = :to_id where item_id = :from_id");
        query.bindValue( ":to_id", to_id );
        query.bindValue( ":from_id", from_id );
        query_check_exec( query );
        log.stream( debug ) << "Modifying itemevents to point at the new id";
        query_check_prepare( query, "update itemevents set item_id = :to_id where item_id = :from_id");
        query.bindValue( ":to_id", to_id );
        query.bindValue( ":from_id", from_id );
        query_check_exec( query );
        // Delete the old item row
        log.stream( debug ) << "Deleting the old item";
        query_check_prepare( query, "delete from items where id = :from_id" );
        query.bindValue( ":from_id", from_id );
        query_check_exec( query );
        // Insert an event for the new id for this
        log.stream( todo ) << "Should add an event line at this point";
        addEventLine( to_id, DB::Item::Event::reid,
                     QString( "Reid from id '%1' to id '%2' (Item::db_reid)" )
                     .arg( from_id ).arg( to_id ) );
    }
    catch( ... ) {
        log.stream( error ) << "Got some kind of error during transaction, trying rollback";
        database_rollback( "Item::db_reid( const QString &from_id, const QString &to_id ) error catcher" );
        throw;
    }
    log.stream( debug ) << "All is well, about to commit";
    database_commit( "Item::db_reid( const QString &from_id, const QString &to_id ) - all well" );
    log.stream( info ) << "Has commit item id change from id '" << from_id << "' to '" << to_id << "'";

}
コード例 #14
0
ファイル: dbmanager.cpp プロジェクト: sgranfius/sns
//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;
    }
}
コード例 #15
0
void AdminWindow::on_btn_ViewDetailTransaction_clicked()
{
    QSqlQueryModel* model = new QSqlQueryModel();
    transactionTable = new QTableView();

    QSqlQuery qr;

    float grandTotalSum = 0.0f;
    float grandDiscount = 0.0f;
    float grandVat = 0.0f;

   // qr.prepare("SELECT TransactionsDetails.TransactionID, (SUM(TransactionsDetails.SubTotal)-Transactions.discount) AS TotalSum, Transactions.discount, datetime(Transactions.period, 'unixepoch', 'localtime'), Transactions.boy, Transactions.dining FROM TransactionsDetails, Transactions WHERE Transactions.id = TransactionsDetails.TransactionID AND (datetime(period, 'unixepoch', 'localtime') >= datetime(:fromDate, 'unixepoch', 'localtime')  AND datetime(period, 'unixepoch', 'localtime') <= datetime(:toDate, 'unixepoch', 'localtime')) GROUP BY TransactionsDetails.TransactionID");
    if(userSelectedForTransaction == "ALL")
    {
        qr.prepare("SELECT TransactionsDetails.TransactionID, (SUM(TransactionsDetails.SubTotal)-((Transactions.discount*SUM(TransactionsDetails.SubTotal))/100) + ((Transactions.vat*SUM(TransactionsDetails.SubTotal))/100) ) AS TotalSum, Transactions.discount, Transactions.vat, datetime(Transactions.period, 'unixepoch', 'localtime') AS Transactions_Time, Transactions.boy, Transactions.dining, Transactions.user, Transactions.comments FROM TransactionsDetails, Transactions WHERE Transactions.id = TransactionsDetails.TransactionID AND ((datetime(period, 'unixepoch', 'localtime') >= datetime(:fromDate, 'unixepoch', 'localtime')  AND datetime(period, 'unixepoch', 'localtime') <= datetime(:toDate, 'unixepoch', 'localtime'))) GROUP BY TransactionsDetails.TransactionID");
        qr.bindValue(":toDate", QString::number(toDateTime.toTime_t()));
        qr.bindValue(":fromDate", QString::number(fromDateTime.toTime_t()));

    }


    else
    {
        qr.prepare("SELECT TransactionsDetails.TransactionID, (SUM(TransactionsDetails.SubTotal)-((Transactions.discount*SUM(TransactionsDetails.SubTotal))/100) + ((Transactions.vat*SUM(TransactionsDetails.SubTotal))/100) ) AS TotalSum, Transactions.discount, Transactions.vat, datetime(Transactions.period, 'unixepoch', 'localtime') AS Transactions_Time, Transactions.boy, Transactions.dining, Transactions.user, Transactions.comments FROM TransactionsDetails, Transactions WHERE Transactions.id = TransactionsDetails.TransactionID AND ((datetime(period, 'unixepoch', 'localtime') >= datetime(:fromDate, 'unixepoch', 'localtime')  AND datetime(period, 'unixepoch', 'localtime') <= datetime(:toDate, 'unixepoch', 'localtime')) AND user = :user) GROUP BY TransactionsDetails.TransactionID");
        qr.bindValue(":toDate", QString::number(toDateTime.toTime_t()));
        qr.bindValue(":fromDate", QString::number(fromDateTime.toTime_t()));
        qr.bindValue(":user", userSelectedForTransaction);

    }


   // qr.prepare("SELECT * FROM Transactions WHERE datetime(period, 'unixepoch', 'localtime') >= datetime(:curr, 'unixepoch', 'localtime')");
  //  qr.bindValue(":curr",QString::number(QDateTime::currentDateTime().toTime_t()));
   // qr.bindValue(":unixepoch", "unixepoch");
    bool r = qr.exec();
    if(r)
    {
           model->setQuery(qr);
           transactionTable->setModel(model);

           int count = transactionTable->model()->rowCount();
           for(int i=0; i<count; i++)
           {

               float sum =  transactionTable->model()->data(transactionTable->model()->index(i,1)).toFloat();
               float dis =  transactionTable->model()->data(transactionTable->model()->index(i,2)).toFloat();
               float vat =  transactionTable->model()->data(transactionTable->model()->index(i,3)).toFloat();

               grandTotalSum += sum;

               grandDiscount += ((sum*100)/(100-dis))*(dis/100);
               grandVat += ((sum*100)/(100+vat))*(vat/100);



           }



//        while(qr.next())
//        {
//            qDebug()<<"nazib.........";

//            grandTotalSum += qr.record().value("TotalSum").toFloat();

//            qDebug()<< qr.record().value("TotalSum").toString();
//            qDebug()<< qr.record().value("TransactionID").toString();
//            qDebug()<< qr.record().value("period").toString();
//            qDebug()<< qr.record().value("boy").toString();
//            qDebug()<< qr.record().value("dining").toString();


//        }

           ui->lbl_totalSum->setText("Total : "+QString::number(grandTotalSum)+" <----> Total Discount: "+QString::number(grandDiscount)+" <----> Total Vat: "+QString::number(grandVat));

         grandTotalSum = 0.0f;
         grandDiscount = 0.0f;
         grandVat = 0.0f;

        connect(transactionTable, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(onTransactionTableDoubleClicked(QModelIndex)), Qt::UniqueConnection);

        transactionTable->resizeColumnsToContents();
        transactionTable->horizontalHeader()->setStretchLastSection(true);
        ui->scrollArea_Detail->setWidget(transactionTable);

    }
    else
    {
        qDebug()<<qr.lastError();
    }
}
コード例 #16
0
void PostSizTableForm::addRecordOfTable()
{
    if(checkingFill()){
        QTextStream stream(&exchangeFile);
        QString line;
        while(!stream.atEnd()){
            stream.readLine();
        }

        ViewListTable listTable("","siznaim",this);
        listTable.exec();
        QString postId = listTable.returnValue();

        QSqlQuery query;
        query.prepare("SELECT * FROM siznaim WHERE siznaimid = :id");
        query.bindValue(":id",postId);
        query.exec();
        while(query.next()){
            int rowCount = sizView->rowCount();
            bool insert = true;
            //Проверка на существование записи
            if (rowCount != 0){
                for(int kk = 0; kk < rowCount; ++kk){
                    QString yy = sizView->item(kk,0)->text();
                    QString pp = query.value(0).toString();
                    if(yy == pp){
                        QString tempString = query.value(1).toString();
                        tempString += QObject::trUtf8(" is availble!");
                        QMessageBox::warning(this,QObject::trUtf8("Atention!!!"),tempString);
                        insert = false;
                        break;
                    }
                }
            }
            if(insert){
//                addIntoTable = true;
//                sizView->insertRow(rowCount);

//                QTableWidgetItem *itemID = new QTableWidgetItem;
//                postView->setItem(rowCount,1,itemID);
//                postView->item(rowCount,1)->setText(query.value(0).toString());

//                QTableWidgetItem *itemName = new QTableWidgetItem;
//                //itemName->setTextAlignment(Qt::AlignCenter);
//                postView->setItem(rowCount,2,itemName);
//                postView->item(rowCount,3)->setText(query.value(1).toString());

//                NumPrefix numPrefix;
//                QString idPostSizList = numPrefix.getPrefix("postsiztable");

//                QSqlQuery queryPSL;
//                queryPSL.prepare("INSERT INTO postsizlist ("
//                                "postsizlistid, postsizid, postid"
//                                ") VALUES(:postsizlistid, :postsizid, :postid)");
//                queryPSL.bindValue(":postsizlistid",idPostSizList);
//                queryPSL.bindValue(":postsizid",indexTemp);
//                queryPSL.bindValue(":postid",query.value(0).toString());
//                queryPSL.exec();
//                if(!queryPSL.isActive()){
//                    QMessageBox::warning(this,QObject::trUtf8("Post SIZ List Table, INSERT ERROR!"),queryPSL.lastError().text());
//                    return;
//                }
//                line += "INSERT INTO postsizlist (postsizlistid, postsizid, postid) VALUES('";
//                line += idPostSizList.toUtf8();
//                line += "', '";
//                line += indexTemp.toUtf8();
//                line += "', '";
//                line += query.value(0).toString().toUtf8();
//                line += "')";
//                line += "\r\n";
//                stream<<line;
            }
        }
    }
}
コード例 #17
0
ファイル: itunesfeature.cpp プロジェクト: MK-42/mixxx
void ITunesFeature::parseTrack(QXmlStreamReader &xml, QSqlQuery &query) {
    //qDebug() << "----------------TRACK-----------------";
    int id = -1;
    QString title;
    QString artist;
    QString album;
    QString album_artist;
    QString year;
    QString genre;
    QString grouping;
    QString location;

    int bpm = 0;
    int bitrate = 0;

    //duration of a track
    int playtime = 0;
    int rating = 0;
    QString comment;
    QString tracknumber;
    QString tracktype;

    while (!xml.atEnd()) {
        xml.readNext();

        if (xml.isStartElement()) {
            if (xml.name() == "key") {
                QString key = xml.readElementText();

                QString content;
                if (readNextStartElement(xml)) {
                    content = xml.readElementText();
                }

                //qDebug() << "Key: " << key << " Content: " << content;

                if (key == "Track ID") {
                    id = content.toInt();
                    continue;
                }
                if (key == "Name") {
                    title = content;
                    continue;
                }
                if (key == "Artist") {
                    artist = content;
                    continue;
                }
                if (key == "Album") {
                    album = content;
                    continue;
                }
                if (key == "Album Artist") {
                    album_artist = content;
                    continue;
                }
                if (key == "Genre") {
                    genre = content;
                    continue;
                }
                if (key == "Grouping") {
                    grouping = content;
                    continue;
                }
                if (key == "BPM") {
                    bpm = content.toInt();
                    continue;
                }
                if (key == "Bit Rate") {
                    bitrate =  content.toInt();
                    continue;
                }
                if (key == "Comments") {
                    comment = content;
                    continue;
                }
                if (key == "Total Time") {
                    playtime = (content.toInt() / 1000);
                    continue;
                }
                if (key == "Year") {
                    year = content;
                    continue;
                }
                if (key == "Location") {
                    QByteArray strlocbytes = content.toUtf8();
                    location = QUrl::fromEncoded(strlocbytes).toLocalFile();
                    // Replace first part of location with the mixxx iTunes Root
                    // on systems where iTunes installed it only strips //localhost
                    // on iTunes from foreign systems the mount point is replaced
                    if (!m_dbItunesRoot.isEmpty()) {
                        location.replace(m_dbItunesRoot, m_mixxxItunesRoot);
                    }
                    continue;
                }
                if (key == "Track Number") {
                    tracknumber = content;
                    continue;
                }
                if (key == "Rating") {
                    //value is an integer and ranges from 0 to 100
                    rating = (content.toInt() / 20);
                    continue;
                }
                if (key == "Track Type") {
                    tracktype = content;
                    continue;
                }
            }
        }
        //exit loop on closing </dict>
        if (xml.isEndElement() && xml.name() == "dict") {
            break;
        }
    }

    // If file is a remote file from iTunes Match, don't save it to the database.
    // There's no way that mixxx can access it.
    if (tracktype == "Remote") {
        return;
    }

    // If we reach the end of <dict>
    // Save parsed track to database
    query.bindValue(":id", id);
    query.bindValue(":artist", artist);
    query.bindValue(":title", title);
    query.bindValue(":album", album);
    query.bindValue(":album_artist", album_artist);
    query.bindValue(":genre", genre);
    query.bindValue(":grouping", grouping);
    query.bindValue(":year", year);
    query.bindValue(":duration", playtime);
    query.bindValue(":location", location);
    query.bindValue(":rating", rating);
    query.bindValue(":comment", comment);
    query.bindValue(":tracknumber", tracknumber);
    query.bindValue(":bpm", bpm);
    query.bindValue(":bitrate", bitrate);

    bool success = query.exec();

    if (!success) {
        LOG_FAILED_QUERY(query);
        return;
    }
}
コード例 #18
0
PostSizTableForm::PostSizTableForm(QString id, QWidget *parent, bool onlyForRead) : QDialog(parent)
{
    exchangeFile.setFileName("Message.txt");
    if(!exchangeFile.isOpen()){
        exchangeFile.open(QIODevice::ReadWrite);
    }
    indexTemp = id;
    addIntoTable = false;

    QFile file(":/ToolButtonStyle.txt");
    file.open(QFile::ReadOnly);
    QVBoxLayout *labelLayout = new QVBoxLayout;
    QVBoxLayout *editLayout = new QVBoxLayout;

    //**********************************************************
    //SIZ
    //**********************************************************
    labelPostSIZ = new QLabel(trUtf8("PostSIZ Name:"));
    editPostSIZ = new LineEdit;
    editPostSIZ->setReadOnly(onlyForRead);
    QRegExp regExpFamiliya("[\\x0410-\\x044f 0-9 \" -]{150}");
    editPostSIZ->setValidator(new QRegExpValidator(regExpFamiliya,this));
    labelPostSIZ->setBuddy(editPostSIZ);

    labelLayout->addWidget(labelPostSIZ);
    editLayout->addWidget(editPostSIZ);


    savePushButton = new QPushButton(trUtf8("Save"));
    connect(savePushButton,SIGNAL(clicked()),this,SLOT(saveRecord()));
    savePushButton->setToolTip(trUtf8("Save And Close Button"));

    cancelPushButton = new QPushButton(trUtf8("Cancel"));
    cancelPushButton->setDefault(true);
    cancelPushButton->setStyleSheet("QPushButton:hover {color: red}");
    connect(cancelPushButton,SIGNAL(clicked()),this,SLOT(cancelRecord()));
    cancelPushButton->setToolTip(trUtf8("Cancel Button"));

    buttonBox = new QDialogButtonBox;
    buttonBox->addButton(cancelPushButton,QDialogButtonBox::ActionRole);
    buttonBox->addButton(savePushButton,QDialogButtonBox::ActionRole);

    QPushButton *addTableButton = new QPushButton(trUtf8("Add"));
    QPixmap pixAdd(":/add.png");
    addTableButton->setIcon(pixAdd);
    connect(addTableButton,SIGNAL(clicked()),this,SLOT(addRecordOfTable()));

    QPushButton *deleteTableButton = new QPushButton(trUtf8("Delete"));
    QPixmap pixDelete(":/delete.png");
    deleteTableButton->setIcon(pixDelete);
    connect(deleteTableButton,SIGNAL(clicked()),this,SLOT(deleteRecordOfTable()));

    QPushButton *editTableButton = new QPushButton(trUtf8("Edit"));
    QPixmap pixEdit(":/edit.png");
    editTableButton->setIcon(pixEdit);
    connect(editTableButton,SIGNAL(clicked()),this,SLOT(editRecordOfTable()));

    QHBoxLayout *buttonTableBox = new QHBoxLayout;
    buttonTableBox->addWidget(addTableButton);
    buttonTableBox->addWidget(deleteTableButton);
    buttonTableBox->addWidget(editTableButton);
    buttonTableBox->addStretch();

    //*****************************************************
    //SIZ TableView
    //*****************************************************
    sizView = new QTableWidget(0,6);
    sizView->setHorizontalHeaderLabels(QStringList()<<trUtf8("ID")<<trUtf8("P")<<trUtf8("Наименование СИЗ")<<
                                       trUtf8("Характеристика")<<trUtf8("Количество")<<trUtf8("Срок"));
    sizView->hideColumn(0);
    sizView->hideColumn(1);
    sizView->setColumnWidth(2,300);
    sizView->setColumnWidth(3,300);
    sizView->setAlternatingRowColors(true);
    QHeaderView *head = sizView->horizontalHeader();
    head->setStretchLastSection(true);
    sizView->setSelectionMode(QAbstractItemView::SingleSelection);
    sizView->setSelectionBehavior(QAbstractItemView::SelectRows);
    sizView->setEditTriggers(QAbstractItemView::NoEditTriggers);

    if(indexTemp != ""){
        QSqlQuery query;
        query.prepare("SELECT postsizname FROM postsiz WHERE postsizid = :postsizid");
        query.bindValue(":postsizid",indexTemp);
        query.exec();
        query.next();
        editPostSIZ->setText(query.value(0).toString());
        //editPostSIZ->setReadOnly(true);
        QSqlQuery queryTable;
        queryTable.prepare("SELECT(SELECT siznaim.siznaimname FROM siznaim WHERE siznaim.siznaimid ="
                           " postsiztable.siznaimid),(SELECT har.harname FROM har WHERE har.harid = "
                           "postsiztable.harid), kolvo, srok FROM postsiztable WHERE "
                           "postsiztable.postsizid = :postsizid");
        queryTable.bindValue(":postsizid",indexTemp);
        queryTable.exec();
        int rowCount = 0;
        while(queryTable.next()){
            sizView->insertRow(rowCount);
            QTableWidgetItem *itemName = new QTableWidgetItem;
            sizView->setItem(rowCount,2,itemName);
            sizView->item(rowCount,2)->setText(queryTable.value(0).toString());

            QTableWidgetItem *itemHar = new QTableWidgetItem;
            sizView->setItem(rowCount,3,itemHar);
            sizView->item(rowCount,3)->setText(queryTable.value(1).toString());

            QTableWidgetItem *itemKol = new QTableWidgetItem;
            sizView->setItem(rowCount,4,itemKol);
            sizView->item(rowCount,4)->setText(queryTable.value(2).toString());

            QTableWidgetItem *itemSrok = new QTableWidgetItem;
            sizView->setItem(rowCount,5,itemSrok);
            sizView->item(rowCount,5)->setText(queryTable.value(3).toString());
        }
    }else{
        editPostSIZ->clear();
        NumPrefix numPrefix;
        indexTemp = numPrefix.getPrefix("postsiz");
        updateRecord = false;

    }

    QGridLayout *mainLayout = new QGridLayout;
    mainLayout->addLayout(labelLayout,0,0);
    mainLayout->addLayout(editLayout,0,1);
    mainLayout->addLayout(buttonTableBox,2,0,1,2);
    mainLayout->addWidget(sizView,3,0,1,2);
    if(!onlyForRead){
        mainLayout->addWidget(buttonBox,4,1);
        editPostSIZ->selectAll();
    }

    setLayout(mainLayout);

    setWindowTitle(trUtf8("Нормы СИЗ"));
    readSettings();
}
コード例 #19
0
ファイル: main.cpp プロジェクト: Wushaowei001/xtuple
int main(int argc, char *argv[])
{
  QCoreApplication application(argc, argv);
  application.addLibraryPath(".");

  QTextStream out(stdout, QIODevice::WriteOnly);

  if (application.argc() > 1)
  {
    QString databaseURL;
    QString username;
    QString passwd;
    QString arguments;

    QString xml_file = QString::null;
    int     report_grade = 0;

    for (int counter = 1; counter < application.argc(); counter++)
    {
      QString arguments(application.argv()[counter]);

      if (arguments.startsWith("-databaseURL=", Qt::CaseInsensitive))
        databaseURL = arguments.right(arguments.length() - 13);
      else if (arguments.startsWith("-username="******"-passwd=", Qt::CaseInsensitive))
        passwd = arguments.right(arguments.length() - 8);
      else if (arguments.startsWith("-f=", Qt::CaseInsensitive))
        xml_file = arguments.right(arguments.length() - 3);
      else if (arguments.startsWith("-grade=", Qt::CaseInsensitive))
        report_grade = (arguments.right(arguments.length() - 7)).toInt();
      else if(!arguments.startsWith("-"))
        xml_file = arguments;
    }

    QString report_name = QString::null;
    QString report_desc = QString::null;
    QString report_src  = QString::null;

    if(xml_file != "") {
        QFile file(xml_file);
        if(file.open( QIODevice::ReadOnly )) {
            QDomDocument doc;
            QString errMsg;
            int errLine, errCol;
            if(doc.setContent(&file, &errMsg, &errLine, &errCol)) {
                QDomElement root = doc.documentElement();
                if(root.tagName() == "report") {
                    for(QDomNode n = root.firstChild();
                            !n.isNull(); n = n.nextSibling() ) {
                        if(n.nodeName() == "name") {
                            report_name = n.firstChild().nodeValue();
                        } else if(n.nodeName() == "description") {
                            report_desc = n.firstChild().nodeValue();
                        }
                    }
                    report_src  = doc.toString();

                    if(report_name == "") {
                        out << "The document " << xml_file << " does not have a report name defined." << endl;
                    }
                } else {
                    out << "XML Document " << xml_file << " does not have root node of report." << endl;
                }
            } else {
                out << "Error parsing file " << xml_file << ": " << errMsg << " on line " << errLine << " column " << errCol << endl;
            }
        } else {
            out << "Could not open the specified file: " << xml_file << endl;
        }
    } else {
        out << "You must specify an XML file to load by using the -f= parameter." << endl;
    }

    if(report_name == "" || report_src == "") {
        // an error message already should have been displayed to the user
        exit(-1);
    }

    if (  (databaseURL != "") &&
          (username != "")    &&
          (passwd != "")          ) {
      QSqlDatabase db;

// Open the Database Driver
      db = databaseFromURL( databaseURL );
      if (!db.isValid())
      {
        out << "Could not load the specified database driver." << endl;
        exit(-1);
      }

//  Try to connect to the Database
      db.setUserName(username);
      db.setPassword(passwd);
      if (!db.open())
      {
        out << "Host=" << db.hostName() << ", Database=" << db.databaseName() << ", port=" << db.port() << endl;
        out << "Could not log into database.  System Error: "
            << db.lastError().text() << endl;
        exit(-1);
      }

      QSqlQuery().exec(getSqlFromTag("fmt05", db.driverName()));		// MANU

      // first we need to determine if there is already a report in the database of the same
      // name and if so then we will perform an update instead of an insert
      QSqlQuery qry;
      qry.prepare(getSqlFromTag("fmt09", db.driverName()));		// MANU
      qry.bindValue(":report_name", report_name);
      qry.bindValue(":report_grade", report_grade);
      qry.exec();
      QSqlQuery query;
      if(qry.first()) {
          // update
          query.prepare(getSqlFromTag("fmt10", db.driverName()));		// MANU
          query.bindValue(":report_desc", report_desc);
          query.bindValue(":report_src", report_src);
          query.bindValue(":report_id", qry.value(0));
          query.bindValue(":report_name", report_name);
      } else {
          // insert
          query.prepare(getSqlFromTag("fmt11", db.driverName()));		// MANU
          query.bindValue(":report_name", report_name);
          query.bindValue(":report_desc", report_desc);
          query.bindValue(":report_src", report_src);
          query.bindValue(":report_grade", report_grade);
      }
      
      if(!query.exec()) {
          QSqlError err = query.lastError();
          out << "Error: " << err.driverText() << endl
              << "\t" << err.databaseText() << endl;
          exit(-1);
      }
      
    }
    else if (databaseURL == "")
      out << "You must specify a Database URL by using the -databaseURL= parameter." << endl;
    else if (username == "")
      out << "You must specify a Database Username by using the -username= parameter." << endl;
    else if (passwd == "")
      out << "You must specify a Database Password by using the -passwd= parameter." << endl;
  }
  else
    out << "Usage: import -databaseURL='$' -username='******' -passwd='$' -grade=# -f='$'" << endl;
  return 0;
}
コード例 #20
0
void DetailsInfo::alterOkBtnClicked()
{
    if (!base->isOpen())
    {
        QMessageBox::about(this, tr("error"), tr("void DetailsInfo::setInfo(QString number)"));
        return;
    }

    if(QMessageBox::No == QMessageBox::information(this, tr("提示"), tr("确认提交"), QMessageBox::Yes, QMessageBox::No))
    {
        return;
    }

    QSqlQuery query;
    //------------------------------------------------------------------------------------------------------------------------------------
    int ok = query.prepare(tr("update studentInfo set 学号=?,姓名=?,性别=?,学校=?,系=?,专业=?,班级=?,教育等级=?,电话=? "
                     "where 学号=%1").arg(numberInfo));
    if (ok == false)
    {
        QMessageBox::about(this, tr("error"), tr("void DetailsInfo::alterOkBtnClicked()\nstudentInfo query is error"));
        return;
    }
    query.bindValue(0, numberLe->text().toInt());
    query.bindValue(1, nameLe->text());
    query.bindValue(2, sexLe->text());
    query.bindValue(3, schoolNameLe->text());
    query.bindValue(4, departmentNameLe->text());
    query.bindValue(5, majorNameLe->text());
    query.bindValue(6, classNameLe->text());
    query.bindValue(7, educationLe->text());
    query.bindValue(8, phoneNumberLe->text());
    if(!query.exec())
    {
        QMessageBox::about(this, tr("error"), tr("void DetailsInfo::alterOkBtnClicked()\nupdate studentInfo is error\n%1").arg(query.lastError().text()));
        return;
    }
    query.clear();

    //------------------------------------------------------------------------------------------------------------------------------------
    ok = query.prepare(tr("update studentDetailsInfo set 民族=?,籍贯=?,住址=?,出生日期=?,政治面貌=?,外语等级=?,QQ号码=?,电子邮箱=?,备注=? "
                     "where 学号=%1").arg(numberInfo));
    if (ok == false)
    {
        QMessageBox::about(this, tr("error"), tr("void DetailsInfo::alterOkBtnClicked()\nstudentDetailsInfo query is error"));
        return;
    }
    query.bindValue(0, nationLe->text());
    query.bindValue(1, nationPlaceLe->text());
    query.bindValue(2, addressLe->text());
    query.bindValue(3, birthdayLe->text());
    query.bindValue(4, politicalLe->text());
    query.bindValue(5, languageLevelLe->text());
    query.bindValue(6, qqNumberLe->text());
    query.bindValue(7, emailLe->text());
    query.bindValue(8, remarkTe->toPlainText());
    if(!query.exec())
    {
        QMessageBox::about(this, tr("error"), tr("void DetailsInfo::alterOkBtnClicked()\nupdate studentDetailsInfo is error\n%1").arg(query.lastError().text()));
        return;
    }
    query.clear();

    //------------------------------------------------------------------------------------------------------------------------------------
    const QPixmap *pix = photoLb->pixmap();
    if(pix != NULL && !pix->isNull())
    {
        QByteArray byte;
        QBuffer buf(&byte);
        buf.open(QIODevice::WriteOnly);
        if (!pix->save(&buf, "JPG"))
        {
            QMessageBox::about(this, tr("error"), tr("void DetailsInfo::alterOkBtnClicked()\nupdate studentImage is error\n%1").arg(query.lastError().text()));
        }
        buf.close();
        ok = query.prepare(tr("update studentImage set 照片=? "
                         "where 学号=%1").arg(numberInfo));
        if (ok == false)
        {
            QMessageBox::about(this, tr("error"), tr("void DetailsInfo::alterOkBtnClicked()\nstudentImage query is error"));
            return;
        }
        query.bindValue(0, byte);
        if(!query.exec())
        {
            QMessageBox::about(this, tr("error"), tr("void DetailsInfo::alterOkBtnClicked()\nupdate studentImage is error\n%1").arg(query.lastError().text()));
            return;
        }
    }
    this->setReadOnly(true);
}
コード例 #21
0
void DBWorker::removeHistoryEntry(int linkId)
{
    QSqlQuery query = prepare("DELETE FROM browser_history WHERE id = ?");
    query.bindValue(0, linkId);
    execute(query);
}
コード例 #22
0
ファイル: numbercycledialog.cpp プロジェクト: dragotin/kraft
void NumberCycleDialog::accept()
{
  // qDebug () << "Slot Ok hit";

  // get the changed stuff from the gui elements
  updateCycleDataFromGUI();

  // First remove the dropped cycles
  if ( mRemovedCycles.count() > 0 ) {
    QSqlQuery qDel;
    qDel.prepare( "DELETE FROM numberCycles WHERE name=:name" );
    for ( QStringList::Iterator it = mRemovedCycles.begin();
          it != mRemovedCycles.end(); ++it ) {
      // qDebug () << "about to drop the number cycle " << *it;
      if ( dropOfNumberCycleOk( *it ) ) {
        qDel.bindValue( ":name", *it );
        qDel.exec();
      }
    }
  }

  // update existing entries and insert new ones
//  CREATE TABLE numberCycles (
//    id INTEGER PRIMARY KEY ASC autoincrement,
//    name VARCHAR(64) NOT NULL,
//    lastIdentNumber  INT NOT NULL,
//    identTemplate VARCHAR(64) NOT NULL
//  );

  QSqlQuery q;
  q.prepare( "SELECT id, name, lastIdentNumber, identTemplate FROM numberCycles WHERE name=:name" );
  QMap<QString, NumberCycle>::Iterator it;
  for ( it = mNumberCycles.begin(); it != mNumberCycles.end(); ++it ) {
    QString cycleName = it.key();
    NumberCycle cycle = it.value();

    q.bindValue( ":name", cycleName );
    // name changes can not happen by design
    q.exec();
    if ( q.next() ) {
        // qDebug () << "Checking existing number cycle " << cycleName << " for update";
        // there is an entry
        if ( q.value( 2 ).toInt() != cycle.counter() ) {
            bool doUpdate = true;
            if ( q.value( 2 ).toInt() > cycle.counter() ) {
                if ( q.value( 3 ).toString() == cycle.getTemplate() ) {
                    // The number has become smaller but the template remains the same.
                    // That has high potential to end up with duplicate doc numbers.
                    QMessageBox msgBox;
                    msgBox.setWindowTitle(i18n("Dangerous Counter Change"));
                    msgBox.setText(i18n("The new counter is lower than the old one. " ));
                    msgBox.setInformativeText(i18n("That has potential to create duplicate document numbers. Do you really want to decrease it?" ));

                    msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
                    msgBox.setDefaultButton( QMessageBox::Yes );

                    int re = msgBox.exec();
                    if( re != QMessageBox::Yes ) {
                        doUpdate = false;
                    }
                }
            }
            if ( doUpdate ) {
                updateField( q.value( 0 ).toInt(),
                             "lastIdentNumber", QString::number( cycle.counter() ) );
            }
        }
        if ( q.value( 3 ).toString() != cycle.getTemplate() ) {
            updateField( q.value( 0 ).toInt(), "identTemplate", cycle.getTemplate() );
        }
    } else {
        // qDebug () << "This number cycle is new: " << cycleName;
        QSqlQuery qIns;
        qIns.prepare( "INSERT INTO numberCycles (name, lastIdentNumber, identTemplate) "
                      "VALUES (:name, :number, :templ)" );

        qIns.bindValue( ":name", cycleName );
        qIns.bindValue( ":number", cycle.counter() );
        qIns.bindValue( ":templ", cycle.getTemplate() );

        qIns.exec();
    }
  }
  QDialog::accept();
}
コード例 #23
0
ファイル: qgsdb2provider.cpp プロジェクト: mterente/QGIS
bool QgsDb2Provider::addFeatures( QgsFeatureList & flist )
{
  QgsDebugMsg( "mGeometryColType: " + mGeometryColType );
  int writeCount = 0;
  bool copyOperation = false;

  if ( !mDatabase.isOpen() )
  {
    QString errMsg;
    mDatabase = getDatabase( mConnInfo, errMsg );
    if ( !errMsg.isEmpty() )
    {
      QgsDebugMsg( "getDatabase failed: " + errMsg );
      return false;
    }
  }
  if ( !mDatabase.transaction() )
  {
    QgsDebugMsg( "transaction failed" );
    return false;
  }
  QSqlQuery query = QSqlQuery( mDatabase );
  query.setForwardOnly( true );
  QSqlQuery queryFid = QSqlQuery( mDatabase );
  queryFid.setForwardOnly( true );

  QgsFeature it = flist.at( 0 );
  QString statement;
  QString values;
  statement = QString( "INSERT INTO %1.%2 (" ).arg( mSchemaName, mTableName );

  bool first = true;

// Get the first geometry and its wkbType as when we are doing drag/drop,
// the wkbType is not passed to the DB2 provider from QgsVectorLayerImport
// Can't figure out how to resolved "unreferenced" wkbType compile message
// Don't really do anything with it at this point
#if 0
  QgsGeometry *geom = it.geometry();
  QgsWkbTypes::Type wkbType = geom->wkbType();
  QgsDebugMsg( QString( "wkbType: %1" ).arg( wkbType ) );
  QgsDebugMsg( QString( "mWkbType: %1" ).arg( mWkbType ) );
#endif

  QgsAttributes attrs = it.attributes();
  QgsDebugMsg( QString( "attrs.count: %1" ).arg( attrs.count() ) );
  QgsDebugMsg( QString( "fields.count: %1" ).arg( mAttributeFields.count() ) );
  if ( mAttributeFields.count() == ( attrs.count() + 1 ) )
  {
    copyOperation = true; // FID is first field but no attribute in attrs
  }
  else if ( mAttributeFields.count() !=  attrs.count() )
  {
    QgsDebugMsg( "Count mismatch - failing" );
    return false;
  }


  if ( attrs.count() != mAttributeFields.count() )
  {
    QgsDebugMsg( "field counts don't match" );
//  return false;
  }

  for ( int i = 0; i < mAttributeFields.count(); ++i )
  {
    QgsField fld = mAttributeFields.at( i );
    QgsDebugMsg( QString( "i: %1; got field: %2" ).arg( i ).arg( fld.name() ) );

    if ( fld.name().isEmpty() )
      continue; // invalid

    if ( mFidColName == fld.name() )
      continue; // skip identity field

//      if ( mDefaultValues.contains( i ) && mDefaultValues[i] == attrs.at( i ) )
//        continue; // skip fields having default values

    if ( !first )
    {
      statement += ',';
      values += ',';
    }
    else
      first = false;

    statement += QString( "%1" ).arg( fld.name() );
    values += QString( "?" );
  }

  // append geometry column name
  if ( !mGeometryColName.isEmpty() )
  {
    if ( !first )
    {
      statement += ',';
      values += ',';
    }

    statement += QString( "%1" ).arg( mGeometryColName );

    values += QString( "db2gse.%1(CAST (%2 AS BLOB(2M)),%3)" )
              .arg( mGeometryColType,
                    QString( "?" ),
                    QString::number( mSRId ) );
  }

  QgsDebugMsg( statement );
  QgsDebugMsg( values );
  statement += ") VALUES (" + values + ')';
  QgsDebugMsg( statement );

  QgsDebugMsg( "Prepare statement" );
  // use prepared statement to prevent from sql injection
  if ( !query.prepare( statement ) )
  {
    QString msg = query.lastError().text();
    QgsDebugMsg( msg );
    pushError( msg );
    return false;
  }


  for ( QgsFeatureList::iterator it = flist.begin(); it != flist.end(); ++it )
  {
    attrs = it->attributes();

    int fieldIdx = 0;
    if ( copyOperation )
    {
      fieldIdx = 1;  // skip first (FID) field if copying from shapefile
    }
    int bindIdx = 0;
    for ( int i = 0; i < attrs.count(); i++ )
    {
      QgsField fld = mAttributeFields.at( fieldIdx++ );
      if ( fld.name().isEmpty() )
        continue; // invalid

      if ( mFidColName == fld.name() )
        continue; // skip identity field

//      if ( mDefaultValues.contains( i ) && mDefaultValues[i] == attrs.at( i ) )
//        continue; // skip fields having default values

      QVariant::Type type = fld.type();
      if ( attrs.at( i ).isNull() || !attrs.at( i ).isValid() )
      {
        // binding null values
        if ( type == QVariant::Date || type == QVariant::DateTime )
          query.bindValue( bindIdx,  QVariant( QVariant::String ) );
        else
          query.bindValue( bindIdx,  QVariant( type ) );
      }
      else if ( type == QVariant::Int )
      {
        // binding an INTEGER value
        query.bindValue( bindIdx,  attrs.at( i ).toInt() );
      }
      else if ( type == QVariant::Double )
      {
        // binding a DOUBLE value
        query.bindValue( bindIdx,  attrs.at( i ).toDouble() );
      }
      else if ( type == QVariant::String )
      {
        // binding a TEXT value
        query.bindValue( bindIdx,  attrs.at( i ).toString() );
      }
      else if ( type == QVariant::Time )
      {
        // binding a TIME value
        query.bindValue( bindIdx,  attrs.at( i ).toTime().toString( Qt::ISODate ) );
      }
      else if ( type == QVariant::Date )
      {
        // binding a DATE value
        query.bindValue( bindIdx,  attrs.at( i ).toDate().toString( Qt::ISODate ) );
      }
      else if ( type == QVariant::DateTime )
      {
        // binding a DATETIME value
        query.bindValue( bindIdx,  attrs.at( i ).toDateTime().toString( Qt::ISODate ) );
      }
      else
      {
        query.bindValue( bindIdx,  attrs.at( i ) );
      }

#if 0
      QgsDebugMsg( QString( "bound i: %1; name: %2; value: %3; bindIdx: %4" ).
                   arg( i ).arg( fld.name() ).arg( attrs.at( i ).toString() ).arg( bindIdx ) );
#endif
      bindIdx++;
    }

    if ( !mGeometryColName.isEmpty() )
    {
      QgsGeometry geom = it->geometry();

      QByteArray bytea = QByteArray(( char* )geom.asWkb(), ( int ) geom.wkbSize() );
      query.bindValue( bindIdx,  bytea, QSql::In | QSql::Binary );
    }

    QList<QVariant> list = query.boundValues().values();

// Show bound values
#if 0
    for ( int i = 0; i < list.size(); ++i )
    {
      QgsDebugMsg( QString( "i: %1; value: %2; type: %3" )
                   .arg( i ).arg( list.at( i ).toString().toLatin1().data() ).arg( list.at( i ).typeName() ) );
    }
#endif
    if ( !query.exec() )
    {
      QString msg = query.lastError().text();
      QgsDebugMsg( msg );
      if ( !mSkipFailures )
      {
        pushError( msg );
        return false;
      }
    }

    statement = QString( "select IDENTITY_VAL_LOCAL() AS IDENTITY "
                         "FROM SYSIBM.SYSDUMMY1" );
//    QgsDebugMsg( statement );
    if ( !queryFid.exec( statement ) )
    {
      QString msg = query.lastError().text();
      QgsDebugMsg( msg );
      if ( !mSkipFailures )
      {
        pushError( msg );
        return false;
      }
    }

    if ( !queryFid.next() )
    {
      QString msg = query.lastError().text();
      QgsDebugMsg( msg );
      if ( !mSkipFailures )
      {
        pushError( msg );
        return false;
      }
    }
    it->setFeatureId( queryFid.value( 0 ).toLongLong() );
    writeCount++;
//    QgsDebugMsg( QString( "count: %1; featureId: %2" ).arg( writeCount ).arg( queryFid.value( 0 ).toLongLong() ) );
  }
  bool commitStatus = mDatabase.commit();
  QgsDebugMsg( QString( "commitStatus: %1; write count: %2; featureId: %3" )
               .arg( commitStatus ).arg( writeCount ).arg( queryFid.value( 0 ).toLongLong() ) );
  if ( !commitStatus )
  {
    pushError( "Commit of new features failed" );
    return false;
  }
  return true;
}
コード例 #24
0
ファイル: commandtake.cpp プロジェクト: jmlemetayer/apm
void CommandTake::run()
{
	if(!parseData()) {
		fail("Failed to parse command");
		return;
	}

	/** Check the arguments */
	if(!m_jsonData.contains("uid") ||
	   !m_jsonData.contains("session") ||
	   !m_jsonData.contains("hours")) {
		fail("Bad request");
		return;
	}

	quint32 ap_uid = m_jsonData["uid"].toUInt();
	QString owner_session = m_jsonData["session"].toString();
	quint32 ap_hours = m_jsonData["hours"].toUInt();

	/** Get AP and PWSW datas */
	QString queryString;
	queryString += "SELECT P.product_uid, P.node, P.username, P.password, ";
	queryString += "D.size, A.switch, A.state ";
	queryString += "FROM pwsw_product D ";
	queryString += "JOIN pwsw P ON D.uid = P.product_uid ";
	queryString += "JOIN ap A ON P.uid = A.pwsw_uid ";
	queryString += "WHERE A.uid=:uid";

	QSqlQuery query;
	query.prepare(queryString);
	query.bindValue(":uid", ap_uid);

	if(!query.exec()) {
		fail("Database error: " + query.lastError().text());
		return;
	}

	query.first();

	int pwsw_puid_idx = query.record().indexOf("product_uid");
	int pwsw_node_idx  = query.record().indexOf("node");
	int pwsw_username_idx = query.record().indexOf("username");
	int pwsw_password_idx = query.record().indexOf("password");
	int pwsw_size_idx = query.record().indexOf("size");
	int pwsw_switch_idx = query.record().indexOf("switch");
	int ap_state_idx = query.record().indexOf("state");

	quint32 pwsw_puid = query.value(pwsw_puid_idx).toUInt();
	QString pwsw_node  = query.value(pwsw_node_idx).toString();
	QString pwsw_username = query.value(pwsw_username_idx).toString();
	QString pwsw_password = query.value(pwsw_password_idx).toString();
	quint32 pwsw_size = query.value(pwsw_size_idx).toUInt();
	quint32 pwsw_switch = query.value(pwsw_switch_idx).toUInt();
	ap_state_t ap_state = (ap_state_t)query.value(ap_state_idx).toInt();
	quint32 ap_deadline = QDateTime::currentMSecsSinceEpoch() / 1000;
	ap_deadline += ap_hours * 3600;

	/** Check AP state */
	if(ap_state == STARTING || ap_state == MANAGED) {
		fail("AP already managed");
		return;
	}

	/** Get User datas */
	User user(owner_session, this);

	if(!user.fetch()) {
		fail("Failed to fetch user datas: " + user.error());
		return;
	}

	if(!user.isValid()) {
		fail("Invalid session: " + user.error());
		return;
	}

	quint32 owner_uid = user.getUid();

	/** Switch on the AP and update database */
	queryString = "UPDATE ap SET ";
	queryString += "state=:state, deadline=:deadline, ";
	queryString += "owner_uid=:owner_uid WHERE uid=:uid";

	query.prepare(queryString);

	query.bindValue(":deadline", ap_deadline);
	query.bindValue(":owner_uid", owner_uid);
	query.bindValue(":uid", ap_uid);

	if(ap_state == STARTED) {
		query.bindValue(":state", MANAGED);
	} else if(ap_state == STOPPED) {
		PwswAbstract *pwsw;
		switch(pwsw_puid) {
			case 1:
			case 2: // Lindy
				pwsw = new PwswLindy(pwsw_node,
									 pwsw_username,
									 pwsw_password,
									 pwsw_size,
									 this);
				break;
			case 3: // Digital Loggers
				pwsw = new PwswDigitalLoggers(pwsw_node,
											  pwsw_username,
											  pwsw_password,
											  pwsw_size,
											  this);
				break;
			default:
				fail("Invalid power switch product");
				return;
		}

		if(!pwsw->start(pwsw_switch)) {
			fail("Failed to start Power Switch");
			return;
		}

		query.bindValue(":state", STARTING);
	}

	if(!query.exec()) {
		fail("Database error: " + query.lastError().text());
		return;
	}

	/** Start to ping the AP if not already started*/
	if(ap_state == STOPPED)
		emit starting(ap_uid);

	success();
}
コード例 #25
0
ファイル: db.cpp プロジェクト: torto9/q4wine
bool DataBase::checkDb() {
    /*
    * Checking database tables.
    * If not exists, we try to create them.
    */

    QTextStream QErr(stderr);

    QStringList tables;
    tables << "prefix" << "dir" << "icon" << "images" << "last_run_icon" << "logging" << "providers" << "sysconfig" << "versions";

    QSqlDatabase db = QSqlDatabase::database();

    if (!db.isValid()) {
        QErr<<"[EE] "<<tr("No database loaded. Aborting...");
        return false;
    }

    QSqlQuery query;

    for (int i=0; i<tables.size(); ++i) {
        QString table=tables.at(i);

#ifdef DEBUG
        qDebug()<<"[ii] Check for table: "<<table;
#endif

        if (db.record(table).isEmpty()) {
            if (table == "prefix") {
                if(!query.exec("CREATE TABLE prefix (wine_dllpath TEXT, wine_loader TEXT, wine_server TEXT, wine_exec TEXT, cdrom_mount TEXT, id INTEGER PRIMARY KEY, name TEXT, path TEXT, version TEXT);"))
                    return false;

                // Creating default prefix reccord
                query.prepare("INSERT INTO prefix(id, name) VALUES(NULL, :name);");
                query.bindValue(":name", "Default");
                if (!query.exec())
                    return false;
                query.clear();
            } else if (table == "dir") {
                if(!query.exec("CREATE TABLE dir (id INTEGER PRIMARY KEY, name TEXT, prefix_id NUMERIC);"))
                    return false;
            } else if (table == "icon") {
                if(!query.exec("CREATE TABLE icon (wrkdir TEXT, override TEXT, winedebug TEXT, useconsole NUMERIC, display TEXT, cmdargs TEXT, exec TEXT, icon_path TEXT, desc TEXT, desktop TEXT, nice TEXT, dir_id NUMERIC, id INTEGER PRIMARY KEY, name TEXT, prefix_id NUMERIC);"))
                    return false;
            } else if (table == "images") {
                if(!query.exec("CREATE TABLE images (id INTEGER PRIMARY KEY, name TEXT, path TEXT);"))
                    return false;
            } else if (table == "last_run_icon") {
                if(!query.exec("CREATE TABLE last_run_icon (wrkdir TEXT, override TEXT, winedebug TEXT, useconsole NUMERIC, display TEXT, cmdargs TEXT, exec TEXT, desktop TEXT, nice TEXT, id INTEGER PRIMARY KEY);"))
                    return false;
            } else if (table == "logging") {
                if(!query.exec("CREATE TABLE logging (id INTEGER PRIMARY KEY, name TEXT, exit NUMERIC, stdout TEXT, prefix_id NUMERIC, date NUMERIC);"))
                    return false;
            } else if (table == "providers") {
                if(!query.exec("CREATE TABLE providers (id INTEGER PRIMARY KEY, name TEXT, icon TEXT);"))
                    return false;

                query.prepare("INSERT INTO providers(id, name, icon) VALUES(NULL, :name, :icon);");
                query.bindValue(":name", "System");
                query.bindValue(":icon", "wine.png");
                if (!query.exec())
                    return false;

                query.bindValue(":name", "Winetricks");
                query.bindValue(":icon", "regedit.png");
                if (!query.exec())
                    return false;
            } else if (table == "sysconfig") {
                if(!query.exec("CREATE TABLE sysconfig (id INTEGER PRIMARY KEY, name TEXT, type TEXT, icon TEXT, desc TEXT, provider_id INTEGER);"))
                    return false;

                // System items
                query.prepare("INSERT INTO sysconfig(id, name, icon, type, desc, provider_id) VALUES(NULL, :name, :icon, NULL, :desc, 1);");
                query.bindValue(":name", "%CREATE_FAKE%");
                query.bindValue(":icon", "fakedrive-new.png");
                query.bindValue(":desc", "%CREATE_FAKE_DESC%");
                if (!query.exec())
                    return false;

                query.prepare("INSERT INTO sysconfig(id, name, icon, type, desc, provider_id) VALUES(NULL, :name, :icon, NULL, :desc, 1);");
                query.bindValue(":name", "%UPDATE_FAKE%");
                query.bindValue(":icon", "fakedrive-update.png");
                query.bindValue(":desc", "%UPDATE_FAKE_DESC%");
                if (!query.exec())
                    return false;

                // Wintricks base
                query.prepare("INSERT INTO sysconfig(id, name, icon, type, desc, provider_id) VALUES(NULL, :name, :icon, NULL, :desc, 2);");
                query.bindValue(":name", "%INSTALL_WINETRICKS%");
                query.bindValue(":icon", "winetricks-install.png");
                query.bindValue(":desc", "%UPDATE_WINETRICKS_DESC%");
                if (!query.exec())
                    return false;

                query.prepare("INSERT INTO sysconfig(id, name, icon, type, desc, provider_id) VALUES(NULL, :name, :icon, NULL, :desc, 2);");
                query.bindValue(":name", "%REFRESH_WINETRICKS%");
                query.bindValue(":icon", "folder-downloads.png");
                query.bindValue(":desc", "%REFRESH_WINETRICKS_DESC%");
                if (!query.exec())
                    return false;
            } else if (table == "versions") {
                if(!query.exec("CREATE TABLE versions (wine_dllpath32 TEXT, wine_dllpath64 TEXT, wine_loader TEXT, wine_server TEXT, wine_exec TEXT, id INTEGER PRIMARY KEY, name TEXT);"))
                    return false;

                // Creating default version reccord
                Version vers;
                vers.name_ = "Default";

                // Use previous data is any
                QSettings settings(APP_SHORT_NAME, "default");
                if (settings.value("configure", "no") == "yes") {
                    settings.beginGroup("wine");
                    vers.wine_exec_ = settings.value("WineBin", QString()).toString();
                    vers.wine_server_ = settings.value("ServerBin", QString()).toString();
                    vers.wine_loader_ = settings.value("LoaderBin", QString()).toString();
                    vers.wine_dllpath32_ = settings.value("WineLibs32", QString()).toString();
                    vers.wine_dllpath64_ = settings.value("WineLibs64", QString()).toString();
                    settings.endGroup();
                }
                if (!vers.save())
                    return false;
            }
        }
    }

    return fixup();
}
コード例 #26
0
ファイル: catalogitem.cpp プロジェクト: 52North/IlwisCore
bool CatalogItem::store(QSqlQuery &queryItem, QSqlQuery &queryProperties) const
{
    bool ok = true;
    queryItem.bindValue(":itemid", id());
    queryItem.bindValue(":name", name());
    queryItem.bindValue(":code", code());
    QString pp = container().toString();
    queryItem.bindValue(":container", container().toString());
    queryItem.bindValue(":resource", url().toString());
    queryItem.bindValue(":type", ilwisType());
    queryItem.bindValue(":extendedtype", _extendedType);
    queryItem.bindValue(":size", size());
    queryItem.bindValue(":dimensions", _dimensions);
    ok = queryItem.exec();
    if (!ok) {
        kernel()->issues()->logSql(queryProperties.lastError());
        return false;
    }

    for(QHash<QString, QVariant>::const_iterator  iter = _properties.constBegin(); iter != _properties.constEnd(); ++iter) {
        queryProperties.bindValue(":itemid", id());
        QString nameItem = iter.key();
        queryProperties.bindValue(":propertyname",nameItem);
        queryProperties.bindValue(":propertyvalue", iter.value().toString());
        ok = queryProperties.exec();
        if (!ok) {
            kernel()->issues()->logSql(queryProperties.lastError());
        }
    }
    return ok;

}
コード例 #27
0
void editRoom::on_catList_currentIndexChanged()
{
    ui->roomList->clear();
    QString nameStr= ui->catList->currentText();

    if(nameStr==" :: Select One :: ")
    {
        ui->roomList->clear();
        ui->roomName->setEnabled(0);
        return;
    }
    ui->roomName->setEnabled(1);


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


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


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

    qDebug( "Connected!" );

    QSqlQuery qry;

    qry.prepare("CREATE TABLE IF NOT EXISTS roomcat (id INTEGET PRIMARY KEY, item VARCHAR(30), price INTEGER)");
    if(!qry.exec())
        qDebug() << qry.lastError();
    else
        qDebug( "Table Created!" );


    qry.prepare("SELECT id FROM roomcat WHERE item = :name");
    qry.bindValue(":name",nameStr);
    if(!qry.exec())
    {
        qDebug() << qry.lastError();
    }
    else
        qDebug( "Table Selected!" );

    int i=0;
    while (qry.next()) {
        i = qry.value(0).toInt();
    }

    if(i==0)
    {
        qFatal("MAYDAY!!! DATABASE ERROR!!!");
    }

    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 roomno FROM roomlist WHERE cat = :item");
    qry.bindValue(":item",i);
    if(!qry.exec())
        qDebug() << qry.lastError();
    else
        qDebug( "Room Table Validated..." );

    while (qry.next()) {
        QString roomno = qry.value(0).toString();
        ui->roomList->addItem(roomno);
    }
}
コード例 #28
0
ファイル: rhythmboxfeature.cpp プロジェクト: AlbanBedel/mixxx
void RhythmboxFeature::importTrack(QXmlStreamReader &xml, QSqlQuery &query) {
    QString title;
    QString artist;
    QString album;
    QString year;
    QString genre;
    QString location;
    QUrl locationUrl;

    int bpm = 0;
    int bitrate = 0;

    //duration of a track
    int playtime = 0;
    int rating = 0;
    QString comment;
    QString tracknumber;

    while (!xml.atEnd()) {
        xml.readNext();
        if (xml.isStartElement()) {
            if (xml.name() == "title") {
                title = xml.readElementText();
                continue;
            }
            if (xml.name() == "artist") {
                artist = xml.readElementText();
                continue;
            }
            if (xml.name() == "genre") {
                genre = xml.readElementText();
                continue;
            }
            if (xml.name() == "album") {
                album = xml.readElementText();
                continue;
            }
            if (xml.name() == "track-number") {
                tracknumber = xml.readElementText();
                continue;
            }
            if (xml.name() == "duration") {
                playtime = xml.readElementText().toInt();;
                continue;
            }
            if (xml.name() == "bitrate") {
                bitrate = xml.readElementText().toInt();
                continue;
            }
            if (xml.name() == "beats-per-minute") {
                bpm = xml.readElementText().toInt();
                continue;
            }
            if (xml.name() == "comment") {
                comment = xml.readElementText();
                continue;
            }
            if (xml.name() == "location") {
                locationUrl = QUrl::fromEncoded( xml.readElementText().toUtf8());
                continue;
            }
        }
        //exit the loop if we reach the closing <entry> tag
        if (xml.isEndElement() && xml.name() == "entry") {
            break;
        }
    }

    location = locationUrl.toLocalFile();

    if (location.isEmpty()) {
        // here in case of smb:// location
        // TODO(XXX) QUrl does not support SMB:// locations does Mixxx?
        // use ~/.gvfs location instead
        return;
    }

    query.bindValue(":artist", artist);
    query.bindValue(":title", title);
    query.bindValue(":album", album);
    query.bindValue(":genre", genre);
    query.bindValue(":year", year);
    query.bindValue(":duration", playtime);
    query.bindValue(":location", location);
    query.bindValue(":rating", rating);
    query.bindValue(":comment", comment);
    query.bindValue(":tracknumber", tracknumber);
    query.bindValue(":bpm", bpm);
    query.bindValue(":bitrate", bitrate);

    bool success = query.exec();

    if (!success) {
        qDebug() << "SQL Error in rhythmboxfeature.cpp: line" << __LINE__
                 << " " << query.lastError();
        return;
    }
}
コード例 #29
0
ファイル: servatrice.cpp プロジェクト: clau911015/Cockatrice
bool Servatrice::initServer()
{
    serverName = settingsCache->value("server/name", "My Cockatrice server").toString();
    serverId = settingsCache->value("server/id", 0).toInt();
    clientIdRequired = settingsCache->value("server/requireclientid",0).toBool();
    regServerOnly = settingsCache->value("authentication/regonly", 0).toBool();

    const QString authenticationMethodStr = settingsCache->value("authentication/method").toString();
    if (authenticationMethodStr == "sql") {
        qDebug() << "Authenticating method: sql";
        authenticationMethod = AuthenticationSql;
    } else if(authenticationMethodStr == "password") {
        qDebug() << "Authenticating method: password";
        authenticationMethod = AuthenticationPassword;
    } else {
        if (regServerOnly) {
            qDebug() << "Registration only server enabled but no authentication method defined: Error.";
            return false;
        }

        qDebug() << "Authenticating method: none";
        authenticationMethod = AuthenticationNone;
    }

    qDebug() << "Store Replays: " << settingsCache->value("game/store_replays", true).toBool();
    qDebug() << "Client ID Required: " << clientIdRequired;
    bool maxUserLimitEnabled = settingsCache->value("security/enable_max_user_limit", false).toBool();
    qDebug() << "Maximum user limit enabled: " << maxUserLimitEnabled;

    if (maxUserLimitEnabled){
        int maxUserLimit = settingsCache->value("security/max_users_total", 500).toInt();
        qDebug() << "Maximum total user limit: " << maxUserLimit;
        int maxTcpUserLimit = settingsCache->value("security/max_users_tcp", 500).toInt();
        qDebug() << "Maximum tcp user limit: " << maxTcpUserLimit;
        int maxWebsocketUserLimit = settingsCache->value("security/max_users_websocket", 500).toInt();
        qDebug() << "Maximum websocket user limit: " << maxWebsocketUserLimit;
    }

    bool registrationEnabled = settingsCache->value("registration/enabled", false).toBool();
    bool requireEmailForRegistration = settingsCache->value("registration/requireemail", true).toBool();
    bool requireEmailActivation = settingsCache->value("registration/requireemailactivation", true).toBool();

    qDebug() << "Accept registered users only: " << regServerOnly;
    qDebug() << "Registration enabled: " << registrationEnabled;
    if (registrationEnabled)
    {
        qDebug() << "Require email address to register: " << requireEmailForRegistration;
        qDebug() << "Require email activation via token: " << requireEmailActivation;
    }

    FeatureSet features;
    features.initalizeFeatureList(serverRequiredFeatureList);
    requiredFeatures = settingsCache->value("server/requiredfeatures","").toString();
    QStringList listReqFeatures = requiredFeatures.split(",", QString::SkipEmptyParts);
    if (!listReqFeatures.isEmpty())
        foreach(QString reqFeature, listReqFeatures)
            features.enableRequiredFeature(serverRequiredFeatureList,reqFeature);

    qDebug() << "Required client features: " << serverRequiredFeatureList;

    QString dbTypeStr = settingsCache->value("database/type").toString();
    if (dbTypeStr == "mysql")
        databaseType = DatabaseMySql;
    else
        databaseType = DatabaseNone;

    servatriceDatabaseInterface = new Servatrice_DatabaseInterface(-1, this);
    setDatabaseInterface(servatriceDatabaseInterface);

    if (databaseType != DatabaseNone) {
        settingsCache->beginGroup("database");
        dbPrefix = settingsCache->value("prefix").toString();
        bool dbOpened =
            servatriceDatabaseInterface->initDatabase("QMYSQL",
                 settingsCache->value("hostname").toString(),
                 settingsCache->value("database").toString(),
                 settingsCache->value("user").toString(),
                 settingsCache->value("password").toString());
        settingsCache->endGroup();
        if (!dbOpened) {
            qDebug() << "Failed to open database";
            return false;
        }

        updateServerList();

        qDebug() << "Clearing previous sessions...";
        servatriceDatabaseInterface->clearSessionTables();
    }

    const QString roomMethod = settingsCache->value("rooms/method").toString();
    if (roomMethod == "sql") {
        QSqlQuery *query = servatriceDatabaseInterface->prepareQuery("select id, name, descr, permissionlevel, auto_join, join_message, chat_history_size from {prefix}_rooms where id_server = :id_server order by id asc");
        query->bindValue(":id_server", serverId);
        servatriceDatabaseInterface->execSqlQuery(query);
        while (query->next()) {
            QSqlQuery *query2 = servatriceDatabaseInterface->prepareQuery("select name from {prefix}_rooms_gametypes where id_room = :id_room AND id_server = :id_server");
            query2->bindValue(":id_server", serverId);
            query2->bindValue(":id_room", query->value(0).toInt());
            servatriceDatabaseInterface->execSqlQuery(query2);
            QStringList gameTypes;
            while (query2->next())
                gameTypes.append(query2->value(0).toString());

            addRoom(new Server_Room(query->value(0).toInt(),
                                    query->value(6).toInt(),
                                    query->value(1).toString(),
                                    query->value(2).toString(),
                                    query->value(3).toString().toLower(),
                                    query->value(4).toInt(),
                                    query->value(5).toString(),
                                    gameTypes,
                                    this
            ));
        }
    } else {
        int size = settingsCache->beginReadArray("rooms/roomlist");
        for (int i = 0; i < size; ++i) {
            settingsCache->setArrayIndex(i);

            QStringList gameTypes;
            int size2 = settingsCache->beginReadArray("game_types");
                for (int j = 0; j < size2; ++j) {
                settingsCache->setArrayIndex(j);
                gameTypes.append(settingsCache->value("name").toString());
            }
            settingsCache->endArray();

            Server_Room *newRoom = new Server_Room(
                i,
                settingsCache->value("chathistorysize").toInt(),
                settingsCache->value("name").toString(),
                settingsCache->value("description").toString(),
                settingsCache->value("permissionlevel").toString().toLower(),
                settingsCache->value("autojoin").toBool(),
                settingsCache->value("joinmessage").toString(),
                gameTypes,
                this
            );
            addRoom(newRoom);
        }

        if(size==0)
        {
            // no room defined in config, add a dummy one
            Server_Room *newRoom = new Server_Room(
                0,
                100,
                "General room",
                "Play anything here.",
                "none",
                true,
                "",
                QStringList("Standard"),
                this
            );
            addRoom(newRoom);
        }

        settingsCache->endArray();
    }

    updateLoginMessage();

    maxGameInactivityTime = settingsCache->value("game/max_game_inactivity_time", 120).toInt();
    maxPlayerInactivityTime = settingsCache->value("server/max_player_inactivity_time", 15).toInt();
    pingClockInterval = settingsCache->value("server/clientkeepalive", 1).toInt();
    maxUsersPerAddress = settingsCache->value("security/max_users_per_address", 4).toInt();
    messageCountingInterval = settingsCache->value("security/message_counting_interval", 10).toInt();
    maxMessageCountPerInterval = settingsCache->value("security/max_message_count_per_interval", 15).toInt();
    maxMessageSizePerInterval = settingsCache->value("security/max_message_size_per_interval", 1000).toInt();
    maxGamesPerUser = settingsCache->value("security/max_games_per_user", 5).toInt();
    commandCountingInterval = settingsCache->value("game/command_counting_interval", 10).toInt();
    maxCommandCountPerInterval = settingsCache->value("game/max_command_count_per_interval", 20).toInt();

    try { if (settingsCache->value("servernetwork/active", 0).toInt()) {
        qDebug() << "Connecting to ISL network.";
        const QString certFileName = settingsCache->value("servernetwork/ssl_cert").toString();
        const QString keyFileName = settingsCache->value("servernetwork/ssl_key").toString();
        qDebug() << "Loading certificate...";
        QFile certFile(certFileName);
        if (!certFile.open(QIODevice::ReadOnly))
            throw QString("Error opening certificate file: %1").arg(certFileName);
        QSslCertificate cert(&certFile);

        const QDateTime currentTime = QDateTime::currentDateTime();
        if(currentTime < cert.effectiveDate() ||
            currentTime > cert.expiryDate() ||
            cert.isBlacklisted())
            throw(QString("Invalid certificate."));

        qDebug() << "Loading private key...";
        QFile keyFile(keyFileName);
        if (!keyFile.open(QIODevice::ReadOnly))
            throw QString("Error opening private key file: %1").arg(keyFileName);
        QSslKey key(&keyFile, QSsl::Rsa, QSsl::Pem, QSsl::PrivateKey);
        if (key.isNull())
            throw QString("Invalid private key.");

        QMutableListIterator<ServerProperties> serverIterator(serverList);
        while (serverIterator.hasNext()) {
            const ServerProperties &prop = serverIterator.next();
            if (prop.cert == cert) {
                serverIterator.remove();
                continue;
            }

            QThread *thread = new QThread;
            thread->setObjectName("isl_" + QString::number(prop.id));
            connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));

            IslInterface *interface = new IslInterface(prop.id, prop.hostname, prop.address.toString(), prop.controlPort, prop.cert, cert, key, this);
            interface->moveToThread(thread);
            connect(interface, SIGNAL(destroyed()), thread, SLOT(quit()));

            thread->start();
            QMetaObject::invokeMethod(interface, "initClient", Qt::BlockingQueuedConnection);
        }

        const int networkPort = settingsCache->value("servernetwork/port", 14747).toInt();
        qDebug() << "Starting ISL server on port" << networkPort;

        islServer = new Servatrice_IslServer(this, cert, key, this);
        if (islServer->listen(QHostAddress::Any, networkPort))
            qDebug() << "ISL server listening.";
        else
            throw QString("islServer->listen()");
    } } catch (QString error) {
        qDebug() << "ERROR --" << error;
        return false;
    }

    pingClock = new QTimer(this);
    connect(pingClock, SIGNAL(timeout()), this, SIGNAL(pingClockTimeout()));
    pingClock->start(pingClockInterval * 1000);

    int statusUpdateTime = settingsCache->value("server/statusupdate", 15000).toInt();
    statusUpdateClock = new QTimer(this);
    connect(statusUpdateClock, SIGNAL(timeout()), this, SLOT(statusUpdate()));
    if (statusUpdateTime != 0) {
        qDebug() << "Starting status update clock, interval " << statusUpdateTime << " ms";
        statusUpdateClock->start(statusUpdateTime);
    }

    // SOCKET SERVER
    const int numberPools = settingsCache->value("server/number_pools", 1).toInt();
    if(numberPools > 0)
    {
        gameServer = new Servatrice_GameServer(this, numberPools, servatriceDatabaseInterface->getDatabase(), this);
        gameServer->setMaxPendingConnections(1000);
        const int gamePort = settingsCache->value("server/port", 4747).toInt();
        qDebug() << "Starting server on port" << gamePort;
        if (gameServer->listen(QHostAddress::Any, gamePort))
            qDebug() << "Server listening.";
        else {
            qDebug() << "gameServer->listen(): Error:" << gameServer->errorString();
            return false;
        }
    }

#if QT_VERSION > 0x050300
    // WEBSOCKET SERVER
    const int wesocketNumberPools = settingsCache->value("server/websocket_number_pools", 1).toInt();
    if(wesocketNumberPools > 0)
    {
        websocketGameServer = new Servatrice_WebsocketGameServer(this, wesocketNumberPools, servatriceDatabaseInterface->getDatabase(), this);
        websocketGameServer->setMaxPendingConnections(1000);
        const int websocketGamePort = settingsCache->value("server/websocket_port", 4748).toInt();
        qDebug() << "Starting websocket server on port" << websocketGamePort;
        if (websocketGameServer->listen(QHostAddress::Any, websocketGamePort))
            qDebug() << "Websocket server listening.";
        else {
            qDebug() << "websocketGameServer->listen(): Error:" << websocketGameServer->errorString();
            return false;
        }
    }
#endif
    return true;
}
コード例 #30
0
ファイル: dbmanager.cpp プロジェクト: sgranfius/sns
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();
                    }
                }
            }
        }
    }
}