Example #1
0
void DBWorker::deleteSetting(QString name)
{
    QSqlQuery query = prepare("DELETE FROM settings WHERE name = ?");
    query.bindValue(0, name);
    execute(query);
}
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();
    }

}
Example #3
0
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE","file.db");
    db.setDatabaseName(QDir::homePath()+"/.rationality/file.db");

    if(!db.open())
           qWarning()<<"Errore di connessione";
    QSqlQuery myQuery = QSqlQuery(db);

  /*  if (myQuery.exec("CREATE TABLE tag (key INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, name TEXT NOT NULL);")) qWarning()<<"Tabella creata";
//    else qWarning()<<"Errore o tabella esistente";
    if (myQuery.exec("CREATE TABLE parent (child INTEGER NOT NULL, parent INTEGER NOT NULL);")) qWarning()<<"Tabella creata";
//    else qWarning()<<"Errore o tabella esistente";
    if (myQuery.exec("CREATE TABLE filetag(file INTEGER NOT NULL, tag INTEGER NOT NULL);")) qWarning()<<"Tabella creata";
//    else qWarning()<<"Errore o tabella esistente";
    if (myQuery.exec("CREATE TABLE file (key INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, name TEXT NOT NULL,  path TEXT NOT NULL);")) qWarning()<<"Tabella creata";
  //  else qWarning()<<"Errore o tabella esistente";
  //   myQuery.exec("INSERT INTO tag VALUES (-1,'Root');");*/
    if (myQuery.exec("CREATE TABLE tag (key INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,parent INTEGER NOT NULL, name TEXT NOT NULL, hidden INTEGER NOT NULL);")) qWarning()<<"Tabella creata";
    if (myQuery.exec("CREATE TABLE filetag(file INTEGER NOT NULL, tag INTEGER NOT NULL);")) qWarning()<<"Tabella creata";
    if (myQuery.exec("CREATE TABLE file (key INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, name TEXT NOT NULL,  path TEXT NOT NULL, rating INTEGER, CONSTRAINT rating_min_5 CHECK rating < 5 );")) qWarning()<<"Tabella creata";


   if (myQuery.exec("SELECT tag.name FROM tag;")) {
        QString t;
        while (myQuery.next()){
            t=myQuery.value(0).toString();
            qWarning()<<t;
        }
    }
    if (myQuery.exec("SELECT file.name FROM file;")) {
        QString t;
        while (myQuery.next()){
            t=myQuery.value(0).toString();
            qWarning()<<t;
        }
     }





     QString cmd="";
     char c[200];
     while (1) {
         cout << "cmd: ";
         cin.getline(c,200);
         cmd = QString::fromStdString(c);
         if (QString::compare(cmd,"exit")==0) break;
         if (myQuery.exec(cmd)) cout << "\n";
         else cout << "Comando non eseguito\n";

     }
    db.close();

    return 0;
}
Example #4
0
void DetailMeeting::updateMeeting()
{
    int duration_minute = (meeting_duration->time().hour()*60) + meeting_duration->time().minute();

    QDateTime *date_begin_real = new QDateTime(QDate(meeting_dt_begin->date().year(),meeting_dt_begin->date().month(),meeting_dt_begin->date().day()),meeting_dt_begin->time());

    QString dt_begin;
    dt_begin = QString::number(meeting_dt_begin->date().year()) + "/" + QString::number(meeting_dt_begin->date().month()) + "/" + QString::number(meeting_dt_begin->date().day()) + " " + QString::number(meeting_dt_begin->time().hour()) + ":" + QString::number(meeting_dt_begin->time().minute());

    QString dt_end;
    dt_end = QString::number(meeting_dt_end->date().year()) + "/" + QString::number(meeting_dt_end->date().month()) + "/" + QString::number(meeting_dt_end->date().day()) + " " + QString::number(meeting_dt_end->time().hour()) + ":" + QString::number(meeting_dt_end->time().minute());

    QSqlQuery query;
    query.prepare("SELECT * FROM Meeting where room = :room");
    query.bindValue(":room", id_room);
    query.exec();
    QSqlRecord rec = query.record();

    while(query.next())
    {
        QStringList date_begin = query.value(rec.indexOf("date_begin")).toString().split(" ").at(0).split("/");
        QStringList time_begin = query.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);

        QStringList date_end_bis = query.value(rec.indexOf("date_end")).toString().split(" ").at(0).split("/");
        QStringList time_end = query.value(rec.indexOf("date_end")).toString().split(" ").at(1).split(":");

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

        QDateTime datetime_begin(date_begin_edit,time_begin_edit);
        QDateTime datetime_end(date_end_edit,time_end_edit);

        if(date_begin_real->operator >(datetime_begin) && date_begin_real->operator <(datetime_end))
        {
            QMessageBox::critical(this, "Salle indisponible", "La salle selectionné est indisponible.");
            return;
        }
    }

    query.prepare("SELECT * FROM Meeting where id_meeting = :id_meeting");
    query.bindValue(":id_meeting", meeting_id);
    query.exec();
    rec = query.record();
    query.next();

    sendEmailUpdateMeeting(meeting_id,dt_begin);

    query.prepare("Update Meeting set date_begin = :date_begin , date_end =:date_end , duration = :duration WHERE id = :id_meeting");
    query.bindValue(":date_begin", dt_begin);
    query.bindValue(":date_end", dt_end);
    query.bindValue(":duration", duration_minute);
    query.bindValue(":id_meeting", meeting_id);
    query.exec();

    this->close();
    emit notifyRefreshList();
}
Example #5
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()));
}
Example #6
0
bool TestAssistance::updateQuestionInfo(const QUESTIONINFO &info, bool updateImage)
{
    //open database
    if (!m_objDatabase.open()) {
        packErrorInfo(m_objDatabase.lastError().text(),
                      TA_ERROR_NOTCONNECTED);
        return false;
    }

    //check if updateImage
    QString imgValue("");
    if(updateImage)
        imgValue = ",qimage=:qimage ";

    QSqlQuery query;
    query.prepare(QString("UPDATE questions SET qtxt=:qtxt,qgrade=:qgrade,") +
                  "qmajor=:qmajor,qcourse=:qcourse," +
                  "qcnt=:qcnt,qhard=:qhard," +
                  "qdate=:qdate,qright=:qright," +
                  "qtype=:qtype,qknowpoint=:qknowpoint " +
                  imgValue +
                  "WHERE qno=:qno");
    query.bindValue(":qno", info.qno);
    query.bindValue(":qtxt", info.qtxt);
    query.bindValue(":qgrade", info.qgrade);
    query.bindValue(":qmajor", info.qmajor);
    query.bindValue(":qcourse", info.qcourse);
    query.bindValue(":qcnt", info.qcnt);
    query.bindValue(":qhard", info.qhard);
    query.bindValue(":qdate", info.qdate);
    query.bindValue(":qright", info.qright);
    query.bindValue(":qtype", info.qtype);
    query.bindValue(":qknowpoint", info.qknowpoint);
    if(updateImage)
        query.bindValue(":qimage", info.qimage);

    if(!query.exec()){
        packErrorInfo(query.lastError().text(),
                      TA_ERROR_SQLERROR);
        m_objDatabase.close();
        return false;
    }
    m_objDatabase.close();
    return true;
}
Example #7
0
File: db.cpp Project: torto9/q4wine
bool DataBase::fixup() {
    QSqlQuery query;
    if (!query.exec("SELECT arch FROM prefix")) {
        if (!query.exec("ALTER TABLE prefix ADD COLUMN arch TEXT")) {
            qDebug()<<"[EE] Cannot alter prefix table";
            return false;
        }
    }
    if (!query.exec("SELECT mountpoint_windrive FROM prefix")) {
        if (!query.exec("ALTER TABLE prefix ADD COLUMN mountpoint_windrive TEXT")) {
            qDebug()<<"[EE] Cannot alter prefix table";
            return false;
        }
    }
    if (!query.exec("SELECT lang FROM icon")) {
        if (!query.exec("ALTER TABLE icon ADD COLUMN lang TEXT")) {
            qDebug()<<"[EE] Cannot alter icon table";
            return false;
        }
    }
    if (!query.exec("SELECT lang FROM last_run_icon")) {
        if (!query.exec("ALTER TABLE last_run_icon ADD COLUMN lang TEXT")) {
            qDebug()<<"[EE] Cannot alter last_run_icon table";
            return false;
        }
    }
    if (!query.exec("SELECT prerun FROM icon")) {
        if (!query.exec("ALTER TABLE icon ADD COLUMN prerun TEXT")) {
            qDebug()<<"[EE] Cannot alter icon table";
            return false;
        }
    }
    if (!query.exec("SELECT postrun FROM icon")) {
        if (!query.exec("ALTER TABLE icon ADD COLUMN postrun TEXT")) {
            qDebug()<<"[EE] Cannot alter icon table";
            return false;
        }
    }
    if (!query.exec("SELECT run_string FROM prefix")) {
        if (!query.exec("ALTER TABLE prefix ADD COLUMN run_string TEXT")) {
            qDebug()<<"[EE] Cannot alter prefix table";
            return false;
        }
    }
    if (!query.exec("SELECT version_id FROM prefix")) {
        if (!query.exec("ALTER TABLE prefix ADD COLUMN version_id INTEGER")) {
            qDebug()<<"[EE] Cannot alter prefix table";
            return false;
        }
        if (!query.exec("UPDATE prefix SET version_id=1")) {
            qDebug()<<"[EE] Cannot update prefix table";
            return false;
        }
    }
    return true;
}
Example #8
0
File: man.cpp Project: Elv13/KliNG
/**
  Load a manPage from /usr/share/man. Also load usage, examples and options
*/
  void Man::loadPage() {
    tblOptions->clear();
    tblOptions->setRowCount(0);
    QSqlQuery query;
    query.exec("SELECT PATH FROM TMAN_PAGE WHERE TITLE = '"+ cbbManPagelist->itemText(cbbManPagelist->currentIndex())+"'");
    
    while (query.next())  {
      system("mkdir /tmp/man");
      std::string cmdCopy = "cp " + query.value(0).toString().toStdString() + " /tmp/man/";
      std::string name;
      std::string command;
      system(cmdCopy.c_str());

      if (query.value(0).toString().toStdString().find(".bz2") != -1) {
          name = query.value(0).toString().toStdString().substr( query.value(0).toString().toStdString().find_last_of("/") +1, (query.value(0).toString().toStdString().size() - query.value(0).toString().toStdString().find_last_of("/") -1));
          command =  "bunzip2 -d /tmp/man/" + name;
          name = name.substr(0, name.find(".bz2"));
      }
      else {
	name = query.value(0).toString().toStdString().substr( query.value(0).toString().toStdString().find_last_of("/") +1, (query.value(0).toString().toStdString().size() - query.value(0).toString().toStdString().find_last_of("/") -1));
	//unGz(name);
	command =  "gunzip /tmp/man/" + name;
	name = name.substr(0, name.find(".gz"));
      }
      system(command.c_str());
      rtfManPage->setHtml(ManParser::parseManPage(name).c_str());
    }

    QSqlQuery query2;
    query2.exec("SELECT OPT_NAME,OPT_DES FROM TOPTION WHERE COMMAND = '"+ cbbManPagelist->itemText(cbbManPagelist->currentIndex())+"'");
    int row = 1;
    tblOptions->setColumnCount(2);
    while (query2.next()) {
      tblOptions->setRowCount(row);
      QWidget* aWidget = new QWidget(tblOptions); //Dirty hack to fix a QT bug
      QLabel* aTableWidget = new QLabel(aWidget);
      aTableWidget->setText(query2.value(0).toString());
      tblOptions->setCellWidget((row-1), 0, aWidget);
      aWidget->setToolTip(query2.value(0).toString());
      
      QWidget* aWidget2 = new QWidget(tblOptions); //Dirty hack to fix a QT bug
      QLabel* aTableWidget2 = new QLabel(aWidget2);
      aTableWidget2->setText(query2.value(1).toString());
      tblOptions->setCellWidget((row-1), 1, aWidget2);
      aWidget2->setToolTip(query2.value(1).toString());
      tblOptions->setRowHeight(row-1, 25);
      row++;
    }

    QSqlQuery query3;
    query3.exec("SELECT USAGE,USAGE_DES FROM TUSAGE WHERE COMMAND = '"+ cbbManPagelist->itemText(cbbManPagelist->currentIndex())+"'");
    int row2 = 1;
    tblUsage->setColumnCount(2);
    while (query3.next()) {
      tblUsage->setRowCount(row2);

      QWidget* aWidget = new QWidget(tblUsage);
      QLabel* aTableWidget = new QLabel(aWidget);
      aTableWidget->setObjectName(QString::fromUtf8("aTableLabel"));
      aTableWidget->setText(query3.value(0).toString().toStdString().c_str());
      tblUsage->setCellWidget((row2-1), 0, aWidget);
      aWidget->setToolTip(query3.value(0).toString());
      
      QWidget* aWidget2 = new QWidget(tblUsage);
      QLabel* aTableWidget2 = new QLabel(aWidget2);
      aTableWidget2->setText(query3.value(1).toString());
      tblUsage->setCellWidget((row2-1), 1, aWidget2);
      aWidget2->setToolTip(query3.value(1).toString());
      tblUsage->setRowHeight(row2-2, 25);
      row2++;
    }
  }
Example #9
0
File: man.cpp Project: Elv13/KliNG
/**
  Man constructor

  @param[in] parent The parent window
*/
  Man::Man(QWidget* parent) : QDockWidget ( 0 ) {
    setObjectName("Man");
    setObjectName(QString::fromUtf8("dockManual"));
    setGeometry(QRect(783, 24, 201, 629));
    QSizePolicy sizePolicy5(QSizePolicy::Ignored, QSizePolicy::Ignored);
    sizePolicy5.setHorizontalStretch(0);
    sizePolicy5.setVerticalStretch(0);
    sizePolicy5.setHeightForWidth(sizePolicy().hasHeightForWidth());
    setSizePolicy(sizePolicy5);
    setMinimumSize(QSize(200, 200));
    setMaximumSize(QSize(16777215, 16777215));
    setAllowedAreas(Qt::AllDockWidgetAreas);
    dockManualContents = new QWidget(this);
    dockManualContents->setObjectName(QString::fromUtf8("dockManualContents"));
    dockManualContents->setGeometry(QRect(2, 22, 197, 605));
    verticalLayout = new QVBoxLayout(dockManualContents);
    verticalLayout->setObjectName(QString::fromUtf8("verticalLayout"));
    verticalLayout->setContentsMargins(0, 0, 0, 0);
    hlFindManPage = new QHBoxLayout();
    hlFindManPage->setObjectName(QString::fromUtf8("hlFindManPage"));
    cbbManPagelist = new KComboBox(dockManualContents);
    cbbManPagelist->setObjectName(QString::fromUtf8("cbbManPagelist"));
    cbbManPagelist->setEditable(true);
    cbbManPagelist->setMaxVisibleItems(50);
    cbbManPagelist->setInsertPolicy(QComboBox::NoInsert);
    cbbManPagelist->setAutoCompletion(false);
    cbbManPagelist->setTrapReturnKey(false);
    hlFindManPage->addWidget(cbbManPagelist);

    btnFindManPage = new KPushButton(dockManualContents);
    btnFindManPage->setObjectName(QString::fromUtf8("btnFindManPage"));
    btnFindManPage->setMaximumSize(QSize(60, 16777215));
    btnFindManPage->setSizeIncrement(QSize(0, 0));
    hlFindManPage->addWidget(btnFindManPage);
    verticalLayout->addLayout(hlFindManPage);

    tbManInfo = new QToolBox(dockManualContents);
    tbManInfo->setObjectName(QString::fromUtf8("tbManInfo"));
    QSizePolicy sizePolicy6(QSizePolicy::Expanding, QSizePolicy::Expanding);
    sizePolicy6.setHorizontalStretch(0);
    sizePolicy6.setVerticalStretch(0);
    sizePolicy6.setHeightForWidth(tbManInfo->sizePolicy().hasHeightForWidth());
    tbManInfo->setSizePolicy(sizePolicy6);
    tbManInfo->setBaseSize(QSize(240, 91));
    tbManInfo->setStyleSheet(QString::fromUtf8(""));
    tbManInfo->setLineWidth(1);
    pageManual = new QWidget();
    pageManual->setObjectName(QString::fromUtf8("pageManual"));
    pageManual->setGeometry(QRect(0, 0, 179, 469));
    verticalLayout_2 = new QVBoxLayout(pageManual);
    verticalLayout_2->setObjectName(QString::fromUtf8("verticalLayout_2"));
    rtfManPage = new QTextBrowser(pageManual);
    rtfManPage->setObjectName(QString::fromUtf8("rtfManPage"));
    verticalLayout_2->addWidget(rtfManPage);

    tbManInfo->addItem(pageManual, "Manuel");
    PageUsage = new QWidget();
    PageUsage->setObjectName(QString::fromUtf8("PageUsage"));
    PageUsage->setGeometry(QRect(0, 0, 179, 469));
    verticalLayout_4 = new QVBoxLayout(PageUsage);
    verticalLayout_4->setObjectName(QString::fromUtf8("verticalLayout_4"));
    tblUsage = new QTableWidget(PageUsage);
    if (tblUsage->columnCount() < 2)
        tblUsage->setColumnCount(2);
    QTableWidgetItem *__colItem = new QTableWidgetItem();
    tblUsage->setHorizontalHeaderItem(0, __colItem);
    QTableWidgetItem *__colItem1 = new QTableWidgetItem();
    tblUsage->setHorizontalHeaderItem(1, __colItem1);
    tblUsage->setObjectName(QString::fromUtf8("tblUsage"));
    tblUsage->setMidLineWidth(0);
    tblUsage->setEditTriggers(QAbstractItemView::NoEditTriggers);
    tblUsage->setSelectionMode(QAbstractItemView::NoSelection);
    tblUsage->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
    tblUsage->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel);
    verticalLayout_4->addWidget(tblUsage);

    tbManInfo->addItem(PageUsage, "Usage");
    pageOptions = new QWidget();
    pageOptions->setObjectName(QString::fromUtf8("pageOptions"));
    pageOptions->setGeometry(QRect(0, 0, 179, 469));
    verticalLayout_3 = new QVBoxLayout(pageOptions);
    verticalLayout_3->setObjectName(QString::fromUtf8("verticalLayout_3"));
    tblOptions = new QTableWidget(pageOptions);
    if (tblOptions->columnCount() < 2)
        tblOptions->setColumnCount(2);
    QTableWidgetItem *__colItem2 = new QTableWidgetItem();
    tblOptions->setHorizontalHeaderItem(0, __colItem2);
    QTableWidgetItem *__colItem3 = new QTableWidgetItem();
    tblOptions->setHorizontalHeaderItem(1, __colItem3);
    tblOptions->setObjectName(QString::fromUtf8("tblOptions"));
    tblOptions->setEnabled(true);
    tblOptions->setDragEnabled(true);
    tblOptions->setDragDropMode(QAbstractItemView::DragOnly);
    tblOptions->setSelectionMode(QAbstractItemView::NoSelection);
    verticalLayout_3->addWidget(tblOptions);
    tbManInfo->addItem(pageOptions, "Options");

    verticalLayout->addWidget(tbManInfo);
    tblUsage->verticalHeader()->hide();
    tblOptions->verticalHeader()->hide();
    
    setWidget(dockManualContents);
    tbManInfo->setCurrentIndex(0);
    translateUi();

    QSqlQuery query;
    query.exec("SELECT TITLE FROM TMAN_PAGE");
    
     while (query.next()) 
       cbbManPagelist->addItem(query.value(0).toString());
         
    cbbManPagelist->model()->sort(0);
    cbbManPagelist->setCurrentIndex(0);
    QObject::connect(cbbManPagelist, SIGNAL(currentIndexChanged(int)), this, SLOT(loadPage()));
  }
Example #10
0
bool QgsDb2Provider::changeAttributeValues( const QgsChangedAttributesMap &attr_map )
{
  QgsDebugMsg( "Entering" );
  if ( attr_map.isEmpty() )
    return true;

  if ( mFidColName.isEmpty() )
    return false;

  for ( QgsChangedAttributesMap::const_iterator it = attr_map.begin(); it != attr_map.end(); ++it )
  {
    QgsFeatureId fid = it.key();

    // skip added features
    if ( FID_IS_NEW( fid ) )
      continue;

    const QgsAttributeMap& attrs = it.value();
    if ( attrs.isEmpty() )
      continue;

    QString statement = QString( "UPDATE %1.%2 SET " ).arg( mSchemaName, mTableName );

    bool first = true;
    if ( !mDatabase.isOpen() )
    {
      QString errMsg;
      mDatabase = getDatabase( mConnInfo, errMsg );
      if ( !errMsg.isEmpty() )
      {
        return false;
      }
    }
    QSqlQuery query = QSqlQuery( mDatabase );
    query.setForwardOnly( true );

    for ( QgsAttributeMap::const_iterator it2 = attrs.begin(); it2 != attrs.end(); ++it2 )
    {
      QgsField fld = mAttributeFields.at( it2.key() );

      if ( fld.typeName().endsWith( " identity", Qt::CaseInsensitive ) )
        continue; // skip identity field

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

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

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

    if ( first )
      return true; // no fields have been changed

    // set attribute filter
    statement += QString( " WHERE %1=%2" ).arg( mFidColName, FID_TO_STRING( fid ) );

    // use prepared statement to prevent from sql injection
    if ( !query.prepare( statement ) )
    {
      QgsDebugMsg( query.lastError().text() );
      return false;
    }
    QgsDebugMsg( statement );
    for ( QgsAttributeMap::const_iterator it2 = attrs.begin(); it2 != attrs.end(); ++it2 )
    {
      QgsField fld = mAttributeFields.at( it2.key() );

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

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

    if ( !query.exec() )
    {
      QgsDebugMsg( query.lastError().text() );
      return false;
    }
  }
  return true;
}
Example #11
0
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;
}
Example #12
0
// update the extent for this layer
void QgsDb2Provider::updateStatistics() const
{
  // get features to calculate the statistics
  QString statement;

  QSqlQuery query = QSqlQuery( mDatabase );
  query.setForwardOnly( true );

  statement = QString( "SELECT MIN(DB2GSE.ST_MINX(%1)), MIN(DB2GSE.ST_MINY(%1)), MAX(DB2GSE.ST_MAXX(%1)), MAX(DB2GSE.ST_MAXY(%1))" ).arg( mGeometryColName );

  statement += QString( " FROM %1.%2" ).arg( mSchemaName, mTableName );

  if ( !mSqlWhereClause.isEmpty() )
  {
    statement += " WHERE (" + mSqlWhereClause + ")";
  }
  QgsDebugMsg( statement );

  if ( !query.exec( statement ) )
  {
    QgsDebugMsg( query.lastError().text() );
  }

  if ( !query.isActive() )
  {
    return;
  }

  if ( query.next() )
  {
    mExtent.setXMinimum( query.value( 0 ).toDouble() );
    mExtent.setYMinimum( query.value( 1 ).toDouble() );
    mExtent.setXMaximum( query.value( 2 ).toDouble() );
    mExtent.setYMaximum( query.value( 3 ).toDouble() );
    QgsDebugMsg( QString( "after setting; mExtent: %1" ).arg( mExtent.toString() ) );
  }

  QgsDebugMsg( QString( "mSRId: %1" ).arg( mSRId ) );
  QgsDb2GeometryColumns gc( mDatabase );
  int rc = gc.open( mSchemaName, mTableName );  // returns SQLCODE if failure
  if ( rc == 0 )
  {
    mEnvironment = gc.db2Environment();
    if ( -1 == mSRId )
    {
      QgsDb2LayerProperty layer;
      gc.populateLayerProperty( layer );
      if ( !layer.srid.isEmpty() )
      {
        mSRId = layer.srid.toInt();
        mSrsName = layer.srsName;
      }
      mGeometryColType = layer.type;
      QgsDebugMsg( QString( "srs_id: %1; srs_name: %2; mGeometryColType: %3" )
                   .arg( mSRId ).arg( mSrsName, mGeometryColType ) );
      return;
    }
  }
  else
  {
    QgsDebugMsg( "Couldn't get srid from geometry columns" );
  }

  // Try to get the srid from the data if srid isn't already set
  QgsDebugMsg( QString( "mSRId: %1" ).arg( mSRId ) );
  if ( -1 == mSRId )
  {
    query.clear();
    statement = QString( "SELECT DB2GSE.ST_SRID(%1) FROM %2.%3 FETCH FIRST ROW ONLY" )
                .arg( mGeometryColName, mSchemaName, mTableName );

    QgsDebugMsg( statement );

    if ( !query.exec( statement ) || !query.isActive() )
    {
      QgsDebugMsg( query.lastError().text() );
    }

    if ( query.next() )
    {
      mSRId = query.value( 0 ).toInt();
      QgsDebugMsg( QString( "srid from data: %1" ).arg( mSRId ) );
      return;
    }
    else
    {
      QgsDebugMsg( "Couldn't get srid from data" );
    }
  }
}
Example #13
0
QgsVectorLayerImport::ImportError QgsDb2Provider::createEmptyLayer( const QString& uri,
    const QgsFields &fields,
    QgsWkbTypes::Type wkbType,
    const QgsCoordinateReferenceSystem& srs,
    bool overwrite,
    QMap<int, int> *oldToNewAttrIdxMap,
    QString *errorMessage,
    const QMap<QString, QVariant> *options )
{
  Q_UNUSED( options );

  // populate members from the uri structure
  QgsDataSourceUri dsUri( uri );

  QString connInfo = dsUri.connectionInfo();
  QString errMsg;
  QString srsName;
  QgsDebugMsg( "uri: " + uri );

  // connect to database
  QSqlDatabase db = QgsDb2Provider::getDatabase( connInfo, errMsg );

  if ( !errMsg.isEmpty() )
  {
    if ( errorMessage )
      *errorMessage = errMsg;
    return QgsVectorLayerImport::ErrConnectionFailed;
  }

  // Get the SRS name using srid, needed to register the spatial column
  // srs->posgisSrid() seems to return the authority id which is
  // most often the EPSG id.  Hopefully DB2 has defined an SRS using this
  // value as the srid / srs_id.  If not, we are out of luck.
  QgsDebugMsg( "srs: " + srs.toWkt() );
  long srid = srs.postgisSrid();
  QgsDebugMsg( QString( "srid: %1" ).arg( srid ) );
  if ( srid >= 0 )
  {
    QSqlQuery query( db );
    QString statement = QString( "SELECT srs_name FROM db2gse.st_spatial_reference_systems where srs_id=%1" )
                        .arg( srid );
    QgsDebugMsg( statement );

    if ( !query.exec( statement ) || !query.isActive() )
    {
      QgsDebugMsg( query.lastError().text() );
    }

    if ( query.next() )
    {
      srsName = query.value( 0 ).toString();
      QgsDebugMsg( QString( "srs_name: %1" ).arg( srsName ) );
    }
    else
    {
      QgsDebugMsg( "Couldn't get srs_name from db2gse.st_spatial_reference_systems" );
    }
  }

  QString schemaName = dsUri.schema().toUpper();
  QString tableName = dsUri.table().toUpper();
  QString fullName;

  if ( schemaName.isEmpty() )
  {
    schemaName = dsUri.username().toUpper();  // set schema to user name
  }
  fullName = schemaName + "." + tableName;

  QString geometryColumn = dsUri.geometryColumn().toUpper();
  QString primaryKey = dsUri.keyColumn().toUpper();
  QString primaryKeyType;

  // TODO - this is a bad hack to cope with shapefiles.
  // The wkbType from the shapefile header is usually a multi-type
  // even if all the data is a single-type. If we create the column as
  // a multi-type, the insert will fail if the actual data is a single-type
  // due to type mismatch.
  // We could potentially defer adding the spatial column until addFeatures is
  // called the first time, but QgsVectorLayerImport doesn't pass the CRS/srid
  // information to the DB2 provider and we need this information to register
  // the spatial column.
  // This hack is problematic because the drag/drop will fail if the
  // actual data is a multi-type which is possible with a shapefile or
  // other data source.
  QgsWkbTypes::Type wkbTypeSingle;
  wkbTypeSingle = QgsWkbTypes::singleType( wkbType );
  if ( wkbType != QgsWkbTypes::NoGeometry && geometryColumn.isEmpty() )
    geometryColumn = "GEOM";

  if ( primaryKey.isEmpty() )
    primaryKey = "QGS_FID";

  // get the pk's name and type
  // if no pk name was passed, define the new pk field name
  int fieldCount = fields.size();
  if ( primaryKey.isEmpty() )
  {
    int index = 0;
    QString pk = primaryKey = "QGS_FID";
    for ( int i = 0; i < fieldCount; ++i )
    {
      if ( fields.at( i ).name() == primaryKey )
      {
        // it already exists, try again with a new name
        primaryKey = QString( "%1_%2" ).arg( pk ).arg( index++ );
        i = 0;
      }
    }
  }
  else
  {
    // search for the passed field
    for ( int i = 0; i < fieldCount; ++i )
    {
      if ( fields.at( i ).name() == primaryKey )
      {
        // found, get the field type
        QgsField fld = fields.at( i );
        if ( convertField( fld ) )
        {
          primaryKeyType = fld.typeName();
        }
      }
    }
  }
  QgsDebugMsg( "primaryKeyType: '" + primaryKeyType + "'" );

  QString sql;
  QSqlQuery q = QSqlQuery( db );
  q.setForwardOnly( true );

  // get wkb type and dimension
  QString geometryType;
  int dim = 2;
  db2WkbTypeAndDimension( wkbTypeSingle, geometryType, dim );
  QgsDebugMsg( QString( "wkbTypeSingle: %1; geometryType: %2" ).arg( wkbTypeSingle ).arg( geometryType ) );
  if ( overwrite )
  {
    // remove the old table with the same name
    sql = "DROP TABLE " + fullName;
    if ( !q.exec( sql ) )
    {
      if ( q.lastError().number() != -206 ) // -206 is "not found" just ignore
      {
        QString lastError = q.lastError().text();
        QgsDebugMsg( lastError );
        if ( errorMessage )
        {
          *errorMessage = lastError;
        }
        return QgsVectorLayerImport::ErrCreateLayer;
      }
    }
  }

  // add fields to the layer
  if ( oldToNewAttrIdxMap )
    oldToNewAttrIdxMap->clear();
  QString attr2Create = "";
  if ( fields.size() > 0 )
  {
    int offset = 0;

    // get the list of fields
    QgsDebugMsg( "PrimaryKey: '" + primaryKey + "'" );
    for ( int i = 0; i < fieldCount; ++i )
    {
      QgsField fld = fields.field( i );
      QgsDebugMsg( QString( "i: %1; fldIdx: %2; offset: %3" )
                   .arg( i ).arg( fields.lookupField( fld.name() ) ).arg( offset ) );

      if ( oldToNewAttrIdxMap && fld.name() == primaryKey )
      {
        oldToNewAttrIdxMap->insert( i , 0 );
        continue;
      }

      if ( fld.name() == geometryColumn )
      {
        // Found a field with the same name of the geometry column. Skip it!
        continue;
      }
      QString db2Field = qgsFieldToDb2Field( fld );

      if ( db2Field.isEmpty() )
      {
        if ( errorMessage )
        {
          *errorMessage = QObject::tr( "Unsupported type for field %1" ).arg( fld.name() );
        }
        return QgsVectorLayerImport::ErrAttributeTypeUnsupported;
      }

      if ( oldToNewAttrIdxMap )
      {
        oldToNewAttrIdxMap->insert( fields.lookupField( fld.name() ), offset++ );
      }
      attr2Create += ',' + db2Field.toUpper();
    }
    QgsDebugMsg( attr2Create );
    if ( !geometryColumn.isEmpty() )
    {
      sql = QString( // need to set specific geometry type
              "CREATE TABLE %1(%2 BIGINT NOT NULL PRIMARY KEY GENERATED ALWAYS AS IDENTITY, "
              "%3 DB2GSE.%4 %5) " )
            .arg( fullName,
                  primaryKey,
                  geometryColumn,
                  geometryType,
                  attr2Create );
    }
    else
    {
      //geometryless table
      sql = QString( // need to set specific geometry type
              "CREATE TABLE %1.%2(%3 INTEGER NOT NULL PRIMARY KEY GENERATED ALWAYS %4) " )
            .arg( schemaName,
                  tableName,
                  primaryKey,
                  attr2Create );
    }
    QgsDebugMsg( sql );
    if ( !q.exec( sql ) )
    {
      QString lastError = q.lastError().text();
      QgsDebugMsg( lastError );
      if ( errorMessage )
      {
        *errorMessage = lastError;
      }
      return QgsVectorLayerImport::ErrCreateLayer;
    }


    if ( !geometryColumn.isEmpty() )
    {
      int computeExtents = 0;
      int msgCode = 0;
      int outCode;
      int outMsg;
      QVariant msgText( " " );
      QSqlQuery query( db );
      int db2Environment = ENV_LUW;

// get the environment
      QgsDb2GeometryColumns gc( db );
      int rc = gc.open( schemaName, tableName );  // returns SQLCODE if failure
      if ( rc == 0 )
      {
        db2Environment = gc.db2Environment();
      }
      if ( ENV_LUW == db2Environment )
      {
        sql = QString( "CALL DB2GSE.ST_Register_Spatial_Column(?, ?, ?, ?, ?, ?, ?)" );
        outCode = 5;
        outMsg = 6;
      }
      else // z/OS doesn't support 'computeExtents' parameter and has different schema
      {
        sql = QString( "CALL SYSPROC.ST_Register_Spatial_Column(?, ?, ?, ?, ?, ?)" );
        outCode = 4;
        outMsg = 5;
      }
      query.prepare( sql );
      query.bindValue( 0, schemaName );
      query.bindValue( 1, tableName );
      query.bindValue( 2, geometryColumn );
      query.bindValue( 3, srsName );
      if ( ENV_LUW == db2Environment )
      {
        query.bindValue( 4, computeExtents );
      }

      query.bindValue( outCode, msgCode, QSql::Out );
      query.bindValue( outMsg, msgText, QSql::Out );

      if ( !query.exec() )
      {
        QgsDebugMsg( QString( "error: %1; sql: %2" ).arg( query.lastError().text(), query.lastQuery() ) );
      }
      else
      {
        msgCode = query.boundValue( outCode ).toInt();
        msgText = query.boundValue( outMsg ).toString();  // never gets a value...
        if ( 0 != msgCode )
        {
          QgsDebugMsg( QString( "Register failed with code: %1; text: '%2'" ).arg( msgCode ).arg( msgText.toString() ) );
        }
        else
        {
          QgsDebugMsg( "Register successful" );
        }
      }

      QList<QVariant> list = query.boundValues().values();
      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() ) );
      }

    }
    // clear any resources hold by the query
    q.clear();
    q.setForwardOnly( true );

  }
  QgsDebugMsg( "successfully created empty layer" );
  return QgsVectorLayerImport::NoError;
}
Example #14
0
Cattle CattleController::getSingleCattle(const int id)
{
   Cattle cow;

   string tagNumber;
   string NLSTag;
   string name;
   string description;
   string imagePath;
   int cowID;
   bool show;

   const QString getSingleCattleTemplate = "select cowID, cowTag, cowNlsTag, entName, entDescription, entImagePath, entShow from Cattle, Entity where entID = %1";

   QSqlQuery query;
   QSqlRecord record;

   const string getSingleCattleQuery = getSingleCattleTemplate.arg(id).toStdString();

   try
   {
      query = databaseController.selectQuery(getSingleCattleQuery);
      record = query.record();
   }
   catch (SQLException & e)
   {
      cerr << "Exception caught at " << __FILE__ << ": " << __LINE__  << endl
            << e.what() << endl;

      throw e;
   }

   query.first();

   name = query.value(record.indexOf("entName")).toString().toStdString();
   tagNumber = query.value(record.indexOf("cowTag")).toString().toStdString();
   NLSTag = query.value(record.indexOf("cowNlsTag")).toString().toStdString();
   description = query.value(record.indexOf("entDescription")).toString().toStdString();
   imagePath = query.value(record.indexOf("entImagePath")).toString().toStdString();
   show = query.value(record.indexOf("entShow")).toBool();

   bool ok;
   cowID = query.value(record.indexOf("cowID")).toInt(&ok);

   cow.setMother(getMother(cow));
   cow.setFather(getFather(cow));

   cow.setTagNumber(tagNumber);
   cow.setNLSTag(NLSTag);
   cow.setName(name);
   cow.setDescription(description);
   cow.setImagePath(imagePath);
   cow.setEntityID(cowID);

   cow.setShow(show);

#warning The controllers have to be implemented here still
	/**

   cow.setHorn(hornController.getHorn(cow));
   cow.setColour(colourController.getColour(cow));
   cow.setGender(genderController.getGender(cow));
   cow.setVariety(varietyController.getVariety(cow));
   cow.setLocation(locationController.getLocation(cow));
   cow.setSource(sourceController.getSource(cow));
   cow.setModule(moduleController.getModule(cow));
   cow.setEvents(eventController.getEvents(cow));
	*/

   query.clear();

   return cow;
}
Example #15
0
bool TestAssistance::packAllQuestions()
{
    allQuestions.clear();
    //open database
    if (!m_objDatabase.open()) {
        packErrorInfo(m_objDatabase.lastError().text(),
                      TA_ERROR_NOTCONNECTED);
        return false;
    }

    //pack questions
    QSqlQuery query;
    query.prepare("SELECT qno,qtxt,qgrade,qmajor,qcourse,qcnt,"
                  "qhard,qdate,qright,qtype,qknowpoint,qimage FROM questions");

    QUESTIONINFO info;
    if(query.exec()){
        while(query.next()){
            info.qno = query.value(0).toInt();
            info.qtxt = query.value(1).toString();
            info.qgrade = query.value(2).toInt();
            info.qmajor = query.value(3).toString();
            info.qcourse = query.value(4).toString();
            info.qcnt = query.value(5).toInt();
            info.qhard = query.value(6).toInt();
            info.qdate = query.value(7).toInt();
            info.qright = query.value(8).toInt();
            info.qtype = query.value(9).toInt();
            info.qknowpoint = query.value(10).toString();
            info.qimage = query.value(11).toByteArray();
            allQuestions.push_back(info);
        }
    }
    else{
        packErrorInfo(query.lastError().text(),
                      TA_ERROR_SQLERROR);
        m_objDatabase.close();
        return false;
    }
    m_objDatabase.close();
    return true;
}
Example #16
0
void MovieMedia::getInfoFromMediaId(unsigned int id) {
    QSqlQuery q;
    QString whereName = "mediaId";
    QString idString = QString("%1").arg(id);
    DatabaseManager::getInstance()->queryImdbInfoWhere(q, whereName, idString);

    int fieldImdbId         = q.record().indexOf("ImdbId");
    int fieldGenre          = q.record().indexOf("genre");
    int fieldYear           = q.record().indexOf("year");
    int fieldRuntime        = q.record().indexOf("runtime");
    int fieldRating         = q.record().indexOf("rating");
    int fieldTitle          = q.record().indexOf("title");
    int fieldDirector       = q.record().indexOf("director");
    int fieldCountry        = q.record().indexOf("country");
    int fieldImage          = q.record().indexOf("image");
    int fieldCast           = q.record().indexOf("cast");
    int fieldPlot           = q.record().indexOf("plot");

    while (q.next()) {
        this->setImdbId(q.value(fieldImdbId).toInt());
        this->setGenre(q.value(fieldGenre).toString());
        this->setYear(q.value(fieldYear).toInt());
        this->setRuntime(q.value(fieldRuntime).toInt());
        this->setRating(q.value(fieldRating).toDouble());
        this->setTitle(q.value(fieldTitle).toString());
        this->setDirector(q.value(fieldDirector).toString());
        this->setCountry(q.value(fieldCountry).toString());
        this->setImage(q.value(fieldImage).toString());
        this->setCast(q.value(fieldCast).toString());
        this->setPlot(q.value(fieldPlot).toString());
    }
}
Example #17
0
bool TestAssistance::addQuestion(const QUESTIONINFO &info, int &newId)
{
    //open database
    if (!m_objDatabase.open()) {
        packErrorInfo(m_objDatabase.lastError().text(),
                      TA_ERROR_NOTCONNECTED);
        return false;
    }


    QSqlQuery query;
    query.prepare("INSERT INTO questions VALUES(NULL,:qtxt,:qgrade,:qmajor,"
                  ":qcourse,:qcnt,:qhard,:qdate,:qright,:qtype,:qknowpoint,NULL)");

    query.bindValue(":qtxt", info.qtxt);
    query.bindValue(":qgrade", info.qgrade);
    query.bindValue(":qmajor", info.qmajor);
    query.bindValue(":qcourse", info.qcourse);
    query.bindValue(":qcnt", info.qcnt);
    query.bindValue(":qhard", info.qhard);
    query.bindValue(":qdate", info.qdate);
    query.bindValue(":qright", info.qright);
    query.bindValue(":qtype", info.qtype);
    query.bindValue(":qknowpoint", info.qknowpoint);

    if(!query.exec()){
        packErrorInfo(query.lastError().text(),
                      TA_ERROR_SQLERROR);
        m_objDatabase.close();
        return false;
    }
    query.prepare("SELECT qno FROM questions WHERE qtxt=:qtxt");
    query.bindValue(":qtxt", info.qtxt);
    query.exec();
    query.next();
    newId = query.value(0).toInt();
    m_objDatabase.close();
    return true;
}
Example #18
0
/**
 * @brief Database::AddStadium
 * Adds new Stadium to the data base with the following attributes.
 * @param stadiumName
 * @param teamName
 * @param address
 * @param phoneNumber
 * @param dateOpened
 * @param capacity
 * @param turfType
 * @param revenue
 * @param leauge
 * @param typology
 * @return true if it worked else false
 */
bool Database::AddStadium(QString stadiumName,QString teamName,QString address,
                          QString phoneNumber,QString dateOpened,QString capacity,QString turfType,
                          long revenue,QString leauge,QString typology)
{
    QSqlQuery query;
    query.prepare("INSERT INTO stadiums(name,team,address,phone,date,capacity,turf,revenue,league,typology)"
                  "VALUES (:name,:team,:address,:phone,:date,:capacity,:turf,:revenue,:league,:typology)");

        query.bindValue(":name", stadiumName);
        query.bindValue(":team", teamName);
        query.bindValue(":address", address);
        query.bindValue(":phone", phoneNumber);
        query.bindValue(":date", dateOpened);
        query.bindValue(":capacity", capacity);
        query.bindValue(":turf", turfType);
        query.bindValue(":revenue", QString::number(revenue));
        query.bindValue(":league", leauge);
        query.bindValue(":typology", typology);
        if(query.exec()){
            return true;
        }

            qDebug() << query.lastError().text();
            return false;
}
Example #19
0
void MainWindow::onReleasePushButtonClicked()
{
    ui->releasePushButton->setEnabled( false );
    QString serial = ui->serialLineEdit->text().replace("-", "");

    QMessageBox msgBox(ui->centralWidget);
    msgBox.setWindowTitle( tr("シリアル番号の入力"));

    DbConnect db;
    if ( ! db.isConnect ) {
        msgBox.setText( tr("サーバーに接続できません。<br>インターネット接続をお確かめください。") );
        msgBox.exec();
        return;
    }
    QHash<QString, QString> selectParams, updateParams;
    selectParams.insert(":SERIAL", serial);
    updateParams.insert(":SERIAL", serial);
    selectParams.insert(":ON", STORES_ON );
    selectParams.insert(":OFF", STORES_OFF );
    {
        QString sql;
        sql =  " UPDATE stores ";
        sql += "   SET ";
        sql += "   on_off = :ON";
        sql += " WHERE serial = :SERIAL ";
        sql += "   AND on_off = :OFF ";
        db.queryPrepareExecute(sql, selectParams);
    }
    {
         QString sql;
         sql =  " SELECT ";
         sql += "        A.name ";
         sql += "       ,A.on_off ";
         sql += "   FROM stores A ";
         sql += "   WHERE A.serial = :SERIAL ";
         QSqlQuery *query = db.queryPrepareExecute(sql, updateParams);

         while ( query->next()) {
            QString name = query->value(0).toString();
            QString on_off = query->value(1).toString();
//            qDebug() << name << on_off;

            if ( on_off == STORES_ON ) {
                msgBox.setStandardButtons(QMessageBox::Ok);
                msgBox.setText( tr("制限は解除されました。") );
                ui->decorativeProgressBar->setMaximum( 100 );
            }
         }
         if ( 0 == query->size() ) {
             msgBox.setStandardButtons(QMessageBox::Yes);
             msgBox.setText( tr("制限が解除できませんでした。\nシリアル番号をご確認ください。") );
             ui->decorativeProgressBar->setMaximum( 50 );
         }
    }
    ui->decorativeProgressBar->setVisible( true );

    /* 飾りプログレスバー */
    QEventLoop loop;
    for (int i = 0; i <= 100; i++ ) {

        QTimer::singleShot( 50, &loop, SLOT( quit() ) );
        loop.exec();
        ui->decorativeProgressBar->setValue(i);
    }

    msgBox.exec();
}
Example #20
0
/**
 * @brief Database::AddRevenue
 * Add amount to revenue attribute in stadiums table
 * @param id stadiums id
 * @param revenue of the stadium
 * @return
 */
bool Database::AddRevenue(int id, double revenue)
{
    QSqlQuery query;
    query.prepare("select revenue from stadiums where id = :id");
    query.bindValue(":id", id);
    if(query.exec()){
        if(query.next()){
            double originalRev = query.record().field("revenue").value().toDouble();
            query.clear();
            query.prepare("update stadiums set revenue = :newRev where id = :id");
            double newRev = originalRev + revenue;
            query.bindValue(":newRev", newRev);
            query.bindValue(":id", id);
            return query.exec();
        }
        else
        {
            qDebug() << query.lastError().text();
            return false;
        }
    }
    else
    {
        qDebug() << query.lastError().text();
        return false;
    }
}
Example #21
0
File: db.cpp Project: 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();
}
Example #22
0
void RecitalTabs::recitalStateChanged(int state)
{

    if(state && !breakComboBoxStateConnection) { //erledigt

        FinishRecitalDialog *dialog = new FinishRecitalDialog;
        dialog->exec();
        if(dialog->result() == QDialog::Accepted) {
            if(dialog->getActivityAnswer()) {
                QSqlQuery query;
                query.prepare("SELECT pieceid FROM pieceatrecital WHERE recitalid=? AND ifexternalpiece=0"); // alle werke aus diesem Vorspiel suchen
                query.addBindValue(recitalId);
                query.exec();
                if (query.lastError().isValid()) {
                    qDebug() << "DB Error: 208 - " << query.lastError();
                } else {
                    while(query.next()) {
                        QSqlQuery query2;
                        query2.prepare("SELECT l.type, pal.pupilid FROM lesson l, piece p, pupilatlesson pal WHERE p.palid=pal.palid AND pal.lessonid=l.lessonid AND p.cpieceid=(SELECT cpieceid FROM piece WHERE pieceid=?)");
                        query2.addBindValue(query.value(0).toInt());
                        query2.exec();
                        if (query2.lastError().isValid()) {
                            qDebug() << "DB Error: 209 - " << query2.lastError();
                        } else {
                            while(query2.next()) {
                                int activityType;
                                if(query2.value(0).toInt() == 3) { //das ist ein Ensemble
                                    activityType = 1;
                                } else { // das ist ein Unterricht Gruppe oder Einzel
                                    activityType = 0;
                                }

                                QSqlQuery query3;
                                query3.prepare("SELECT desc, location, date FROM recital WHERE recitalid=?");
                                query3.addBindValue(recitalId);
                                query3.exec();
                                if (query3.lastError().isValid()) {
                                    qDebug() << "DB Error: 210 - " << query3.lastError();
                                } else {
                                    query3.next();

                                    QSqlQuery query4;
                                    query4.prepare("SELECT p.title , pc.composer FROM piece p, piececomposer pc WHERE p.piececomposerid=pc.piececomposerid AND p.pieceid=?");
                                    query4.addBindValue(query.value(0).toInt());
                                    query4.exec();
                                    if (query4.lastError().isValid()) {
                                        qDebug() << "DB Error: 211 - " << query4.lastError();
                                    } else {
                                        query4.next();

                                        QSqlQuery query5;
                                        query5.prepare("INSERT INTO activity (pupilid, ifcontinous, desc, date, noncontinoustype) VALUES (?, 0, ?, ?, ?)");
                                        query5.addBindValue(query2.value(1).toInt());
                                        query5.addBindValue(query3.value(0).toString()+", "+query3.value(1).toString()+": "+query4.value(1).toString()+" - "+query4.value(0).toString());
                                        query5.addBindValue(query3.value(2).toString());
                                        query5.addBindValue(activityType);
                                        query5.exec();
                                        if (query5.lastError().isValid()) {
                                            qDebug() << "DB Error: 231 - " << query5.lastError();
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            if(dialog->getPieceAnswer()) {

                QSqlQuery query;
                query.prepare("SELECT pieceid FROM pieceatrecital WHERE recitalid=? AND ifexternalpiece=0"); // alle werke aus diesem Vorspiel suchen
                query.addBindValue(recitalId);
                query.exec();
                if (query.lastError().isValid()) {
                    qDebug() << "DB Error: 213 - " << query.lastError();
                } else {
                    while(query.next()) {
                        QSqlQuery query2;
                        query2.prepare("UPDATE piece SET state = 4, stopdate = date('now') WHERE cpieceid=(SELECT cpieceid FROM piece WHERE pieceid=?)");
                        query2.addBindValue(query.value(0).toInt());
                        query2.exec();
                        if (query2.lastError().isValid()) {
                            qDebug() << "DB Error: 214 - " << query2.lastError();
                        }
                    }
                }
            }
        }
    }

    QSqlQuery query;
    query.prepare("UPDATE recital SET state = ? WHERE recitalid = ?");
    query.addBindValue(state);
    query.addBindValue(recitalId);
    query.exec();
    if (query.lastError().isValid()) {
        qDebug() << "DB Error: 212 - " << query.lastError();
    }

}
Example #23
0
void DetailMeeting::deleteMeeting()
{
    QSqlQuery query;
    query.prepare("SELECT * FROM Meeting where id_meeting = :id_meeting");
    query.bindValue(":id_meeting", meeting_id);
    query.exec();
    QSqlRecord rec = query.record();
    query.next();

    sendEmailDeleteMeeting(meeting_id,query.value(rec.indexOf("date_begin")).toString());

    query.prepare("DELETE FROM UsersMeeting where id_meeting = :id_meeting");
    query.bindValue(":id_meeting", meeting_id);
    query.exec();

    query.prepare("DELETE FROM Meeting where id = :id_meeting");
    query.bindValue(":id_meeting", meeting_id);
    query.exec();

    this->close();
    emit notifyRefreshList();
}
Example #24
0
QVariant QCDRTableModel::data(const QModelIndex & idx, int role) const
{
    if (!idx.isValid())
        return QVariant();

    if (role == Qt::TextColorRole) { // расскрасим
        int typecall = data(index(idx.row(), QCDRSortFilterModel::COL_CALL_TYPE), Qt::UserRole).toInt();

        switch (typecall) {
            case Qcallog::TYPE_LOCAL: return QBrush(QColor(90, 90, 90));;
            case Qcallog::TYPE_IN_LOCAL: return QBrush(QColor(50, 255, 50));
            case Qcallog::TYPE_OUT_INTERNATIONAL: return QBrush(QColor(20, 20, 20));;
            case Qcallog::TYPE_OUT_NATIONAL: return QBrush(QColor(20, 20, 20));;
            case Qcallog::TYPE_OUT_LOCAL: return QBrush(QColor(100, 200, 100));
            case Qcallog::TYPE_TRANZIT_INTERNATIONAL: return QBrush(QColor(255, 80, 80));
            case Qcallog::TYPE_TRANZIT_NATIONAL: return QBrush(QColor(255, 10, 20));
            case Qcallog::TYPE_TRANZIT_LOCAL: return QBrush(QColor(100, 100, 200));
            default: return QBrush(QColor(0, 0, 0));
        }
    }

    if (role == Qt::DisplayRole || role == Qt::UserRole) {
        if (idx.column() == QCDRSortFilterModel::COL_IN_TYPE || idx.column() == QCDRSortFilterModel::COL_OUT_TYPE) {
            QString strtype = QSqlTableModel::data(idx, Qt::DisplayRole).toString();
            int module = QSqlTableModel::data(QSqlTableModel::index(idx.row(), idx.column() + 1), Qt::DisplayRole).toInt();
            int pcm = QSqlTableModel::data(QSqlTableModel::index(idx.row(), idx.column() + 2), Qt::DisplayRole).toInt();
            int ch = QSqlTableModel::data(QSqlTableModel::index(idx.row(), idx.column() + 3), Qt::DisplayRole).toInt();

            QString str1 = QString("%1").arg(module, 3, 10, QLatin1Char('0'));
            QString str2 = QString("%1").arg(pcm, 3, 10, QLatin1Char('0'));
            QString str3 = QString("%1").arg(ch, 3, 10, QLatin1Char('0'));

            QString val = QString("%1%2%3%4").arg(strtype).arg(str1).arg(strtype == "A" ? "" : str2).arg(strtype == "A" ? "" : str3);
            if (strtype == "C") {
                // попытаемся найти имя этого канала по базе
                qint64 address = ((qint64)module << 32) | (pcm << 16) | ch;
                QSqlQuery query;
                if (query.exec(QString("select name from DirectionChannel, DirectionName where key = id and fr <= %1 and by >= %1").arg(address))) {
                    if (query.next())
                        return query.value(0).toString();
                }
            }

            return val;
        }
    }

    if (role == Qt::DisplayRole) {
        if (idx.column() == QCDRSortFilterModel::COL_DATE)
            return QDate::fromJulianDay(QSqlTableModel::data(idx, role).toLongLong()).toString("dd-MM-yyyy");

        if (idx.column() == QCDRSortFilterModel::COL_TIME)
            return QTime(0, 0).addSecs(QSqlTableModel::data(idx, role).toLongLong()).toString("hh:mm:ss");

        if (idx.column() == QCDRSortFilterModel::COL_TIME_SEIZ)
            return QTime(0, 0).addSecs(QSqlTableModel::data(idx, role).toLongLong()).toString("hh:mm:ss");

        if (idx.column() == QCDRSortFilterModel::COL_TIME_TALK)
            return QTime(0, 0).addSecs(QSqlTableModel::data(idx, role).toLongLong()).toString("hh:mm:ss");

        if (idx.column() == QCDRSortFilterModel::COL_CALL_TYPE)
            return Qcallog::getQStringTypeCalls(data(idx, Qt::UserRole).toInt());

        if (idx.column() == QCDRSortFilterModel::COL_CRELEASE)
            return QCDRSortFilterModel::causeValue.value(QSqlTableModel::data(idx, role).toInt()).second;

    }
    if (role == Qt::UserRole) {
//        if (idx.column() == QCDRSortFilterModel::COL_CRELEASE)
//            return QSqlTableModel::data(idx, Qt::DisplayRole);

        if (idx.column() == QCDRSortFilterModel::COL_CALL_TYPE) {
            QString strTypeIn = QSqlTableModel::data(index(idx.row(), QCDRSortFilterModel::COL_IN_TYPE), Qt::DisplayRole).toString();
            QString strTypeOut = QSqlTableModel::data(index(idx.row(), QCDRSortFilterModel::COL_OUT_TYPE), Qt::DisplayRole).toString();
            QString strNumberIn = QSqlTableModel::data(index(idx.row(), QCDRSortFilterModel::COL_IN_NUMBER), Qt::DisplayRole).toString();
            QString strNumberOut = QSqlTableModel::data(index(idx.row(), QCDRSortFilterModel::COL_OUT_NUMBER), Qt::DisplayRole).toString();
            return Qcallog::getIntTypeCalls(QStringList() << strTypeIn << strTypeOut << strNumberIn << strNumberOut);
        }
    }

    return QSqlTableModel::data(idx, role);
}
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);
    }
}
Example #26
0
bool TestAssistance::userRegister(const QString &username, const QString password, bool isadmin, int &newId)
{
    //open database
    if (!m_objDatabase.open()) {
        packErrorInfo(m_objDatabase.lastError().text(),
                      TA_ERROR_NOTCONNECTED);
        return false;
    }


    //register

    QSqlQuery query;
    query.prepare("SELECT username FROM userinfo WHERE username=:username");
    query.bindValue(":username", username);
    if(query.exec()){
        if(query.next()){//check if username existed
            packErrorInfo("Username existed.",
                          TA_ERROR_USERNAME_EXISTED);
            m_objDatabase.close();
            return false;
        }
        else{//username doesnot exist
            query.prepare("INSERT INTO userinfo VALUES(NULL, :username, :password, :isadmin)");
            query.bindValue(":username", username);
            query.bindValue(":password", password);
            query.bindValue(":isadmin", (isadmin?1:0));
            if(!query.exec()){
                packErrorInfo(query.lastError().text(),
                              TA_ERROR_SQLERROR);
                m_objDatabase.close();
                return false;
            }

            //get new id
            query.prepare("SELECT id FROM userinfo WHERE username=:username");
            query.bindValue(":username", username);
            query.exec();
            query.next();
            newId = query.value(0).toInt();
        }
    }
    else{
        packErrorInfo(query.lastError().text(),
                      TA_ERROR_SQLERROR);
        m_objDatabase.close();
        return false;
    }
    m_objDatabase.close();
    return true;
}
Example #27
0
void ScreenshotManager::updateHistory(QString fileName, QString url, QString deleteHash)
{
  if (!mSettings->value("/options/history", true).toBool() || url.isEmpty())
    return;

  QSqlQuery query;
  query.prepare("SELECT fileName FROM history WHERE URL IS NOT EMPTY AND fileName = ?");
  query.addBindValue(fileName);
  query.exec();

  if (query.record().count() > 0) {
    QSqlQuery updateQuery;
    updateQuery.prepare("UPDATE history SET URL = ?, deleteURL = ?, time = ? WHERE fileName = ?");
    updateQuery.addBindValue(url);
    updateQuery.addBindValue("https://imgur.com/delete/" + deleteHash);
    updateQuery.addBindValue(QDateTime::currentMSecsSinceEpoch());
    updateQuery.addBindValue(fileName);

    updateQuery.exec();
  }
  else {
    saveHistory(fileName, url, deleteHash);
  }
}
Example #28
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;
}
/*!
 * \brief Database::logSqlError Logs a SQL error
 * \param q
 */
void Database::logSqlError(QSqlQuery& q) const
{
    qDebug() << "SQLite error: " << q.lastError();
    qDebug() << "SQLite string: " << q.lastQuery();
}
Example #30
0
void DBWorker::removeHistoryEntry(int linkId)
{
    QSqlQuery query = prepare("DELETE FROM browser_history WHERE id = ?");
    query.bindValue(0, linkId);
    execute(query);
}