예제 #1
0
/**
\param val
**/
void BlSearchWidget::setFieldValue ( QString campo, QString val )
{
    BL_FUNC_DEBUG
    BlDebug::blDebug ( "BlSearchWidget::setcifprofesor", 0, val );

    QString SQLQuery("");
    SQLQuery = "SELECT * FROM " + m_tabla + " WHERE " + campo + " = $1";
    BlDbRecordSet *cur = mainCompany() ->load ( SQLQuery, val );

    if ( !cur->eof() ) {
        /// Inicializamos los valores de vuelta a ""
        QMapIterator<QString, QString> i ( m_valores );
        while ( i.hasNext() ) {
            i.next();
            m_valores.insert ( i.key(), cur->value( i.key() ) );
        } // end while
    } else {
        /// Inicializamos los valores de vuelta a ""
        QMapIterator<QString, QString> i ( m_valores );
        while ( i.hasNext() ) {
            i.next();
            m_valores.insert ( i.key(), "" );
        } // end while
    } // end if
    delete cur;
    pinta();
    
}
예제 #2
0
void ReportWindow::colorList() {

    //
    // ADD CODE HERE TO CHECK FOR CHANGES TO DOCUMENT
    //
    QMap<QString, QColor> cm = _colorMap;
    ColorList cl(this);
    cl.init(&_colorMap);
    cl.exec();
    if(cm.count() == _colorMap.count()) {
        // the two lists have the same number of items so
        // we will have to check each item for equality
        // to see if a change was made
        QMapIterator<QString, QColor> cit;
        for(cit = cm.begin(); cit != cm.end(); ++cit) {
            if(!_colorMap.contains(cit.key()) || _colorMap[cit.key()] != cm[cit.key()]) {
                setModified(TRUE);
                break;
            }
        }
    } else {
        // they don't have the same number of items
        // so we can just assume the list was changed
        setModified(TRUE);
    }
}
예제 #3
0
bool KisBaseNode::check(const KoProperties & properties) const
{
    QMapIterator<QString, QVariant> iter = properties.propertyIterator();
    while (iter.hasNext()) {
        iter.next();
        if (m_d->properties.contains(iter.key())) {
            if (m_d->properties.value(iter.key()) != iter.value())
                return false;
        }
    }
    return true;
}
예제 #4
0
QString FRegister::generateBindingOfTheRegister()
{
    QString code = "";

    QStringList keyList;
    QString name = this->attributes().value("name").toString();
    QMapIterator<QString, QVariant> iterator (this->attributes());
    while(iterator.hasNext())
    {
        iterator.next();
        if(iterator.key() != "name" && iterator.key() != "registrator")
        {
            keyList.append(iterator.key());
        }
    }
    code += "function register_" + name + "_Binding(x)\n{\n\nthis.object = x;\nthis.map = x.attributes();\n";
    for(int i=0; i<keyList.size(); i++)
    {
        code += "this." + keyList[i] + ";\n";// + " = Current_" + keyList[i] + ";\n";
    }

    code += "this.Write = function()\n{\n";
    for(int i=0; i<keyList.size(); i++)
    {
        code += "this.object.setAttribute(\"" + keyList[i] + "\", this." + keyList[i] + ");\n";
    }
    code += "}\n";

    code += "this.Add = function()\n{\n";
    for(int i=0; i<keyList.size(); i++)
    {
        code += "this.object.setAttribute(\"" + keyList[i] + "\", \"\");\n";
    }
    code += "return this;\n";
    code += "}\n";

    code += "}\n";
    //code += "var " + name + " = new register_" + name + "_Binding(" + name + ");\n";

    QFile file ("./scripts/binding" + name + ".qs");
    if(file.open(QIODevice::WriteOnly))
    {
        QTextStream stream (&file);
        stream<<code;
    }
    file.close();

    return code;
}
예제 #5
0
void LocationTable::splitByAnchors(const QByteArray& text, const KDevelop::SimpleCursor& textStartPosition, QList<QByteArray>& strings, QList<KDevelop::SimpleCursor>& anchors) const {

  KDevelop::SimpleCursor currentCursor = textStartPosition;
  size_t currentOffset = 0;
  
  QMapIterator<std::size_t, KDevelop::SimpleCursor> it = m_offsetTable;

  while (currentOffset < (size_t)text.length())
  {
    KDevelop::SimpleCursor nextCursor;
    size_t nextOffset;
    
    if(it.hasNext()) {
      it.next();
      nextOffset = it.key();
      nextCursor = it.value();
    }else{
      nextOffset = text.length();
      nextCursor = KDevelop::SimpleCursor::invalid();
    }

    if( nextOffset-currentOffset > 0 ) {
      strings.append(text.mid(currentOffset, nextOffset-currentOffset));
      anchors.append(currentCursor);
    }
    
    currentOffset = nextOffset;
    currentCursor = nextCursor;
  }
}
예제 #6
0
void LocationTable::splitByAnchors(const PreprocessedContents& text, const Anchor& textStartPosition, QList<PreprocessedContents>& strings, QList<Anchor>& anchors) const {

  Anchor currentAnchor = Anchor(textStartPosition);
  size_t currentOffset = 0;

  QMapIterator<std::size_t, Anchor> it = m_offsetTable;

  while (currentOffset < (size_t)text.size())
  {
    Anchor nextAnchor(KDevelop::CursorInRevision::invalid());
    size_t nextOffset;

    if(it.hasNext()) {
      it.next();
      nextOffset = it.key();
      nextAnchor = it.value();
    }else{
      nextOffset = text.size();
      nextAnchor = Anchor(KDevelop::CursorInRevision::invalid());
    }

    if( nextOffset-currentOffset > 0 ) {
      strings.append(text.mid(currentOffset, nextOffset-currentOffset));
      anchors.append(currentAnchor);
    }

    currentOffset = nextOffset;
    currentAnchor = nextAnchor;
  }
}
예제 #7
0
//---------------------------------------------------------------------------
//  getWordItems
//
//! Construct a list of word items to be inserted into a word list, based on
//! the results of a list of searches.
//
//! @param searchSpecs the list of search specifications
//! @return a list of word items
//---------------------------------------------------------------------------
QList<WordTableModel::WordItem>
WordVariationDialog::getWordItems(const QList<SearchSpec>& searchSpecs) const
{
    QList<WordTableModel::WordItem> wordItems;
    QMap<QString, QString> wordMap;
    QListIterator<SearchSpec> lit (searchSpecs);
    while (lit.hasNext()) {
        QStringList wordList = wordEngine->search(lexicon, lit.next(), false);
        QStringListIterator wit (wordList);
        while (wit.hasNext()) {
            QString str = wit.next();
            wordMap.insert(str.toUpper(), str);
        }
    }

    QMapIterator<QString, QString> mit (wordMap);
    while (mit.hasNext()) {
        mit.next();
        QString value = mit.value();
        QList<QChar> wildcardChars;
        for (int i = 0; i < value.length(); ++i) {
            QChar c = value[i];
            if (c.isLower())
                wildcardChars.append(c);
        }
        QString wildcard;
        if (!wildcardChars.isEmpty()) {
            qSort(wildcardChars.begin(), wildcardChars.end(),
                  Auxil::localeAwareLessThanQChar);
            foreach (const QChar& c, wildcardChars)
                wildcard.append(c.toUpper());
        }
        wordItems.append(WordTableModel::WordItem(
            mit.key(), WordTableModel::WordNormal, wildcard));
    }
예제 #8
0
void Emotions::storeClass(QString klassName, NaiveBayesClassifier *classifier){
    double acc=0;
    if(klassName.contains("calm") || klassName.contains("exited")){
        acc=EMOTION_AROUSAL_ACCURACY;
    }else if(klassName.contains("positive") || klassName.contains("negative")){
        acc=EMOTION_VALENCE_ACCURACY;
    }else{
        return;
    }

    if(classifier->getTrainedClasses().contains(klassName)){
        QFile file(_dataPath+"."+klassName);
        if (!file.open(QIODevice::WriteOnly)) {
            qDebug() << "Emotions : cannot open file "+file.fileName()+" : "
                     << qPrintable(file.errorString()) << file.fileName()<< endl;
            return;
        }

        QMapIterator<double, double>* clasIt = new QMapIterator<double,double>(*classifier->getTrainedClasses().value(klassName));
        while(clasIt->hasNext()){
            clasIt->next();
            for(int j=0;j<clasIt->value();++j){
                QString* strVal=new QString("");
                strVal->setNum(clasIt->key(),'f', acc);
                file.write(strVal->toAscii());
                file.putChar('\n');
            }
        }
    }
}
예제 #9
0
int Plot::closestCurve(int xpos, int ypos, int &dist, int &point)
{
QwtScaleMap map[QwtPlot::axisCnt];
for ( int axis = 0; axis < QwtPlot::axisCnt; axis++ )
	map[axis] = canvasMap(axis);

double dmin = 1.0e10;
int key = -1;
for (QMapIterator<int, QwtPlotCurve *> it = d_curves.begin(); it != d_curves.end(); ++it ) 
	{
	QwtPlotCurve *c = (QwtPlotCurve *)it.data();
	if (!c)
		continue;

	for (int i=0; i<c->dataSize(); i++)
		{
		double cx = map[c->xAxis()].xTransform(c->x(i)) - double(xpos);
		double cy = map[c->yAxis()].xTransform(c->y(i)) - double(ypos);
		double f = qwtSqr(cx) + qwtSqr(cy);
		if (f < dmin)
			{
			dmin = f;
			key = it.key();
			point = i;
			}
		 }
	}
dist = int(sqrt(dmin));
return key;
}
예제 #10
0
void SingleXmlSerializer::exportProperties(const Id&id, QDomDocument &doc, QDomElement &root
		, QHash<Id, Object *> const &objects)
{
	QDomElement props = doc.createElement("properties");

	const GraphicalObject * const graphicalObject = dynamic_cast<const GraphicalObject *>(objects[id]);
	const LogicalObject * const logicalObject
			= dynamic_cast<const LogicalObject *>(objects[graphicalObject->logicalId()]);

	QMap<QString, QVariant> properties;

	QMapIterator<QString, QVariant> i = logicalObject->propertiesIterator();
	while (i.hasNext()) {
		i.next();
		properties[i.key()] = i.value();

	}

	i = graphicalObject->propertiesIterator();
	while (i.hasNext()) {
		i.next();
		properties[i.key()] = i.value();
	}

	foreach (const QString &key, properties.keys()) {
		QDomElement prop = doc.createElement("property");

		QString typeName = properties[key].typeName();
		QVariant value = properties[key];
		if (typeName == "qReal::IdList" && (value.value<IdList>().size() != 0)) {
			QDomElement list = ValuesSerializer::serializeIdList("list", value.value<IdList>(), doc);
			prop.appendChild(list);
		} else if (typeName == "qReal::Id"){
			prop.setAttribute("value", value.value<Id>().toString());
		} else if (value.toString().isEmpty()) {
			continue;
		} else {
			prop.setAttribute("value", properties[key].toString());
		}

		prop.setAttribute("name", key);

		props.appendChild(prop);
	}

	root.appendChild(props);
}
예제 #11
0
void KisBaseNode::mergeNodeProperties(const KoProperties & properties)
{
    QMapIterator<QString, QVariant> iter = properties.propertyIterator();
    while (iter.hasNext()) {
        iter.next();
        m_d->properties.setProperty(iter.key(), iter.value());
    }
}
예제 #12
0
void LocationTable::dump() const
{
  QMapIterator<std::size_t, KDevelop::SimpleCursor> it = m_offsetTable;
  kDebug(9007) << "Location Table:";
  while (it.hasNext()) {
    it.next();
    kDebug(9007) << it.key() << " => " << it.value().textCursor();
  }
}
예제 #13
0
void LocationTable::dump() const
{
  QMapIterator<std::size_t, Anchor> it = m_offsetTable;
  qCDebug(RPP) << "Location Table:";
  while (it.hasNext()) {
    it.next();
    qCDebug(RPP) << it.key() << " => " << it.value().castToSimpleCursor();
  }
}
예제 #14
0
void
QDialogButtons::handleClicked()
{
    const QObject *s = sender();
    if(!s)
	return;

    for(QMapIterator<QDialogButtons::Button, QWidget *> it = d->buttons.begin(); it != d->buttons.end(); ++it) {
	if(it.data() == s) {
	    emit clicked((QDialogButtons::Button)it.key());
	    switch(it.key()) {
	    case Retry:
		emit retryClicked();
		break;
	    case Ignore:
		emit ignoreClicked();
		break;
	    case Abort:
		emit abortClicked();
		break;
	    case All:
		emit allClicked();
		break;
	    case Accept:
		emit acceptClicked();
		break;
	    case Reject:
		emit rejectClicked();
		break;
	    case Apply:
		emit applyClicked();
		break;
	    case Help:
		emit helpClicked();
		break;
	    default:
		break;
	    }
	    return;
	}
    }
}
예제 #15
0
QHash<QString, QVariant> RefactoringApplier::properties(Id const &id) const
{
	QHash<QString, QVariant> result;

	QMapIterator<QString, QVariant> properties =
			(mLogicalModelApi.isLogicalId(id))
			? mLogicalModelApi.logicalRepoApi().propertiesIterator(id)
			: mLogicalModelApi.logicalRepoApi().propertiesIterator(
					mGraphicalModelApi.logicalId(id));

	while (properties.hasNext()) {
		properties.next();

		if (!defaultProperties.contains(properties.key())) {
			result.insert(properties.key(), properties.value());
		}
	}

	return result;
}
예제 #16
0
KisBaseNode::KisBaseNode(const KisBaseNode & rhs)
        : QObject()
        , KisShared(rhs)
        ,  m_d(new Private())
{
    QMapIterator<QString, QVariant> iter = rhs.m_d->properties.propertyIterator();
    while (iter.hasNext()) {
        iter.next();
        m_d->properties.setProperty(iter.key(), iter.value());
    }
    m_d->linkedTo = rhs.m_d->linkedTo;
}
예제 #17
0
bool MSqlQuery::exec()
{
    // Database connection down.  Try to restart it, give up if it's still
    // down
    if (!m_db)
    {
        // Database structure's been deleted
        return false;
    }

    if (!m_db->isOpen() && !m_db->Reconnect())
    {
        LOG(VB_GENERAL, LOG_INFO, "MySQL server disconnected");
        return false;
    }

    bool result = QSqlQuery::exec();

    // if the query failed with "MySQL server has gone away"
    // Close and reopen the database connection and retry the query if it
    // connects again
    if (!result && QSqlQuery::lastError().number() == 2006 && m_db->Reconnect())
        result = QSqlQuery::exec();

    if (VERBOSE_LEVEL_CHECK(VB_DATABASE) && logLevel <= LOG_DEBUG)
    {
        QString str = lastQuery();

        // Database logging will cause an infinite loop here if not filtered
        // out
        if (!str.startsWith("INSERT INTO logging "))
        {
       	    // Sadly, neither executedQuery() nor lastQuery() display
            // the values in bound queries against a MySQL5 database.
            // So, replace the named placeholders with their values.

            QMapIterator<QString, QVariant> b = boundValues();
            while (b.hasNext())
            {
                b.next();
                str.replace(b.key(), '\'' + b.value().toString() + '\'');
            }

            LOG(VB_DATABASE, LOG_DEBUG,
                QString("MSqlQuery::exec(%1) %2%3")
                        .arg(m_db->MSqlDatabase::GetConnectionName()).arg(str)
                        .arg(isSelect() ? QString(" <<<< Returns %1 row(s)")
                                              .arg(size()) : QString()));
        }
    }

    return result;
}
예제 #18
0
/*!
  Lists values used during initialization
*/
QStringList TEIniFile::usedValues()
{
  QStringList sl;
  QMapIterator<QString, type_ValueList> it;
  for(it=SectionListDef.begin();it!=SectionListDef.end();++it)
  {
    type_ValueListIterator it1;
    for(it1=(*it).begin();it1!=(*it).end();++it1)
      sl << it.key()+"->"+it1.key();
  }
  return sl;
}
예제 #19
0
void ClientPrivate::tuiLaunched () {
    qDebug () << "ClientPrivate::tuiLaunched";
    QMapIterator<QString, Transfer *> iter (transfers);

    if (transfers.count() == 0) {
        // There are no transfers
        return;
    }

    while (iter.hasNext()) {
        iter.next();
        Transfer *transfer = iter.value ();

        if (iter.key() != transfer->transferId ()) {
            qCritical () <<
                "Client::tuiLaunched -> Key does not match transfer id";
        }

        QDBusReply<bool> exists =
            interface->transferExists (transfer->transferId ());
        if (exists.isValid ()) {
            if (exists.value () == true) {
                qDebug() << transfer->transferId () << "exists in TUI"
                    << "- not registering this. Moving to next";

                // Transfer exists in TUI - go to next transfer
                continue;
            }
        } else {
            qCritical() << "Got invalid reply when checking if transfer "
                << transfer->transferId () << " exists in TUI";
            continue;
        }

        QDBusReply<QString> reply =
            interface->registerTransientTransfer (transfer->transferId ());

        if (reply.isValid()) {
            if (reply.value () == transfer->transferId ()) {
                transfer->tuiLaunched ();
            } else {
                qCritical() << "Got " << reply.value () <<
                    " as reply from registerPersistentTransfer instead of "
                    << "expected value of " << transfer->transferId ();
            }
        } else {
            qWarning() << "Transfer with tracker uri" << transfer->transferId ()
                << "not found.";
        }
    }
}
예제 #20
0
/** Esta funcion lanza un signal avisando de que se ha cambiado el id. Y debe tenerse en cuenta que el
    id puede estar vacio ya que tambien se puede haber borrado el que estaba puesto.
**/
void BlSearchWidget::pinta()
{
    BL_FUNC_DEBUG
    m_semaforo = TRUE;
    QString cad = "";

    if (m_mask == "") {
      
	/// Iteramos y concatenamos"
	QMapIterator<QString, QString> i ( m_valores );
	if ( i.hasNext() ) {
	    i.next();
	    m_inputBusqueda->setText ( m_valores[i.key() ] );
	} // end if
	while ( i.hasNext() ) {
	    i.next();
	    cad = cad + " " + m_valores.value ( i.key() );
	}

    } else {
      
	cad = m_mask;
	/// Iteramos y reemplazamos
	QMapIterator<QString, QString> i ( m_valores );
	while ( i.hasNext() ) {
	    i.next();
	    cad.replace("["+i.key()+"]", m_valores.value(i.key()));
	}
      
      
    } // end if

    m_textBusqueda->setText ( cad );

    m_semaforo = FALSE;
    emit ( valueChanged ( mdb_id ) );
    
}
void Container::documentTitleChanged(Sublime::Document* doc)
{
    QMapIterator<QWidget*, View*> it = d->viewForWidget;
    while (it.hasNext()) {
        if (it.next().value()->document() == doc) {
            d->fileNameCorner->setText( doc->title() );
            int tabIndex = d->stack->indexOf(it.key());
            if (tabIndex != -1) {
                d->tabBar->setTabText(tabIndex, doc->title());
            }
            break;
        }
    }
}
void Container::statusIconChanged(Document* doc)
{
    QMapIterator<QWidget*, View*> it = d->viewForWidget;
    while (it.hasNext()) {
        if (it.next().value()->document() == doc) {
            d->fileStatus->setPixmap( doc->statusIcon().pixmap( QSize( 16,16 ) ) );
            int tabIndex = d->stack->indexOf(it.key());
            if (tabIndex != -1) {
                d->tabBar->setTabIcon(tabIndex, doc->statusIcon());
            }
            break;
        }
    }
}
예제 #23
0
/**
\param val
**/
void BlSearchWidget::setId ( QString val, bool cargarvalores )
{
    BL_FUNC_DEBUG
    BlDebug::blDebug ( "BlSearchWidget::setId", 0, val );
    mdb_id = val;

    if ( m_tabla == "" || !cargarvalores) {
        return;
    } // end if

    if ( val == "" ) {
        m_inputBusqueda->setText ( "" );
        m_textBusqueda->setText ( "" );
        mdb_id = "";
        /// Inicializamos los valores de vuelta a ""
        QMapIterator<QString, QString> i ( m_valores );
        while ( i.hasNext() ) {
            i.next();
            m_valores.insert ( i.key(), "" );
        } // end while
    } else {
        QString SQLQuery("");
	SQLQuery = "SELECT * FROM " + m_tabla + " WHERE " + m_campoid + "= $1";
        BlDbRecordSet *cur = mainCompany() ->load( SQLQuery, mdb_id );
        if ( !cur->eof() ) {
            /// Inicializamos los valores de vuelta a ""
            QMapIterator<QString, QString> i ( m_valores );
            while ( i.hasNext() ) {
                i.next();
                m_valores.insert ( i.key(), cur->value( i.key() ) );
            } // end while
        } // end if
        delete cur;
    } // end if
    pinta();
    
}
예제 #24
0
/**
 * @brief reads the commands that are available form the stored settings
 * @param commandMap the map that is to store
 * @return
 *	void
 */
void DLDConfigureOB::writeCommandMap (QMap<QString, QString> commandMap)
{
	QMapIterator<QString, QString> iter (commandMap);
	int i;
	QString nameBase = "%1-commandName";
	QString descBase = "%1-commandDescription";
	for (i = 0; iter.hasNext (); i++)
	{
		iter.next();
		settings->setValue(nameBase.arg(i), iter.key());
		settings->setValue(descBase.arg(i), iter.value());
	}
	settings->setValue("numberOfCommands", i);
	emit commandListChanged ();
}
예제 #25
0
bool InformWindow::keyProcessing(const int &key)
{
    QMapIterator<int, Command*> it (kbCommand);
    while (it.hasNext())
    {
        it.next();
        if (key == it.key())
        {
            if (it.value() != NULL)
            {
                it.value()->execute();
                return true;
            }
        }
    }
    return false;
}
void QtPropertyDataIntrospection::ChildNeedUpdate()
{
	QMapIterator<QtPropertyDataDavaVariant*, const DAVA::IntrospectionMember *> i = QMapIterator<QtPropertyDataDavaVariant*, const DAVA::IntrospectionMember *>(childVariantMembers);

	while(i.hasNext())
	{
		i.next();

		QtPropertyDataDavaVariant *childData = i.key();
		DAVA::VariantType childCurValue = i.value()->Value(object);

		if(childCurValue != childData->GetVariantValue())
		{
			childData->SetVariantValue(childCurValue);
		}

	}
}
예제 #27
0
void ViewManager::ViewManagerPrivate::slotLockedChanged(bool locked)
{
    if(locked) {
        // When the view is locked, all draggers should be destroyed
        QMapIterator<WidgetProperties *, QDeclarativeItem *> iterator =
                QMapIterator<WidgetProperties *, QDeclarativeItem *>(registeredDraggers);
        while (iterator.hasNext()) {
            iterator.next();
            QDeclarativeItem *item = iterator.value();
            registeredDraggers.remove(iterator.key());
            item->deleteLater();
        }

        q->setCurrentDraggedWidget("");
    } else {
        // For each item in the current page, a dragger should
        // be created
        DisplayedPageWidgetsModel * pageModel = displayedPagesModel->pageModel(currentPageIndex);
        for (int i = 0; i < pageModel->rowCount(); i++) {
            emit q->requestCreateDragger(pageModel->widget(i));
        }
    }
}
예제 #28
0
/**
\param parent
**/
BlSearchWidget::BlSearchWidget ( QWidget *parent )
        : BlWidget ( parent )
{
    BL_FUNC_DEBUG
    setupUi ( this );
    m_textBusqueda->setText ( "" );
    mdb_id = "";
    m_campoid = "";

    /// Inicializamos los valores de vuelta a ""
    QMapIterator<QString, QString> i ( m_valores );
    while ( i.hasNext() ) {
        i.next();
        m_valores.insert ( i.key(), "" );
    } // end while

    m_semaforo = FALSE;
    m_mask = "";
    
    /// Establecemos la delegacion del foco en el texto
    setFocusProxy(m_textBusqueda);
    
}
예제 #29
0
int Go2Car2GoEngine::request ( const Car2goMethod &method, bool get )
{
    QMap<QString,QString> map = method.args;

    QMapIterator<QString, QString> i ( map );
    QStringList keyList;
    while ( i.hasNext() )
    {
        i.next();
        keyList << i.key();
    }
    qSort ( keyList.begin(), keyList.end() );

    QUrl url ( GO2CAR2GO_HOST + method.method, QUrl::TolerantMode );
    for ( int i = 0; i < keyList.size(); ++i )
    {
        url.addQueryItem ( keyList.at ( i ),  map.value ( keyList.at ( i ) ) );
    }


    requestCounter++;
    RequestData requestData;
    requestData.requestId = requestCounter;

    QNetworkReply *reply;

    if ( get )
        reply = net_manager->get ( QNetworkRequest ( url ) );
    else
        reply = net_manager->post ( QNetworkRequest ( QUrl(GO2CAR2GO_SECURED_HOST) ), url.encodedQuery () );

    requestDataMap.insert ( reply , requestData );
    qDebug() << "request id: " << url;

    return requestData.requestId;
}
예제 #30
0
bool MSqlQuery::exec()
{
    if (!m_db)
    {
        // Database structure's been deleted
        return false;
    }

    if (m_last_prepared_query.isEmpty())
    {
        LOG(VB_GENERAL, LOG_ERR,
            "MSqlQuery::exec(void) called without a prepared query.");
        return false;
    }

#if DEBUG_RECONNECT
    if (random() < RAND_MAX / 50)
    {
        LOG(VB_GENERAL, LOG_INFO,
            "MSqlQuery disconnecting DB to test reconnection logic");
        m_db->m_db.close();
    }
#endif

    // Database connection down.  Try to restart it, give up if it's still
    // down
    if (!m_db->isOpen() && !Reconnect())
    {
        LOG(VB_GENERAL, LOG_INFO, "MySQL server disconnected");
        return false;
    }

    QElapsedTimer timer;
    timer.start();

    bool result = QSqlQuery::exec();
    qint64 elapsed = timer.elapsed();

    // if the query failed with "MySQL server has gone away"
    // Close and reopen the database connection and retry the query if it
    // connects again
    if (!result && QSqlQuery::lastError().number() == 2006 && Reconnect())
        result = QSqlQuery::exec();

    if (!result)
    {
        QString err = MythDB::GetError("MSqlQuery", *this);
        MSqlBindings tmp = QSqlQuery::boundValues();
        bool has_null_strings = false;
        for (MSqlBindings::iterator it = tmp.begin(); it != tmp.end(); ++it)
        {
            if (it->type() != QVariant::String)
                continue;
            if (it->isNull() || it->toString().isNull())
            {
                has_null_strings = true;
                *it = QVariant(QString(""));
            }
        }
        if (has_null_strings)
        {
            bindValues(tmp);
            timer.restart();
            result = QSqlQuery::exec();
            elapsed = timer.elapsed();
        }
        if (result)
        {
            LOG(VB_GENERAL, LOG_ERR,
                QString("Original query failed, but resend with empty "
                        "strings in place of NULL strings worked. ") +
                "\n" + err);
        }
    }

    if (VERBOSE_LEVEL_CHECK(VB_DATABASE, LOG_INFO))
    {
        QString str = lastQuery();

        // Database logging will cause an infinite loop here if not filtered
        // out
        if (!str.startsWith("INSERT INTO logging "))
        {
            // Sadly, neither executedQuery() nor lastQuery() display
            // the values in bound queries against a MySQL5 database.
            // So, replace the named placeholders with their values.

            QMapIterator<QString, QVariant> b = boundValues();
            while (b.hasNext())
            {
                b.next();
                str.replace(b.key(), '\'' + b.value().toString() + '\'');
            }

            LOG(VB_DATABASE, LOG_INFO,
                QString("MSqlQuery::exec(%1) %2%3%4")
                        .arg(m_db->MSqlDatabase::GetConnectionName()).arg(str)
                        .arg(QString(" <<<< Took %1ms").arg(QString::number(elapsed)))
                        .arg(isSelect() ? QString(", Returned %1 row(s)")
                                              .arg(size()) : QString()));
        }
    }

    return result;
}