Example #1
0
void ImportWindow::sImport()
{
  _log->append(tr("Import Started..."));
  Q3ListBoxItem * item = _reports->firstItem();
  Q3ListBoxItem * next = 0;
  while(item)
  {
    next = item->next();
    if(item->isSelected())
    {
      QString xml_file = ((ListBoxReportItem*)item)->report();

      QString report_name  = QString::null;
      QString report_desc  = QString::null;
      QString report_src   = QString::null;
      int     report_grade = ((ListBoxReportItem*)item)->grade();

      if(!xml_file.isEmpty())
      {
        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.isEmpty())
              {
                QSqlQuery qry;
                QSqlQuery query;

                qry.prepare("SELECT report_id "
                            "  FROM report "
                            " WHERE ((report_name=:rptname) "
                            "   AND (report_grade=:rptgrade));");
                qry.bindValue(":rptname",  report_name);
                qry.bindValue(":rptgrade", report_grade);
                qry.exec();
                if(qry.first())
                {
                  // update
                  query.prepare("UPDATE report "
                                "   SET report_descrip=:rptdescr, "
                                "       report_source=:rptsrc "
                                " where report_id=:rptid "
                                "   and report_name=:rptname;");
                  query.bindValue(":rptdescr", report_desc);
                  query.bindValue(":rptsrc",   report_src);
                  query.bindValue(":rptid", qry.value(0));
                  query.bindValue(":rptname",  report_name);
                }
                else
                {
                  // insert
                  query.prepare("INSERT INTO report "
                                "       (report_name, report_descrip, report_source, report_grade) "
                                "VALUES (:rptname, :rptdescr, :rptsrc, :rptgrade);");
                  query.bindValue(":rptname",  report_name);
                  query.bindValue(":rptdescr", report_desc);
                  query.bindValue(":rptsrc",   report_src);
                  query.bindValue(":rptgrade", report_grade);
                }
                
                if(!query.exec())
                {
                  QSqlError err = query.lastError();
                  _log->append(tr("<font color=red>The following error was encountered while trying to import %1 into the database:\n"
                                  "\t%2\n\t%3\n</font>")
                                .arg(xml_file)
                                .arg(err.driverText())
                                .arg(err.databaseText()));
                }
                else
                  _log->append(tr("Import successful of %1").arg(xml_file));
              }
              else
                _log->append(tr("<font color=orange>The document %1 does not have a report name defined\n</font>")
                              .arg(xml_file));
            }
            else
              _log->append(tr("<font color=red>XML Document %1 does not have root node of report\n</font>")
                            .arg(xml_file));
          }
          else
            _log->append(tr("<font color=red>Error parsing file %1: %2 on line %3 column %4\n</font>")
                          .arg(xml_file).arg(errMsg).arg(errLine).arg(errCol));
        }
        else
          _log->append(tr("<font color=red>Could not open the specified file: %1\n</font>")
                        .arg(xml_file));
      }
      else
        _log->append("<font color=red>Encountered and empty entry: No file name was given.\n</font>");
    }
    item = next;
  }
  _log->append(tr("Import complete!\n\n\n"));
}
int CSqliteDbOper::_AddDataArrayBar(unsigned int nTableKey, LstInstrumentBarInfoT*  pListBar)
{
	BOOST_LOG_FUNCTION();
	int nFunRes = 0;
	bool bExecRes = false;
	std::string strSQL;
	std::string strTimeStr;
	LstInstrumentBarInfoIterT iterLst;
	CInstrumentBarInfo* pInstrumentBarInfo = NULL;
	//QVariantList lstInstrumentID;
	QVariantList lstTimestamp;
	QVariantList lstOpen;
	QVariantList lstClose;
	QVariantList lstHigh;
	QVariantList lstLow;
	QVariantList lstVolume;
	QSqlQuery* pQSqlQueryForInseert = NULL;

	if (pListBar->empty())
	{
		nFunRes = 0;
		return nFunRes;
	}

	pQSqlQueryForInseert = new QSqlQuery(*m_pQSqlDataBaseBAR);

	strSQL = _BuildSQLForInsertBarData(nTableKey);

	LOG_DEBUG<<"m_pDBOperParam->m_nInstrumentID="<<m_pDBOperParam->m_nInstrumentID
		<<"  "<<"strSQL="<<strSQL
		<<"  "<<"pLstInstrumentBarInfo.size="<<pListBar->size();

	pQSqlQueryForInseert->prepare(strSQL.c_str());

	iterLst = pListBar->begin();
	while (iterLst != pListBar->end())
	{
		pInstrumentBarInfo = (*iterLst);

		//lstInstrumentID<<m_pDBOperParam->m_nInstrumentID;
		strTimeStr = m_pUtilityFun->dataTimeToStr(pInstrumentBarInfo->m_BarInfo.Time);
		lstTimestamp << strTimeStr.c_str();
		lstOpen<<pInstrumentBarInfo->m_BarInfo.Open;
		lstClose<<pInstrumentBarInfo->m_BarInfo.Close;
		lstHigh<<pInstrumentBarInfo->m_BarInfo.High;
		lstLow<<pInstrumentBarInfo->m_BarInfo.Low;
		lstVolume<<pInstrumentBarInfo->m_BarInfo.Volume;

		iterLst++;
	}//while

	//pQSqlQueryForInseert->addBindValue(lstInstrumentID);
	pQSqlQueryForInseert->addBindValue(lstTimestamp);
	pQSqlQueryForInseert->addBindValue(lstOpen);
	pQSqlQueryForInseert->addBindValue(lstClose);
	pQSqlQueryForInseert->addBindValue(lstHigh);
	pQSqlQueryForInseert->addBindValue(lstLow);
	pQSqlQueryForInseert->addBindValue(lstVolume);

	bExecRes = pQSqlQueryForInseert->execBatch();
	if (!bExecRes)
	{
		nFunRes = -1;
		LOG_ERROR<<"execBatch strSQL="<<strSQL<<" pLstInstrumentBarInfo.size="<<pListBar->size()
			<<" "<<"error:"<<pQSqlQueryForInseert->lastError().text().toStdString();
	}

	if (NULL != pQSqlQueryForInseert)
	{
		delete pQSqlQueryForInseert;
		pQSqlQueryForInseert = NULL;
	}
	return nFunRes;
}
void SizPostForm::addRecordOfTablePost()
{
    QTextStream stream(&exchangeFile);
    QString line;
    while(!stream.atEnd()){
        stream.readLine();
    }
    if(checkingFill()){
        ViewListTable listTable("","post",this);
        listTable.exec();
        QString postId = listTable.returnValue();

        QSqlQuery query;
        query.prepare("SELECT * FROM post WHERE postid = :id");
        query.bindValue(":id",postId);
        query.exec();
        while(query.next()){
            int rowCount = postView->rowCount();
            bool insert = true;
            //Проверка на существование записи
            if (rowCount != 0){
                for(int kk = 0; kk < rowCount; ++kk){
                    QString yy = postView->item(kk,2)->text();
                    QString pp = query.value(1).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;
                postView->insertRow(rowCount);

                NumPrefix numPrefix;
                QString idPostSizList = numPrefix.getPrefix("postsizlist");

                QTableWidgetItem *itemID = new QTableWidgetItem;
                postView->setItem(rowCount,0,itemID);
                postView->item(rowCount,0)->setText(idPostSizList);

                QTableWidgetItem *itemPostSiz = new QTableWidgetItem;
                postView->setItem(rowCount,1,itemPostSiz);
                postView->item(rowCount,1)->setText(indexTemp);

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

                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;
            }
        }
    }
}
Example #4
0
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=", Qt::CaseInsensitive))
        username = arguments.right(arguments.length() - 10);
      else if (arguments.startsWith("-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;
}
void ImportWindow::sImport()
{
  _log->append(tr("Import Started..."));
  QListWidgetItem * item = 0;
  QList<QListWidgetItem *> list = _reports->selectedItems();
  for(int i = 0; i < list.count(); i++)
  {
    item = list.at(i);
    QString xml_file = item->text();

    QString report_name  = QString::null;
    QString report_desc  = QString::null;
    QString report_src   = QString::null;
    int     report_grade = item->data(Qt::UserRole).toInt();

    if(!xml_file.isEmpty())
    {
      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.isEmpty())
            {
              QSqlQuery qry;
              QSqlQuery query;

              qry.prepare(getSqlFromTag("fmt09", QSqlDatabase::database().driverName()));	// MANU
              qry.bindValue(":report_name",  report_name);	// MANU
              qry.bindValue(":report_grade", report_grade);	// MANU
              qry.exec();
              if(qry.first())
              {
                // update
                query.prepare(getSqlFromTag("fmt10", QSqlDatabase::database().driverName()));	// MANU
                query.bindValue(":report_desc", report_desc);		// MANU
                query.bindValue(":report_src",   report_src);		// MANU
                query.bindValue(":report_id", qry.value(0));		// MANU
                query.bindValue(":report_name",  report_name);	// MANU
              }
              else
              {
                // insert
                query.prepare(getSqlFromTag("fmt11", QSqlDatabase::database().driverName()));	// MANU
                query.bindValue(":report_name",  report_name);	// MANU
                query.bindValue(":report_desc", report_desc);		// MANU
                query.bindValue(":report_src",   report_src);		// MANU
                query.bindValue(":report_grade", report_grade);	// MANU
              }
              
              if(!query.exec())
              {
                QSqlError err = query.lastError();
                _log->append(tr("<font color=red>The following error was encountered while trying to import %1 into the database:\n"
                                "\t%2\n\t%3\n</font>")
                              .arg(xml_file)
                              .arg(err.driverText())
                              .arg(err.databaseText()));
              }
              else
                _log->append(tr("Import successful of %1").arg(xml_file));
            }
            else
              _log->append(tr("<font color=orange>The document %1 does not have a report name defined\n</font>")
                            .arg(xml_file));
          }
          else
            _log->append(tr("<font color=red>XML Document %1 does not have root node of report\n</font>")
                          .arg(xml_file));
        }
        else
          _log->append(tr("<font color=red>Error parsing file %1: %2 on line %3 column %4\n</font>")
                        .arg(xml_file).arg(errMsg).arg(errLine).arg(errCol));
      }
      else
        _log->append(tr("<font color=red>Could not open the specified file: %1\n</font>")
                      .arg(xml_file));
    }
    else
      _log->append("<font color=red>Encountered and empty entry: No file name was given.\n</font>");
  }
  _log->append(tr("Import complete!\n\n\n"));
}
Example #6
0
bool AbstractDocument::addTrasact(int artId, int storage, int storageOut,
                                  double count, double price, QString name,
                                  QString suborder, int mol, int transType, int formDirection)
{
    QSqlQuery sqlTransact;
    sqlTransact.prepare("INSERT INTO storage_transaction (tr_article,"
                        "tr_storage,tr_storage_out,tr_count_transac,"
                        "tr_count_current,tr_price_transac,tr_price_current,"
                        "tr_document,tr_type,tr_name,tr_mol,tr_suborder,"
                        "tr_form_direction) VALUES ("
                        ":art,:storage,:storage_out,:count_tr,:count_cur,"
                        ":price_tr,:price_cur,:doc,:type,:name,:mol,:suborder,"
                        ":form_direction)");

    int direction_type = transType;

    if (transType == -1) {
        direction_type = count > 0
                         ? TransactionType::In
                         : TransactionType::Out;
    }

    double currCount = 0.0;
    double currPrice = 0.0;

    QSqlQuery sql;

    if (formDirection == 1) {
        sql.exec(QString("SELECT tr_count_current,tr_price_current FROM current_balance_n "
                         "WHERE tr_article = %1 AND tr_storage = %2 AND tr_form_direction = %3")
                 .arg(artId)
                 .arg(storage)
                 .arg(formDirection));
    } else if (formDirection == 2) {
        sql.exec(QString("SELECT tr_count_current,tr_price_current FROM current_balance_mol "
                         "WHERE tr_article = %1 AND tr_mol = %2 AND tr_suborder = '%4' AND tr_form_direction = %3")
                 .arg(artId)
                 .arg(mol)
                 .arg(formDirection)
                 .arg(suborder));
    }
    if (direction_type == TransactionType::Inventarize && count == 0) {
    } else {
        if (sql.next()) {
            currCount = sql.value(0).toDouble();
            currPrice = sql.value(1).toDouble();
        }
    }


    sqlTransact.bindValue(":art",artId);
    sqlTransact.bindValue(":storage",storage);
    sqlTransact.bindValue(":storage_out",storageOut);
    sqlTransact.bindValue(":count_tr",count < 0 ? - count : count);
    sqlTransact.bindValue(":count_cur",currCount + count);
    sqlTransact.bindValue(":price_tr",price);
    sqlTransact.bindValue(":price_cur",currCount + count != 0
                          ? ((currCount * currPrice) +
                             (count * price))/
                          (currCount + count)
                          : 0);

    sqlTransact.bindValue(":doc",_id);
    sqlTransact.bindValue(":type",direction_type);
    sqlTransact.bindValue(":name",name);
    sqlTransact.bindValue(":mol",mol);
    sqlTransact.bindValue(":suborder",suborder);
    sqlTransact.bindValue(":form_direction",formDirection);
    sqlTransact.exec();

    if (sqlTransact.lastError().isValid()) {
        _error = sqlTransact.lastError();
        return false;
    }

    return true;
}
Example #7
0
int LoadPriv::writeToDB(const QString pkgname, QString &errMsg)
{
  if (_name.isEmpty())
  {
    errMsg = TR("<font color=orange>The Privilege does not have a name.</font>")
               .arg(_name);
    return -1;
  }

  if (_module.isEmpty())
  {
    errMsg = TR("<font color=orange>The Privilege %1 has not been "
                 "assigned to a module and so may not be assignable.</font>")
               .arg(_name);
  }

  QSqlQuery select;
  QSqlQuery upsert;

  int privid    = -1;
  int pkgheadid = -1;
  int pkgitemid = -1;
  if (pkgname.isEmpty())
    select.prepare(QString("SELECT priv_id, -1, -1"
                           "  FROM %1priv "
                           " WHERE (priv_name=:name);")
                      .arg(_system ? "" : "pkg"));
  else
    select.prepare(_pkgitemQueryStr);
  select.bindValue(":name",    _name);
  select.bindValue(":pkgname", pkgname);
  select.bindValue(":type",    _pkgitemtype);
  select.exec();
  if(select.first())
  {
    privid    = select.value(0).toInt();
    pkgheadid = select.value(1).toInt();
    pkgitemid = select.value(2).toInt();
  }
  else if (select.lastError().type() != QSqlError::NoError)
  {
    QSqlError err = select.lastError();
    errMsg = _sqlerrtxt.arg(_name).arg(err.driverText()).arg(err.databaseText());
    return -5;
  }

  if (privid >= 0)
    upsert.prepare(QString("UPDATE %1priv "
                           "   SET priv_module=:module, "
                           "       priv_descrip=:comment "
                           " WHERE (priv_id=:id); ")
              .arg(_system ? "" : "pkg"));
  else
  {
    upsert.prepare("SELECT NEXTVAL('priv_priv_id_seq');");
    upsert.exec();
    if (upsert.first())
      privid = upsert.value(0).toInt();
    else if (upsert.lastError().type() != QSqlError::NoError)
    {
      QSqlError err = upsert.lastError();
      errMsg = _sqlerrtxt.arg(_name).arg(err.driverText()).arg(err.databaseText());
      return -6;
    }
    upsert.prepare(QString("INSERT INTO %1priv ("
                           "       priv_id, priv_module, priv_name, priv_descrip "
                           ") VALUES (:id, :module, :name, :comment);")
              .arg(_system ? "" : "pkg"));
  }

  upsert.bindValue(":id",      privid);
  upsert.bindValue(":module",  _module);
  upsert.bindValue(":name",    _name);
  upsert.bindValue(":comment", _comment);

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

  if (pkgheadid >= 0)
  {
    int tmp = upsertPkgItem(pkgitemid, pkgheadid, privid, errMsg);
    if (tmp < 0)
      return tmp;
  }

  return privid;
}
void CustomsManage::savaFun()
{
    QSqlQuery query;
    if(nameLineEdit->text().isEmpty())
    {
        QMessageBox::warning(this,"警告","请输入客户的姓名");
        return;
    }

    switch(oper)
    {
    case 1:
    {


        QString update_sql="update customs set name =:name, company =:company ,  address =:address ,\
                phonenumber =:phonenumber  , customstype =:customstype  where id = :updatedId";
        query.prepare(update_sql);
        query.bindValue(":updatedId",updatedId);
        qDebug() << updatedId;
        query.bindValue(":name", nameLineEdit->text());
        query.bindValue(":company", companyLineEdit->text());
        query.bindValue(":address",addressLineEdit->text() );
        query.bindValue(":phonenumber",phonenumLineEdit->text());
        query.bindValue(":customstype", customstypeComboBox->currentText());

        if(!query.exec())
        {
            qDebug() << query.lastError();
            resetFun();
        }
        else
        {
            msgLabel->setText("<h3><font color=red>客户信息修改成功!</font></h3>");

            tableModel->item(rowNum, 1)->setText(nameLineEdit->text());
            tableModel->item(rowNum, 2)->setText(companyLineEdit->text());
            tableModel->item(rowNum, 3)->setText(addressLineEdit->text());
            tableModel->item(rowNum, 4)->setText(phonenumLineEdit->text());
            tableModel->item(rowNum, 5)->setText(customstypeComboBox->currentText());
            resetFun();
        }

            oper=0;
            break;
    }
    case 0:
    {
        msgLabel->setText("<h3><font color=red>当前操作:添加客户信息</font></h3>");
        QString insert_sql = "insert into customs(name ,company, address,phonenumber, customstype )  values (?,?,?,?,?)";//


        query.prepare(insert_sql);

        query.addBindValue(nameLineEdit->text());
        query.addBindValue(companyLineEdit->text());
        query.addBindValue(addressLineEdit->text());
        query.addBindValue(phonenumLineEdit->text());
        query.addBindValue(customstypeComboBox->currentText());

        if(!query.exec())
        {
            qDebug() << query.lastError();
            resetFun();
        }
        else
        {
            int rowCount=tableModel->rowCount();
            tableModel->setItem(rowCount,0,new QStandardItem(query.lastInsertId().toString()));
            tableModel->setItem(rowCount,1,new QStandardItem(nameLineEdit->text()));
            tableModel->setItem(rowCount,2,new QStandardItem(companyLineEdit->text()));
            tableModel->setItem(rowCount,3,new QStandardItem(addressLineEdit->text()));
            tableModel->setItem(rowCount,4,new QStandardItem(phonenumLineEdit->text()));
            tableModel->setItem(rowCount,5,new QStandardItem(customstypeComboBox->currentText()));

            msgLabel->setText("<h3><font color=red>商品信息添加成功!</font></h3>");
            resetFun();
        }

    break;
    }
    }

}
Example #9
0
void
FormMain::folderChanged( QTreeWidgetItem * current, QTreeWidgetItem * )
{
	editInfo->clear();

	if ( ! current )
		return;

	const int folder_id = current->data( 0, Qt::UserRole ).toInt();

	QString text("Folder: ");

	QSqlQuery q;

	// self
	q.prepare("SELECT "
			"name, "
			"path, "
			"size "
		"FROM "
			"folders "
		"WHERE "
			"id = :id ");

	q.bindValue(":id", folder_id );

	if ( q.exec() ) {
		if ( q.first() )
			text += q.value( 0 ).toString() + "<BR>" +
				"Path: " + q.value( 1 ).toString() + "<BR>" +
				"Size: " + prettyPrint( q.value( 2 ).toLongLong() ) + "<BR>";

	} else {
		emit yell( q.lastError().text() );
		return;
	}

	// count of folders
	int folderCount = 0;
	countFolders( folder_id, folderCount );

	// count of types
	int typeCount = 0;
	QHash< QString, int > types;
	countTypes( folder_id, types, typeCount );

	// ordering
	QMultiMap< int, QString > typesMap;
	QHash< QString, int >::const_iterator h = types.constBegin();

	while ( h != types.constEnd() ) {
		typesMap.insert( h.value(), h.key() );
		++h;
	}

	// percent of folders
	text += tr("folders: %1 (%2%)<BR>")
		.arg( folderCount )
		.arg( folderCount / ( qreal )( folderCount + typeCount ) * 100., 0, 'f', 1 );

	// percents of files

	chart->clear();

	if ( typesMap.count() > 0 ) {
		QMultiMap< int, QString >::const_iterator mm = typesMap.constEnd();

		do {
			--mm;

			const qreal percent = mm.key() / ( qreal )( folderCount + typeCount ) * 100;

			text += tr("%1: %2 (%3%)<BR>")
				.arg( mm.value() )
				.arg( mm.key() )
				.arg( percent, 0, 'f', 1 );

			chart->addPiece( percent, mm.value() );

		} while ( mm != typesMap.constBegin() );
	}

	text += QString( 50, '-' ) + "<BR>";		// horizontal line -------

	// folders
	text += "<BR><B>folders:</B><BR>";

	q.prepare("SELECT "
			"name, "
			"size "
		"FROM "
			"folders "
		"WHERE "
			"parent_id = :id "
		"ORDER BY "
			"size DESC");

	q.bindValue(":id", folder_id );

	if ( q.exec() ) {
		while ( q.next() )
			text += q.value( 0 ).toString() +
				" (" + prettyPrint( q.value( 1 ).toLongLong() ) + ")<BR>";

	} else {
		emit yell( q.lastError().text() );
		return;
	}

	// files
	text += "<BR><B>files:</B><BR>";

	q.prepare("SELECT "
			"name, "
			"size "
		"FROM "
			"files "
		"WHERE "
			"folders_id = :id "
		"ORDER BY "
			"size DESC");

	q.bindValue(":id", folder_id );

	if ( q.exec() ) {
		while ( q.next() )
			text += q.value( 0 ).toString() +
				" (" + prettyPrint( q.value( 1 ).toLongLong() ) + ")<BR>";

	} else {
		emit yell( q.lastError().text() );
		return;
	}

	editInfo->setHtml( text );
}
Example #10
0
void SecurityManager::loadSqlMembers() {

    QSqlQuery query;

    query.setForwardOnly(true);

    query.exec("select * from trainers limit 1");

    int count = query.record().count();

    if (count == 8) {
        /* Outdated database, we are going to add ban time */
        QSqlDatabase::database().transaction();

        query.exec("alter table trainers add column ban_expire_time int");
        query.exec("update trainers set ban_expire_time=0");
        //query.exec("create index ban_expire_time_index on trainers (ban_expire_time)");

        QSqlDatabase::database().commit();
    } else if (!query.next()) {
        if (SQLCreator::databaseType == SQLCreator::PostGreSQL) {
            /* The only way to have an auto increment field with PostGreSQL is to my knowledge using the serial type */
            query.exec("create table trainers (id serial, "
                       "name varchar(20), laston char(19), auth int, banned boolean,"
                       "salt varchar(7), hash varchar(32), ip varchar(39), ban_expire_time int, primary key(id), unique(name))");
        } else if (SQLCreator::databaseType == SQLCreator::MySQL) {
            query.exec("CREATE TABLE IF NOT EXISTS trainers (id int(11) NOT NULL auto_increment, "
                       "name varchar(20), laston char(19), auth int(11), banned bool, "
                       "salt varchar(7), hash varchar(32), ip varchar(39), "
                       "ban_expire_time int(11), PRIMARY KEY (id));");
        } else if (SQLCreator::databaseType == SQLCreator::SQLite){
            /* The only way to have an auto increment field with SQLite is to my knowledge having a 'integer primary key' field -- that exact quote */
            query.exec("create table trainers (id integer primary key autoincrement, name varchar(20) unique, "
                       "laston char(19), auth int, banned boolean, salt varchar(7), hash varchar(32), "
                       "ip varchar(39), ban_expire_time int);");
        } else {
            throw QString("Using a not supported database");
        }

        query.exec("create index tname_index on trainers (name)");
        query.exec("create index tip_index on trainers (ip)");

        QFile memberFile("serverdb/members.txt");
        if (memberFile.exists()) {
            Server::print("importing text db");

            if (!memberFile.open(QFile::ReadWrite)) {
                throw QObject::tr("Error: cannot open the file that contains the members ");
            }

            clock_t t = clock();

            query.prepare("insert into trainers(name, laston, auth,  banned, salt, hash, ip, ban_expire_time) values (:name, :laston, :auth,"
                          ":banned, :salt, :hash, :ip, :banexpire)");

            QSqlDatabase::database().transaction();
            int counter = 0;
            while (!memberFile.atEnd()) {
                if (query.lastError().isValid() && counter > 0) {
                    Server::print(QString("Error in last query (number %1): %2").arg(counter).arg(query.lastError().text()));
                    break;
                }

                ++counter;

                if (counter % 1000 == 0) {
                    Server::print(QString("Loaded %1 members so far...").arg(counter));
                }

                QByteArray arr = memberFile.readLine();
                QString s = QString::fromUtf8(arr.constData(), std::max(0,arr.length()-1)); //-1 to remove the \n

                QStringList ls = s.split('%');

                if (ls.size() >= 6 && isValid(ls[0])) {
                    query.bindValue(":name", ls[0].toLower());
                    query.bindValue(":laston",ls[1]);
                    query.bindValue(":auth", ls[2][0].toLatin1()-'0');
                    query.bindValue(":banned", ls[2][1] == '1');
                    /* Weirdly, i seem to have problems when updating something that has a salt containing \, probably postgresql driver,
                       so i remove them. */
                    if (!ls[3].contains('\\')) {
                        query.bindValue(":salt", ls[3].trimmed().toLatin1());
                        query.bindValue(":hash", ls[4].trimmed().toLatin1());
                    } else {
                        query.bindValue(":salt", "");
                        query.bindValue(":hash", "");
                    }
                    query.bindValue(":ip", ls[5].trimmed());
                    if (ls.size() >= 7) {
                        query.bindValue(":banexpire", ls[6]);
                    } else {
                        query.bindValue(":banexpire", 0);
                    }
                    query.exec();
                }
            }

            QSqlDatabase::database().commit();

            t = clock() - t;

            Server::print(QString::number(float(t)/CLOCKS_PER_SEC) + " secs");
            Server::print(query.lastError().text());
        }
    }

    /* Expire old temp bans */
    if (SQLCreator::databaseType == SQLCreator::MySQL) {
        query.prepare("update trainers set banned=0 where banned=1 and ban_expire_time < :now and ban_expire_time != 0");
    } else {
        query.prepare("update trainers set banned='false' where banned='true' and ban_expire_time < :now and ban_expire_time != 0");
    }
    query.bindValue(":now", QDateTime::currentDateTimeUtc().toTime_t());
    query.exec();
    QSqlDatabase::database().commit();

    /* Loading the ban list */

    if (SQLCreator::databaseType == SQLCreator::MySQL) {
        query.exec("select name, ip, ban_expire_time from trainers where banned=1");
    }
    else {
        query.exec("select name, ip, ban_expire_time from trainers where banned='true'");
    }

    while (query.next()) {
        bannedIPs.insert(query.value(1).toString(), query.value(2).toInt());
        bannedMembers.insert(query.value(0).toString().toLower(), std::make_pair(query.value(1).toString(), query.value(2).toInt()));
    }
}
Example #11
0
void TraktorFeature::parseTrack(QXmlStreamReader &xml, QSqlQuery &query) {
    QString title;
    QString artist;
    QString album;
    QString year;
    QString genre;
    //drive letter
    QString volume;
    QString path;
    QString filename;
    QString location;
    float bpm = 0.0;
    int bitrate = 0;
    QString key;
    //duration of a track
    int playtime = 0;
    int rating = 0;
    QString comment;
    QString tracknumber;

    //get XML attributes of starting ENTRY tag
    QXmlStreamAttributes attr = xml.attributes ();
    title = attr.value("TITLE").toString();
    artist = attr.value("ARTIST").toString();

    //read all sub tags of ENTRY until we reach the closing ENTRY tag
    while (!xml.atEnd()) {
        xml.readNext();
        if (xml.isStartElement()) {
            if (xml.name() == "ALBUM") {
                QXmlStreamAttributes attr = xml.attributes ();
                album = attr.value("TITLE").toString();
                tracknumber = attr.value("TRACK").toString();
                continue;
            }
            if (xml.name() == "LOCATION") {
                QXmlStreamAttributes attr = xml.attributes ();
                volume = attr.value("VOLUME").toString();
                path = attr.value("DIR").toString();
                filename = attr.value("FILE").toString();
                // compute the location, i.e, combining all the values
                // On Windows the volume holds the drive letter e.g., d:
                // On OS X, the volume is supposed to be "Macintosh HD" at all times,
                // which is a folder in /Volumes/
                #if defined(__APPLE__)
                location = "/Volumes/"+volume;
                #else
                location = volume;
                #endif
                location += path.replace(QString(":"), QString(""));
                location += filename;
                continue;
            }
            if (xml.name() == "INFO") {
                QXmlStreamAttributes attr = xml.attributes();
                key = attr.value("KEY").toString();
                bitrate = attr.value("BITRATE").toString().toInt() / 1000;
                playtime = attr.value("PLAYTIME").toString().toInt();
                genre = attr.value("GENRE").toString();
                year = attr.value("RELEASE_DATE").toString();
                comment = attr.value("COMMENT").toString();
                QString ranking_str = attr.value("RANKING").toString();
                // A ranking in Traktor has ranges between 0 and 255 internally.
                // This is same as the POPULARIMETER tag in IDv2,
                // see http://help.mp3tag.de/main_tags.html
                //
                // Our rating values range from 1 to 5. The mapping is defined as follow
                // ourRatingValue = TraktorRating / 51
                 if (ranking_str != "" && qVariantCanConvert<int>(ranking_str)) {
                    rating = ranking_str.toInt()/51;
                 }
                continue;
            }
            if (xml.name() == "TEMPO") {
                QXmlStreamAttributes attr = xml.attributes ();
                bpm = attr.value("BPM").toString().toFloat();
                continue;
            }
        }
        //We leave the infinte loop, if twe have the closing tag "ENTRY"
        if (xml.name() == "ENTRY" && xml.isEndElement()) {
            break;
        }
    }

    // If we reach the end of ENTRY within the COLLECTION tag
    // Save parsed track to database
    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(":key", key);
    query.bindValue(":bpm", bpm);
    query.bindValue(":bitrate", bitrate);

    bool success = query.exec();
    if (!success) {
        qDebug() << "SQL Error in TraktorTableModel.cpp: line"
                 << __LINE__ << " " << query.lastError();
        return;
    }
}
void addoredir_raspisanie::on_pushButton_save_clicked()
{
    if (ui->comboBox_sotr->currentIndex() ==-1)
    {
        QMessageBox::warning(this, tr("Ошибка"), tr("Выберите сотрудника"));
        return;
    }
    if (! dal_main->checkConnection())
    {
        QMessageBox::warning(this, tr("Ошибка соединения"), tr("Соединение не установлено"));
        return;
    }
    QSqlQuery* insertQuery = new QSqlQuery();
    insertQuery->prepare("INSERT INTO is_raspisanie(sotr_id, den_nedeli, vremya, predmet) VALUES (:sotr_id, :den_nedeli, :vremya, :predmet)");
    insertQuery->bindValue(":sotr_id", ui->comboBox_sotr->model()->index(ui->comboBox_sotr->currentIndex(),0).data().toInt());

    if (!this->isEdit)
    {
        for (int den = 0; den < 6; den++)
        {
            for (int i = 0; i < 7; i++)
            {
                QString vr = ui->tableWidget_rasp->item(i, 0)->text();
                QString pr = ui->tableWidget_rasp->item(i, den+1)->text();
                if(pr.isEmpty())
                    pr = "-";
                insertQuery->bindValue(":den_nedeli", days.at(den));
                insertQuery->bindValue(":vremya", vr);
                insertQuery->bindValue(":predmet", pr);
                insertQuery->exec();
            }
        }
        QMessageBox::information(this, tr("Информация"), tr("Запись успешно добавлена"));
    }
    else
    {
        QSqlQuery* deleteQuery = new QSqlQuery;
        int id = ui->comboBox_sotr->model()->index(ui->comboBox_sotr->currentIndex(),0).data().toInt();
        deleteQuery->prepare("DELETE FROM is_raspisanie WHERE sotr_id = " + QString::number(id));
        deleteQuery->exec();
        qDebug()<<ui->comboBox_sotr->model()->index(ui->comboBox_sotr->currentIndex(),0).data().toInt()<<deleteQuery->executedQuery()<<deleteQuery->lastError();
        for (int den = 0; den < 6; den++)
        {
            for (int i = 0; i < 7; i++)
            {
                QString vr = ui->tableWidget_rasp->item(i, 0)->text();
                QString pr = ui->tableWidget_rasp->item(i, den+1)->text();
                if(pr.isEmpty())
                    pr = "-";
                insertQuery->bindValue(":den_nedeli", days.at(den));
                insertQuery->bindValue(":vremya", vr);
                insertQuery->bindValue(":predmet", pr);
                insertQuery->exec();
            }
        }
        QMessageBox::information(this, tr("Информация"), tr("Данные успешно отредактированы"));

    }
    this->close();
}
Example #13
0
void RecipeWidget::on_listWidget_itemDoubleClicked(QListWidgetItem *item)
{
    ui->optionButton->setEnabled(true);
    int id = item->data(Qt::UserRole).toInt();
    this->current_id = id;
    QSqlQuery query;
    if(query.exec("SELECT * FROM Recipe WHERE id="+QString::number(id)+";")){
        query.next();
        ui->stackedWidget->setCurrentIndex(1);
        ui->backButton->setEnabled(true);
        ui->nameLabel->setText(query.value(1).toString()); //name
        ui->typeLabel->setText(query.value(2).toString()); //type
        ui->preparationText->setText(query.value(3).toString());
        QSqlQuery subquery;
        QString subquerytext = "SELECT Ingredient.amount, Ingredient.verbose_name, Ingredient.food_id "
                         "FROM Ingredient JOIN Recipe WHERE Ingredient.recipe_id=Recipe.id "
                         "AND Recipe.id="+QString::number(id)+";";
        bool canCook=true;
        if(subquery.exec(subquerytext)){
            ui->ingredientText->clear();
            while(subquery.next()){
                ui->ingredientText->insertPlainText(subquery.value(0).toString()+" "+subquery.value(1).toString());
                //check if there is enough of this on the fridge and add the right icon
                QSqlQuery subsubquery;
                subsubquery.prepare("SELECT amount FROM Item WHERE food_id=?");
                subsubquery.addBindValue(subquery.value(2).toInt());
                if(subsubquery.exec()){
                    int amount = 0;
                    while(subsubquery.next()){
                        amount+=subsubquery.value(0).toInt();
                    }
                    if(amount>=subquery.value(0).toInt()){
                        ui->ingredientText->insertHtml("<img src=\":/res/checkicon.png\" height=\"20\" width=\"20\"><br>");
                    }else{
                        canCook=false;
                        ui->ingredientText->insertHtml("<img src=\":/res/noicon.png\" height=\"20\" width=\"20\"><br>");
                    }
                }else{
                    qDebug()<<subsubquery.lastError().text();
                    ui->ingredientText->insertPlainText("\n");
                }
            }
            subquery.prepare("SELECT VerboseIngredient.verbose_name FROM VerboseIngredient JOIN Recipe WHERE VerboseIngredient.recipe_id=Recipe.id AND Recipe.id=?");
            subquery.addBindValue(id);
            if(subquery.exec()){
                while(subquery.next()){
                    ui->ingredientText->insertPlainText(subquery.value(0).toString());
                    //set ok icon
                    ui->ingredientText->insertHtml("<img src=\":/res/checkicon.png\" height=\"20\" width=\"20\"><br>");

                }
            }
        if(canCook){
            ui->statusLabel->setText("Todos los ingredientes disponibles!");
            ui->optionButton->setIcon(QIcon(":/res/cookicon.png"));
            ui->optionButton->setText("Preparar esta receta");
        }else{
            ui->statusLabel->setText("Faltan ingredientes!");
            ui->optionButton->setIcon(QIcon(":/res/listrecipeicon.png"));
            ui->optionButton->setText("Agregar a la lista de compras");
        }
        }else{
            qDebug()<<"Couldn't retrieve ingredientes";
            qDebug()<<subquery.lastError().text();
        }
    }else{
        qDebug()<<"Couldn't retrieve recipe from database";
    }


}
Example #14
0
//------------------------------------------------------------------------------
void ctkDICOMIndexerBase::insert ( DcmDataset *dataset, QString filename ) {
  Q_D(ctkDICOMIndexerBase);

  // Check to see if the file has already been loaded
  QSqlQuery fileExists ( d->db );
  fileExists.prepare("SELECT InsertTimestamp FROM Images WHERE Filename == ?"); 
  fileExists.bindValue(0,filename);
  fileExists.exec();
  if ( fileExists.next() && QFileInfo(filename).lastModified() < QDateTime::fromString(fileExists.value(0).toString(),Qt::ISODate) )
    {
    logger.debug ( "File " + filename + " already added" );
    return;
    }

  OFString patientsName, patientID, patientsBirthDate, patientsBirthTime, patientsSex,
    patientComments, patientsAge;

  OFString studyInstanceUID, studyID, studyDate, studyTime,
    accessionNumber, modalitiesInStudy, institutionName, performingPhysiciansName, referringPhysician, studyDescription;

  OFString seriesInstanceUID, seriesDate, seriesTime,
    seriesDescription, bodyPartExamined, frameOfReferenceUID,
    contrastAgent, scanningSequence;
  OFString instanceNumber;

  Sint32 seriesNumber = 0, acquisitionNumber = 0, echoNumber = 0, temporalPosition = 0;

  //If the following fields can not be evaluated, cancel evaluation of the DICOM file
  dataset->findAndGetOFString(DCM_PatientsName, patientsName);
  dataset->findAndGetOFString(DCM_StudyInstanceUID, studyInstanceUID);
  dataset->findAndGetOFString(DCM_SeriesInstanceUID, seriesInstanceUID);
  dataset->findAndGetOFString(DCM_PatientID, patientID);

  dataset->findAndGetOFString(DCM_PatientsBirthDate, patientsBirthDate);
  dataset->findAndGetOFString(DCM_PatientsBirthTime, patientsBirthTime);
  dataset->findAndGetOFString(DCM_PatientsSex, patientsSex);
  dataset->findAndGetOFString(DCM_PatientsAge, patientsAge);
  dataset->findAndGetOFString(DCM_PatientComments, patientComments);
  dataset->findAndGetOFString(DCM_StudyID, studyID);
  dataset->findAndGetOFString(DCM_StudyDate, studyDate);
  dataset->findAndGetOFString(DCM_StudyTime, studyTime);
  dataset->findAndGetOFString(DCM_AccessionNumber, accessionNumber);
  dataset->findAndGetOFString(DCM_ModalitiesInStudy, modalitiesInStudy);
  dataset->findAndGetOFString(DCM_InstitutionName, institutionName);
  dataset->findAndGetOFString(DCM_PerformingPhysiciansName, performingPhysiciansName);
  dataset->findAndGetOFString(DCM_ReferringPhysiciansName, referringPhysician);
  dataset->findAndGetOFString(DCM_StudyDescription, studyDescription);

  dataset->findAndGetOFString(DCM_SeriesDate, seriesDate);
  dataset->findAndGetOFString(DCM_SeriesTime, seriesTime);
  dataset->findAndGetOFString(DCM_SeriesDescription, seriesDescription);
  dataset->findAndGetOFString(DCM_BodyPartExamined, bodyPartExamined);
  dataset->findAndGetOFString(DCM_FrameOfReferenceUID, frameOfReferenceUID);
  dataset->findAndGetOFString(DCM_ContrastBolusAgent, contrastAgent);
  dataset->findAndGetOFString(DCM_ScanningSequence, scanningSequence);

  dataset->findAndGetSint32(DCM_SeriesNumber, seriesNumber);
  dataset->findAndGetSint32(DCM_AcquisitionNumber, acquisitionNumber);
  dataset->findAndGetSint32(DCM_EchoNumbers, echoNumber);
  dataset->findAndGetSint32(DCM_TemporalPositionIdentifier, temporalPosition);

  QSqlQuery check_exists_query(d->db);
  //The patient UID is a unique number within the database, generated by the sqlite autoincrement
  int patientUID = -1;
  if ( patientID != "" && patientsName != "" )
    {
    //Check if patient is already present in the db
    check_exists_query.prepare ( "SELECT * FROM Patients WHERE PatientID = ? AND PatientsName = ?" );
    check_exists_query.bindValue ( 0, QString ( patientID.c_str() ) );
    check_exists_query.bindValue ( 1, QString ( patientsName.c_str() ) );
    check_exists_query.exec();
    
    if (check_exists_query.next())
      {
      patientUID = check_exists_query.value(check_exists_query.record().indexOf("UID")).toInt();
      }
    else
      {
      // Insert it
      QSqlQuery statement ( d->db );
      statement.prepare ( "INSERT INTO Patients ('UID', 'PatientsName', 'PatientID', 'PatientsBirthDate', 'PatientsBirthTime', 'PatientsSex', 'PatientsAge', 'PatientsComments' ) values ( NULL, ?, ?, ?, ?, ?, ?, ? )" );
      statement.bindValue ( 0, QString ( patientsName.c_str() ) );
      statement.bindValue ( 1, QString ( patientID.c_str() ) );
      statement.bindValue ( 2, QString ( patientsBirthDate.c_str() ) );
      statement.bindValue ( 3, QString ( patientsBirthTime.c_str() ) );
      statement.bindValue ( 4, QString ( patientsSex.c_str() ) );
      statement.bindValue ( 5, QString ( patientsAge.c_str() ) );
      statement.bindValue ( 6, QString ( patientComments.c_str() ) );
      statement.exec ();
      patientUID = statement.lastInsertId().toInt();
      logger.debug ( "New patient inserted: " + QString().setNum ( patientUID ) );
      }
    }

  if ( studyInstanceUID != "" )
    {
    check_exists_query.prepare ( "SELECT * FROM Studies WHERE StudyInstanceUID = ?" );
    check_exists_query.bindValue ( 0, QString ( studyInstanceUID.c_str() ) );
    check_exists_query.exec();
    if(!check_exists_query.next())
      {
      QSqlQuery statement ( d->db );
      statement.prepare ( "INSERT INTO Studies ( 'StudyInstanceUID', 'PatientsUID', 'StudyID', 'StudyDate', 'StudyTime', 'AccessionNumber', 'ModalitiesInStudy', 'InstitutionName', 'ReferringPhysician', 'PerformingPhysiciansName', 'StudyDescription' ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )" );
      statement.bindValue ( 0, QString ( studyInstanceUID.c_str() ) );
      statement.bindValue ( 1, patientUID );
      statement.bindValue ( 2, QString ( studyID.c_str() ) );
      statement.bindValue ( 3, QDate::fromString ( studyDate.c_str(), "yyyyMMdd" ) );
      statement.bindValue ( 4, QString ( studyTime.c_str() ) );
      statement.bindValue ( 5, QString ( accessionNumber.c_str() ) );
      statement.bindValue ( 6, QString ( modalitiesInStudy.c_str() ) );
      statement.bindValue ( 7, QString ( institutionName.c_str() ) );
      statement.bindValue ( 8, QString ( referringPhysician.c_str() ) );
      statement.bindValue ( 9, QString ( performingPhysiciansName.c_str() ) );
      statement.bindValue ( 10, QString ( studyDescription.c_str() ) );
      if ( !statement.exec() )
        {
        logger.error ( "Error executing statament: " + statement.lastQuery() + " Error: " + statement.lastError().text() );
        }
      }
    }

  if ( seriesInstanceUID != "" )
    {
    check_exists_query.prepare ( "SELECT * FROM Series WHERE SeriesInstanceUID = ?" );
    check_exists_query.bindValue ( 0, QString ( seriesInstanceUID.c_str() ) );
    logger.warn ( "Statement: " + check_exists_query.lastQuery() );
    check_exists_query.exec();
    if(!check_exists_query.next())
      {
      QSqlQuery statement ( d->db );
      statement.prepare ( "INSERT INTO Series ( 'SeriesInstanceUID', 'StudyInstanceUID', 'SeriesNumber', 'SeriesDate', 'SeriesTime', 'SeriesDescription', 'BodyPartExamined', 'FrameOfReferenceUID', 'AcquisitionNumber', 'ContrastAgent', 'ScanningSequence', 'EchoNumber', 'TemporalPosition' ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )" );
      statement.bindValue ( 0, QString ( seriesInstanceUID.c_str() ) );
      statement.bindValue ( 1, QString ( studyInstanceUID.c_str() ) );
      statement.bindValue ( 2, static_cast<int>(seriesNumber) );
      statement.bindValue ( 3, QString ( seriesDate.c_str() ) );
      statement.bindValue ( 4, QDate::fromString ( seriesTime.c_str(), "yyyyMMdd" ) );
      statement.bindValue ( 5, QString ( seriesDescription.c_str() ) );
      statement.bindValue ( 6, QString ( bodyPartExamined.c_str() ) );
      statement.bindValue ( 7, QString ( frameOfReferenceUID.c_str() ) );
      statement.bindValue ( 8, static_cast<int>(acquisitionNumber) );
      statement.bindValue ( 9, QString ( contrastAgent.c_str() ) );
      statement.bindValue ( 10, QString ( scanningSequence.c_str() ) );
      statement.bindValue ( 11, static_cast<int>(echoNumber) );
      statement.bindValue ( 12, static_cast<int>(temporalPosition) );
      if ( !statement.exec() )
        {
        logger.error ( "Error executing statament: " + statement.lastQuery() + " Error: " + statement.lastError().text() );
        }
      }
    }
  if ( !filename.isEmpty() )
    {
    check_exists_query.prepare ( "SELECT * FROM Images WHERE Filename = ?" );
    check_exists_query.bindValue ( 0, filename );
    check_exists_query.exec();
    if(!check_exists_query.next())
      {
      QSqlQuery statement ( d->db );
      statement.prepare ( "INSERT INTO Images ( 'Filename', 'SeriesInstanceUID', 'InsertTimestamp' ) VALUES ( ?, ?, ? )" );
      statement.bindValue ( 0, filename );
      statement.bindValue ( 1, QString ( seriesInstanceUID.c_str() ) );
      statement.bindValue ( 2, QDateTime::currentDateTime() );
      statement.exec();
      }
    }
}
Example #15
0
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;
    }
}
Example #16
0
void dlgRegHistoria::on_claveIntroducida(bool correcta)
{
    if(correcta){
        infoHistoria["nombre"] = ui->lineaNombre->text();
        infoHistoria["apellido"] = ui->lineaApellido->text();
        infoHistoria["fecha_nac"] = ui->editFechaNac->date().toString("yyyy-MM-dd");
        infoHistoria["fecha_ingreso"] = QDate::currentDate().toString("yyyy-MM-dd");

        if(ui->cBoxSexo->currentIndex() == 1)
            infoHistoria["sexo"] = "F";
        else
            infoHistoria["sexo"] = "M";

        if(!ui->lineaCI->text().isEmpty()){
            infoHistoria["cedula"] = ui->cBoxCI->currentText() + ui->lineaCI->text();
        }

        QString consulta;

        consulta = "INSERT INTO spectradb.historia(nombre, apellido, fecha_nac, fecha_ingreso, sexo";

        if(infoHistoria.contains("cedula")){
            consulta+= ", cedula";
        }

        consulta += ") VALUES(:nombre, :apellido, :fecha_nac, :fecha_ingreso, :sexo";

        if(infoHistoria.contains("cedula")){
            consulta+= ", :cedula";
        }

        consulta += ")";

        QSqlQuery query;

        query.prepare(consulta);

        query.bindValue(":nombre", infoHistoria["nombre"]);
        query.bindValue(":apellido", infoHistoria["apellido"]);
        query.bindValue(":fecha_nac", infoHistoria["fecha_nac"]);
        query.bindValue(":fecha_ingreso", infoHistoria["fecha_ingreso"]);
        query.bindValue(":sexo", infoHistoria["sexo"]);

        if(infoHistoria.contains("cedula")){
            query.bindValue(":cedula", infoHistoria["cedula"]);
        }

        if(query.exec()){
            infoHistoria["id_historia"] = query.lastInsertId().toString();

            QMessageBox::information(this, "Historia registrada", "Se ha registrado la historia correctamente.");
            close();
            emit historia_registrada(infoHistoria);
        }else{
            //el codigo 23505 significa que se intento insertar un valor unico que ya existe
            if(query.lastError().number() == 23505){
                QMessageBox::critical(this, "Error al registrar", "La cédula de identidad " + infoHistoria["cedula"] + " ya está siendo utilizada.");
            }

            infoHistoria.clear();
            ui->lineaCI->clear();
        }
    }else{
        QMessageBox::critical(this, "Contraseña incorrecta", "La contraseña que introdujo es incorrecta.");
    }
}
void UserManagement::on_commandLinkButton_forceCLockOut_clicked()
{
    QDate currentDate = QDate::currentDate();
    QTime currentTime = QTime::currentTime();

    int hour = currentTime.toString("HH").toInt();
    int minutes = currentTime.toString("mm").toInt();

    if(minutes > 30)
    {
        hour++;
    }

    currentTime = currentTime.fromString(QString::number(hour) + ":" + "00", "HH:mm");

    QString date = currentDate.toString("yyyy-MM-dd");
    QString time = currentTime.toString("HH:mm");
    {
        Database conn;

        conn.connOpen("Clock");

        QSqlQuery * qry = new QSqlQuery(conn.mydb);

        QString queryString;
        QTextStream queryStream(&queryString);

        queryStream << "UPDATE '" << currentEmpId <<"'"
                      << " SET 'Time Out' = '" << time << "' where Date ='" << date << "'";


        qry->prepare(queryString);

        if(!qry->exec())
        {
            QMessageBox::critical(this, tr("Error"), qry->lastError().text());
        }
        else
        {}

        conn.connClose();
    }

    {
    Database conn;

    if(!conn.connOpen("Employee"))
    {
        qDebug () << "Database Connection Fatal Error";
    }

    QSqlQuery * qry = new QSqlQuery(conn.mydb);

    QString queryString;
    QTextStream queryStream(&queryString);

    queryStream << "UPDATE 'Employees'"
                << " SET ONCLOCK = '0' where ID = '" << currentEmpId << "'";


    qry->prepare(queryString);

    if(!qry->exec())
    {
        QMessageBox::critical(this, tr("Error"), qry->lastError().text());
    }
    else
    {}

    conn.connClose();
    }

    this->setup();
}
Example #18
0
//------------------------------------------------------------------------------
void ctkDICOMDatabasePrivate::insert( const ctkDICOMDataset& ctkDataset, const QString& filePath, bool storeFile, bool generateThumbnail)
{
  Q_Q(ctkDICOMDatabase);

  // Check to see if the file has already been loaded
  // TODO:
  // It could make sense to actually remove the dataset and re-add it. This needs the remove
  // method we still have to write.
  //

  QString sopInstanceUID ( ctkDataset.GetElementAsString(DCM_SOPInstanceUID) );

  QSqlQuery fileExists ( Database );
  fileExists.prepare("SELECT InsertTimestamp,Filename FROM Images WHERE SOPInstanceUID == ?");
  fileExists.bindValue(0,sopInstanceUID);
  fileExists.exec();
  if ( fileExists.next() && QFileInfo(fileExists.value(1).toString()).lastModified() < QDateTime::fromString(fileExists.value(0).toString(),Qt::ISODate) )
  {
    logger.debug ( "File " + fileExists.value(1).toString() + " already added" );
    return;
  }

  //If the following fields can not be evaluated, cancel evaluation of the DICOM file
  QString patientsName(ctkDataset.GetElementAsString(DCM_PatientName) );
  QString studyInstanceUID(ctkDataset.GetElementAsString(DCM_StudyInstanceUID) );
  QString seriesInstanceUID(ctkDataset.GetElementAsString(DCM_SeriesInstanceUID) );
  QString patientID(ctkDataset.GetElementAsString(DCM_PatientID) );
  if ( patientsName.isEmpty() || studyInstanceUID.isEmpty() || patientID.isEmpty() )
  {
    logger.error("Dataset is missing necessary information!");
    return;
  } 

  QString patientsBirthDate(ctkDataset.GetElementAsString(DCM_PatientBirthDate) );
  QString patientsBirthTime(ctkDataset.GetElementAsString(DCM_PatientBirthTime) );
  QString patientsSex(ctkDataset.GetElementAsString(DCM_PatientSex) );
  QString patientsAge(ctkDataset.GetElementAsString(DCM_PatientAge) );
  QString patientComments(ctkDataset.GetElementAsString(DCM_PatientComments) );
  QString studyID(ctkDataset.GetElementAsString(DCM_StudyID) );
  QString studyDate(ctkDataset.GetElementAsString(DCM_StudyDate) );
  QString studyTime(ctkDataset.GetElementAsString(DCM_StudyTime) );
  QString accessionNumber(ctkDataset.GetElementAsString(DCM_AccessionNumber) );
  QString modalitiesInStudy(ctkDataset.GetElementAsString(DCM_ModalitiesInStudy) );
  QString institutionName(ctkDataset.GetElementAsString(DCM_InstitutionName) );
  QString performingPhysiciansName(ctkDataset.GetElementAsString(DCM_PerformingPhysicianName) );
  QString referringPhysician(ctkDataset.GetElementAsString(DCM_ReferringPhysicianName) );
  QString studyDescription(ctkDataset.GetElementAsString(DCM_StudyDescription) );

  QString seriesDate(ctkDataset.GetElementAsString(DCM_SeriesDate) );
  QString seriesTime(ctkDataset.GetElementAsString(DCM_SeriesTime) );
  QString seriesDescription(ctkDataset.GetElementAsString(DCM_SeriesDescription) );
  QString bodyPartExamined(ctkDataset.GetElementAsString(DCM_BodyPartExamined) );
  QString frameOfReferenceUID(ctkDataset.GetElementAsString(DCM_FrameOfReferenceUID) );
  QString contrastAgent(ctkDataset.GetElementAsString(DCM_ContrastBolusAgent) );
  QString scanningSequence(ctkDataset.GetElementAsString(DCM_ScanningSequence) );

  long seriesNumber(ctkDataset.GetElementAsInteger(DCM_SeriesNumber) );
  long acquisitionNumber(ctkDataset.GetElementAsInteger(DCM_AcquisitionNumber) );
  long echoNumber(ctkDataset.GetElementAsInteger(DCM_EchoNumbers) );
  long temporalPosition(ctkDataset.GetElementAsInteger(DCM_TemporalPositionIdentifier) );

  // store the file if the database is not in memomry
  // TODO: if we are called from insert(file) we
  // have to do something else
  // 
  QString filename = filePath;
  if ( storeFile && !q->isInMemory() && !seriesInstanceUID.isEmpty() )
  {
    // QString studySeriesDirectory = studyInstanceUID + "/" + seriesInstanceUID;
    QString destinationDirectoryName = q->databaseDirectory() + "/dicom/";
    QDir destinationDir(destinationDirectoryName);
    filename = destinationDirectoryName +
        studyInstanceUID + "/" +
        seriesInstanceUID + "/" +
        sopInstanceUID;

    destinationDir.mkpath(studyInstanceUID + "/" +
                          seriesInstanceUID);

    if(filePath.isEmpty())
    {
      logger.debug ( "Saving file: " + filename );

      if ( !ctkDataset.SaveToFile( filename) )
      {
        logger.error ( "Error saving file: " + filename );
        return;
      }
    }
    else
    {
      // we're inserting an existing file

      QFile currentFile( filePath );
      currentFile.copy(filename);
      logger.debug( "Copy file from: " + filePath );
      logger.debug( "Copy file to  : " + filename );
    }
  }

  QSqlQuery checkPatientExistsQuery(Database);
  //The dbPatientID  is a unique number within the database, 
  //generated by the sqlite autoincrement
  //The patientID  is the (non-unique) DICOM patient id
  int dbPatientID = -1;

  if ( patientID != "" && patientsName != "" )
    {
    //Speed up: Check if patient is the same as in last file; 
    // very probable, as all images belonging to a study have the same patient
    if ( lastPatientID != patientID 
          || lastPatientsBirthDate != patientsBirthDate 
          || lastPatientsName != patientsName )
      {
      // Ok, something is different from last insert, let's insert him if he's not
      // already in the db.
      //

      // Check if patient is already present in the db
      // TODO: maybe add birthdate check for extra safety
      checkPatientExistsQuery.prepare ( "SELECT * FROM Patients WHERE PatientID = ? AND PatientsName = ?" );
      checkPatientExistsQuery.bindValue ( 0, patientID );
      checkPatientExistsQuery.bindValue ( 1, patientsName );
      loggedExec(checkPatientExistsQuery);

      if (checkPatientExistsQuery.next())
      {
        // we found him
        dbPatientID = checkPatientExistsQuery.value(checkPatientExistsQuery.record().indexOf("UID")).toInt();
      }
      else
        {
        // Insert it
        QSqlQuery insertPatientStatement ( Database );
        insertPatientStatement.prepare ( "INSERT INTO Patients ('UID', 'PatientsName', 'PatientID', 'PatientsBirthDate', 'PatientsBirthTime', 'PatientsSex', 'PatientsAge', 'PatientsComments' ) values ( NULL, ?, ?, ?, ?, ?, ?, ? )" );
        insertPatientStatement.bindValue ( 0, patientsName );
        insertPatientStatement.bindValue ( 1, patientID );
        insertPatientStatement.bindValue ( 2, patientsBirthDate );
        insertPatientStatement.bindValue ( 3, patientsBirthTime );
        insertPatientStatement.bindValue ( 4, patientsSex );
        // TODO: shift patient's age to study, 
        // since this is not a patient level attribute in images
        // insertPatientStatement.bindValue ( 5, patientsAge );
        insertPatientStatement.bindValue ( 6, patientComments );
        loggedExec(insertPatientStatement);
        dbPatientID = insertPatientStatement.lastInsertId().toInt();
        logger.debug ( "New patient inserted: " + QString().setNum ( dbPatientID ) );
        }
      /// keep this for the next image
      lastPatientUID = dbPatientID;
      lastPatientID = patientID;
      lastPatientsBirthDate = patientsBirthDate;
      lastPatientsName = patientsName;
      }

    // Patient is in now. Let's continue with the study

    if ( studyInstanceUID != "" && lastStudyInstanceUID != studyInstanceUID )
    {
      QSqlQuery checkStudyExistsQuery (Database);
      checkStudyExistsQuery.prepare ( "SELECT * FROM Studies WHERE StudyInstanceUID = ?" );
      checkStudyExistsQuery.bindValue ( 0, studyInstanceUID );
      checkStudyExistsQuery.exec();
      if(!checkStudyExistsQuery.next())
      {
        QSqlQuery insertStudyStatement ( Database );
        insertStudyStatement.prepare ( "INSERT INTO Studies ( 'StudyInstanceUID', 'PatientsUID', 'StudyID', 'StudyDate', 'StudyTime', 'AccessionNumber', 'ModalitiesInStudy', 'InstitutionName', 'ReferringPhysician', 'PerformingPhysiciansName', 'StudyDescription' ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )" );
        insertStudyStatement.bindValue ( 0, studyInstanceUID );
        insertStudyStatement.bindValue ( 1, dbPatientID );
        insertStudyStatement.bindValue ( 2, studyID );
        insertStudyStatement.bindValue ( 3, QDate::fromString ( studyDate, "yyyyMMdd" ) );
        insertStudyStatement.bindValue ( 4, studyTime );
        insertStudyStatement.bindValue ( 5, accessionNumber );
        insertStudyStatement.bindValue ( 6, modalitiesInStudy );
        insertStudyStatement.bindValue ( 7, institutionName );
        insertStudyStatement.bindValue ( 8, referringPhysician );
        insertStudyStatement.bindValue ( 9, performingPhysiciansName );
        insertStudyStatement.bindValue ( 10, studyDescription );
        if ( !insertStudyStatement.exec() )
        {
          logger.error ( "Error executing statament: " + insertStudyStatement.lastQuery() + " Error: " + insertStudyStatement.lastError().text() );
        }
        else
        {
          lastStudyInstanceUID = studyInstanceUID;
        }

      }
    }

    if ( seriesInstanceUID != "" && seriesInstanceUID != lastSeriesInstanceUID )
    {
      QSqlQuery checkSeriesExistsQuery (Database);
      checkSeriesExistsQuery.prepare ( "SELECT * FROM Series WHERE SeriesInstanceUID = ?" );
      checkSeriesExistsQuery.bindValue ( 0, seriesInstanceUID );
      logger.warn ( "Statement: " + checkSeriesExistsQuery.lastQuery() );
      loggedExec(checkSeriesExistsQuery);
      if(!checkSeriesExistsQuery.next())
      {
        QSqlQuery insertSeriesStatement ( Database );
        insertSeriesStatement.prepare ( "INSERT INTO Series ( 'SeriesInstanceUID', 'StudyInstanceUID', 'SeriesNumber', 'SeriesDate', 'SeriesTime', 'SeriesDescription', 'BodyPartExamined', 'FrameOfReferenceUID', 'AcquisitionNumber', 'ContrastAgent', 'ScanningSequence', 'EchoNumber', 'TemporalPosition' ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )" );
        insertSeriesStatement.bindValue ( 0, seriesInstanceUID );
        insertSeriesStatement.bindValue ( 1, studyInstanceUID );
        insertSeriesStatement.bindValue ( 2, static_cast<int>(seriesNumber) );
        insertSeriesStatement.bindValue ( 3, seriesDate );
        insertSeriesStatement.bindValue ( 4, QDate::fromString ( seriesTime, "yyyyMMdd" ) );
        insertSeriesStatement.bindValue ( 5, seriesDescription );
        insertSeriesStatement.bindValue ( 6, bodyPartExamined );
        insertSeriesStatement.bindValue ( 7, frameOfReferenceUID );
        insertSeriesStatement.bindValue ( 8, static_cast<int>(acquisitionNumber) );
        insertSeriesStatement.bindValue ( 9, contrastAgent );
        insertSeriesStatement.bindValue ( 10, scanningSequence );
        insertSeriesStatement.bindValue ( 11, static_cast<int>(echoNumber) );
        insertSeriesStatement.bindValue ( 12, static_cast<int>(temporalPosition) );
        if ( !insertSeriesStatement.exec() )
        {
          logger.error ( "Error executing statament: " 
            + insertSeriesStatement.lastQuery() 
            + " Error: " + insertSeriesStatement.lastError().text() );
          lastSeriesInstanceUID = "";
        }
        else
        {
          lastSeriesInstanceUID = seriesInstanceUID;
        }

      }
    }
    // TODO: what to do with imported files
    //
   if ( !filename.isEmpty() && !seriesInstanceUID.isEmpty() )
   {
     QSqlQuery checkImageExistsQuery (Database);
     checkImageExistsQuery.prepare ( "SELECT * FROM Images WHERE Filename = ?" );
     checkImageExistsQuery.bindValue ( 0, filename );
     checkImageExistsQuery.exec();
     if(!checkImageExistsQuery.next())
      {
        QSqlQuery insertImageStatement ( Database );
        insertImageStatement.prepare ( "INSERT INTO Images ( 'SOPInstanceUID', 'Filename', 'SeriesInstanceUID', 'InsertTimestamp' ) VALUES ( ?, ?, ?, ? )" );
        insertImageStatement.bindValue ( 0, sopInstanceUID );
        insertImageStatement.bindValue ( 1, filename );
        insertImageStatement.bindValue ( 2, seriesInstanceUID );
        insertImageStatement.bindValue ( 3, QDateTime::currentDateTime() );
        insertImageStatement.exec();
      }
    }

    if( generateThumbnail && thumbnailGenerator && !seriesInstanceUID.isEmpty() )
      {
      QString studySeriesDirectory = studyInstanceUID + "/" + seriesInstanceUID;
      //Create thumbnail here
      QString thumbnailPath = q->databaseDirectory() +
        "/thumbs/" + studyInstanceUID + "/" + seriesInstanceUID 
        + "/" + sopInstanceUID + ".png";
      QFileInfo thumbnailInfo(thumbnailPath);
      if( !(thumbnailInfo.exists() 
            && (thumbnailInfo.lastModified() > QFileInfo(filename).lastModified())))
        {
        QDir(q->databaseDirectory() + "/thumbs/").mkpath(studySeriesDirectory);
        DicomImage dcmImage(QDir::toNativeSeparators(filename).toAscii());
        thumbnailGenerator->generateThumbnail(&dcmImage, thumbnailPath);
        }
      }

    if (q->isInMemory())
      {
      emit q->databaseChanged();
      }
    }
}
Example #19
0
bool Inventory::transactDocument()
{
    if (!isValidDocumentFromProvod())
        return false;

    bool setToZero =
        QMessageBox::information(QApplication::activeWindow(),"transactDocument",
                                 tr("Обнулить остатки не вошедшие в инвертаризацию?  "
                                   ),
                                 QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes;

    bool ok = true;
    QSqlQuery sql;
    QSqlDatabase::database().transaction();

    if (setToZero) {
        sql.exec(QString("SELECT tr_article FROM current_balance_n "
                         "WHERE tr_storage = %1 AND tr_mol = %2")
                 .arg(_storageFrom)
                 .arg(_contractorFrom));

        if (sql.lastError().isValid()) {
            ok = false;
            qDebug() << sql.lastError() << Q_FUNC_INFO;
        }

        while (sql.next() && ok) {
            ok = addTrasact(sql.value(0).toInt(),
                            _storageFrom,
                            -1,
                            0,
                            0,
                            QString(),
                            QString(),
                            _contractorFrom,
                            TransactionType::Inventarize,
                            1);
        }

        sql.exec(QString("SELECT tr_article FROM current_balance_mol "
                         "WHERE tr_mol = %1")
                 .arg(_contractorFrom));

        if (sql.lastError().isValid()) {
            ok = false;
            qDebug() << sql.lastError() << Q_FUNC_INFO;
        }

        while (sql.next() && ok) {
            ok = addTrasact(sql.value(0).toInt(),
                            _storageFrom,
                            -1,
                            0,
                            0,
                            QString(),
                            QString(),
                            _contractorFrom,
                            TransactionType::Inventarize,
                            2);
        }
    }


    sql.exec(QString("SELECT dd_article,dd_suborder,dd_name,"
                     "dd_count,dd_price FROM document_detail "
                     "WHERE dd_doc = %1")
             .arg(_id));

    while (sql.next() && ok) {
        ok = transactDetail(_contractorFrom,
                            _storageFrom,
                            -1,
                            sql.value(1).toString(),
                            sql.value(2).toString(),
                            sql.value(0).toInt(),
                            sql.value(3).toDouble(),
                            sql.value(4).toDouble(),
                            TransactionType::Inventarize);
    }



    if (ok)
        ok = setProvod(true);

    if (ok) {
        QSqlDatabase::database().commit();
    } else {
        QSqlDatabase::database().rollback();
    }


    return ok;
}
Example #20
0
bool ctkDICOMDatabase::removeSeries(const QString& seriesInstanceUID)
{
  Q_D(ctkDICOMDatabase);

  // get all images from series
  QSqlQuery fileExists ( d->Database );
  fileExists.prepare("SELECT Filename, SOPInstanceUID, StudyInstanceUID FROM Images,Series WHERE Series.SeriesInstanceUID = Images.SeriesInstanceUID AND Images.SeriesInstanceUID = :seriesID");
  fileExists.bindValue(":seriesID",seriesInstanceUID);
  bool success = fileExists.exec();
  if (!success)
  {
    logger.error("SQLITE ERROR: " + fileExists.lastError().driverText());
    return false;
  }

  QList< QPair<QString,QString> > removeList;
  while ( fileExists.next() )
  {
    QString dbFilePath = fileExists.value(fileExists.record().indexOf("Filename")).toString();
    QString sopInstanceUID = fileExists.value(fileExists.record().indexOf("SOPInstanceUID")).toString();
    QString studyInstanceUID = fileExists.value(fileExists.record().indexOf("StudyInstanceUID")).toString();
    QString internalFilePath = studyInstanceUID + "/" + seriesInstanceUID + "/" + sopInstanceUID;
    removeList << qMakePair(dbFilePath,internalFilePath);
  }

  QSqlQuery fileRemove ( d->Database );
  fileRemove.prepare("DELETE FROM Images WHERE SeriesInstanceUID == ?");
  fileRemove.bindValue(0,seriesInstanceUID);
  fileRemove.exec();
  
  QPair<QString,QString> fileToRemove;
  foreach (fileToRemove, removeList)
  {
    QString dbFilePath = fileToRemove.first;
    QString thumbnailToRemove = databaseDirectory() + "/thumbs/" + fileToRemove.second + ".png";

    // check that the file is below our internal storage
    if (dbFilePath.startsWith( databaseDirectory() + "/dicom/"))
    {
      if (!dbFilePath.endsWith(fileToRemove.second))
      {
        logger.error("Database inconsistency detected during delete!");
        continue;
      }
      if (QFile( dbFilePath ).remove())
      {
        logger.debug("Removed file " + dbFilePath );
      }
      else
      {
        logger.warn("Failed to remove file " + dbFilePath );
      }
    }
    if (QFile( thumbnailToRemove ).remove())
      {
        logger.debug("Removed thumbnail " + thumbnailToRemove);
      }
      else
      {
        logger.warn("Failed to remove thumbnail " + thumbnailToRemove);
      }
    }    
Example #21
0
void Actor::editActor()
{
	int rowIndex = table->selectionModel()->currentIndex().row();    //takes the index of the clicked row
 	ActorAddEditDialog* dlg = new ActorAddEditDialog(this);          
	QString currentName, currentMiddleName, currentLastName, currentRole, currentOu;
	QSqlQuery getRoleId;   //QSqlQuery object that will map the rol name in the role combobox to a rol_id (actors table saves roles id not roles names)
	QSqlQuery getOuId;     //QSqlQuery object that will map the organizational unit name in the ou combobox to a ou_id (actors table saves ou id not ou names)
	QSqlQuery qry;         //this is the object that will hold the update query
	int roleId = 0;        // to save the role id number
	int ouId = 0;          // to save the ou id number
	QString queryString;   // to create the query that will map the ou and role name to their respectives ids	

		/*sets the text into the dialog controls*/
		dlg->setName(table->model()->index(rowIndex,1).data().toString());
		dlg->setMiddleName(table->model()->index(rowIndex,2).data().toString());
		dlg->setLastName(table->model()->index(rowIndex,3).data().toString()); 
		dlg->setRole(table->model()->index(rowIndex,4).data().toString());
		dlg->setOu(table->model()->index(rowIndex,5).data().toString());

		currentName = dlg->name();
		currentMiddleName = dlg->middleName();
		currentLastName = dlg->lastName();	
		currentRole = dlg->role();	
		currentOu = dlg->ou();
		
		dlg->exec();

		if(QDialog::Accepted){
						
			
			/*edit the database row*/
			//prepare the sql statment
			QString id = table->model()->index(rowIndex,0).data().toString();
			qry.prepare(QString("UPDATE Actors SET name = :name, middleName = :middleName, lastName = :lastName, rol_id = :rolId, ou_id = :ouId where actor_id = %1").arg(id));
			
			//does nothing if the data is not changed
			if((dlg->name()==currentName) 
			   && (dlg->middleName()==currentMiddleName) 
			   && (dlg->lastName()==currentLastName)
			   && (dlg->role()==currentRole)
			   && (dlg->ou()==currentOu))
				return;
			
			//get current role id
			queryString = QString("SELECT rol_id FROM Roles WHERE name = '%1'").arg(dlg->role());
			getRoleId.exec(queryString);
			while(getRoleId.next())
				roleId = getRoleId.value(0).toInt();
			
			// get current ou id
			queryString = QString("SELECT ou_id FROM OrganizationalUnits WHERE name ='%1'").arg(dlg->ou());
			getOuId.exec(queryString);
			while(getOuId.next())
				ouId = getOuId.value(0).toInt();
	

			//gives each field it value
			qry.bindValue(":name", dlg->name());
			qry.bindValue(":middleName", dlg->middleName());
			qry.bindValue(":lastName", dlg->lastName());
			qry.bindValue(":rolId", roleId);
			qry.bindValue(":ouId", ouId);
			
			//ifsomething went wrong with the querry print what was it
			if (!qry.exec()){
				qDebug()<<qry.lastError();
			}
			qDebug()<<"antes de actualizar la tabla";
			refreshActorTable();			//update table data
		}
}
int CSqliteDbOper::_AddDataArray(LstHistoryDataT* pLstData)
{
	int nFunRes = 0;
	bool bExecRes = false;
	std::string strDBTableName;
	std::string strSQL;
	LstHistoryDataIterT iterLst;
	CHistoryData* pDataTmp = NULL;
	//QVariantList lstInstrumentID;
	QVariantList lst_COLUMN_DATE;
	QVariantList lst_COLUMN_OPEN;
	QVariantList lst_COLUMN_HIGH;
	QVariantList lst_COLUMN_LOW;
	QVariantList lst_COLUMN_CLOSE;
	QVariantList lst_COLUMN_VOLUME;
	QVariantList lst_COLUMN_ADJCLOSE;
	QSqlQuery* pQSqlQueryForInseert = NULL;

	if (pLstData->empty())
	{
		nFunRes = 0;
		return nFunRes;
	}

	pQSqlQueryForInseert = new QSqlQuery(*m_pQSqlDataBase);

	strDBTableName = str_Table_bar_data_1day;
	strSQL = _BuildSQLForInsert();

	MYLOG4CPP_DEBUG<<" "<<m_strSqliteDbFileFullPath.toStdString()
		<<" "<<"exec strSQL="<<strSQL
		<<" "<<"LstHistoryDataT.size="<<pLstData->size();

	pQSqlQueryForInseert->prepare(strSQL.c_str());

	iterLst = pLstData->begin();
	while (iterLst != pLstData->end())
	{
		pDataTmp = (*iterLst);

		//lstInstrumentID<<m_pDBOperParam->m_nInstrumentID;
		lst_COLUMN_DATE << pDataTmp->m_strDate;
		lst_COLUMN_OPEN << pDataTmp->m_strOpen;
		lst_COLUMN_HIGH << pDataTmp->m_strHigh;
		lst_COLUMN_LOW << pDataTmp->m_strLow;
		lst_COLUMN_CLOSE << pDataTmp->m_strClose;
		lst_COLUMN_VOLUME << pDataTmp->m_strVolume;
		lst_COLUMN_ADJCLOSE << pDataTmp->m_strAdjClose;

		iterLst++;
	}//while

	//pQSqlQueryForInseert->addBindValue(lstInstrumentID);
	pQSqlQueryForInseert->addBindValue(lst_COLUMN_DATE);
	pQSqlQueryForInseert->addBindValue(lst_COLUMN_OPEN);
	pQSqlQueryForInseert->addBindValue(lst_COLUMN_HIGH);
	pQSqlQueryForInseert->addBindValue(lst_COLUMN_LOW);
	pQSqlQueryForInseert->addBindValue(lst_COLUMN_CLOSE);
	pQSqlQueryForInseert->addBindValue(lst_COLUMN_VOLUME);
	pQSqlQueryForInseert->addBindValue(lst_COLUMN_ADJCLOSE);

	bExecRes = pQSqlQueryForInseert->execBatch();
	if (!bExecRes)
	{
		nFunRes = -1;
		MYLOG4CPP_DEBUG<<"execBatch strSQL="<<strSQL
			<<" "<<"LstHistoryDataT.size="<<pLstData->size()
			<<" "<<"error:"<<pQSqlQueryForInseert->lastError().text().toStdString();
	}

	if (NULL != pQSqlQueryForInseert)
	{
		delete pQSqlQueryForInseert;
		pQSqlQueryForInseert = NULL;
	}
	return nFunRes;
}
Example #23
0
void MarketListWidget::calculateMarketList(){
    QSqlQuery query;
    QHash<int,int> table;
    //get all last week's consumptions and add them up
    query.prepare("SELECT Food.id,Consumption.amount,Food.name"
                  " FROM Consumption JOIN Food"
                  " WHERE Consumption.food_id=Food.id"
                  " AND Consumption.consumption_Date >= ?");
    query.addBindValue(QDate::currentDate().addDays(-7));
    if(query.exec()){
        while(query.next()){
            int amount=query.value(1).toInt();
            int food_id=query.value(0).toInt();
            if(!table.contains(food_id)){
                table.insert(food_id,amount);
            }else{
                table[food_id]=table.value(food_id)+amount;
            }
        }
    }else{
        qDebug()<<"Failed to retrieve consumptions"<<query.lastError().text();
    }

    QSqlQuery subquery;
    subquery.prepare("UPDATE Food SET weekly_consumption=? WHERE id=?");
    if(query.exec("SELECT id,weekly_consumption,name,measure_unit FROM Food")){
        ui->listWidget->clear();
        int i=0;
        while(query.next()){
            int id=query.value(0).toInt();
            float weekly_consumption = query.value(1).toFloat();
            float estimate = 0;
            if(!table.contains(id)){
                if(weekly_consumption==0){
                    continue;
                }
                estimate = (1-BETHA)*weekly_consumption;
            }else{
                estimate = (1-BETHA)*weekly_consumption + BETHA*table.value(id);
            }
            if(estimate<0.05){ //we asume this value insignificantly small
                estimate=0;
            }
            subquery.addBindValue(estimate);
            subquery.addBindValue(id);
            if(subquery.exec()){
                qDebug()<<"Updated weekly consumption estimate for"<<query.value(2).toString()<<estimate;
            }else{
                qDebug()<<"Failed to update weekly consumption";
            }
            if(estimate>0.5){
                int int_estimate = qRound(estimate);
                QSqlQuery auxquery;
                auxquery.prepare("INSERT INTO MarketList (amount,food_id) VALUES (?,?) ");
                auxquery.addBindValue(int_estimate); qDebug()<<int_estimate;
                auxquery.addBindValue(id); qDebug()<<id;
                if(auxquery.exec()){
                    qDebug()<<"sucessfully added to market list";
                }else{
                    qDebug()<<"failed to add to market list"<<auxquery.lastError().text();
                }
            }
        }
    }else{
        qDebug()<<"Failed to retrieve foods";
    }
    //clear the consumption table after we are done
    if(query.exec("DELETE FROM Consumption")){
        qDebug()<<"consumption table cleared";
    }else{
        qDebug()<<"Failed to update consumption table";
    }
    FillList();


}
Example #24
0
void Database::createTable()
{
    QStringList tables=QSqlDatabase::database().tables();
    if(tables.isEmpty() || !tables.contains(TableName))
    {
        QSqlQuery query;
        QString str =
                QString("CREATE TABLE IF NOT EXISTS %18 ( "
                        "'%1' INTEGER PRIMARY KEY NOT NULL, "
                        "'%2' TEXT, "
                        "'%3' TEXT, "
                        "'%4' TEXT, "
                        "'%5' TEXT, "
                        "'%6' TEXT, "
                        "'%7' TEXT, "
                        "'%8' TEXT, "
                        "'%9' TEXT, "
                        "'%10' TEXT, "
                        "'%11' TEXT, "
                        "'%12' TEXT, "
                        "'%13' TEXT, "
                        "'%14' TEXT, "
                        "'%15' TEXT, "
                        "'%16' TEXT, "
                        "'%17' TEXT "
                        ")"
                        )
                .arg(MapColumnNames[BUILD_ID])
                .arg(MapColumnNames[STREET])
                .arg(MapColumnNames[STREET_ID])
                .arg(MapColumnNames[KORP])
                .arg(MapColumnNames[BUILD])
                .arg(MapColumnNames[TYPE_OF_STREET])
                .arg(MapColumnNames[ADDITIONAL])
                .arg(MapColumnNames[TYPE_OF_CITY1])
                .arg(MapColumnNames[CITY1])
                .arg(MapColumnNames[TYPE_OF_CITY2])
                .arg(MapColumnNames[CITY2])
                .arg(MapColumnNames[DISTRICT])
                .arg(MapColumnNames[FSUBJ])
                .arg(MapColumnNames[RAW_ADDR])
                .arg(MapColumnNames[LITERA])
                .arg(MapColumnNames[CORRECT])
                .arg(MapColumnNames[TYPE_OF_FSUBJ])
                .arg(TableName);

        if(!query.exec(str))
            emit toDebug(objectName(),
                         QString("Невозможно создать таблицу '%1'. Ошибка: '%2'.")
                         .arg(TableName)
                         .arg(query.lastError().text()));
        else
            emit toDebug(objectName(),
                         QString("Таблица '%1' была создана.").arg(TableName));

        str =
        "PRAGMA synchronous = OFF;"
        "PRAGMA journal_mode = OFF;"
        "CREATE INDEX bid_indx ON base1(BUILD_ID);"
        "CREATE INDEX sid_indx ON base1(STREET_ID);"
        "CREATE INDEX tof_indx ON base1(TYPE_OF_FSUBJ);"
        "CREATE INDEX fs_indx ON base1(FSUBJ);"
        "CREATE INDEX d_indx ON base1(DISTRICT);"
        "CREATE INDEX toc1_indx ON base1(TYPE_OF_CITY1);"
        "CREATE INDEX c1_indx ON base1(CITY1);"
        "CREATE INDEX toc2_indx ON base1(TYPE_OF_CITY2);"
        "CREATE INDEX c2_indx ON base1(CITY2);"
        "CREATE INDEX tos_indx ON base1(TYPE_OF_STREET);"
        "CREATE INDEX s_indx ON base1(STREET);"
        "CREATE INDEX b_indx ON base1(BUILD);"
        "CREATE INDEX k_indx ON base1(KORP);"
        "CREATE INDEX l_indx ON base1(LITERA);"
        "CREATE INDEX c_indx ON base1(CORRECT);"
        "CREATE INDEX a_indx ON base1(ADDITIONAL);"
        "CREATE INDEX all_indx ON base1(STREET, STREET_ID, KORP, BUILD, BUILD_ID, ADDITIONAL, DISTRICT, FSUBJ, TYPE_OF_CITY1, CITY1, TYPE_OF_CITY2, CITY2, TYPE_OF_STREET, LITERA, CORRECT, TYPE_OF_FSUBJ);"
        "CREATE INDEX all2_indx ON base1(TYPE_OF_FSUBJ, FSUBJ, DISTRICT, TYPE_OF_CITY1, CITY1, TYPE_OF_CITY2, CITY2, TYPE_OF_STREET, STREET, BUILD, KORP, LITERA, CORRECT);";
        QStringList queries = str.split(";");
        foreach (QString q, queries) {
            if(q.isEmpty())
                continue;
            if(!query.exec(q))
                emit toDebug(objectName(),
                             QString("Невозможно выполнить '%1'. Ошибка: '%2'.")
                             .arg(q)
                             .arg(query.lastError().text()));
            else
                emit toDebug(objectName(),
                             QString("Выполнен запрос '%1'").arg(q));
        }
    }
//! Removes all items from the checked in table.
void wndInventoryCheck::resetInventoryCheck( void )
{
    if ( QMessageBox::question( this, "Inventory Information: Confirm Reset", "Are you sure you would like to reset the inventory check?",
                                QMessageBox::Yes, QMessageBox::No ) == QMessageBox::Yes )
    {

        QSqlQuery qryDelete( "DELETE FROM inventorycheck WHERE 1=1" );
        _pDB->query( qryDelete );

        QSqlQuery copyQuery;
        // If the filter category is all, do not condition SELECT query
        if ( _pUI->cmbCategory->currentText() == "[All]" )
        {
            copyQuery.prepare( "INSERT INTO inventorycheck (iid,name,description,category,checked)"
                               "SELECT id,name,description,category,0 FROM inventory" );
        }
        else // Otherwise, append the filter text to a condition in the query
        {
            copyQuery.prepare( "INSERT INTO inventorycheck (iid,name,description,category,checked)"
                               "SELECT id,name,description,category,0 FROM inventory WHERE inventory.category=?" );
            copyQuery.addBindValue( _pUI->cmbCategory->currentText() );
        }

        if ( !_pDB->query( copyQuery ) )
        {
            QMessageBox::warning( this, "Inventory Error", "Could not copy inventory into check table. See log for more information." );
            qWarning( "Inventory Error: Could not copy inventory into check table. Database Error: %s", qPrintable( copyQuery.lastError().text() ) );
        }
        refreshTables();
    }
}
Example #26
0
QMap<int, CadastroColaborador *> BancoDados::listarColaboradores(QString _empresa, QString _filial,QString _dtIni,QString _dtFim)
{
    QString query;
    QMap<int, CadastroColaborador*> mapColaboradores;
    if(_empresa.isEmpty() || _empresa.endsWith(" ")){
        QMessageBox::critical(0, QString("Banco de Dados"),
                              QString("A empresa não foi definida para criar uma query para consulta!"),"OK");
    } else {
        QSqlQuery consulta;
        if(_empresa.isEmpty() || _filial.count() == 0 || _filial.endsWith(" ")) {
            query = QString("SELECT FUN.NUMEMP, "
                            "FUN.CODFIL, "
                            "FUN.NUMCAD, "
                            "FUN.NOMFUN, "
                            "FUN.NUMCAD, "
                            "FUN.NUMCPF, "
                            "FUN.NUMPIS, "
                            "DATNAS = CONVERT(VARCHAR(10),FUN.DATNAS,103), "
                            "DATADM = CONVERT(VARCHAR(10),FUN.DATADM,103), "
                            "FUN.TIPSEX, "
                            "ORN.NOMLOC, "
                            "FIL.NOMFIL, "
                            "FUN.NUMCRA, "
                            "FUN.CONRHO, "
                            "FUN.SITAFA, "
                            "CAR.TITRED "
                            "FROM R034FUN FUN "
                            "LEFT JOIN R016ORN ORN ON (ORN.TABORG = FUN.TABORG AND ORN.NUMLOC = FUN.NUMLOC) "
                            "LEFT JOIN R030FIL FIL ON (FIL.NUMEMP = FUN.NUMEMP AND FIL.CODFIL = FUN.CODFIL) "
                            "LEFT JOIN R024CAR CAR ON (CAR.ESTCAR = FUN.ESTCAR AND CAR.CODCAR = FUN.CODCAR) "
                            "WHERE FUN.NUMEMP = %0 AND FUN.CONRHO = 2 AND FUN.DATADM >= '%1' AND FUN.DATADM <= '%2' "
                            "AND FUN.SITAFA = 1 AND FUN.TIPCON = 1 ORDER BY FUN.NUMEMP, FUN.CODFIL, FUN.NUMCAD").arg(_empresa).arg(_dtIni).arg(_dtFim);
        } else {
            query = QString("SELECT FUN.NUMEMP, "
                            "FUN.CODFIL, "
                            "FUN.NUMCAD, "
                            "FUN.NOMFUN, "
                            "FUN.NUMCPF, "
                            "FUN.NUMPIS, "
                            "DATNAS = CONVERT(VARCHAR(10),FUN.DATNAS,103), "
                            "DATADM = CONVERT(VARCHAR(10),FUN.DATADM,103), "
                            "FUN.TIPSEX, "
                            "ORN.NOMLOC, "
                            "FIL.NOMFIL, "
                            "FUN.NUMCRA, "
                            "FUN.CONRHO, "
                            "FUN.SITAFA, "
                            "CAR.TITRED "
                            "FROM R034FUN FUN "
                            "LEFT JOIN R016ORN ORN ON (ORN.TABORG = FUN.TABORG AND ORN.NUMLOC = FUN.NUMLOC) "
                            "LEFT JOIN R030FIL FIL ON (FIL.NUMEMP = FUN.NUMEMP AND FIL.CODFIL = FUN.CODFIL) "
                            "LEFT JOIN R024CAR CAR ON (CAR.ESTCAR = FUN.ESTCAR AND CAR.CODCAR = FUN.CODCAR) "
                            "WHERE FUN.NUMEMP = %0 AND FUN.CONRHO = 2 AND FUN.DATADM >= '%1' AND FUN.DATADM <= '%2' "
                            "AND FUN.SITAFA = 1 AND FUN.TIPCON = 1 AND FUN.CODFIL = %3 ORDER BY FUN.NUMEMP, FUN.CODFIL, FUN.NUMCAD").arg(_empresa).arg(_dtIni).arg(_dtFim).arg(_filial);
        }

        consulta.prepare(query);
        if(!consulta.exec()){
            QMessageBox::critical(0, QString("Banco de Dados"),
                                  QString("Não foi possível executar consulta da lista de filais!\n%1")
                                  .arg(consulta.lastError().text()));
        } else {
            int index = 0;
            while (consulta.next()) {
                index++;
                mapColaboradores.insert(index,
                                        new CadastroColaborador(consulta.value(0).toString(),
                                                                consulta.value(1).toString(),
                                                                consulta.value(2).toString(),
                                                                consulta.value(3).toString(),
                                                                consulta.value(4).toString(),
                                                                consulta.value(5).toString(),
                                                                consulta.value(6).toString(),
                                                                consulta.value(7).toString(),
                                                                consulta.value(8).toString(),
                                                                consulta.value(9).toString(),
                                                                consulta.value(10).toString().toUpper(),
                                                                consulta.value(11).toString(),
                                                                consulta.value(12).toString(),
                                                                consulta.value(13).toString(),
                                                                consulta.value(14).toString()));
            }
        }
    }
    return mapColaboradores;
}
int CSqliteDbOper::_AddDataArrayTick(LstInstrumentTickInfoT* pLstTick)
{
	BOOST_LOG_FUNCTION();
	int nFunRes = 0;
	bool bExecRes = false;
	std::string strDBTableName;
	std::string strSQL;
	std::string strTimeStr;
	LstInstrumentTickInfoIterT iterLst;
	CInstrumentTickInfo* pInstrumentTickInfo = NULL;
	//QVariantList lstInstrumentID;
	QVariantList lstTimestamp;
	QVariantList lstBidPx;
	QVariantList lstAskPx;
	QVariantList lstLastPx;
	QVariantList lstBidVol;
	QVariantList lstAskVol;
	QVariantList lstLastVol;
	QSqlQuery* pQSqlQueryForInseert = NULL;

	if (pLstTick->empty())
	{
		nFunRes = 0;
		return nFunRes;
	}

	pQSqlQueryForInseert = new QSqlQuery(*m_pQSqlDataBaseTIK);

	strDBTableName = str_Table_tick_data;
	strSQL = _BuildSQLForInsertTickData();

	LOG_DEBUG<<"m_pDBOperParam->m_nInstrumentID="<<m_pDBOperParam->m_nInstrumentID
		<<" "<<"strSQL="<<strSQL
		<<" "<<"pLstInstrumentTickInfo.size="<<pLstTick->size();

	pQSqlQueryForInseert->prepare(strSQL.c_str());

	iterLst = pLstTick->begin();
	while (iterLst != pLstTick->end())
	{
		pInstrumentTickInfo = (*iterLst);
		strTimeStr = m_pUtilityFun->dataTimeToStr(pInstrumentTickInfo->m_TickInfo.Time);

		//lstInstrumentID<<m_pDBOperParam->m_nInstrumentID;
		lstTimestamp << strTimeStr.c_str();
		lstBidPx << pInstrumentTickInfo->m_TickInfo.BidPx;
		lstAskPx << pInstrumentTickInfo->m_TickInfo.AskPx;
		lstLastPx << pInstrumentTickInfo->m_TickInfo.LastPx;
		lstBidVol << pInstrumentTickInfo->m_TickInfo.BidVol;
		lstAskVol << pInstrumentTickInfo->m_TickInfo.AskVol;
		lstLastVol << pInstrumentTickInfo->m_TickInfo.LastVol;

		iterLst++;
	}//while

	//pQSqlQueryForInseert->addBindValue(lstInstrumentID);
	pQSqlQueryForInseert->addBindValue(lstTimestamp);
	pQSqlQueryForInseert->addBindValue(lstBidPx);
	pQSqlQueryForInseert->addBindValue(lstAskPx);
	pQSqlQueryForInseert->addBindValue(lstLastPx);
	pQSqlQueryForInseert->addBindValue(lstBidVol);
	pQSqlQueryForInseert->addBindValue(lstAskVol);
	pQSqlQueryForInseert->addBindValue(lstLastVol);

	bExecRes = pQSqlQueryForInseert->execBatch();
	if (!bExecRes)
	{
		nFunRes = -1;
		LOG_ERROR<<"execBatch strSQL="<<strSQL<<" pLstInstrumentTickInfo.size="<<pLstTick->size()
			<<" "<<"error:"<<pQSqlQueryForInseert->lastError().text().toStdString();
	}

	if (NULL != pQSqlQueryForInseert)
	{
		delete pQSqlQueryForInseert;
		pQSqlQueryForInseert = NULL;
	}
	return nFunRes;
}
Example #28
0
bool NoteTable::updateNoteList(qint32 lid, Note &t, bool isDirty) {

    NotebookTable notebookTable;
    qint32 notebookLid = notebookTable.getLid(t.notebookGuid);
    Notebook notebook;
    notebookTable.get(notebook, notebookLid);
    // Now let's update the user table
    QSqlQuery query;

    query.prepare("Delete from NoteTable where lid=:lid");
    query.bindValue(":lid", lid);
    query.exec();

    query.prepare(QString("Insert into NoteTable (lid, title, author, ") +
                  QString("dateCreated, dateUpdated, dateSubject, dateDeleted, source, sourceUrl, sourceApplication, ") +
                  QString("latitude, longitude, altitude, hasEncryption, hasTodo, isDirty, size, notebook, notebookLid, tags) ") +
                  QString("Values (:lid, :title, :author, ") +
                  QString(":dateCreated, :dateUpdated, :dateSubject, :dateDeleted, :source, :sourceUrl, :sourceApplication, ") +
                  QString(":latitude, :longitude, :altitude, :hasEncryption, :hasTodo, :isDirty, :size, :notebook, :notebookLid, :tags) ")) ;

    query.bindValue(":lid", lid);

    if (t.__isset.title)
        query.bindValue(":title", QString::fromStdString(t.title));
    else
        query.bindValue(":title", "");
    if (t.__isset.attributes && t.attributes.__isset.author)
        query.bindValue(":author", QString::fromStdString(t.attributes.author));
    else
        query.bindValue(":author", "");
    if (t.__isset.created)
        query.bindValue(":dateCreated", QVariant::fromValue(t.created));
    else
        query.bindValue(":dateCreated", 0);
    if (t.__isset.updated)
        query.bindValue(":dateUpdated", QVariant::fromValue(t.updated));
    else
        query.bindValue(":dateUpdated", 0);
    if (t.__isset.attributes && t.attributes.__isset.subjectDate)
        query.bindValue(":dateSubject", QVariant::fromValue(t.attributes.subjectDate));
    else
        query.bindValue(":dateSubject", 0);
    if (t.__isset.deleted)
        query.bindValue(":dateDeleted", QVariant::fromValue(t.deleted));
    else
        query.bindValue(":dateDeleted", 0);
    if (t.__isset.attributes && t.attributes.__isset.source)
        query.bindValue(":source", QString::fromStdString(t.attributes.source));
    else
        query.bindValue(":source", "");
    if (t.__isset.attributes && t.attributes.__isset.sourceURL)
        query.bindValue(":sourceUrl", QString::fromStdString(t.attributes.sourceURL));
    else
        query.bindValue("::sourceUrl", "");
    if (t.__isset.attributes && t.attributes.__isset.sourceApplication)
        query.bindValue(":sourceApplication", QString::fromStdString(t.attributes.sourceApplication));
    else
        query.bindValue(":sourceApplication", "");
    if (t.__isset.attributes && t.attributes.__isset.latitude)
        query.bindValue(":latitude", QVariant::fromValue(t.attributes.latitude));
    else
        query.bindValue(":latitude", 0);
    if (t.__isset.attributes && t.attributes.__isset.longitude)
        query.bindValue(":longitude", QVariant::fromValue(t.attributes.longitude));
    else
        query.bindValue(":longitude", 0);
    if (t.__isset.attributes && t.attributes.__isset.altitude)
        query.bindValue(":altitude", QVariant::fromValue(t.attributes.altitude));
    else
        query.bindValue(":altitude", 0);


    bool hasEncryption;
    if (t.content.find("<en-crypt") != string::npos)
        hasEncryption = true;
    else
        hasEncryption = false;
    query.bindValue(":hasEncryption", hasEncryption);
    bool hasTodo;
    if (t.content.find("<en-todo") != string::npos)
        hasTodo = true;
    else
        hasTodo = false;
    query.bindValue(":hasTodo", hasTodo);
    query.bindValue(":isDirty", isDirty);
    qlonglong size = t.content.length();
    for (unsigned int i=0; i<t.resources.size(); i++) {
        size+=t.resources[i].data.size;
    }
    query.bindValue(":size", size);

    query.bindValue(":notebook", QString::fromStdString(notebook.name));
    query.bindValue(":notebookLid", notebookLid);

    QString tagNames;
    QStringList sortedNames;
    for (unsigned int i=0; i<t.tagNames.size(); i++) {
        sortedNames.append(QString::fromStdString(t.tagNames.at(i)).toLower());
    }
    sortedNames.sort();

    TagTable tagTable;
    for (int i=0; i<sortedNames.size(); i++) {
        if (i>0)
            tagNames = tagNames+", ";
        Tag currentTag;
        qint32 tagLid = tagTable.findByName(sortedNames[i]);
        tagTable.get(currentTag, tagLid);
        tagNames = tagNames + QString::fromStdString(currentTag.name);
    }

    query.bindValue(":tags", tagNames);

    if (!query.exec()) {
        QLOG_ERROR() << "Error inserting into NoteTable: " << query.lastError();
        return false;
    }
    return true;
}
Example #29
0
void PrintDialog::writeResults()
{
	QTextCursor cursor(m_ui.m_text_edit->textCursor());
	cursor.movePosition(QTextCursor::Start);

	//Race id
	const int race_id = CHRONOCONTEXT.getCurrentRace();

	//Race query
	QSqlQuery queryRaceName;
	queryRaceName.prepare("SELECT name, place, date FROM t_races "
			"WHERE id=:race_id");
	queryRaceName.bindValue(":race_id", race_id);
	if (!queryRaceName.exec() || !queryRaceName.next())
	{
		QMessageBox::critical(
				this,
				tr("Database error"),
				tr("Race query : %1").arg(queryRaceName.lastError().text()));
		return;
	}

	const QString race_name = queryRaceName.value(0).toString();
	const QString race_place = queryRaceName.value(1).toString();
	const QString race_date = queryRaceName.value(2).toString();

	insertTitleResult(cursor, race_name);
	insertHeaderResult(cursor, race_place, race_date);


	//Category query
	QSqlQuery category_query;
	category_query.prepare("SELECT id, name FROM t_categories "
			"WHERE race_id=:race_id");
	category_query.bindValue(":race_id", race_id);
	if (!category_query.exec())
	{
		QMessageBox::critical(
				this,
				tr("Database error"),
				tr("Category query : %1").arg(category_query.lastError().text()));
		return;
	}

	while(category_query.next())
	{
		const QString category_id = category_query.value(0).toString();
		const QString category_name = category_query.value(1).toString();

		//Result query
		QSqlQuery result_query;
		result_query.prepare("SELECT res.time, pe.first_name, pe.last_name FROM t_results res "
				"JOIN t_registrations reg ON res.registration_id=reg.id "
				"JOIN t_persons pe ON reg.person_id=pe.id "
				"JOIN t_categories cat ON reg.category_id=cat.id WHERE cat.race_id=:race_id "
				"ORDER BY res.time ASC");
		result_query.bindValue(":race_id", race_id);

		if (!result_query.exec())
		{
			QMessageBox::critical(
				this,
				tr("Database error"),
				tr("Result query : %1").arg(result_query.lastError().text()));
			return;
		}

		cursor = m_ui.m_text_edit->textCursor();
		insertSeparatorLine(cursor);

		QTextTable * tableCategory = insertCategoryTable(cursor, category_name);

		if (tableCategory)
		{
			int pos = 1;
			while(result_query.next())
			{
				//Draw
				const QString result_time = result_query.value(0).toString();
				const QString result_firstname = result_query.value(1).toString();
				const QString result_lastname = result_query.value(2).toString();
				fillCategoryTableLine(tableCategory, pos-1, QString::number(pos), result_lastname, result_firstname, result_time);
				++pos;
			}
		}
	}
}
Example #30
0
int main(int argc, char* argv[])
{
  QSqlDatabase db;
  QString dbName;
  QString hostName;
  QString passwd;
  QString pkgfile;
  QString port;
  QString username;
  XAbstractMessageHandler *handler;
  bool    autoRunArg      = false;
  bool    autoRunCheck    = false;
  bool    debugpkg        = false;
  bool    haveDatabaseURL = false;
  bool    acceptDefaults  = false;

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

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

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

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

  ParameterList params;
  params.append("name",      Updater::name);
  params.append("copyright", Updater::copyright);
  params.append("version",   Updater::version);
  params.append("build",     Updater::build);
  if (username.length() > 0)
    params.append("username",  username);
  params.append("password",  passwd);

  if (haveDatabaseURL)
    params.append("databaseURL", _databaseURL.toLatin1().data());
  
  if (autoRunArg)
  {
    if (!haveDatabaseURL)
    {
      buildDatabaseURL(_databaseURL, "psql", hostName, dbName, port);
      params.append("databaseURL", _databaseURL.toLatin1().data());
    }
    params.append("cmd");
    params.append("login");
  }

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

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

  if (!autoRunArg)
  {
    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();
}