Ejemplo n.º 1
0
void DocumentSaverDB::saveDocumentPositions( KraftDoc *doc )
{
    DocPositionList posList = doc->positions();

    // invert all pos numbers to avoid a unique violation
    // FIXME: We need non-numeric ids
    QSqlQuery upq;
    QString queryStr = "UPDATE docposition SET ordNumber = -1 * ordNumber WHERE docID=";
    queryStr +=  doc->docID().toString();
    queryStr += " AND ordNumber > 0";
    upq.prepare( queryStr );
    upq.exec();

    int ordNumber = 1;

    QSqlTableModel model;
    model.setTable("docposition");
    model.setEditStrategy(QSqlTableModel::OnManualSubmit);

    QVector<int> deleteIds;

    DocPositionListIterator it( posList );
    while( it.hasNext() ) {
        DocPositionBase *dpb = it.next();

        DocPosition *dp = static_cast<DocPosition*>(dpb);
        QSqlRecord record ;
        bool doInsert = true;

        int posDbID = dp->dbId().toInt();
        kDebug() << "Saving Position DB-Id: " << posDbID << endl;

        if( dp->toDelete() ) {
            kDebug() << "Delete item " << dp->dbId().toString() << endl;

            // store the id to delete, rather than killing the model index.
            // did that before here, which removed wrong items.
            deleteIds << posDbID;

            // delete all existing attributes no, which will not disturb the model index
            dp->attributes().dbDeleteAll( dp->dbId() );
            continue;
        }

        if( posDbID > -1 ) {
            const QString selStr = QString("docID=%1 AND positionID=%2").arg( doc->docID().toInt() ).arg( posDbID );
            // kDebug() << "Selecting with " << selStr << endl;
            model.setFilter( selStr );
            model.select();
            if ( model.rowCount() > 0 ) {
                if( ! dp->toDelete() )
                    record = model.record(0);
                doInsert = false;
            } else {
                kError() << "ERR: Could not select document position record" << endl;
                return;
            }
        } else {
            // The record is new
            record = model.record();
        }

        if( record.count() > 0 ) {
            // kDebug() << "Updating position " << dp->position() << " is " << dp->text() << endl;
            QString typeStr = PosTypePosition;
            double price = dp->unitPrice().toDouble();

            if ( dp->type() == DocPositionBase::ExtraDiscount ) {
                typeStr = PosTypeExtraDiscount;
            }

            record.setValue( "docID",     QVariant(doc->docID().toInt()));
            record.setValue( "ordNumber", QVariant(ordNumber));
            record.setValue( "text",      QVariant(dp->text()));
            record.setValue( "postype",   QVariant(typeStr));
            record.setValue( "amount",    QVariant(dp->amount()));
            int unitId = dp->unit().id();
            record.setValue( "unit",      QVariant(unitId));
            record.setValue( "price",     QVariant(price));
            record.setValue( "taxType",   QVariant(dp->taxType()));

            ordNumber++; // FIXME

            if( doInsert ) {
                kDebug() << "Inserting!" << endl;
                model.insertRecord(-1, record);
                model.submitAll();
                dp->setDbId( KraftDB::self()->getLastInsertID().toInt() );
            } else {
                kDebug() << "Updating!" << endl;
                model.setRecord(0, record);
                model.submitAll();
            }
        } else {
            kDebug() << "ERR: No record object found!" << endl;
        }

        dp->attributes().save( dp->dbId() );

        QSqlError err = model.lastError();
        if( err.type() != QSqlError::NoError ) {
            kDebug() << "SQL-ERR: " << err.text() << " in " << model.tableName() << endl;
        }

    }
    model.submitAll();

    /*  remove the docpositions that were marked to be deleted */
    if( deleteIds.count() ) {
        QSqlQuery delQuery;
        delQuery.prepare( "DELETE FROM docposition WHERE positionID=:id" );
        foreach( int id, deleteIds ) {
            kDebug() << "Deleting attribute id " << id;
            delQuery.bindValue( ":id", id );
            delQuery.exec();
        }
Ejemplo n.º 2
0
// this differs from the version it was copied from in loadable.cpp
int CreateDBObj::upsertPkgItem(const int pkgheadid, const int itemid,
                               QString &errMsg)
{
  QString sqlerrtxt = TR("<font color=red>The following error was "
                                  "encountered while trying to import %1 into "
                                  "the database:<br>%2<br>%3</font>");
  if (pkgheadid < 0)
    return 0;

  int pkgitemid = -1;

  QSqlQuery select;
  select.prepare("SELECT pkgitem_id "
                 "FROM pkgitem "
                 "WHERE ((pkgitem_pkghead_id=:headid)"
                 "  AND  (pkgitem_type=:type)"
                 "  AND  (pkgitem_name=:name));");
  select.bindValue(":headid", pkgheadid);
  select.bindValue(":type",  _pkgitemtype);
  select.bindValue(":name",  _name);
  select.exec();
  if (select.first())
    pkgitemid = select.value(0).toInt();
  if (select.lastError().type() != QSqlError::NoError)
  {
    errMsg = sqlerrtxt.arg(_filename)
                      .arg(select.lastError().databaseText())
                      .arg(select.lastError().driverText());
    return -20;
  }

  QSqlQuery upsert;

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

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

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

  return pkgitemid;
}
Ejemplo n.º 3
0
void Database::writeLinkSet()
{
    /*Before the opening of each transaction,adding this code to improve the speed*/
    QSqlDatabase::database().transaction();
    QSqlQuery query;
    query.prepare("INSERT INTO linkset(linkid, linkshield, linksetup, linktype, linknum, "
                  "linkINInfo1, linkINInfo2, linkINInfo3, linkINInfo4, linkINInfo5, linkINInfo6, linkINInfo7, linkINInfo8, linkINInfo9, linkINInfo10,"
                  "linkINInfo11, linkINInfo12, linkINInfo13, linkINInfo14, linkINInfo15, linkINInfo16, linkINInfo17, linkINInfo18, linkINInfo19,"
                  "linkINInfo20, linkINInfo21, linkINInfo22, linkINInfo23, linkINInfo24, linkINInfo25, linkINInfo26, linkINInfo27, linkINInfo28, "
                  "linkINInfo29, linkINInfo30, linkINInfo31, linkOUTInfo1, linkOUTInfo2, linkOUTInfo3, linkOUTInfo4, linkOUTInfo5, linkOUTInfo6,"
                  "linkOUTInfo7, linkOUTInfo8, linkOUTInfo9, linkOUTInfo10, linkOUTInfo11, linkOUTInfo12, linkOUTInfo13, linkOUTInfo14,"
                  "linkOUTInfo15, linkOUTInfo16, linkOUTInfo17, linkOUTInfo18, linkOUTInfo19, linkOUTInfo20, linkOUTInfo21, linkOUTInfo22, "
                  "linkOUTInfo23, linkOUTInfo24, linkOUTInfo25, linkOUTInfo26, linkOUTInfo27, linkOUTInfo28, linkOUTInfo29, linkOUTInfo30, linkOUTInfo31)"
                  "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
    for (int i = 0;i<30; i++)
    {
        long long int host = 0;
        long long int iobr = 0;
        int loop = 0;
        int dnode = 0;
        int dline = 0;

        long  long   int linkINInfo1 = (host<<32) | (iobr<<24) | (loop<<16) | (dnode<<8) | (dline);
        int znodestar = 0;
        int znodeend = 0;
        int zequiptype = 0;
        int zsetupnum = 0;

        long  long  int linkOUTInfo1 =  ((long  long  int)host<<48)
                | ((long  long  int)iobr<<40)
                | ((long  long  int)loop<<32)
                | (znodestar<<24)
                | (znodeend<<16)
                | (zequiptype<<8)
                | zsetupnum;

        query.bindValue(0,i+1);
        query.bindValue(1,0);
        query.bindValue(2,0);
        query.bindValue(3,4);
        query.bindValue(4,1);

        for (int j=0; j<31; j++)
        {
            query.bindValue(j+5,linkINInfo1);
        }
        for (int j=0; j<31; j++)
        {
            query.bindValue(j+36,linkOUTInfo1);
        }

        bool bSuccess = query.exec();
        if (!bSuccess)
        {
            QSqlError lastError = query.lastError();
            qDebug() << lastError.driverText()
                     <<QString(QObject::tr("insert 联动error"));
        }
    }
    /*Close the transaction*/
    QSqlDatabase::database().commit();
}
Ejemplo n.º 4
0
int LoadMetasql::writeToDB(const QByteArray &pdata, const QString pkgname, QString &errMsg)
{
  if (pdata.isEmpty())
  {
    errMsg = TR("<font color=orange>The MetaSQL statement %1 is empty.</font>")
                         .arg(_name);
    return -2;
  }

  QString metasqlStr = QString(pdata);
  QStringList lines  = metasqlStr.split("\n");
  QRegExp groupRE    = QRegExp("(^\\s*--\\s*GROUP:\\s*)(.*)",Qt::CaseInsensitive);
  QRegExp nameRE     = QRegExp("(^\\s*--\\s*NAME:\\s*)(.*)", Qt::CaseInsensitive);
  QRegExp notesRE    = QRegExp("(^\\s*--\\s*NOTES:\\s*)(.*)",Qt::CaseInsensitive);
  QRegExp dashdashRE = QRegExp("(^\\s*--\\s*)(.*)");

  for (int i = 0; i < lines.size(); i++)
  {
    if (DEBUG)
      qDebug("LoadMetasql::writeToDB looking at %s", qPrintable(lines.at(i)));

    if (groupRE.indexIn(lines.at(i)) >= 0)
    {
      _group = groupRE.cap(2).trimmed();
      if (DEBUG)
        qDebug("LoadMetasql::writeToDB() found group %s", qPrintable(_group));
    }
    else if (nameRE.indexIn(lines.at(i)) >= 0)
    {
      _name = nameRE.cap(2).trimmed();
      if (DEBUG)
        qDebug("LoadMetasql::writeToDB() found name %s", qPrintable(_name));
    }
    else if (notesRE.indexIn(lines.at(i)) >= 0)
    {
      _comment = notesRE.cap(2).trimmed();
      while (dashdashRE.indexIn(lines.at(++i)) >= 0)
        _comment += " " + dashdashRE.cap(2).trimmed();
      if (DEBUG)
        qDebug("LoadMetasql::writeToDB() found notes %s", qPrintable(_comment));
    }
  }

  if (DEBUG)
    qDebug("LoadMetasql::writeToDB(): name %s group %s notes %s\n%s",
           qPrintable(_name), qPrintable(_group), qPrintable(_comment),
           qPrintable(metasqlStr));

  QString destschema = "public";
  if (_schema.isEmpty()        &&   pkgname.isEmpty())
    ;   // leave it alone
  else if (_schema.isEmpty()   && ! pkgname.isEmpty())
    destschema = pkgname;
  else if ("public" == _schema)
    ;   // leave it alone
  else if (! _schema.isEmpty())
    destschema = _schema;

  XSqlQuery gradedsavepoint("SAVEPOINT savemetasql_graded;");
  MetaSQLQuery upsertm("SELECT saveMetasql(<? value('group') ?>,"
                       "       <? value('name') ?>,  <? value('notes') ?>,"
                       "       E<? value('query') ?>,"
                       "       CAST(<? value('system') ?> AS BOOLEAN),"
                       "       <? value('schema') ?>"
                       "<? if not exists('skipgrade') ?>"
                       "        , <? value('grade') ?>"
                       "<? endif ?>"
                       ") AS result;");
  ParameterList upsertp;
  upsertp.append("group", _group);
  upsertp.append("name",  _name);
  upsertp.append("notes", _comment);
  upsertp.append("query", metasqlStr);
  upsertp.append("system",_system);
  upsertp.append("schema",destschema);
  upsertp.append("grade", _grade);

  int metasqlid = -1;

  XSqlQuery upsert = upsertm.toQuery(upsertp);
  if (upsert.first())
    metasqlid = upsert.value(0).toInt();
  else if (upsert.lastError().type() != QSqlError::NoError)
  {
    XSqlQuery gradedrollback("ROLLBACK TO SAVEPOINT savemetasql_graded;");
    upsertp.append("skipgrade");
    upsert = upsertm.toQuery(upsertp);
    if (upsert.first())
      metasqlid = upsert.value(0).toInt();
    if (upsert.lastError().type() != QSqlError::NoError)
    {
      QSqlError err = upsert.lastError();
      errMsg = _sqlerrtxt.arg(_filename).arg(err.driverText()).arg(err.databaseText());
      return -6;
    }
  }
  else
  {
    errMsg = TR("Saving the MetaSQL statement returned 0 rows. This should "
                "not be possible.");
    return -6;
  }

  if (metasqlid < 0)
  {
    errMsg = TR("The %1 stored procedure failed, returning %2.")
              .arg("saveMetasql").arg(metasqlid);
    return -5;
  }
  else
    XSqlQuery gradedrelease("RELEASE SAVEPOINT savemetasql_graded;");

  if (DEBUG)
    qDebug("LoadMetasql::writeToDB() executed %s and got %d in return",
           qPrintable(upsert.executedQuery()), metasqlid);

  return metasqlid;
}
Ejemplo n.º 5
0
int LoadCmd::writeToDB(const QString pkgname, QString &errMsg)
{
    QSqlQuery select;
    QSqlQuery upsert;

    int cmdid     = -1;
    int pkgheadid = -1;
    int pkgitemid = -1;
    if (pkgname.isEmpty())
        select.prepare(QString("SELECT cmd_id, -1, -1"
                               "  FROM %1cmd "
                               " WHERE (cmd_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())
    {
        cmdid    = 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 (cmdid >= 0)
        upsert.prepare(QString("UPDATE %1cmd "
                               "   SET cmd_module=:module, "
                               "       cmd_title=:title, "
                               "       cmd_privname=:privname, "
                               "       cmd_executable=:executable, "
                               "       cmd_descrip=:comment "
                               " WHERE (cmd_id=:id); ")
                       .arg(_system ? "" : "pkg"));
    else
    {
        upsert.prepare("SELECT NEXTVAL('cmd_cmd_id_seq');");
        upsert.exec();
        if (upsert.first())
            cmdid = 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 %1cmd ("
                               "       cmd_id, cmd_module, cmd_title, cmd_descrip, "
                               "       cmd_privname, cmd_executable, cmd_name "
                               ") VALUES (:id, :module, :title, :comment,"
                               "          :privname, :executable, :name);")
                       .arg(_system ? "" : "pkg"));
    }

    upsert.bindValue(":id",        cmdid);
    upsert.bindValue(":module",    _module);
    upsert.bindValue(":title",     _title);
    upsert.bindValue(":comment",   _comment);
    upsert.bindValue(":privname",  _privname);
    upsert.bindValue(":executable",_executable);
    upsert.bindValue(":name",      _name);

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

    QSqlQuery delargs;
    delargs.prepare(QString("DELETE FROM %1cmdarg WHERE (cmdarg_cmd_id=:cmd_id);")
                    .arg(_system ? "" : "pkg"));
    delargs.bindValue(":cmd_id", cmdid);
    if (! delargs.exec())
    {
        QSqlError err = delargs.lastError();
        errMsg = _sqlerrtxt.arg(_name).arg(err.driverText()).arg(err.databaseText());
        return -8;
    }

    if (_args.size() > 0)
    {
        QSqlQuery insargs;
        insargs.prepare(QString("INSERT INTO %1cmdarg (cmdarg_cmd_id, cmdarg_order, "
                                "cmdarg_arg) VALUES (:cmd_id, :order, :arg);")
                        .arg(_system ? "" : "pkg"));
        for (int i = 0; i < _args.size(); i++)
        {
            insargs.bindValue(":cmd_id", cmdid);
            insargs.bindValue(":order",  i);
            insargs.bindValue(":arg",    _args.at(i));
            if (! insargs.exec())
            {
                QSqlError err = insargs.lastError();
                errMsg = _sqlerrtxt.arg(_name).arg(err.driverText()).arg(err.databaseText());
                return -9;
            }
        }
    }

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

    return cmdid;
}
Ejemplo n.º 6
0
void DatabaseFacade::addUserStat( int userId, const QString& gameName_, int score_ )
{
    if(!connected)
    {
        qDebug() << "Not connected to database";
        return;
    }

    QSqlQuery query;
    QSqlQuery query2;

    qDebug() << "Executing query : \n\t" << queryGetGamerHighScore.arg(gameName_).arg(userId);
    query.exec(queryGetGamerHighScore.arg(gameName_).arg(userId));

    QSqlError err = query.lastError();
    if(err.isValid())
        qDebug() << err.databaseText() << "\n" << err.driverText() << "\n" << err.nativeErrorCode();

    if(query.next())
    {
        if(query.value(1).toInt() < score_)
        {
            qDebug() << "Executing query : \n\t" << queryUpdateHighScore.arg(score_).arg(query.value(0).toString()).arg(userId);
            query2.exec(queryUpdateHighScore.arg(score_).arg(query.value(0).toString()).arg(userId));

            err = query2.lastError();
            if(err.isValid())
                qDebug() << err.databaseText() << "\n" << err.driverText() << "\n" << err.nativeErrorCode();
        }
    }
    else
    {
        qDebug() << "Executing query : \n\t" << queryInsertHighScore.arg(userId).arg(gameName_).arg(score_);
        query2.exec(queryInsertHighScore.arg(userId).arg(gameName_).arg(score_));

        err = query2.lastError();
        if(err.isValid())
            qDebug() << err.databaseText() << "\n" << err.driverText() << "\n" << err.nativeErrorCode();
    }
}
Ejemplo n.º 7
0
void ErrorDialog::operator <<(const QSqlError& rhs)
{
	m_message = rhs.text();
	this->show();
}
Ejemplo n.º 8
0
void Database::showError(const QSqlError &err)
{
    QMessageBox::critical(0, QMessageBox::tr("Erro"),QMessageBox::tr("Erro no banco de dados: ") + err.text());
}
Ejemplo n.º 9
0
DatabaseException::DatabaseException(const QSqlError& error)
{
    m_message = error.text();
    qDebug() << "DatabaseException: error = " << m_message;
}
Ejemplo n.º 10
0
int Prerequisite::writeToDB(const QString pkgname, QString &errMsg)
{
  if (DEBUG)
    qDebug("Prerequisite::writeToDB(%s, &errMsg)", qPrintable(pkgname));

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

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

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

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

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

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

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

    return pkgdepid;
  }

  return 0;
}
Ejemplo n.º 11
0
quint64 IssueLogger::logSql(const QSqlError &err)
{
    //TODO more info about the error for databases
   return log(err.text(), IssueObject::itError);
}
Ejemplo n.º 12
0
_qbe_browser::_qbe_browser(QWidget *_parent, QString _sSQL, QString _sSQLREAL) : QTableView(0)
{
  parent = _parent;
  sSQL = _sSQL;
  sSQLREAL = _sSQLREAL;
  

  setAttribute(Qt::WA_DeleteOnClose);
  setWindowTitle(_sSQLREAL);
  setWindowIcon(kbasicIcon(kbasicPath("ide/PROJECT_NEW_QUERY.png")));

 // bool bb  = CurrentDatabase.open();
/*  QSqlQuery query("", db);
  bb = query.exec("SELECT * FROM address");
  while (query.next()){
    QMessageBox::information(this, "", query.value(0).toString());
  }
  QMessageBox::information(this, "Database Error", query.lastError().text());
*/

  
 
//  QSqlQuery *query = new QSqlQuery("", CurrentDatabase);
//  bb = query->exec(sSQL);

  //mydb = CurrentDatabase.cloneDatabase();

  model = new QSqlQueryModel();
  model->setQuery(sSQL, CurrentDatabase);
  setWindowTitle(tr("#") + QString("%1").arg(model->rowCount()) + " : " + windowTitle());

  //model->clear();
 // query->clear();

  QSqlError e = CurrentDatabase.lastError();
  if (e.type() != QSqlError::NoError){
    QMessageBox::information(this, "Database Error",  e.text());
    //if (model) delete model; model = 0;
    //query.clear();
    close();
    return;
  }

  this->setModel(model);
  //int n = 0;
  //bool b = model->query().exec();

  if (model->lastError().type() != QSqlError::NoError){
      QMessageBox::information(this, "Database Error", (model->lastError().text()));
      //query.clear();
      //if (model) delete model; model = 0;
      close();
      return;
  }
  showMaximized();
/*
  if (model->query().isSelect());
      //QMessageBox::information(this, MYAPP, (tr("Query OK.")));
  else
      QMessageBox::information(this, MYAPP, (tr("Query OK, number of affected rows: %1").arg(
                        model->query().numRowsAffected())));
*/
  
}
Ejemplo n.º 13
0
int PkgSchema::upsertPkgItem(const int itemid,
                               QString &errMsg)
{
  int pkgheadid = -1;
  int pkgitemid = -1;

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

  QSqlQuery upsert;

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

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

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

  return pkgitemid;
}
Ejemplo n.º 14
0
bool DocumentSaverDB::saveDocument(KraftDoc *doc )
{
    bool result = false;
    if( ! doc ) return result;

    QSqlTableModel model;
    model.setTable("document");

    QSqlRecord record;

    kDebug() << "############### Document Save ################" << endl;

    if( doc->isNew() ) {
        record = model.record();
    } else {
      model.setFilter("docID=" + doc->docID().toString());
      model.select();
      if ( model.rowCount() > 0 ) {
        record = model.record(0);
      } else {
        kError() << "Could not select document record" << endl;
        return result;
      }
       // The document was already saved.
    }

    if( !doc->isNew() && doc->docTypeChanged() && doc->newIdent() ) {
        // an existing doc has a new document type. Fix the doc number cycle and pick a new ident
        DocType dt( doc->docType() );
        QString ident = dt.generateDocumentIdent( doc );
        doc->setIdent( ident );
    }

    fillDocumentBuffer( record, doc );

    if( doc->isNew() ) {
      kDebug() << "Doc is new, inserting" << endl;
      if( !model.insertRecord(-1, record)) {
          QSqlError err = model.lastError();
          kDebug() << "################# SQL Error: " << err.text();
      }
      model.submitAll();

      dbID id = KraftDB::self()->getLastInsertID();
      doc->setDocID( id );

      // get the uniq id and write it into the db
      DocType dt( doc->docType() );
      QString ident = dt.generateDocumentIdent( doc );
      doc->setIdent( ident );
      model.setFilter("docID=" + id.toString());
      model.select();
      if ( model.rowCount() > 0 ) {
        model.setData(model.index(0, 1), ident);
        model.submitAll();
      }

    } else {
      kDebug() << "Doc is not new, updating #" << doc->docID().intID() << endl;

      record.setValue( "docID", doc->docID().toString() );

      model.setRecord(0, record);
      model.submitAll();
    }

    saveDocumentPositions( doc );

    kDebug() << "Saved document no " << doc->docID().toString() << endl;

    return result;
}
Ejemplo n.º 15
0
bool DatabaseDialog::databaseDoNext()
{
    m_dbConnection = QSqlDatabase::addDatabase(m_driver->currentText());

    if (m_dbConnection.isValid()) {
        m_dbConnection.setDatabaseName(m_databaseName->text());
        m_dbConnection.setHostName(m_host->text());

        if (!m_username->text().isEmpty())
            m_dbConnection.setUserName(m_username->text());

        if (!m_password->text().isEmpty())
            m_dbConnection.setPassword(m_password->text());

        if (!m_port->text().isEmpty()) {
            bool ok = false;
            int port = m_port->text().toInt(&ok);
            if (!ok) {
                KMessageBox::error(this, i18n("The port must be a number"));
                return false;
            }
            m_dbConnection.setPort(port);
        }

        m_databaseStatus->setText(i18n("Connecting to database..."));
        if (m_dbConnection.open()) {
            m_databaseStatus->setText(i18n("Connected. Retrieving table information..."));
            QStringList tableList(m_dbConnection.tables());

            if (tableList.isEmpty()) {
                KMessageBox::error(this, i18n("This database contains no tables"));
                m_databaseStatus->setText(" ");
                return false;
            }

            m_tableView->clear();

            for (int i = 0; i < tableList.size(); ++i) {
                QListWidgetItem * item = new QListWidgetItem(tableList[i]);
                item->setFlags(item->flags() | Qt::ItemIsUserCheckable);
                item->setCheckState(Qt::Unchecked);
                m_tableView->addItem(item);
            }

            m_tableView->setEnabled(true);
            m_databaseStatus->setText(" ");
        } else {
            QSqlError error = m_dbConnection.lastError();
            QString errorMsg;
            QString err1 = error.driverText();
            QString err2 = error.databaseText();
            if (!err1.isEmpty()) {
                errorMsg.append(error.driverText());
                errorMsg.append('\n');
            }
            if (!err2.isEmpty() && err1 != err2) {
                errorMsg.append(error.databaseText());
                errorMsg.append('\n');
            }

            KMessageBox::error(this, errorMsg);
            m_databaseStatus->setText(" ");
            return false;
        }
    } else {
        KMessageBox::error(this, i18n("Driver could not be loaded"));
        m_databaseStatus->setText(" ");
        return false;
    }
    setValid(m_table, true);

    return true;
}
Ejemplo n.º 16
0
int Package::writeToDB(QString &errMsg)
{
    XSqlQuery select;
    XSqlQuery upsert;
    QString sqlerrtxt = TR("<font color=red>The following error was "
                           "encountered while trying to import %1 into "
                           "the database:<br>%2<br>%3</font>");

    if (_name.isEmpty())
        return 0;   // if there's no name then there's no package to create

    int pkgheadid = -1;
    select.prepare("SELECT pkghead_id FROM pkghead WHERE (pkghead_name=:name);");
    select.bindValue(":name", _name);
    select.exec();
    if (select.first())
    {
        pkgheadid = select.value(0).toInt();
        upsert.prepare("UPDATE pkghead "
                       "   SET pkghead_name=:name,"
                       "       pkghead_descrip=:descrip,"
                       "       pkghead_version=:version,"
                       "       pkghead_developer=:developer,"
                       "       pkghead_notes=:notes "
                       "WHERE (pkghead_id=:id);");
    }
    else if (select.lastError().type() != QSqlError::NoError)
    {
        QSqlError err = select.lastError();
        errMsg = sqlerrtxt.arg(_name).arg(err.driverText()).arg(err.databaseText());
        return -1;
    }
    else
    {
        upsert.exec("SELECT NEXTVAL('pkghead_pkghead_id_seq');");
        if (upsert.first())
            pkgheadid = 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 -2;
        }
        upsert.prepare("INSERT INTO pkghead ("
                       "       pkghead_id, pkghead_name, pkghead_descrip,"
                       "       pkghead_version, pkghead_developer, pkghead_notes"
                       ") VALUES ("
                       "     :id, :name, :descrip, :version, :developer, :notes);");
    }
    upsert.bindValue(":id",        pkgheadid);
    upsert.bindValue(":name",      _name);
    upsert.bindValue(":descrip",   _descrip);
    upsert.bindValue(":version",   _pkgversion.toString());
    upsert.bindValue(":developer", _developer);
    upsert.bindValue(":notes",     _notes);
    if (!upsert.exec())
    {
        QSqlError err = upsert.lastError();
        errMsg = sqlerrtxt.arg(_name).arg(err.driverText()).arg(err.databaseText());
        return -3;
    }

    return pkgheadid;
}
Ejemplo n.º 17
0
bool SyncJournalDb::checkConnect()
{
    if( _db.isOpen() ) {
        return true;
    }

    if( _dbFile.isEmpty() || !QFile::exists(_dbFile) ) {
        return false;
    }

    QStringList list = QSqlDatabase::drivers();
    if( list.size() == 0 ) {
        qDebug() << "Database Drivers could not be loaded.";
        return false ;
    } else {
        if( list.indexOf( QSQLITE ) == -1 ) {
            qDebug() << "Database Driver QSQLITE could not be loaded!";
            return false;
        }
    }

    // Add the connection
    _db = QSqlDatabase::addDatabase( QSQLITE,  _dbFile);

    // Open the file
    _db.setDatabaseName(_dbFile);

    if (!_db.isOpen()) {
        if( !_db.open() ) {
            QSqlError error = _db.lastError();
            qDebug() << "Error opening the db: " << error.text();
            return false;
        }
    }

    QSqlQuery pragma1(_db);
    pragma1.prepare("PRAGMA synchronous = 1;");
    if (!pragma1.exec()) {
        return sqlFail("Set PRAGMA synchronous", pragma1);
    }
    pragma1.prepare("PRAGMA case_sensitive_like = ON;");
    if (!pragma1.exec()) {
        return sqlFail("Set PRAGMA case_sensitivity", pragma1);
    }

    /* Because insert are so slow, e do everything in a transaction, and one need to call commit */
    startTransaction();

    QSqlQuery createQuery(_db);
    createQuery.prepare("CREATE TABLE IF NOT EXISTS metadata("
                         "phash INTEGER(8),"
                         "pathlen INTEGER,"
                         "path VARCHAR(4096),"
                         "inode INTEGER,"
                         "uid INTEGER,"
                         "gid INTEGER,"
                         "mode INTEGER,"
                         "modtime INTEGER(8),"
                         "type INTEGER,"
                         "md5 VARCHAR(32)," /* This is the etag.  Called md5 for compatibility */
                         "PRIMARY KEY(phash)"
                         ");");

    if (!createQuery.exec()) {
        return sqlFail("Create table metadata", createQuery);
    }

    createQuery.prepare("CREATE TABLE IF NOT EXISTS downloadinfo("
                         "path VARCHAR(4096),"
                         "tmpfile VARCHAR(4096),"
                         "etag VARCHAR(32),"
                         "errorcount INTEGER,"
                         "PRIMARY KEY(path)"
                         ");");

    if (!createQuery.exec()) {
        return sqlFail("Create table downloadinfo", createQuery);
    }

    createQuery.prepare("CREATE TABLE IF NOT EXISTS uploadinfo("
                           "path VARCHAR(4096),"
                           "chunk INTEGER,"
                           "transferid INTEGER,"
                           "errorcount INTEGER,"
                           "size INTEGER(8),"
                           "modtime INTEGER(8),"
                           "PRIMARY KEY(path)"
                           ");");

    if (!createQuery.exec()) {
        return sqlFail("Create table uploadinfo", createQuery);
    }

    // create the blacklist table.
    createQuery.prepare("CREATE TABLE IF NOT EXISTS blacklist ("
                        "path VARCHAR(4096),"
                        "lastTryEtag VARCHAR[32],"
                        "lastTryModtime INTEGER[8],"
                        "retrycount INTEGER,"
                        "errorstring VARCHAR[4096],"
                        "PRIMARY KEY(path)"
                        ");");

    if (!createQuery.exec()) {
        return sqlFail("Create table blacklist", createQuery);
    }

    commitInternal("checkConnect");

    bool rc = updateDatabaseStructure();
    if( rc ) {
        _getFileRecordQuery.reset(new QSqlQuery(_db));
        _getFileRecordQuery->prepare("SELECT path, inode, uid, gid, mode, modtime, type, md5, fileid FROM "
                                     "metadata WHERE phash=:ph" );

        _setFileRecordQuery.reset(new QSqlQuery(_db) );
        _setFileRecordQuery->prepare("INSERT OR REPLACE INTO metadata "
                                     "(phash, pathlen, path, inode, uid, gid, mode, modtime, type, md5, fileid) "
                                     "VALUES ( ? , ?, ? , ? , ? , ? , ?,  ? , ? , ?, ? )" );

        _getDownloadInfoQuery.reset(new QSqlQuery(_db) );
        _getDownloadInfoQuery->prepare( "SELECT tmpfile, etag, errorcount FROM "
                                        "downloadinfo WHERE path=:pa" );

        _setDownloadInfoQuery.reset(new QSqlQuery(_db) );
        _setDownloadInfoQuery->prepare( "INSERT OR REPLACE INTO downloadinfo "
                                        "(path, tmpfile, etag, errorcount) "
                                        "VALUES ( ? , ?, ? , ? )" );

        _deleteDownloadInfoQuery.reset(new QSqlQuery(_db) );
        _deleteDownloadInfoQuery->prepare( "DELETE FROM downloadinfo WHERE path=?" );

        _getUploadInfoQuery.reset(new QSqlQuery(_db));
        _getUploadInfoQuery->prepare( "SELECT chunk, transferid, errorcount, size, modtime FROM "
                                      "uploadinfo WHERE path=:pa" );

        _setUploadInfoQuery.reset(new QSqlQuery(_db));
        _setUploadInfoQuery->prepare( "INSERT OR REPLACE INTO uploadinfo "
                                      "(path, chunk, transferid, errorcount, size, modtime) "
                                      "VALUES ( ? , ?, ? , ? ,  ? , ? )");

        _deleteUploadInfoQuery.reset(new QSqlQuery(_db));
        _deleteUploadInfoQuery->prepare("DELETE FROM uploadinfo WHERE path=?" );


        _deleteFileRecordPhash.reset(new QSqlQuery(_db));
        _deleteFileRecordPhash->prepare("DELETE FROM metadata WHERE phash=?");

        _deleteFileRecordRecursively.reset(new QSqlQuery(_db));
        _deleteFileRecordRecursively->prepare("DELETE FROM metadata WHERE path LIKE(?||'/%')");

        _blacklistQuery.reset(new QSqlQuery(_db));
        _blacklistQuery->prepare("SELECT lastTryEtag, lastTryModtime, retrycount, errorstring "
                                 "FROM blacklist WHERE path=:path");
    }
    return rc;
}
Ejemplo n.º 18
0
void BookWindow::showError(const QSqlError &err)
{
    QMessageBox::critical(this, "Unable to initialize Database",
                "Error initializing database: " + err.text());
}
Ejemplo n.º 19
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;
}
Ejemplo n.º 20
0
BookWindow::BookWindow()
{
    ui.setupUi(this);

    if (!QSqlDatabase::drivers().contains("QSQLITE"))
        QMessageBox::critical(this, "Unable to load database", "This demo needs the SQLITE driver");

    // initialize the database
    QSqlError err = initDb();
    if (err.type() != QSqlError::NoError) {
        showError(err);
        return;
    }

    // Create the data model
    model = new QSqlRelationalTableModel(ui.bookTable);
    model->setEditStrategy(QSqlTableModel::OnManualSubmit);
    model->setTable("books");

    // Rememeber the indexes of the columns
    authorIdx = model->fieldIndex("author");
    genreIdx = model->fieldIndex("genre");

    // Set the relations to the other database tables
    model->setRelation(authorIdx, QSqlRelation("authors", "id", "name"));
    model->setRelation(genreIdx, QSqlRelation("genres", "id", "name"));

    // Set the localized header captions
    model->setHeaderData(authorIdx, Qt::Horizontal, tr("Author Name"));
    model->setHeaderData(genreIdx, Qt::Horizontal, tr("Genre"));
    model->setHeaderData(model->fieldIndex("title"), Qt::Horizontal, tr("Title"));
    model->setHeaderData(model->fieldIndex("year"), Qt::Horizontal, tr("Year"));
    model->setHeaderData(model->fieldIndex("rating"), Qt::Horizontal, tr("Rating"));

    // Populate the model
    if (!model->select()) {
        showError(model->lastError());
        return;
    }

    // Set the model and hide the ID column
    ui.bookTable->setModel(model);
    ui.bookTable->setItemDelegate(new BookDelegate(ui.bookTable));
    ui.bookTable->setColumnHidden(model->fieldIndex("id"), true);
    ui.bookTable->setSelectionMode(QAbstractItemView::SingleSelection);

    // Initialize the Author combo box
    ui.authorEdit->setModel(model->relationModel(authorIdx));
    ui.authorEdit->setModelColumn(model->relationModel(authorIdx)->fieldIndex("name"));

    ui.genreEdit->setModel(model->relationModel(genreIdx));
    ui.genreEdit->setModelColumn(model->relationModel(genreIdx)->fieldIndex("name"));

    QDataWidgetMapper *mapper = new QDataWidgetMapper(this);
    mapper->setModel(model);
    mapper->setItemDelegate(new BookDelegate(this));
    mapper->addMapping(ui.titleEdit, model->fieldIndex("title"));
    mapper->addMapping(ui.yearEdit, model->fieldIndex("year"));
    mapper->addMapping(ui.authorEdit, authorIdx);
    mapper->addMapping(ui.genreEdit, genreIdx);
    mapper->addMapping(ui.ratingEdit, model->fieldIndex("rating"));

    connect(ui.bookTable->selectionModel(), SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),
            mapper, SLOT(setCurrentModelIndex(QModelIndex)));

    ui.bookTable->setCurrentIndex(model->index(0, 0));

    ui.exportTheme->insertItems(0, QStringList() << "simple" << "coloured" << "simple2" << "coloured2" );

    connect(ui.exportButton, SIGNAL(pressed()), SLOT(renderBooks()));

    m_engine = new Grantlee::Engine();
    Grantlee::FileSystemTemplateLoader::Ptr loader = Grantlee::FileSystemTemplateLoader::Ptr( new Grantlee::FileSystemTemplateLoader() );
    loader->setTemplateDirs( QStringList() << GRANTLEE_TEMPLATE_PATH );
    m_engine->addTemplateLoader(loader);

    m_engine->setPluginPaths( QStringList() << GRANTLEE_PLUGIN_PATH );
}
Ejemplo n.º 21
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;
}
Ejemplo n.º 22
0
void ReplicateTask::setSQLError(const QSqlError &AError)
{
	FFailed = true;
	FError = AError;
	Logger::reportError("ReplicateTask",QString("Failed to execute SQL command: %1").arg(AError.databaseText()),false);
}
Ejemplo n.º 23
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"));
}
Ejemplo n.º 24
0
void IndexDialog::create()
{
    if(!create_flag){
        close();
        return;
    }
    QString unique;
    if(ckUnique->isChecked())
    {
        unique = QString("unique");
    }
    else
    {
        unique = QString();
    }
    QString iname = txtName->text();
    QString collist;

    int row_count = tbColumnList->rowCount();
    int selected_count=0;
    for(int i=0;i<row_count;i++){
        QTableWidgetItem *item = tbColumnList->item(i,0);
        bool isSelected = item->data(Qt::EditRole).toBool();
        if(isSelected){
            QString col;
            if(tbColumnList->item(i,2)->text().isEmpty()){
                col = QString("%1 %3")
                        .arg(tbColumnList->item(i,1)->text())
                        .arg(tbColumnList->item(i,3)->text());
            }else{
                col = QString("%1 Collate%2 %3")
                    .arg(tbColumnList->item(i,1)->text())
                    .arg(tbColumnList->item(i,2)->text())
                    .arg(tbColumnList->item(i,3)->text());
            }
            collist.append(col.trimmed());
            collist.append(",");
            selected_count ++;
        }
    }
    if(selected_count>0){
        collist = collist.left(collist.length()-1);
    }

    QString sql = QString("create %1 index if not exists %2 on %3(%4)")
            .arg(unique).arg(iname).arg(tbname).arg(collist);

    qDebug()<<sql;
    QSqlDatabase db = QSqlDatabase::database(conname);
    QSqlQuery q(db);
    if(q.exec(sql)){
        MainWindow *mw = qobject_cast<MainWindow*>(qApp->activeWindow());
        if(mw!=0)mw->refresh(conname);
    }else{
        QSqlError se = q.lastError();
        QString err = QString(
           "database:%1\ndriver:%2\nerror number:%3"
           "\nerror type:%4\nerror text:%5")
                .arg(se.databaseText())
                .arg(se.driverText())
                .arg(se.number())
                .arg(se.type()).arg(se.text());
        QMessageBox::warning(this,QString("创建错误"),err);
    }
    close();
}
Ejemplo n.º 25
0
bool ReportWindow::saveToDb() {
    // do what we need to do
    DBFileDialog rptDiag;
    rptDiag.setCaption(tr("Save Report to Database"));
    if(!dbRecordName.isEmpty()) {
        rptDiag._name->setText(dbRecordName);
    } else {
        rptDiag._name->setText(reportName());
    }
    rptDiag._grade->setValue(dbRecordGrade);
    if(rptDiag.exec() == QDialog::Accepted) {
        QString name = rptDiag.getName();
        QString desc = reportDescription();
        QString src  = document().toString();
        int grade = rptDiag.getGrade();

        XSqlQuery q;
        XSqlQuery qry;

        q.prepare("SELECT report_id "
                  "  FROM report "
                  " WHERE ((report_name=:report_name) "
                  "   AND (report_grade=:report_grade)); ");
        q.bindValue(":report_name", name);
        q.bindValue(":report_grade", grade);
        q.exec();
        if(q.first()) {
            // update old record
            qry.prepare("UPDATE report "
                        "   SET report_source=:report_source, "
                        "       report_descrip=:report_descrip "
                        " WHERE (report_id=:report_id);");
            qry.bindValue(":report_source", src);
            qry.bindValue(":report_descrip", desc);
            qry.bindValue(":report_id", q.value("report_id").toInt());
        } else {
            // insert new record
            qry.prepare("INSERT INTO report "
                        "       (report_name, report_source, report_descrip, report_grade) "
                        "VALUES (:report_name, :report_source, :report_descrip, :report_grade);");
            qry.bindValue(":report_name", name);
            qry.bindValue(":report_source", src);
            qry.bindValue(":report_descrip", desc);
            qry.bindValue(":report_grade", grade);
        }

        if(qry.exec()) {
            lastSaveToDb = TRUE;
            setModified(FALSE);
            dbRecordName = name;
            dbRecordGrade = grade;
            if(_handler)
            {
              q.exec();
              if(q.first())
                _handler->sReportsChanged(q.value("report_id").toInt(), true);
              else
                _handler->sReportsChanged(-1, true);
            }
            return TRUE;
        } else {
            // no good lets tell the user
	          QSqlError sqlErr = qry.lastError();   
            QMessageBox::critical(this,tr("Error saving to database"),sqlErr.databaseText());
        }
    }
    return FALSE;   
}
Ejemplo n.º 26
0
bool reConnectToDatabase(QSqlError lasterror, QString SQLquery, QString callingfunction)
{
    vvimDebug() << callingfunction << QObject::tr("Cannot execute query. DB lost? Try to reconnect!") << lasterror.text();

    if(!connectToDatabase())
    {
        QString textforlogfile = QString(QObject::tr("Something went wrong, could not reconnect to execute query: %1 error %2").arg(SQLquery).arg(lasterror.text()));
        vvimDebug() << callingfunction << "FATAL:" << textforlogfile ;
        qFatal((textforlogfile).toStdString().c_str());
        return false;
    }
    else
    {
        vvimDebug() << callingfunction << QObject::tr("Reconnection successful!");
        return true;
    }
}
Ejemplo n.º 27
0
void Database::writeUnitSet()
{
#if 0
    /*Before the opening of each transaction,adding this code to improve the speed*/
    QSqlDatabase::database().transaction();
    QSqlQuery query;
    query.prepare("INSERT INTO unitset(id, regist, shield, restated, level, unitid, geo_addr, type, delay, str)"
                  "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

    for (int iobr = 1;iobr <= 32;iobr++)
    {
        for (int loop = 1;loop <= 4;loop++)
        {
            for (int node = 1;node <= 255;node++)
            {
                //if((iobr-1)*4*255+(loop-1)*255+node != rowCount++)
                //qDebug() << QObject::tr("false");
                query.addBindValue((iobr-1)*4*255+(loop-1)*255+node);
                query.addBindValue(false);
                query.addBindValue(false);
                query.addBindValue(false);
                query.addBindValue(false);
                query.addBindValue((host<<24) | (iobr<<16) | (loop<<8) | node);
                query.addBindValue(0x00000000);
                query.addBindValue(0x00FFFF00);
                query.addBindValue(0x00000000);
                query.addBindValue(QString("华中科技大学南一楼%1室").arg(node));
                bool bSuccess = query.exec();
                if (!bSuccess)
                {
                    QSqlError lastError = query.lastError();
                    qDebug() << lastError.driverText()
                             <<QString(QObject::tr("insert unitset error"));
                }
            }
        }
    }
#endif

    int host = 1;
    //QDateTime dt = QDateTime::currentDateTime();

    //add by qingwu :2013-4-2
    /*增加节点号依次为: 01-00-00-000 的设备,
    作为本机非接口板设备的报警所用,比如 声光警报器,系统主电,系统备电 等。。*/
    QSqlDatabase::database().transaction();
    QSqlQuery query;
    query.clear();
    query.prepare("INSERT INTO unitset(id, regist, shield, restated, level, unitid, geo_addr, type, delay, str)"
                  "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
    query.addBindValue(0);
    query.addBindValue(true);//registed
    query.addBindValue(false);//unshield
    query.addBindValue(false);
    query.addBindValue(false);
    query.addBindValue((host<<24) | 0);//1-0-0-0
    query.addBindValue(0x00000000);
    query.addBindValue(0x00FFFF00);
    query.addBindValue(0x00000000);
    query.addBindValue(QString("本机设备"));
    bool bSuccess = query.exec();
    if (!bSuccess)
    {
        QSqlError lastError = query.lastError();
        qDebug() << lastError.driverText()
                 <<QString(QObject::tr("insert unitset 1-0-0-0 node error"));
    }

    //add by linwotian :为了33线路通信故障!为33接口板增加虚拟的回路号,并初始为1
    query.clear();
    query.prepare("INSERT INTO unitset(id, regist, shield, restated, level, unitid, geo_addr, type, delay, str)"
                  "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
    for (int iobr = 33,loop = 0,node = 0;iobr < 35; iobr++)//for board 33 and board 34,33-0-0-0,34-0-0-0
    {
        //if((iobr-1)*4*255+(loop-1)*255+node != rowCount++)
        //qDebug() << QObject::tr("false");
        query.addBindValue((iobr-1)*4*255);
        query.addBindValue(true);//initialized unregisted
        query.addBindValue(false);//initialized unshield
        query.addBindValue(false);
        query.addBindValue(false);
        query.addBindValue((host<<24) | (iobr<<16) | (loop<<8) | node);
        query.addBindValue(0x00000000);
        if(iobr == 33)
            query.addBindValue(0x00FF0000|(0x41<<8));//LOUXIAN 0x41
        else
            query.addBindValue(0x00FFFF00);
        query.addBindValue(0x00000000);
        if(iobr == 33)
            query.addBindValue(QString("1号主机33号接口板"));
        else
            query.addBindValue(QString("1号主机34号接口板"));
        bool bSuccess = query.exec();
        if (!bSuccess)
        {
            QSqlError lastError = query.lastError();
            qDebug() << lastError.driverText()
                     <<QString(QObject::tr("insert louxian error"));
        }
    }


    //add by linwotian ,init the zhikong information
    query.clear();
    query.prepare("INSERT INTO unitset(id, regist, shield, restated, level, unitid, geo_addr, type, delay, str)"
                  "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
    for (int iobr = 34, loop = 1;loop <= 20;loop++)
    {
        for (int node = 0;node <= 8;node++)
        {
            //if((iobr-1)*4*255+(loop-1)*255+node != rowCount++)
            //qDebug() << QObject::tr("false");
            query.addBindValue((iobr-1)*4*255+(loop-1)*8+node);
            query.addBindValue(false);//initialized unregisted
            query.addBindValue(false);//initialized unshield
            query.addBindValue(false);
            query.addBindValue(false);
            query.addBindValue((host<<24) | (iobr<<16) | (loop<<8) | node);
            query.addBindValue(0x00000000);
            query.addBindValue(0x00FFFF00);
            query.addBindValue(0x00000000);
            query.addBindValue(QString("%1号直控盘%2号直控点").arg(loop).arg(node));
            bool bSuccess = query.exec();
            if (!bSuccess)
            {
                QSqlError lastError = query.lastError();
                qDebug() << lastError.driverText()
                         <<QString(QObject::tr("insert zhikong error"));
            }
        }
    }

    //add by qingwu :为了34线路通信故障!为34接口板增加接口板号 回路号不变 节点号为0的节点
    query.clear();
    query.prepare("INSERT INTO unitset(id, regist, shield, restated, level, unitid, geo_addr, type, delay, str)"
                  "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
    for (int iobr = 34,loop = 21;loop <= 84;loop++)
    {
        query.addBindValue((iobr-1)*4*255+(loop-1)*64 + 0);
        query.addBindValue(false);//initialized unregisted
        query.addBindValue(false);//initialized shield
        query.addBindValue(false);
        query.addBindValue(false);
        query.addBindValue((host<<24) | (iobr<<16) | (loop<<8) | 0);
        query.addBindValue(0x00000000);
        query.addBindValue(0x00FFFF00);
        query.addBindValue(0x00000000);
        query.addBindValue(QString("%1号总线盘%2号总线点").arg(iobr).arg(loop));
        bool bSuccess = query.exec();
        if (!bSuccess)
        {
            QSqlError lastError = query.lastError();
            qDebug() << lastError.driverText()
                     <<QString(QObject::tr("insert 0 node error"));
        }
    }

    /*Close the transaction*/
    QSqlDatabase::database().commit();
}
Ejemplo n.º 28
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"));
}
Ejemplo n.º 29
0
void MQLEdit::execQuery()
{
  if(!OpenRPT::loggedIn)
  {
    QMessageBox::warning(this, tr("Not Connected"),
                         tr("You must be connected to a database in order "
                            "to execute a query."));
    return;
  }

  _results->_table->setRowCount(0);
  _results->_table->setColumnCount(0);
  
  _sql->_log->clear();
  _log->_log->clear();
  _log->_log->append(tr("---- Parsing Query ----\n"));
  MetaSQLQuery mql(_text->toPlainText());
  _log->_log->append(mql.parseLog());
  if(mql.isValid())
  {
    _log->_log->append(tr("Query parsed."));
    _log->_log->append(tr("---- Executing Query ----"));
    ParameterList plist = _pEdit->getParameterList();

    if (toolsTest_ModeAction->isChecked())
      XSqlQuery begin("BEGIN;");

    XSqlQuery qry = mql.toQuery(plist);
    _sql->_log->append(qry.executedQuery());
    if(qry.isActive()) {
        QSqlRecord rec = qry.record();
        int ncols = rec.count();
        _results->_table->setColumnCount(ncols);
        int c;
        for(c = 0; c < ncols; c++)
          _results->_table->setHorizontalHeaderItem(c, new QTableWidgetItem(rec.fieldName(c)));
        int nrows = 0;
        while(qry.next())
        {
          _results->_table->setRowCount(nrows + 1);
          for(c = 0; c < ncols; c++)
            _results->_table->setItem(nrows, c, new QTableWidgetItem(qry.value(c).toString()));
          nrows++;
        }
        showResults();
    }
    else
    {
      _log->_log->append(tr("Failed to execute query."));
      QSqlError err = qry.lastError();
      _log->_log->append(err.text());
    }

    if (toolsTest_ModeAction->isChecked())
      XSqlQuery begin("ROLLBACK;");
  }
  else
  {
    _log->_log->append(tr("ERROR: Invalid query!"));
    showLog();
  }   
}
Ejemplo n.º 30
0
void tableTemplateWidget::savePrivateData(void)
{
  int lastId = 0, cc = 0;

  crossInfo *cross;
  QSqlQuery query, query2;
  QSqlError le;

  query.prepare("DELETE FROM crossword.private_data WHERE _template = ?;");
  query.addBindValue(QVariant(templateId));
  query.exec();

  le = query.lastError();
  if (le.type() == QSqlError::NoError)
    {
      query.prepare("DELETE FROM crossword.crosses WHERE _template = ?;");
      query.addBindValue(QVariant(templateId));
      query.exec();

      le = query.lastError();
      if (le.type() != QSqlError::NoError)
        qDebug() << "2. savePrivateData: " << le.text();
    }
  else
    qDebug() << "1.  savePrivateData: " << le.text();

  QVariantList tmp;
  QVariantList pdid;
  QVariantList cpos;
  QVariantList ctype;
  QVariantList nw;

  QSqlDriver *drv = db->driver();

  drv->beginTransaction();
  for (int i = 0; i < wi.count(); i++)
    {
      query.prepare("INSERT INTO crossword.private_data (_template, _numword, "
                    "_row, _column, _lenght, _crosscount, _orientation) "
                    "VALUES (?, ?, ?, ?, ?, ?, ?);");

      query.addBindValue(QVariant(templateId));
      query.addBindValue(QVariant(wi[i]->numWord));
      query.addBindValue(QVariant(wi[i]->row));
      query.addBindValue(QVariant(wi[i]->col));
      query.addBindValue(QVariant(wi[i]->length));
      query.addBindValue(QVariant(wi[i]->crossCount));
      query.addBindValue(QVariant(wi[i]->orient));
      query.exec();

      le = query.lastError();
      if (le.type() == QSqlError::NoError)
        {
          lastId = query.lastInsertId().toInt();

          query2.prepare("INSERT INTO crossword.crosses (_template, _pd_id, _cpos, "
                         "_ctype, _numword) VALUES (?, ?, ?, ?, ?);");

          cc = wi[i]->crossCount;
          for (int j = 0; j < cc; j++)
            {
              cross = wi[i]->cil[j];

              tmp << templateId;
              pdid << lastId;
              cpos << cross->crossPos;
              ctype << cross->crossType;
              nw << cross->numWord2;
            }

          query2.addBindValue(tmp);
          query2.addBindValue(pdid);
          query2.addBindValue(cpos);
          query2.addBindValue(ctype);
          query2.addBindValue(nw);

          query2.execBatch(QSqlQuery::ValuesAsRows);

          tmp.clear();
          pdid.clear();
          cpos.clear();
          ctype.clear();
          nw.clear();
        }
      else
        qDebug() << "3. savePrivateData: " << le.text();
    }
  drv->commitTransaction();
}