Example #1
0
void DbFunc::createTable(const QSqlDatabase& db, const QString& tablename,
                         const QList<Field>& fieldlist,
                         const QString& tempsuffix)
{
    QString creation_sql = sqlCreateTable(tablename, fieldlist);
    if (!tableExists(db, tablename)) {
        // Create table from scratch.
        exec(db, creation_sql);
        return;
    }

    // Otherwise, it's a bit more complex...

    // 1. Create a list of plans. Start with the fields we want, which we
    //    will add (unless later it turns out they exist already).
    QList<FieldCreationPlan> planlist;
    QStringList goodfieldlist;
    for (int i = 0; i < fieldlist.size(); ++i) {
        const Field& field = fieldlist.at(i);
        FieldCreationPlan p;
        p.name = field.name();
        p.intended_field = &field;
        p.add = true;
        planlist.append(p);
        goodfieldlist.append(delimit(p.name));
    }

    // 2. Fetch a list of existing fields.
    // - If any are in our "desired" list, and we didn't know they were in
    //   the database, don't add them (but maybe change them if we want them
    //   to have a different type).
    // - If they're not in our "desired" list, then they're superfluous, so
    //   aim to drop them.
    QList<SqlitePragmaInfoField> infolist = getPragmaInfo(db, tablename);
    for (int i = 0; i < infolist.size(); ++i) {
        const SqlitePragmaInfoField& info = infolist.at(i);
        bool existing_is_superfluous = true;
        for (int j = 0; j < planlist.size(); ++j) {
            FieldCreationPlan& plan = planlist[j];
            const Field* intended_field = plan.intended_field;
            if (!intended_field) {
                // This shouldn't happen!
                continue;
            }
            if (!plan.exists_in_db && intended_field->name() == info.name) {
                plan.exists_in_db = true;
                plan.add = false;
                plan.change = (
                    info.type != intended_field->sqlColumnType() ||
                    info.notnull != intended_field->allowsNull() ||
                    info.pk != intended_field->isPk()
                );
                plan.existing_type = info.type;
                plan.existing_not_null = info.notnull;
                existing_is_superfluous = false;
            }
        }
        if (existing_is_superfluous) {
            FieldCreationPlan plan;
            plan.name = info.name;
            plan.exists_in_db = true;
            plan.existing_type = info.type;
            plan.drop = true;
            planlist.append(plan);
        }
    }

    // 3. For any fields that require adding: add them.
    //    For any that require dropping or altering, make a note for the
    //    complex step.
    bool drop_or_change_mods_required = false;
    for (int i = 0; i < planlist.size(); ++i) {
        const FieldCreationPlan& plan = planlist.at(i);
        if (plan.add && plan.intended_field) {
            if (plan.intended_field->isPk()) {
                UiFunc::stopApp(QString(
                    "DbFunc::createTable: Cannot add a PRIMARY KEY column "
                    "(%s.%s)").arg(tablename, plan.name));
            }
            exec(db, QString("ALTER TABLE %1 ADD COLUMN %2 %3").arg(
                tablename,
                delimit(plan.name),
                plan.intended_field->sqlColumnDef()));
        }
        if (plan.drop || plan.change) {
            drop_or_change_mods_required = true;
        }
    }

    /*
    qDebug() << Q_FUNC_INFO
             << "tablename:" << tablename
             << "goodfieldlist:" << goodfieldlist
             << "infolist:" << infolist
             << "modifications_required:" << drop_or_change_mods_required
             << "plan:" << planlist;
    */

    if (!drop_or_change_mods_required) {
        qDebug() << "Table" << tablename
                 << "OK; no drop/change alteration required";
        return;
    }

    // 4. Implement drop/change modifications (via a temporary table).
    qDebug().nospace() << "Amendment plan for " << tablename
                       << ": " << planlist;
    // Deleting columns: http://www.sqlite.org/faq.html#q11
    // ... also http://stackoverflow.com/questions/8442147/
    // Basically, requires (a) copy data to temporary table; (b) drop original;
    // (c) create new; (d) copy back.
    // Or, another method: (a) rename table; (b) create new; (c) copy data
    // across; (d) drop temporary.
    // We deal with fields of incorrect type similarly (in this case, any
    // conversion occurs as we SELECT back the values into the new, proper
    // fields). Not sure it really is important, though:
    // http://sqlite.org/datatype3.html
    QString dummytable = tablename + tempsuffix;
    if (tableExists(db, dummytable)) {
        UiFunc::stopApp("DbFunc::createTable: temporary table exists: " +
                        dummytable);
    }
    QString delimited_tablename = delimit(tablename);
    QString delimited_dummytable = delimit(dummytable);
    QString goodfieldstring = goodfieldlist.join(",");
    exec(db, "BEGIN TRANSACTION");
    exec(db, QString("ALTER TABLE %1 RENAME TO %2").arg(delimited_tablename,
                                                        delimited_dummytable));
    exec(db, creation_sql);  // make a new clean table
    exec(db, QString("INSERT INTO %1 (%2) SELECT %3 FROM %4").arg(
         delimited_tablename,
         goodfieldstring,
         goodfieldstring,
         delimited_dummytable));
    exec(db, QString("DROP TABLE %1").arg(delimited_dummytable));
    commit(db);
}
Example #2
0
KviModeEditor::KviModeEditor(QWidget * par, KviWindowToolPageButton * button, const char * name, KviChannelWindow * pChan)
    : KviWindowToolWidget(par, button)
{
	setObjectName(name);
	m_pChannel = pChan;

	QGridLayout * pMasterLayout = new QGridLayout(this);

	setFocusPolicy(Qt::ClickFocus);

	QScrollArea * pScrollArea = new QScrollArea(this);
	pScrollArea->viewport()->setBackgroundRole(QPalette::Background);
	pMasterLayout->addWidget(pScrollArea, 0, 0);

	pMasterLayout->setRowStretch(1, 1);

	m_pButton = new QPushButton("", this);
	pMasterLayout->addWidget(m_pButton, 1, 0);
	connect(m_pButton, SIGNAL(clicked()), this, SLOT(commit()));

	if(!m_pChannel || !m_pChannel->connection())
		m_pButton->setText(__tr2qs("Close"));

	QWidget * pBackground = new QWidget(pScrollArea->viewport());

	QGridLayout * g = new QGridLayout(pBackground);

	QLabel * l = new QLabel("", pBackground);
	l->setPixmap(*(g_pIconManager->getSmallIcon(KviIconManager::Mode)));
	g->addWidget(l, 0, 0);

	l = new QLabel(__tr2qs("Channel modes"), pBackground);

	g->addWidget(l, 0, 1, 1, 1);

	QFrame * f = new QFrame(pBackground);
	f->setFrameStyle(QFrame::HLine | QFrame::Sunken);
	g->addWidget(f, 1, 0, 1, 3);

	QCheckBox * pCheckBox = nullptr;
	QLineEdit * pLineEdit = nullptr;
	int iRow = 1;
	QString szTmp;
	QString cDesc;
	char cMode = 0;

	//NOTE: this is a fallback is for some reason we don't have a serverInfo() struct available fot this connection

	// The connection is dead and the context was destroyed, don't guess on what was there
	if(!m_pChannel || !m_pChannel->connection())
		return;

	// first, the basic checkable modes pstnmi
	QString szModes = "pstnmi";

	while(!szModes.isEmpty())
	{
		cMode = szModes[0].unicode();
		szModes.remove(0, 1);

		szTmp = QString("%1: %2").arg(cMode).arg(*(getModeDescription(cMode)));
		pCheckBox = new QCheckBox(szTmp, pBackground);
		m_pCheckBoxes.insert(cMode, pCheckBox);
		if(pChan)
			pCheckBox->setChecked(pChan->plainChannelMode().contains(cMode));
		iRow++;
		g->addWidget(pCheckBox, iRow, 0, 1, 3);
	}

	// second, che basic modes with parameter lk
	szModes = "lk";

	while(!szModes.isEmpty())
	{
		cMode = szModes[0].unicode();
		szModes.remove(0, 1);

		szTmp = QString("%1: %2").arg(cMode).arg(*(getModeDescription(cMode)));
		pCheckBox = new QCheckBox(szTmp, pBackground);
		m_pCheckBoxes.insert(cMode, pCheckBox);
		iRow++;
		g->addWidget(pCheckBox, iRow, 0, 1, 3);

		connect(pCheckBox, SIGNAL(toggled(bool)), this, SLOT(checkBoxToggled(bool)));
		pLineEdit = new QLineEdit(pBackground);
		m_pLineEdits.insert(cMode, pLineEdit);
		iRow++;
		g->addWidget(pLineEdit, iRow, 1, 1, 2);

		if(pChan)
		{
			if(pChan->hasChannelMode(cMode))
			{
				pCheckBox->setChecked(true);
				pLineEdit->setText(pChan->channelModeParam(cMode));
			}
			else
			{
				pLineEdit->setEnabled(false);
			}
		}
	}

	// third, check if the we have any info about other modes supported by the server
	KviIrcConnectionServerInfo * pServerInfo = nullptr;
	if(m_pChannel)
		pServerInfo = m_pChannel->serverInfo();
	if(!pServerInfo)
	{
		g->setRowStretch(++iRow, 1);
		g->setColumnStretch(2, 1);
		pScrollArea->setWidget(pBackground);
		return;
	}

	// 4th, more plain modes supported by the server
	szModes = pServerInfo->supportedPlainModes();

	// remove modes that we already implemented
	szModes.remove("p");
	szModes.remove("s");
	szModes.remove("t");
	szModes.remove("n");
	szModes.remove("m");
	szModes.remove("i");

	while(!szModes.isEmpty())
	{
		cMode = szModes[0].unicode();
		szModes.remove(0, 1);

		cDesc = *(getModeDescription(cMode));

		szTmp = QString("%1: %2").arg(cMode).arg(!cDesc.isEmpty() ? cDesc : "Unknown");
		pCheckBox = new QCheckBox(szTmp, pBackground);
		m_pCheckBoxes.insert(cMode, pCheckBox);
		if(pChan)
			pCheckBox->setChecked(pChan->plainChannelMode().contains(cMode));

		iRow++;
		g->addWidget(pCheckBox, iRow, 0, 1, 3);
	}

	iRow++;

	// parameterized modes
	szModes = pServerInfo->supportedParameterModes();
	szModes.append(pServerInfo->supportedParameterWhenSetModes());

	// remove modes that we already implemented
	szModes.remove("k");
	szModes.remove("l");

	while(!szModes.isEmpty())
	{
		cMode = szModes[0].unicode();
		szModes.remove(0, 1);

		cDesc = *(getModeDescription(cMode));

		szTmp = QString("%1: %2").arg(cMode).arg(!cDesc.isEmpty() ? cDesc : "Unknown");
		pCheckBox = new QCheckBox(szTmp, pBackground);
		m_pCheckBoxes.insert(cMode, pCheckBox);
		iRow++;
		g->addWidget(pCheckBox, iRow, 0, 1, 3);

		connect(pCheckBox, SIGNAL(toggled(bool)), this, SLOT(checkBoxToggled(bool)));
		pLineEdit = new QLineEdit(pBackground);
		m_pLineEdits.insert(cMode, pLineEdit);
		iRow++;
		g->addWidget(pLineEdit, iRow, 1, 1, 2);

		if(pChan->hasChannelMode(cMode))
		{
			pCheckBox->setChecked(true);
			pLineEdit->setText(pChan->channelModeParam(cMode));
		}
		else
		{
			pLineEdit->setEnabled(false);
		}
	}

	g->setRowStretch(++iRow, 1);
	g->setColumnStretch(2, 1);
	pScrollArea->setWidget(pBackground);

	updateOpStatus();

	if(m_pChannel)
		connect(m_pChannel, SIGNAL(opStatusChanged()), this, SLOT(updateOpStatus()));
}
Example #3
0
void c2040_fdc_t::stop_writing(const attotime &tm)
{
	commit(tm);
	cur_live.write_start_time = attotime::never;
}
Example #4
0
void blizzard::http::process()
{
	bool quit = false;
	int res = 0;

	while (!quit)
	{
		switch (state_)
		{
		case sUndefined:
			want_read = true;
			want_write = false;
			state_ = sReadingHead;
			break;

		case sReadingHead:
			res = parse_title();
			if (res > 0)
			{
				state_ = sDone;
				quit = true;
			}
			else if (res < 0)
			{
				quit = true;
			}
			break;

		case sReadingHeaders:
			res = parse_header_line();
			if (res > 0)
			{
				state_ = sDone;
				quit = true;
			}
			else if (res < 0)
			{
				quit = true;
			}
			if (state_ == sReadyToHandle)
			{
				quit = true;
			}
			break;

		case sReadingPost:
			res = parse_post();
			if (res < 0)
			{
				quit = true;
			}
			break;

		case sReadyToHandle:
			commit();
			state_ = sWriting;
			break;

		case sWriting:
			want_write = true;
			res = write_data();
			if (res < 0)
			{
				quit = true;
			}
			break;

		case sDone:
			quit = true;
			break;

		default:
			break;
		}
	}
}
QQuickShaderEffectNode* QQuickCustomParticle::buildCustomNodes()
{
    if (QOpenGLContext::currentContext()->isOpenGLES() && m_count * 4 > 0xffff) {
        printf("CustomParticle: Too many particles... \n");
        return 0;
    }

    if (m_count <= 0) {
        printf("CustomParticle: Too few particles... \n");
        return 0;
    }

    if (m_groups.isEmpty())
        return 0;

    QQuickShaderEffectNode *rootNode = 0;
    QQuickShaderEffectMaterial *material = new QQuickShaderEffectMaterial;
    m_dirtyProgram = true;

    foreach (const QString &str, m_groups){
        int gIdx = m_system->groupIds[str];
        int count = m_system->groupData[gIdx]->size();

        QQuickShaderEffectNode* node = new QQuickShaderEffectNode();
        m_nodes.insert(gIdx, node);

        node->setMaterial(material);

        //Create Particle Geometry
        int vCount = count * 4;
        int iCount = count * 6;
        QSGGeometry *g = new QSGGeometry(PlainParticle_AttributeSet, vCount, iCount);
        g->setDrawingMode(GL_TRIANGLES);
        node->setGeometry(g);
        node->setFlag(QSGNode::OwnsGeometry, true);
        PlainVertex *vertices = (PlainVertex *) g->vertexData();
        for (int p=0; p < count; ++p) {
            commit(gIdx, p);
            vertices[0].tx = 0;
            vertices[0].ty = 0;

            vertices[1].tx = 1;
            vertices[1].ty = 0;

            vertices[2].tx = 0;
            vertices[2].ty = 1;

            vertices[3].tx = 1;
            vertices[3].ty = 1;
            vertices += 4;
        }
        quint16 *indices = g->indexDataAsUShort();
        for (int i=0; i < count; ++i) {
            int o = i * 4;
            indices[0] = o;
            indices[1] = o + 1;
            indices[2] = o + 2;
            indices[3] = o + 1;
            indices[4] = o + 3;
            indices[5] = o + 2;
            indices += 6;
        }
    }
Example #6
0
void PerforcePart::slotCommit()
{
    commit( popupfile );
}
Example #7
0
void c64h156_device::live_run(const attotime &limit)
{
	if(cur_live.state == IDLE || cur_live.next_state != -1)
		return;

	for(;;) {
		switch(cur_live.state) {
		case RUNNING: {
			bool syncpoint = false;

			if (cur_live.tm > limit)
				return;

			int bit = get_next_bit(cur_live.tm, limit);
			if(bit < 0)
				return;

			int cell_counter = cur_live.cell_counter;

			if (bit) {
				cur_live.cycle_counter = cur_live.ds;
				cur_live.cell_counter = 0;
			} else {
				cur_live.cycle_counter++;
			}

			if (cur_live.cycle_counter == 16) {
				cur_live.cycle_counter = cur_live.ds;

				cur_live.cell_counter++;
				cur_live.cell_counter &= 0xf;
			}

			if (!BIT(cell_counter, 1) && BIT(cur_live.cell_counter, 1)) {
				// read bit
				cur_live.shift_reg <<= 1;
				cur_live.shift_reg |= !(BIT(cur_live.cell_counter, 3) || BIT(cur_live.cell_counter, 2));
				cur_live.shift_reg &= 0x3ff;

				if (LOG) logerror("%s read bit %u (%u) >> %03x, oe=%u soe=%u sync=%u byte=%u\n", cur_live.tm.as_string(), cur_live.bit_counter,
					!(BIT(cur_live.cell_counter, 3) || BIT(cur_live.cell_counter, 2)), cur_live.shift_reg, cur_live.oe, cur_live.soe, cur_live.sync, cur_live.byte);

				syncpoint = true;
			}

			if (BIT(cell_counter, 1) && !BIT(cur_live.cell_counter, 1) && !cur_live.oe) {
				write_next_bit(BIT(cur_live.shift_reg_write, 7), limit);
			}

			int sync = !((cur_live.shift_reg == 0x3ff) && cur_live.oe);

			if (!sync) {
				cur_live.bit_counter = 8;
			} else if (!BIT(cell_counter, 1) && BIT(cur_live.cell_counter, 1) && cur_live.sync) {
				cur_live.bit_counter++;
				cur_live.bit_counter &= 0xf;
			}

			int byte = !(((cur_live.bit_counter & 7) == 7) && cur_live.soe && !(cur_live.cell_counter & 2));
			int load = !(((cur_live.bit_counter & 7) == 7) && ((cur_live.cell_counter & 3) == 3));

			if (!load) {
				if (cur_live.oe) {
					cur_live.shift_reg_write = cur_live.shift_reg;
					if (LOG) logerror("%s load write shift register from read shift register %02x\n",cur_live.tm.as_string(),cur_live.shift_reg_write);
				} else {
					cur_live.shift_reg_write = cur_live.yb;
					if (LOG) logerror("%s load write shift register from YB %02x\n",cur_live.tm.as_string(),cur_live.shift_reg_write);
				}
			} else if (!BIT(cell_counter, 1) && BIT(cur_live.cell_counter, 1)) {
				cur_live.shift_reg_write <<= 1;
				cur_live.shift_reg_write &= 0xff;
				if (LOG) logerror("%s shift write register << %02x\n", cur_live.tm.as_string(), cur_live.shift_reg_write);
			}

			// update signals
			if (byte != cur_live.byte) {
				if (!byte || !cur_live.accl) {
					if (LOG) logerror("%s BYTE %u\n", cur_live.tm.as_string(),byte);
					cur_live.byte = byte;
					syncpoint = true;
				}
				if (!byte) {
					cur_live.accl_yb = cur_live.shift_reg & 0xff;
				}
			}

			if (sync != cur_live.sync) {
				if (LOG) logerror("%s SYNC %u\n", cur_live.tm.as_string(),sync);
				cur_live.sync = sync;
				syncpoint = true;
			}

			if (syncpoint) {
				commit(cur_live.tm);

				cur_live.tm += m_period;
				live_delay(RUNNING_SYNCPOINT);
				return;
			}

			cur_live.tm += m_period;
			break;
		}

		case RUNNING_SYNCPOINT: {
			m_write_sync(cur_live.sync);
			m_write_byte(cur_live.byte);

			cur_live.state = RUNNING;
			checkpoint();
			break;
		}
		}
	}
}
Example #8
0
bool employee::sSave(const bool pClose)
{
  bool dupCode   = false;
  bool dupNumber = false;

  XSqlQuery dupq;
  dupq.prepare("SELECT emp_id"
               "  FROM emp"
               " WHERE(emp_code=:code) AND (emp_id != :id);");
  dupq.bindValue(":code", _code->text());
  dupq.bindValue(":id",   _empid);
  dupq.exec();
  if(dupq.first())
    dupCode = true;
  else if (ErrorReporter::error(QtCriticalMsg, this, tr("Database Error"),
                                dupq, __FILE__, __LINE__))
    return false;

  dupq.prepare("SELECT emp_id"
               "  FROM emp"
               " WHERE(emp_number=:number) AND (emp_id != :id);");
  dupq.bindValue(":number", _number->text());
  dupq.bindValue(":id",     _empid);
  dupq.exec();
  if(dupq.first())
    dupNumber = true;
  else if (ErrorReporter::error(QtCriticalMsg, this, tr("Database Error"),
                                dupq, __FILE__, __LINE__))
    return false;

  QList<GuiErrorCheck> errors;
  errors << GuiErrorCheck(_code->text().isEmpty(), _code,
                          tr("You must enter a valid Employee Code."))
         << GuiErrorCheck(_number->text().isEmpty(), _number,
                          tr("You must enter an Employee Number."))
         << GuiErrorCheck(dupCode, _code,
                          tr("An Employee already exists for the Code specified."))
         << GuiErrorCheck(_code->text() == _mgr->number(), _number,
                          tr("An Employee already exists for the Number specified."))
         << GuiErrorCheck(_code->text() == _mgr->number(), _mgr,
                          tr("An Employee cannot be his or her own Manager."))
    ;
  if (GuiErrorCheck::reportErrors(this, tr("Cannot Save Employee"), errors))
    return false;

  _contact->check();

  XSqlQuery rollback;
  rollback.prepare("ROLLBACK;");

  XSqlQuery begin("BEGIN;");
  int cntctResult = _contact->save();
  if (cntctResult < 0)
  {
    rollback.exec();
    ErrorReporter::error(QtCriticalMsg, this, tr("Error Saving Contact"),
                         storedProcErrorLookup("saveContact", cntctResult));
    return false;
  }

  XSqlQuery upsq;
  if (_mode == cNew)
    upsq.prepare("INSERT INTO emp ("
                 " emp_code,        emp_number,   emp_active,       emp_cntct_id,"
                 " emp_warehous_id, emp_mgr_emp_id,"
                 " emp_wage_type,   emp_wage,     emp_wage_curr_id, emp_wage_period,"
                 " emp_dept_id,     emp_shift_id, emp_notes,        emp_image_id,"
                 " emp_extrate,     emp_extrate_period, emp_startdate, emp_name"
                 ") VALUES ("
                 " :code,        :number,   :active,       :cntct_id,"
                 " :warehous_id, :mgr_emp_id,"
                 " :wage_type,   :wage,     :wage_curr_id, :wage_period,"
                 " :dept_id,     :shift_id, :notes,        :image_id,"
                 " :extrate,     :extrate_period, :startdate, :name"
                 ") RETURNING emp_id;");

  else if (_mode == cEdit)
  {
    upsq.prepare("UPDATE emp SET"
                 " emp_code=:code,"
                 " emp_number=:number,"
                 " emp_active=:active,"
                 " emp_cntct_id=:cntct_id,"
                 " emp_warehous_id=:warehous_id,"
                 " emp_mgr_emp_id=:mgr_emp_id,"
                 " emp_wage_type=:wage_type,"
                 " emp_wage=:wage,"
                 " emp_wage_curr_id=:wage_curr_id,"
                 " emp_wage_period=:wage_period,"
                 " emp_dept_id=:dept_id,"
                 " emp_shift_id=:shift_id,"
                 " emp_notes=:notes,"
                 " emp_image_id=:image_id,"
                 " emp_extrate=:extrate,"
                 " emp_extrate_period=:extrate_period,"
                 " emp_startdate=:startdate,"
                 " emp_name=:name"
              " WHERE (emp_id=:emp_id)"
              " RETURNING emp_id;" );
    upsq.bindValue(":emp_id", _empid);
  }

  upsq.bindValue(":code",           _code->text());
  upsq.bindValue(":number",         _number->text());
  upsq.bindValue(":active",         _active->isChecked());
  if (_contact->isValid())
    upsq.bindValue(":cntct_id",     _contact->id());
  if (_site->isValid())
    upsq.bindValue(":warehous_id",  _site->id());
  if (_mgr->isValid())
    upsq.bindValue(":mgr_emp_id",   _mgr->id());
  upsq.bindValue(":wage_type",      _wagetype->code());
  upsq.bindValue(":wage",           _rate->localValue());
  if (_rate->id() > 0)
    upsq.bindValue(":wage_curr_id", _rate->id());
  upsq.bindValue(":wage_period",    _per->code());
  if (_dept->isValid())
    upsq.bindValue(":dept_id",      _dept->id());
  if (_shift->isValid())
    upsq.bindValue(":shift_id",     _shift->id());
  upsq.bindValue(":notes",          _notes->toPlainText());
  if (_image->isValid())
    upsq.bindValue(":image_id",     _image->id());
  upsq.bindValue(":extrate",        _externalRate->localValue());
  upsq.bindValue(":extrate_period", _perExt->code());
  upsq.bindValue(":startdate",      _startDate->date());
  upsq.bindValue(":name",           _name->text());

  upsq.exec();
  if (upsq.first())
    _empid = upsq.value("emp_id").toInt();
  else if (upsq.lastError().type() != QSqlError::NoError)
  {
    rollback.exec();
    ErrorReporter::error(QtCriticalMsg, this, tr("Error saving Employee"),
                         upsq, __FILE__, __LINE__);
    return false;
  }

  XSqlQuery commit("COMMIT;");

  emit saved();
  omfgThis->sEmployeeUpdated(_empid);

  if (pClose)
    done(_empid);
  else
    sPopulate();

  return true;
}
 void setMethodBodyByAssignment(std::function<R(const typename fakeit::test_arg<arglist>::type...)> method) {
     appendAction(new RepeatForever<R, arglist...>(method));
     commit();
 }
Example #10
0
File: batch.c Project: patcon/eVACS
void append_entry(PGconn *conn,struct entry *newentry,
                  unsigned int batch_number,unsigned int paper_index,
                  unsigned int paper_version)
/*
  Insert the entry into the database.
*/
{
    char *table_name,*oi;
    int electorate_code;
    int paper_id,entry_index=1,i;

    /* get electorate code */
    electorate_code = SQL_singleton_int(conn,
                                        "SELECT electorate_code "
                                        "FROM batch "
                                        "WHERE number = %u;",
                                        batch_number);
    if (electorate_code < 0)
        bailout("append_entry could not find batch number %u.\n",
                batch_number);

    /* get electorate name in order to access that Electorates
       preference table */
    table_name = resolve_electorate_name(conn,electorate_code);

    /* Start the transaction */
    begin(conn);

    /* Check paper exists */
    paper_id = SQL_singleton_int(conn,
                                 "SELECT id FROM paper WHERE index = %u "
                                 "AND batch_number = %u;",
                                 paper_index,batch_number);

    /* Insert new paper if necessary */
    if (paper_id < 0) {
        SQL_command(conn,
                    "INSERT INTO "
                    "paper(batch_number,index) "
                    "VALUES(%u,%u);",batch_number,paper_index);
        entry_index = 1;
        paper_id = get_seq_currval(conn,"paper_id_seq");

    }
    else {
        /* Get last entry index for this paper */
        entry_index = SQL_singleton_int(conn,
                                        "SELECT MAX(index) FROM entry "
                                        "WHERE paper_id = %d;",
                                        paper_id);
        if (entry_index < 0)
            entry_index = 1;   /* It must be the first one */
        else
            entry_index++;

    }

    /* Insert new entry */
    SQL_command(conn,
                "INSERT INTO entry(index,operator_id,"
                "paper_id,num_preferences,paper_version) "
                "VALUES(%u,'%s',%u,%u,%u);",
                entry_index,oi=eq_malloc(newentry->e.operator_id),
                paper_id,newentry->e.num_preferences,paper_version);
    free(oi);
    /* Insert the preferences */
    for (i=0; i<newentry->e.num_preferences; i++) {
        SQL_command(conn,
                    "INSERT INTO %s "
                    "VALUES(CURRVAL('entry_id_seq'),%u,%u,%u);",
                    table_name,
                    newentry->preferences[i].group_index,
                    newentry->preferences[i].db_candidate_index,
                    newentry->preferences[i].prefnum);
    }
    /* Complete the transaction */
    commit(conn);
}
Example #11
0
void ElementManager::reset()
{
    // We disconnect from Interpreter
    disconnect(Interpreter::getInstance(), SIGNAL(workDone()), this, SLOT(commit()));
}
Example #12
0
bool database::_push_block(const signed_block& new_block)
{ try {
   uint32_t skip = get_node_properties().skip_flags;
   if( !(skip&skip_fork_db) )
   {
      /// TODO: if the block is greater than the head block and before the next maitenance interval
      // verify that the block signer is in the current set of active witnesses.

      shared_ptr<fork_item> new_head = _fork_db.push_block(new_block);
      //If the head block from the longest chain does not build off of the current head, we need to switch forks.
      if( new_head->data.previous != head_block_id() )
      {
         //If the newly pushed block is the same height as head, we get head back in new_head
         //Only switch forks if new_head is actually higher than head
         if( new_head->data.block_num() > head_block_num() )
         {
            wlog( "Switching to fork: ${id}", ("id",new_head->data.id()) );
            auto branches = _fork_db.fetch_branch_from(new_head->data.id(), head_block_id());

            // pop blocks until we hit the forked block
            while( head_block_id() != branches.second.back()->data.previous )
               pop_block();

            // push all blocks on the new fork
            for( auto ritr = branches.first.rbegin(); ritr != branches.first.rend(); ++ritr )
            {
                ilog( "pushing blocks from fork ${n} ${id}", ("n",(*ritr)->data.block_num())("id",(*ritr)->data.id()) );
                optional<fc::exception> except;
                try {
                   undo_database::session session = _undo_db.start_undo_session();
                   apply_block( (*ritr)->data, skip );
                   _block_id_to_block.store( (*ritr)->id, (*ritr)->data );
                   session.commit();
                }
                catch ( const fc::exception& e ) { except = e; }
                if( except )
                {
                   wlog( "exception thrown while switching forks ${e}", ("e",except->to_detail_string() ) );
                   // remove the rest of branches.first from the fork_db, those blocks are invalid
                   while( ritr != branches.first.rend() )
                   {
                      _fork_db.remove( (*ritr)->data.id() );
                      ++ritr;
                   }
                   _fork_db.set_head( branches.second.front() );

                   // pop all blocks from the bad fork
                   while( head_block_id() != branches.second.back()->data.previous )
                      pop_block();

                   // restore all blocks from the good fork
                   for( auto ritr = branches.second.rbegin(); ritr != branches.second.rend(); ++ritr )
                   {
                      auto session = _undo_db.start_undo_session();
                      apply_block( (*ritr)->data, skip );
                      _block_id_to_block.store( new_block.id(), (*ritr)->data );
                      session.commit();
                   }
                   throw *except;
                }
            }
            return true;
         }
         else return false;
      }
   }

   try {
      auto session = _undo_db.start_undo_session();
      apply_block(new_block, skip);
      _block_id_to_block.store(new_block.id(), new_block);
      session.commit();
   } catch ( const fc::exception& e ) {
      elog("Failed to push new block:\n${e}", ("e", e.to_detail_string()));
      _fork_db.remove(new_block.id());
      throw;
   }

   return false;
} FC_CAPTURE_AND_RETHROW( (new_block) ) }
Example #13
0
/* Commit_edit handler - find the correct backend handler for this object
 * type and call its commit handler
 */
void
GncSqlBackend::commit_edit (QofInstance* inst)
{
    sql_backend be_data;
    gboolean is_dirty;
    gboolean is_destroying;
    gboolean is_infant;

    g_return_if_fail (inst != NULL);

    if (qof_book_is_readonly(m_book))
    {
        qof_backend_set_error (&qof_be, ERR_BACKEND_READONLY);
        (void)m_conn->rollback_transaction ();
        return;
    }
    /* During initial load where objects are being created, don't commit
    anything, but do mark the object as clean. */
    if (m_loading)
    {
        qof_instance_mark_clean (inst);
        return;
    }

    // The engine has a PriceDB object but it isn't in the database
    if (strcmp (inst->e_type, "PriceDB") == 0)
    {
        qof_instance_mark_clean (inst);
        qof_book_mark_session_saved (m_book);
        return;
    }

    ENTER (" ");

    is_dirty = qof_instance_get_dirty_flag (inst);
    is_destroying = qof_instance_get_destroying (inst);
    is_infant = qof_instance_get_infant (inst);

    DEBUG ("%s dirty = %d, do_free = %d, infant = %d\n",
           (inst->e_type ? inst->e_type : "(null)"),
           is_dirty, is_destroying, is_infant);

    if (!is_dirty && !is_destroying)
    {
        LEAVE ("!dirty OR !destroying");
        return;
    }

    if (!m_conn->begin_transaction ())
    {
        PERR ("begin_transaction failed\n");
        LEAVE ("Rolled back - database transaction begin error");
        return;
    }

    bool is_ok = true;

    auto obe = m_backend_registry.get_object_backend(std::string{inst->e_type});
    if (obe != nullptr)
        is_ok = obe->commit(this, inst);
    else
    {
        PERR ("Unknown object type '%s'\n", inst->e_type);
        (void)m_conn->rollback_transaction ();

        // Don't let unknown items still mark the book as being dirty
        qof_book_mark_session_saved(m_book);
        qof_instance_mark_clean (inst);
        LEAVE ("Rolled back - unknown object type");
        return;
    }
    if (!is_ok)
    {
        // Error - roll it back
        (void)m_conn->rollback_transaction();

        // This *should* leave things marked dirty
        LEAVE ("Rolled back - database error");
        return;
    }

    (void)m_conn->commit_transaction ();

    qof_book_mark_session_saved(m_book);
    qof_instance_mark_clean (inst);

    LEAVE ("");
}
Example #14
0
void
GncSqlBackend::sync_all(QofBook* book)
{
    g_return_if_fail (book != NULL);

    reset_version_info();
    ENTER ("book=%p, sql_be->book=%p", book, m_book);
    update_progress();

    /* Create new tables */
    m_is_pristine_db = true;
    create_tables();

    /* Save all contents */
    m_book = book;
    auto is_ok = m_conn->begin_transaction();

    // FIXME: should write the set of commodities that are used
    // write_commodities(sql_be, book);
    if (is_ok)
    {
        auto obe = m_backend_registry.get_object_backend(GNC_ID_BOOK);
        is_ok = obe->commit (this, QOF_INSTANCE (book));
    }
    if (is_ok)
    {
        is_ok = write_accounts();
    }
    if (is_ok)
    {
        is_ok = write_transactions();
    }
    if (is_ok)
    {
        is_ok = write_template_transactions();
    }
    if (is_ok)
    {
        is_ok = write_schedXactions();
    }
    if (is_ok)
    {
        for (auto entry : m_backend_registry)
            std::get<1>(entry)->write (this);
    }
    if (is_ok)
    {
        is_ok = m_conn->commit_transaction();
    }
    if (is_ok)
    {
        m_is_pristine_db = false;

        /* Mark the session as clean -- though it shouldn't ever get
         * marked dirty with this backend
         */
        qof_book_mark_session_saved(book);
    }
    else
    {
        if (!qof_backend_check_error (&qof_be))
            qof_backend_set_error (&qof_be, ERR_BACKEND_SERVER_ERR);
        is_ok = m_conn->rollback_transaction ();
    }
    finish_progress();
    LEAVE ("book=%p", book);
}
Example #15
0
void Controller::connectMainWindow(){
    QObject::connect(window->getWidget()->calendarWidget, SIGNAL(clicked(QDate)), this, SLOT(changeDate(QDate)));
    QObject::connect(window->getWidget()->addTimeSlotButton, SIGNAL(clicked()), this, SLOT(openEditTimeSlot())); 
    QObject::connect(window->getWidget()->commitButton, SIGNAL(clicked()), this, SLOT(commit()));
    QObject::connect(window->getWidget()->tabWidget, SIGNAL(currentChanged(int)), this, SLOT(tabIndexChanged()));
    QObject::connect(window->getWidget()->comboBoxClassroom, SIGNAL(currentIndexChanged(int)), this, SLOT(tabIndexChanged()));
    QObject::connect(window->getWidget()->comboBoxGroup, SIGNAL(currentIndexChanged(int)), this, SLOT(tabIndexChanged()));
    QObject::connect(window->getWidget()->comboBoxStudent, SIGNAL(currentIndexChanged(int)), this, SLOT(tabIndexChanged()));
    QObject::connect(window->getWidget()->actionAdministrator, SIGNAL(triggered()), this, SLOT(openAdministrator()));
    QObject::connect(window->getWidget()->checkBoxMagistral, SIGNAL(stateChanged(int)), this, SLOT(tabIndexChanged()));
    QObject::connect(window->getWidget()->checkBoxTutorial, SIGNAL(stateChanged(int)), this, SLOT(tabIndexChanged()));
    QObject::connect(window->getWidget()->checkBoxPractical, SIGNAL(stateChanged(int)), this, SLOT(tabIndexChanged()));
    QObject::connect(window, SIGNAL(signal_addTimeSlot(QTimeSlot*)), this, SLOT(addQTimeSlot(QTimeSlot*)));
}
Example #16
0
void PredType::commit(H5Location& loc, const H5std_string& name)
{
    commit(loc, name.c_str());
}
Example #17
0
void PerforcePart::slotActionCommit()
{
    commit( currentFile() );
}
Example #18
0
bool executeCommand(sqlite3 *db, const char *command)
{
    char **params;
    int paramsCount;
    int i;

    int from, to;
    double sum;

    (void)db;   // unused


    // parse command
    paramsCount = countWords(command);
    params = malloc(sizeof(char*) * paramsCount);
    for (i=0; i<paramsCount; i++)
        params[i] = getWord(command, i);            

    if ((paramsCount >= 1) && (!strcmp(params[0], COMMAND_HELP)))
        commandHelp();

    if ((paramsCount >= 1) && (!strcmp(params[0], COMMAND_1)))
        command1();

    if ((paramsCount >= 1) && (!strcmp(params[0], COMMAND_2)))
        command2();

    if ((paramsCount >= 4) && (!strcmp(params[0], COMMAND_TRANSF)))
    {
        sscanf(params[1], "%i", &from);
        sscanf(params[3], "%lf", &sum);
        sscanf(params[2], "%i", &to);
        //transfer(db, from, to, sum);
        if (sum < 0 ) return false;
        debit(db, from, sum);
        credit(db, to, sum);
    }

    if ((paramsCount >= 3) && (!strcmp(params[0], COMMAND_DEB)))
    {
        sscanf(params[1], "%i", &from);
        sscanf(params[2], "%lf", &sum);
        if (sum < 0 ) return false;
        debit(db, from, sum);
    }

    if ((paramsCount >= 3) && (!strcmp(params[0], COMMAND_CRED)))
    {
        sscanf(params[1], "%i", &to);
        sscanf(params[2], "%lf", &sum);
        if (sum < 0) return false;
        credit(db, to, sum);
    }

    if ((paramsCount >= 2) && (!strcmp(params[0], COMMAND_CHCK)))
    {
        sscanf(params[1], "%i", &to);
        checkAccount(db, to);
    }

    if ((paramsCount >= 1) && (!strcmp(params[0], COMMAND_UNDO)))
        undo(db);

    if ((paramsCount >= 1) && (!strcmp(params[0], COMMAND_ADD)))
        createNewCustomer(db);

    if ((paramsCount >= 1) && (!strcmp(params[0], COMMAND_DEL)))
        deleteCustomer(db);

    if ((paramsCount >= 1) && (!strcmp(params[0], COMMAND_DELACC)))
        deleteAccount(db);

    if ((paramsCount >= 1) && (!strcmp(params[0], COMMAND_ADDACC)))
        addAccount(db);

    if ((paramsCount >= 1) && (!strcmp(params[0], COMMAND_COMMIT)))
        commit(db);

    if ((paramsCount >= 1) && (!strcmp(params[0], COMMAND_SHOW)))
        showAll(db);

    if ((paramsCount >= 1) && (!strcmp(params[0], COMMAND_LOGGER)))
        logger(db);

    for (i=0; i<paramsCount; i++)
        free(params[i]);
    free(params);

    return true;
}
Example #19
0
void c64h156_device::stop_writing(const attotime &tm)
{
	commit(tm);
	cur_live.write_start_time = attotime::never;
}
Example #20
0
bool CreatePartitionJob::run(Report& parent)
{
	Q_ASSERT(partition().devicePath() == device().deviceNode());

	bool rval = false;

	Report* report = jobStarted(parent);

	// According to libParted docs, PedPartitionType can be "NULL if unknown". That's obviously wrong,
	// it's a typedef for an enum. So let's use something the libparted devs will hopefully never
	// use...
	PedPartitionType pedType = static_cast<PedPartitionType>(0xffffffff);

	if (partition().roles().has(PartitionRole::Extended))
		pedType = PED_PARTITION_EXTENDED;
	else if (partition().roles().has(PartitionRole::Logical))
		pedType = PED_PARTITION_LOGICAL;
	else if (partition().roles().has(PartitionRole::Primary))
		pedType = PED_PARTITION_NORMAL;
			
	if (pedType == static_cast<int>(0xffffffff))
	{
		report->line() << i18nc("@info/plain", "Unknown partition role for new partition <filename>%1</filename> (roles: %2)", partition().deviceNode(), partition().roles().toString());
	}
	else if (openPed(device().deviceNode()))
	{
		PedFileSystemType* pedFsType = (partition().roles().has(PartitionRole::Extended) || partition().fileSystem().type() == FileSystem::Unformatted) ? NULL : getPedFileSystemType(partition().fileSystem().type());

		PedPartition* pedPartition = ped_partition_new(pedDisk(), pedType, pedFsType, partition().firstSector(), partition().lastSector());

		if (pedPartition)
		{
			PedConstraint* pedConstraint = NULL;
			PedGeometry* pedGeometry = ped_geometry_new(pedDevice(), partition().firstSector(), partition().length());

			if (pedGeometry)
				pedConstraint = ped_constraint_exact(pedGeometry);

			if (pedConstraint)
			{
				if (ped_disk_add_partition(pedDisk(), pedPartition, pedConstraint) && commit())
				{
					partition().setNumber(pedPartition->num);
					partition().setState(Partition::StateNone);

					partition().setFirstSector(pedPartition->geom.start);
					partition().setLastSector(pedPartition->geom.end);

					rval = true;
				}
				else
					report->line() << i18nc("@info/plain", "Failed to add partition <filename>%1</filename> to device <filename>%2</filename>.", partition().deviceNode(), device().deviceNode());

				ped_constraint_destroy(pedConstraint);
			}
			else
				report->line() << i18nc("@info/plain", "Failed to create a new partition: could not get geometry for constraint.");
		}
		else
			report->line() << i18nc("@info/plain", "Failed to create new partition <filename>%1</filename>.", partition().deviceNode());
	
		closePed();
	}
	else
		report->line() << i18nc("@info/plain", "Could not open device <filename>%1</filename> to create new partition <filename>%2</filename>.", device().deviceNode(), partition().deviceNode());
	
	jobFinished(*report, rval);
	
	return rval;
}
Example #21
0
DatabaseThread::DatabaseThread( const QString &fileName )
: QObject()
, mpSqlDB( 0 )
, mpQuery( 0 )
, mpCommitTimer( 0 )
, mpSatellite( 0 )
, mDatabaseVersion( 0 )
, mCodeVersion( 1 )
, mUpdateCount( 0 )
, mUpdateMessage()
, mNotifyDisabled( false )
{
   setObjectName( "DatabaseThread" );
   qsrand( time((time_t*)0) );
   mpSqlDB = new QSqlDatabase( QSqlDatabase::addDatabase( "QSQLITE" ) );
   mpCommitTimer = new QTimer( this );
   mpCommitTimer->setSingleShot( true );
   mpCommitTimer->setInterval( 250 );
   connect( mpCommitTimer, SIGNAL(timeout()),
            this, SLOT(commit()) );

   qRegisterMetaType<TrackInfo>( "TrackInfo" );
   qRegisterMetaType<TrackInfoList>( "TrackInfoList" );

   if( mpSqlDB->lastError().type() != QSqlError::NoError )
   {
      QMessageBox::critical( 0, QApplication::applicationName() + ": " + QWidget::tr("Error"),
                             QWidget::tr("Could not open database.\nPlease make sure that the SQLite driver for Qt is installed.") );
      exit(1);
   }

   if( fileName.isEmpty() )
   {
      mpSqlDB->setDatabaseName( getDatabaseFileName() );
   }
   else
   {
      mpSqlDB->setDatabaseName( fileName );
   }

   if(!mpSqlDB->open())
   {
      // \todo: some error handling
      logError( QString("open() failed\nDatabase: ") + mpSqlDB->lastError().driverText() );
   }
   mpQuery = new QSqlQuery;

   if( mpQuery->exec( "SELECT value FROM slart_config WHERE key = 'Version';" ) )
   {
      if( mpQuery->next() )
      {
         mDatabaseVersion = mpQuery->value(0).toUInt();
      }
   }
   else
   {
      logError();
   }
   mpQuery->clear();

   if( !mDatabaseVersion )
   {
      /* create database */
      QStringList initSQL;
      initSQL
            << "CREATE TABLE slart_config (key VARCHAR PRIMARY KEY,"
            "value VARCHAR);"
            << "INSERT OR REPLACE INTO slart_config(key,value) VALUES ('Version'," +
            QString::number(mCodeVersion) + ");"

            << "CREATE TABLE slart_tracks (id INTEGER PRIMARY KEY,"
            "Directory VARCHAR,"
            "FileName VARCHAR,"
            "Artist VARCHAR,"
            "Title VARCHAR,"
            "Album VARCHAR,"
            "TrackNr INTEGER,"
            "Year INTEGER,"
            "Genre VARCHAR,"
            "PlayTime INTEGER,"
            "LastScanned INTEGER,"
            "LastTagsRead INTEGER,"
            "TimesPlayed INTEGER,"
            "Volume DOUBLE,"
            "Folders VARCHAR,"
            "Flags INTEGER);"
            << "CREATE UNIQUE INDEX slart_tracks_file ON slart_tracks (Directory,FileName);"
            << "CREATE INDEX slart_tracks_filename ON slart_tracks (FileName);"
            << "CREATE INDEX slart_tracks_artist ON slart_tracks (Artist);"
            << "CREATE INDEX slart_tracks_title ON slart_tracks (Title);"

            << "CREATE TABLE slart_folders (id INTEGER PRIMARY KEY,"
            "Name VARCHAR,"
            "FileName VARCHAR);"
            << "CREATE UNIQUE INDEX slart_folders_name ON slart_folders (Name);"

            ;

      foreach( const QString &statement, initSQL )
      {
         if( !mpQuery->exec( statement ) )
         {
            logError();
         }
         mpQuery->clear();
      }
   }
Example #22
0
void Transaction::commit()
{
    ErrorCode ec;
    commit(ec);
    ec.check_();
}
void SelectionRectGraphicsWidget::createActions()
{
  QAction *c;
  { c = new QAction(tr("Commit"),this);
    QList<QKeySequence> shortcuts;
    shortcuts.push_back( QKeySequence(Qt::Key_Return));
    shortcuts.push_back( QKeySequence(Qt::Key_Enter ));
    c->setShortcuts(shortcuts);    
    c->setShortcutContext(Qt::WidgetShortcut);
    connect(c,SIGNAL(triggered()),this,SLOT(commit()));
    addAction(c);
  }
  { c = new QAction(tr("Cancel"),this);
    c->setShortcut(Qt::Key_Backspace);
    c->setShortcutContext(Qt::WidgetShortcut);
    connect(c,SIGNAL(triggered()),this,SLOT(cancel()));
    addAction(c);
  }
  { c = new QAction(tr("Mark Active"),this);
    QList<QKeySequence> shortcuts;
    shortcuts.push_back( QKeySequence(tr("+")));
    shortcuts.push_back( QKeySequence(tr("=")));
    c->setShortcuts(shortcuts);
    c->setShortcutContext(Qt::WidgetShortcut);
    connect(c,SIGNAL(triggered()),this,SLOT(setOpAdd()));
    addAction(c);
  }
  { c = new QAction(tr("Mark Not Active"),this);
    c->setShortcut(Qt::Key_Minus);
    c->setShortcutContext(Qt::WidgetShortcut);
    connect(c,SIGNAL(triggered()),this,SLOT(setOpRemove()));
    addAction(c);
  }
  { c = new QAction(tr("Mark Done"),this);        
    connect(c,SIGNAL(triggered()),this,SLOT(setOpDone()));
    addAction(c);
  }  
  {
    c = new QAction(tr("Mark Not Done"),this);        
    connect(c,SIGNAL(triggered()),this,SLOT(setOpUnDone()));
    addAction(c);
  }
  { c = new QAction(tr("Mark Explorable"),this);
    connect(c,SIGNAL(triggered()),this,SLOT(setOpExplorable()));
    addAction(c);
  }
  { c = new QAction(tr("Mark Not Explorable"),this);
    connect(c,SIGNAL(triggered()),this,SLOT(setOpUnExplorable()));
    addAction(c);
  }
  { c = new QAction(tr("Mark Safe"),this);
    connect(c,SIGNAL(triggered()),this,SLOT(setOpSafe()));
    addAction(c);
  }
  { c = new QAction(tr("Mark Not Safe"),this);
    connect(c,SIGNAL(triggered()),this,SLOT(setOpUnSafe()));
    addAction(c);
  }
  { c = new QAction(tr("Reset"),this);
    connect(c,SIGNAL(triggered()),this,SLOT(setOpUserReset()));
    addAction(c);
  }
}
void l_class_OC_EchoRequestOutput::run()
{
    commit();
}
Example #25
0
void wb_dbms::create(pwr_tVid vid, pwr_tCid cid, const char *volumeName, const char *fileName)
{
    m_vid = vid;
    m_cid = cid;
    pwr_tStatus sts;
    strcpy(m_volumeName, volumeName);
    char l_fileName[512];
    dcli_translate_filename(l_fileName, fileName);
    size_t rbSize = 0;
    pwr_tTime time;
    pwr_tOid oid;
    pwr_mClassDef flags;

    flags.m = pwr_mClassDef_System | pwr_mClassDef_TopObject;

    if (!m_env) {
        m_env = new wb_dbms_env(l_fileName);
        m_env->open();
    }

    if (m_env->exists())
        createDb();
    else
        return;

    switch (cid) {
    case pwr_eClass_RootVolume:
        rbSize = sizeof(pwr_sRootVolume);
        break;
    case pwr_eClass_SubVolume:
        rbSize = sizeof(pwr_sSubVolume);
        break;
    case pwr_eClass_SystemVolume:
        rbSize = sizeof(pwr_sSystemVolume);
        break;
    case pwr_eClass_ClassVolume:
    case pwr_eClass_DetachedClassVolume:
        rbSize = sizeof(pwr_sClassVolume);
        break;
    case pwr_eClass_WorkBenchVolume:
        rbSize = sizeof(pwr_sWorkBenchVolume);
        break;
    case pwr_eClass_DirectoryVolume:
        rbSize = sizeof(pwr_sDirectoryVolume);
        break;
    case pwr_eClass_SharedVolume:
        rbSize = sizeof(pwr_sSharedVolume);
        break;
    case pwr_eClass_CreateVolume:
    case pwr_eClass_MountVolume:
        flags.m = pwr_mClassDef_System | pwr_mClassDef_NoAdopt;
        break;
    case pwr_eClass_MountObject:
        flags.m = pwr_mClassDef_System | pwr_mClassDef_TopObject | pwr_mClassDef_NoAdopt;
        break;
    case pwr_eClass_VolatileVolume:
    case pwr_eClass_ExternVolume:
        flags.m = pwr_mClassDef_System | pwr_mClassDef_TopObject | pwr_mClassDef_DevOnly;
        break;
    case pwr_eClass_DynamicVolume:
        break;
    default:
        ;
    }

    oid.vid = vid;
    oid.oix = pwr_cNOix;
    wb_name n(volumeName);

    try {
        m_env->txn_begin(0, (wb_dbms_txn **)&m_txn);

        importHead(oid, cid, pwr_cNOid, pwr_cNOid, pwr_cNOid, pwr_cNOid, pwr_cNOid, n.name(), n.normName(), flags, time, time, time, rbSize, 0);

        if ( rbSize) {
            void *body = calloc( 1, rbSize);

            importRbody(oid, rbSize, body);
            free( body);
        }

        wb_dbms_info i(this);
        i.get(m_txn);
        m_vid = i.vid();
        m_cid = i.cid();
        strcpy(m_volumeName, i.name());
        commit(&sts);
    }
    catch (wb_dbms_error &e) {
        m_txn->abort();
        printf("exeption: %s\n", e.what().c_str());
    }

}
Example #26
0
UserPalette::UserPalette() :
    Palette(static_cast<int>(UserColorId::USER_COLOR_LAST))
{
    mColors[static_cast<size_t>(UserColorId::BEING)] = ColorElem();
    mColors[static_cast<size_t>(UserColorId::PC)] = ColorElem();
    mColors[static_cast<size_t>(UserColorId::SELF)] = ColorElem();
    mColors[static_cast<size_t>(UserColorId::GM)] = ColorElem();
    mColors[static_cast<size_t>(UserColorId::NPC)] = ColorElem();
    mColors[static_cast<size_t>(UserColorId::MONSTER)] = ColorElem();

    addLabel(UserColorId::LABEL_BEING,
        // TRANSLATORS: palette label
        _("Beings"));
    addColor(UserColorId::BEING,
        0xffffff,
        GradientType::STATIC,
        // TRANSLATORS: palette color
        _("Being"));
    addColor(UserColorId::FRIEND,
        0xb0ffb0,
        GradientType::STATIC,
        // TRANSLATORS: palette color
        _("Friend names"));
    addColor(UserColorId::DISREGARDED,
        0xa00000,
        GradientType::STATIC,
        // TRANSLATORS: palette color
        _("Disregarded names"));
    addColor(UserColorId::IGNORED,
        0xff0000,
        GradientType::STATIC,
        // TRANSLATORS: palette color
        _("Ignored names"));
    addColor(UserColorId::ERASED,
        0xff0000,
        GradientType::STATIC,
        // TRANSLATORS: palette color
        _("Erased names"));
    addColor(UserColorId::ENEMY,
        0xff4040,
        GradientType::STATIC,
        // TRANSLATORS: palette color
        _("Enemy"));
    addColor(UserColorId::PC,
        0xffffff,
        GradientType::STATIC,
        // TRANSLATORS: palette color
        _("Other players names"));
    addColor(UserColorId::SELF,
        0xff8040,
        GradientType::STATIC,
        // TRANSLATORS: palette color
        _("Own name"));
    addColor(UserColorId::GM,
        0x00ff00,
        GradientType::STATIC,
        // TRANSLATORS: palette color
        _("GM names"));
    addColor(UserColorId::NPC,
        0xc8c8ff,
        GradientType::STATIC,
        // TRANSLATORS: palette color
        _("NPCs"));
    addColor(UserColorId::MONSTER,
        0xff4040,
        GradientType::STATIC,
        // TRANSLATORS: palette color
        _("Monsters"));
    addColor(UserColorId::PET,
        0xffffff,
        GradientType::STATIC,
        // TRANSLATORS: palette color
        _("Pets"));
    addColor(UserColorId::MERCENARY,
        0xffffff,
        GradientType::STATIC,
        // TRANSLATORS: palette color
        _("Mercenary"));
    addColor(UserColorId::HOMUNCULUS,
        0xffffff,
        GradientType::STATIC,
        // TRANSLATORS: palette color
        _("Homunculus"));
    addColor(UserColorId::PARTY,
        0xff00d8,
        // TRANSLATORS: palette color
        GradientType::STATIC,
        _("Party members"));
    addColor(UserColorId::GUILD,
        0xff00d8,
        // TRANSLATORS: palette color
        GradientType::STATIC,
        _("Guild members"));
    addColor(UserColorId::TEAM1,
        0x0000ff,
        GradientType::STATIC,
        // TRANSLATORS: palette color
        strprintf(_("Team %d"), 1));
    addColor(UserColorId::TEAM2,
        0x00a020,
        GradientType::STATIC,
        // TRANSLATORS: palette color
        strprintf(_("Team %d"), 2));
    addColor(UserColorId::TEAM3,
        0xffff20,
        GradientType::STATIC,
        // TRANSLATORS: palette color
        strprintf(_("Team %d"), 3));
    addLabel(UserColorId::LABEL_PARTICLES,
        // TRANSLATORS: palette label
        _("Particles"));
    addColor(UserColorId::PARTICLE,
        0xffffff,
        GradientType::STATIC,
        // TRANSLATORS: palette color
        _("Particle effects"));
    addColor(UserColorId::PICKUP_INFO,
        0x28dc28,
        GradientType::STATIC,
        // TRANSLATORS: palette color
        _("Pickup notification"));
    addColor(UserColorId::EXP_INFO,
        0xffff00,
        GradientType::STATIC,
        // TRANSLATORS: palette color
        _("Exp notification"));
    addLabel(UserColorId::LABEL_HP,
        // TRANSLATORS: palette label
        _("Hp bars"));
    addColor(UserColorId::PLAYER_HP,
        0x00ff00,
        GradientType::STATIC,
        // TRANSLATORS: palette color
        _("Player HP bar"), 50);
    addColor(UserColorId::PLAYER_HP2,
        0xff0000,
        GradientType::STATIC,
        // TRANSLATORS: palette color
        _("Player HP bar (second color)"),
        50);
    addColor(UserColorId::MONSTER_HP,
        0x00ff00,
        GradientType::STATIC,
        // TRANSLATORS: palette color
        _("Monster HP bar"),
        50);
    addColor(UserColorId::MONSTER_HP2,
        0xff0000,
        GradientType::STATIC,
        // TRANSLATORS: palette color
        _("Monster HP bar (second color)"),
        50);
    addLabel(UserColorId::LABEL_HITS,
        // TRANSLATORS: palette label
        _("Hits"));
    addColor(UserColorId::HIT_PLAYER_MONSTER,
        0x0064ff,
        GradientType::STATIC,
        // TRANSLATORS: palette color
        _("Player hits monster"));
    addColor(UserColorId::HIT_MONSTER_PLAYER,
        0xff3232,
        GradientType::STATIC,
        // TRANSLATORS: palette color
        _("Monster hits player"));
    addColor(UserColorId::HIT_PLAYER_PLAYER,
        0xff5050,
        GradientType::STATIC,
       // TRANSLATORS: palette color
       _("Other player hits local player"));
    addColor(UserColorId::HIT_CRITICAL,
        0xff0000,
        GradientType::RAINBOW,
        // TRANSLATORS: palette color
        _("Critical Hit"));
    addColor(UserColorId::HIT_LOCAL_PLAYER_MONSTER,
        0x00ff00,
        GradientType::STATIC,
        // TRANSLATORS: palette color
        _("Local player hits monster"));
    addColor(UserColorId::HIT_LOCAL_PLAYER_CRITICAL,
        0xff0000,
        GradientType::RAINBOW,
        // TRANSLATORS: palette color
        _("Local player critical hit"));
    addColor(UserColorId::HIT_LOCAL_PLAYER_MISS,
        0x00ffa6,
        GradientType::STATIC,
        // TRANSLATORS: palette color
        _("Local player miss"));
    addColor(UserColorId::MISS, 0xffff00,
        GradientType::STATIC,
        // TRANSLATORS: palette color
        _("Misses"));
    addLabel(UserColorId::LABEL_TILES,
        // TRANSLATORS: palette label
        _("Tiles"));
    addColor(UserColorId::PORTAL_HIGHLIGHT,
        0xC80000,
        GradientType::STATIC,
        // TRANSLATORS: palette color
        _("Portal highlight"));
    addColor(UserColorId::COLLISION_HIGHLIGHT,
        0x0000C8,
        GradientType::STATIC,
        // TRANSLATORS: palette color
        _("Default collision highlight"),
        64);
    addColor(UserColorId::AIR_COLLISION_HIGHLIGHT,
        0xe0e0ff,
        GradientType::STATIC,
        // TRANSLATORS: palette color
        _("Air collision highlight"),
        64);
    addColor(UserColorId::WATER_COLLISION_HIGHLIGHT,
        0x2050e0,
        GradientType::STATIC,
        // TRANSLATORS: palette color
        _("Water collision highlight"),
        64);
    addColor(UserColorId::GROUNDTOP_COLLISION_HIGHLIGHT,
        0xffff00,
        GradientType::STATIC,
        // TRANSLATORS: palette color
        _("Special ground collision highlight"),
        20);
    addColor(UserColorId::WALKABLE_HIGHLIGHT,
        0x00D000,
        GradientType::STATIC,
        // TRANSLATORS: palette color
        _("Walkable highlight"),
        255);
    addColor(UserColorId::NET,
        0x000000,
        GradientType::STATIC,
        // TRANSLATORS: palette color
        _("Tiles border"), 64);
    addLabel(UserColorId::LABEL_RANGES,
        // TRANSLATORS: palette label
        _("Ranges"));
    addColor(UserColorId::ATTACK_RANGE,
        0xffffff,
        GradientType::STATIC,
        // TRANSLATORS: palette color
        _("Local player attack range"),
        5);
    addColor(UserColorId::ATTACK_RANGE_BORDER,
        0x0,
        GradientType::STATIC,
        // TRANSLATORS: palette color
        _("Local player attack range border"),
        76);
    addColor(UserColorId::MONSTER_ATTACK_RANGE,
        0xff0000,
        GradientType::STATIC,
        // TRANSLATORS: palette color
        _("Monster attack range"),
        20);
    addLabel(UserColorId::LABEL_OTHER,
        // TRANSLATORS: palette label
        _("Other"));
    addColor(UserColorId::FLOOR_ITEM_TEXT,
        0xffffff,
        GradientType::STATIC,
        // TRANSLATORS: palette color
        _("Floor item amount color"),
        100);
    addColor(UserColorId::HOME_PLACE,
        0xffffff,
        GradientType::STATIC,
        // TRANSLATORS: palette color
        _("Home place"),
        20);
    addColor(UserColorId::HOME_PLACE_BORDER,
        0xffff00,
        GradientType::STATIC,
        // TRANSLATORS: palette color
        _("Home place border"),
        200);
    addColor(UserColorId::ROAD_POINT,
        0x000000,
        GradientType::STATIC,
        // TRANSLATORS: palette color
        _("Road point"), 100);
    commit(true);
}
Example #27
0
 transaction::~transaction(){
     commit();
     end();
 }
Example #28
0
void OracleConn::disconnect()
{
    commit();
    oci_database.disconnect();
    Connected = false;
}
Example #29
0
void c2040_fdc_t::live_run(const attotime &limit)
{
	if(cur_live.state == IDLE || cur_live.next_state != -1)
		return;

	for(;;) {
		switch(cur_live.state) {
		case RUNNING: {
			bool syncpoint = false;

			if (cur_live.tm > limit)
				return;

			int bit = get_next_bit(cur_live.tm, limit);
			if(bit < 0)
				return;

			int cell_counter = cur_live.cell_counter;

			if (bit) {
				cur_live.cycle_counter = cur_live.ds;
				cur_live.cell_counter = 0;
			} else {
				cur_live.cycle_counter++;
			}

			if (cur_live.cycle_counter == 16) {
				cur_live.cycle_counter = cur_live.ds;

				cur_live.cell_counter++;
				cur_live.cell_counter &= 0xf;
			}

			if (!BIT(cell_counter, 1) && BIT(cur_live.cell_counter, 1)) {
				// read bit
				cur_live.shift_reg <<= 1;
				cur_live.shift_reg |= !(BIT(cur_live.cell_counter, 3) || BIT(cur_live.cell_counter, 2));
				cur_live.shift_reg &= 0x3ff;

				if (LOG) logerror("%s read bit %u (%u) >> %03x, rw=%u mode=%u\n", cur_live.tm.as_string(), cur_live.bit_counter,
					!(BIT(cur_live.cell_counter, 3) || BIT(cur_live.cell_counter, 2)), cur_live.shift_reg, cur_live.rw_sel, cur_live.mode_sel);

				// write bit
				if (!cur_live.rw_sel) { // TODO WPS
					write_next_bit(BIT(cur_live.shift_reg_write, 9), limit);
				}

				syncpoint = true;
			}

			int sync = !((cur_live.shift_reg == 0x3ff) && cur_live.rw_sel);

			if (!sync) {
				cur_live.bit_counter = 0;
			} else if (!BIT(cell_counter, 1) && BIT(cur_live.cell_counter, 1) && cur_live.sync) {
				cur_live.bit_counter++;
				if (cur_live.bit_counter == 10) {
					cur_live.bit_counter = 0;
				}
			}

			// update GCR
			if (cur_live.rw_sel) {
				cur_live.i = (cur_live.rw_sel << 10) | cur_live.shift_reg;
			} else {
				cur_live.i = (cur_live.rw_sel << 10) | ((cur_live.pi & 0xf0) << 1) | (cur_live.mode_sel << 4) | (cur_live.pi & 0x0f);
			}

			cur_live.e = m_gcr_rom->base()[cur_live.i];

			int ready = !(BIT(cell_counter, 1) && !BIT(cur_live.cell_counter, 1) && (cur_live.bit_counter == 9));

			if (!ready) {
				// load write shift register
				cur_live.shift_reg_write = GCR_ENCODE(cur_live.e, cur_live.i);

				if (LOG) logerror("%s load write shift register %03x\n",cur_live.tm.as_string(),cur_live.shift_reg_write);
			} else if (BIT(cell_counter, 1) && !BIT(cur_live.cell_counter, 1)) {
				// clock write shift register
				cur_live.shift_reg_write <<= 1;
				cur_live.shift_reg_write &= 0x3ff;

				if (LOG) logerror("%s write shift << %03x\n",cur_live.tm.as_string(),cur_live.shift_reg_write);
			}

			int error = !(BIT(cur_live.e, 3) || ready);

			if (ready != cur_live.ready) {
				if (LOG) logerror("%s READY %u\n", cur_live.tm.as_string(),ready);
				cur_live.ready = ready;
				syncpoint = true;
			}

			if (sync != cur_live.sync) {
				if (LOG) logerror("%s SYNC %u\n", cur_live.tm.as_string(),sync);
				cur_live.sync = sync;
				syncpoint = true;
			}

			if (error != cur_live.error) {
				cur_live.error = error;
				syncpoint = true;
			}

			if (syncpoint) {
				commit(cur_live.tm);

				cur_live.tm += m_period;
				live_delay(RUNNING_SYNCPOINT);
				return;
			}

			cur_live.tm += m_period;
			break;
		}

		case RUNNING_SYNCPOINT: {
			m_write_ready(cur_live.ready);
			m_write_sync(cur_live.sync);
			m_write_error(cur_live.error);

			cur_live.state = RUNNING;
			checkpoint();
			break;
		}
		}
	}
}
Example #30
0
void DbFunc::renameColumns(const QSqlDatabase& db, QString tablename,
                           const QList<QPair<QString, QString>>& from_to,
                           const QString& tempsuffix)
{
    if (!tableExists(db, tablename)) {
        qWarning() << "WARNING: ignoring renameColumns for non-existent table:"
                   << tablename;
        return;
    }
    QString creation_sql = dbTableDefinitionSql(db, tablename);
    QStringList old_fieldnames = dbFieldNames(db, tablename);
    QStringList new_fieldnames = old_fieldnames;
    QString dummytable = tablename + tempsuffix;
    if (tableExists(db, dummytable)) {
        UiFunc::stopApp("DbFunc::renameColumns: temporary table exists: " +
                        dummytable);
    }
    int n_changes = 0;
    for (int i = 0; i < from_to.size(); ++i) {  // For each rename...
        QString from = from_to.at(i).first;
        QString to = from_to.at(i).second;
        if (from == to) {
            continue;
        }
        // Check the source is valid
        if (!old_fieldnames.contains(from)) {
            UiFunc::stopApp("DbFunc::renameColumns: 'from' field doesn't "
                            "exist: " + tablename + "." + from);
        }
        // Check the destination doesn't exist already
        if (new_fieldnames.contains(to)) {
            UiFunc::stopApp(
                "DbFunc::renameColumns: destination field already exists (or "
                "attempt to rename two columns to the same name): " +
                tablename + "." + to);
        }
        // Rename the fieldname in the new_fieldnames list, and in the SQL
        new_fieldnames[new_fieldnames.indexOf(from)] = to;
        creation_sql.replace(delimit(from), delimit(to));
        ++n_changes;
    }
    if (n_changes == 0) {
        qDebug() << "renameColumns: nothing to do:" << tablename;
        return;
    }
    qDebug() << Q_FUNC_INFO;
    qDebug() << "- table:" << tablename;
    qDebug() << "- from_to:" << from_to;
    qDebug() << "- old_fieldnames:" << old_fieldnames;
    qDebug() << "- new_fieldnames:" << new_fieldnames;
    // Delimit everything
    QString delimited_tablename = delimit(tablename);
    QString delimited_dummytable = delimit(dummytable);
    for (int i = 0; i < old_fieldnames.size(); ++i) {
        old_fieldnames[i] = delimit(old_fieldnames[i]);
        new_fieldnames[i] = delimit(new_fieldnames[i]);
    }
    exec(db, "BEGIN TRANSACTION");
    exec(db, QString("ALTER TABLE %1 RENAME TO %2").arg(delimited_tablename,
                                                        delimited_dummytable));
    // Make a new, clean table:
    exec(db, creation_sql);
    // Copy the data across:
    exec(db, QString("INSERT INTO %1 (%2) SELECT %3 FROM %4").arg(
             delimited_tablename,
             new_fieldnames.join(","),
             old_fieldnames.join(","),
             delimited_dummytable));
    // Drop the temporary table:
    exec(db, QString("DROP TABLE %1").arg(delimited_dummytable));
    commit(db);
}