Ejemplo n.º 1
0
    virtual void process()
    {
        IRecordSize *recordSize = helper->queryOutputMeta();

        Owned<IThorRowInterfaces> rowIf = createThorRowInterfaces(queryRowManager(), helper->queryOutputMeta(), queryId(), queryCodeContext());
        OwnedConstThorRow result = getAggregate(*this, container.queryJob().querySlaves(), *rowIf, *helper, mpTag);
        if (!result)
            return;
        CMessageBuffer msg;
        CMemoryRowSerializer mbs(msg);
        rowIf->queryRowSerializer()->serialize(mbs, (const byte *)result.get());
        if (!queryJobChannel().queryJobComm().send(msg, 1, mpTag, 5000))
            throw MakeThorException(0, "Failed to give result to slave");
    }
Ejemplo n.º 2
0
// ==== CONFIRMA alterações feitas
void MovimentoEditDialog::on_okBtn_clicked()
{
	/* FAZER AQUI as análises necessarias, analisando o conteúdo dos widgets
  e verificando se eles são válidos de acordo com as regras estabelecidas para o caso.
  Se algum estiver inválido, retornar e não prosseguir.
  *** O mesmo que fizemos no exercício "Dialogo" ***
 */
	int cliComboRow= ui->clienteCombo->currentIndex();
	if ( cliComboRow<0)
	{
		QMessageBox::warning(this, "Erro", "Selecione um cliente");
		ui->clienteCombo->setFocus();
		return;
	}
	// outras validações...

	QSqlDatabase db = m_movModel->database();
	db.transaction();

	// linha atual do mapper:
	int mapperRow = m_movMapper->currentIndex();

	if ( !m_insert)
	{
		// == recupera o 'id' do movimento no model de movimento (já que permite navegação):
		m_currentMovimentoId = m_movModel->index( mapperRow, m_colInd.movId).data().toInt();
	}

	// = recupera o 'id' do cliente, já que permite mudar o cliente(tanto em edição quanto em inserção)
	m_currentClienteId = ui->clienteCombo->model()->index(cliComboRow, 0).data().toInt();
	// onde 0(zero) é o índice da coluna "chave" no "relationModel" da "combo"), no caso o "id" do cliente.

	// o mapper deve fazer com que o model submeta os dados, atualizando a fonte de dados
	// (pois está posicionado para "ManualSubmit"):

	QString errMsg;
	if ( m_canSubmit || m_insert ) // "submit" não falha nas inserções.
	{
		if ( !m_movMapper->submit())
			errMsg = "Falha ao enviar dados ao banco:\n" + m_movModel->lastError().text();
	}
	else // executa a query UPDATE diretamente no banco
	{
		QSqlQuery query(db);
		int tipo_id = ui->tipoCombo->model()->index(ui->tipoCombo->currentIndex(), 0).data().toInt();
		QString mov_date = ui->movDate->date().toString("dd/MM/yyyy");
		QString descr = ui->descrEdit->text();
		if ( query.exec(QString("UPDATE movimento SET cliente_id = %1, tipo_id = %2, mov_date = '%3', description = '%4' WHERE mov_id = %5")
							  .arg(m_currentClienteId).arg(tipo_id).arg(mov_date).arg(descr).arg(m_currentMovimentoId)))
		{
			m_movModel->query().finish();
			m_movModel->select(); // select, pois a alteração foi feita sem conhecimento do model(diretamente no banco)
		}
		else
			errMsg = "Falha ao enviar dados diretamente ao banco:\n" + query.lastError().text();
	}

	if ( !errMsg.isEmpty() )
	{
		QMessageBox::warning(this, "ERRO", errMsg);
		db.rollback(); // desfaz a transação
		on_cancelBtn_clicked(); // cancela
		return;
	}

	if ( m_insert ) // se inserido, o "id" do movimento só poderá ser recuperado agora (após o "submit")
	{
		// pegar o "lastInsertId", caso o driver suporte essa 'feature':

		QString queryIdText;

		if (db.driverName()=="QPSQL" ) // POSTGRE suporta a 'feature' "lastInsertID", mas depende de configuração não-default...
			queryIdText = "select currval('movimento_mov_id_seq')"; // então é mais seguro usar uma query de acesso nativo
		else if (db.driverName()=="QOCI") // ORACLE, idem...
			queryIdText = "select movimento_mov_id_seq.currval from dual";
		// else if {} ... // outras exceções...

		if ( queryIdText.isEmpty())  // tenta recuperar id pelo "lastInsertId":
		{
			if ( db.driver()->hasFeature(QSqlDriver::LastInsertId))
				m_currentMovimentoId = m_movModel->query().lastInsertId().toInt();
			else
				qDebug() << "Driver " << db.driverName() << " nao suporta 'lastInsertId' - pesquisar na documentação do banco";
		}
		else  // usa query específica do banco
		{
			QSqlQuery queryId(db);
			if ( queryId.exec(queryIdText) && queryId.next()) // executa e tenta posicionar na primeira(e única) linha da query
				m_currentMovimentoId = queryId.value(0).toInt(); // pega o valor da primeira(e única) coluna da query
			else
				QMessageBox::warning(this, "ERRO",  "Falha ao recuperar id do registro inserido:\n" + queryId.lastError().text());
		}
	}
	// finaliza transação:
	db.commit();

	accept(); // "accept", ao invés de "close": -> além de fechar o diálogo (chamando "close()"),
	// "accept" faz com que o retorno da função "exec",
	// no codigo de quem criou o diálogo, retorne "QDialog::Accepted" e assim fique sabendo
	// que a edição foi CONFIRMADA e não cancelada.
}
Ejemplo n.º 3
0
    virtual void start() override
    {
        ActivityTimer s(totalCycles, timeActivities);
        try
        {
            try
            {
                PARENT::start();
            }
            catch (IException *e)
            {
                fireException(e);
                barrier->cancel();
                throw;
            }
            catch (CATCHALL)
            {
                Owned<IException> e = MakeActivityException(this, 0, "Unknown exception starting sort input");
                fireException(e);
                barrier->cancel();
                throw;
            }

            Linked<IThorRowInterfaces> rowif = queryRowInterfaces(input);
            Owned<IThorRowInterfaces> auxrowif = createThorRowInterfaces(queryRowManager(), helper->querySortedRecordSize(),queryId(),queryCodeContext());
            sorter->Gather(
                rowif,
                inputStream,
                helper->queryCompare(),
                helper->queryCompareLeftRight(),
                NULL,helper->querySerialize(),
                NULL,
                NULL,
                false,
                isUnstable(),
                abortSoon,
                auxrowif);

            PARENT::stop();
            if (abortSoon)
            {
                ActPrintLogEx(&queryContainer(), thorlog_null, MCwarning, "MSortSlaveActivity::start aborting");
                barrier->cancel();
                return;
            }
        }
        catch (IException *e)
        {
            fireException(e);
            barrier->cancel();
            throw;
        }
        catch (CATCHALL)
        {
            Owned<IException> e = MakeActivityException(this, 0, "Unknown exception gathering sort input");
            fireException(e);
            barrier->cancel();
            throw;
        }
        ActPrintLog("SORT waiting barrier.1");
        if (!barrier->wait(false)) {
            Sleep(1000); // let original error through
            throw MakeThorException(TE_BarrierAborted,"SORT: Barrier Aborted");
        }
        ActPrintLog("SORT barrier.1 raised");
        output.setown(sorter->startMerge(totalrows));
    }
Ejemplo n.º 4
0
IThorRowInterfaces * CDiskReadSlaveActivityBase::queryDiskRowInterfaces()
{
    if (!diskRowIf) 
        diskRowIf.setown(createThorRowInterfaces(queryRowManager(), helper->queryDiskRecordSize(),queryId(),queryCodeContext()));
    return diskRowIf;
}