bool QSqlRecordProto::contains(const QString &name) const
{
  QSqlRecord *item = qscriptvalue_cast<QSqlRecord*>(thisObject());
  if (item)
    return item->contains(name);
  return false;
}
Example #2
0
/*!
 *\~english
 *	Emit signal on select record.
 *	Signal give information about selected record database id.
 *\~russian
 *	Выдает сигнал при выборе записи.
 *	Сигнал содержит информацию об id, выбранного объекта в базе данных.
 *\param -\~english Not use, only for signal compatibility.\~russian
 *	Не используются, заданы только для совместимости с сигналом таблицы.\~
 *\~
 */
void
wDBTable::lineChange(int, int)
{
	QSqlRecord * rec = currentRecord();
	if ( !rec ) return;
	qulonglong id = 0;
	if(rec->contains("id")) id = rec->value("id").toLongLong();
	//if (containerType() == "wJournal")
	//{
		//if(rec->contains("idd")) id = rec->value("idd").toLongLong();
	//}
	aLog::print(aLog::Info, tr("wDBTable: select document %1").arg(id));
	emit( selectRecord( id ) );
}
Example #3
0
list_t Query::requestOne(QString sql)
{
    list_t result;
    QSqlQuery *query = new QSqlQuery(database);
    query->prepare(sql);
    try
    {
        if(query->exec())
        {
            while(query->next())
            {
                for(int i = 0; i < query->record().count(); i++)
                {
                    QPair <QString, QVariant> pair(query->record().fieldName(i), query->value(i));
                    if((innerJoin == "") && (outerJoin == ""))
                    {
                        result.append(pair);
                    }
                    else
                    {
                        QSqlRecord records = database.record(schema->getRelation(rName).model->getSchema()->getTableName());
                        if(records.contains(query->record().fieldName(i)))
                        {
                            result.append(pair);
                        }
                    }
                }
                result.append(QPair <QString, QVariant> ("", ""));
            }
        }
        else
        {
            throw query;
        }
    }
    catch (QSqlQuery *)
    {
        qDebug() << "[Query error]: " << query->lastError();
    }

    return result;
}
Example #4
0
QVariant Essence::getValue(QString n, int row)
{
    QVariant result;
    if (n.size() > 0)
    {
        QString name = n.toUpper();
        QSqlRecord record = tableModel->record();
        if (record.contains(name))
        {
            if (row >= 0)
            {
                result =  tableModel->record(row).value(name);
            }
            else
            {
                int r = 0;
                if (grdTable != 0 && grdTable->currentIndex().isValid())
                    r = grdTable->currentIndex().row();

                result = tableModel->record(r).value(name);
            }
            QVariant::Type type = record.field(name).type();
            if (type == QVariant::Double ||
                type == QVariant::Int)
            {
                if (!result.isValid())
                    result = QVariant(0);
                result.convert(type);
                result = QString::number(result.toDouble(), 'f', record.field(name).precision()).toDouble();
            }

            // Округлим значение числового поля до точности как и в БД
        }
        else
            app->showError(QObject::trUtf8("Не существует колонки ") + n);
    }
    return result;
}
Example #5
0
void CSVAtlasWindow::sMapChanged( int )
{
  CSVMap map;
  if(!_selectedMap.isEmpty())
  {
    map = _atlas->map(_selectedMap);
    if(tr("Insert") == _action->currentText())
      map.setAction(CSVMap::Insert);
    else if(tr("Update") == _action->currentText())
      map.setAction(CSVMap::Update);
    else if(tr("Append") == _action->currentText())
      map.setAction(CSVMap::Append);
    map.setDescription(_description->toPlainText());
    map.setSqlPre(_preSql->toPlainText().trimmed());
    map.setSqlPreContinueOnError(_sqlPreContinueOnError->isChecked());
    map.setSqlPost(_postSql->toPlainText().trimmed());
    for(int r = 0; r < _fields->rowCount(); r++)
    {
      CSVMapField field = map.field(_fields->item(r, 1)->data(Qt::EditRole).toString());
      field.setName(_fields->item(r, 1)->data(Qt::EditRole).toString());

      if (qobject_cast<QCheckBox*>(_fields->cellWidget(r, 0)))
        field.setIsKey(qobject_cast<QCheckBox*>(_fields->cellWidget(r,0))->isChecked());
      else
        field.setIsKey(FALSE);

      field.setType(QVariant::nameToType(_fields->item(r, 2)->data(Qt::EditRole).toString().toAscii().data()));

      if (qobject_cast<QComboBox*>(_fields->cellWidget(r, 4)))
        field.setAction(CSVMapField::nameToAction(qobject_cast<QComboBox*>(_fields->cellWidget(r, 4))->currentText()));
      else
        field.setAction(CSVMapField::Action_Default);

      if (qobject_cast<QSpinBox*>(_fields->cellWidget(r, 5)))
        field.setColumn(qobject_cast<QSpinBox*>(_fields->cellWidget(r,5))->value());
      else
        field.setColumn(0);

      if (qobject_cast<QComboBox*>(_fields->cellWidget(r, 6)))
        field.setIfNullAction(CSVMapField::nameToIfNull(qobject_cast<QComboBox*>(_fields->cellWidget(r, 6))->currentText()));
      else
        field.setIfNullAction(CSVMapField::Nothing);

      if (qobject_cast<QSpinBox*>(_fields->cellWidget(r, 7)))
        field.setColumnAlt(qobject_cast<QSpinBox*>(_fields->cellWidget(r, 7))->value());
      else
        field.setColumnAlt(1);

      if (qobject_cast<QComboBox*>(_fields->cellWidget(r, 8)))
        field.setIfNullActionAlt(CSVMapField::nameToIfNull(qobject_cast<QComboBox*>(_fields->cellWidget(r, 8))->currentText()));
      else
        field.setIfNullActionAlt(CSVMapField::Nothing);

      field.setValueAlt(_fields->item(r, 9)->data(Qt::EditRole).toString());
      map.setField(field);
    }
    map.simplify();
    _atlas->setMap(map);
  }
 
  QSqlDatabase db = QSqlDatabase::database();
  if (db.isValid())
  {
    _fields->setRowCount(0);
    if(_map->count() && ! _map->currentText().isEmpty())
    {
      // CODE TO SELECT MAP
      _selectedMap = _map->currentText();
      map = _atlas->map(_selectedMap);

      _table->setTitle(tr("Table: ") + map.table());
      _table->setEnabled(TRUE);

      _action->setCurrentIndex(map.action());
      _description->setText(map.description());
      _preSql->setText(map.sqlPre());
      _sqlPreContinueOnError->setChecked(map.sqlPreContinueOnError());
      _postSql->setText(map.sqlPost());

      QSqlRecord record = db.record(map.table());
      QStringList fieldnames;
      if (record.isEmpty())
      {
        _msghandler->message(QtWarningMsg, tr("No Existing Table"),
                             tr("<p>The table %1 does not exist in this "
                                "database. You may continue to use and edit "
                                "this map but only those fields that are known "
                                "will be shown.").arg(map.table()),
                             QUrl(), QSourceLocation());
        fieldnames = map.fieldList();
      }
      else
      {
        QStringList fList = map.fieldList();

        for(int i = 0; i < fList.size(); ++i)
        {
          CSVMapField f = map.field(fList.at(i));
          if(!record.contains(fList.at(i)))
          {
            map.removeField(fList.at(i));
            MissingField diag(this, f.name(), record);
            if(diag.exec() == QDialog::Accepted)
            {
              f.setName(diag._fields->currentText());
              map.setField(f);
            }
            _atlas->setMap(map);
          }
        }

        for (int i = 0; i < record.count(); i++)
          fieldnames.append(record.fieldName(i));
      }

      _fields->setRowCount(fieldnames.size());
      for(int row = 0; row < fieldnames.size(); ++row)
      {
        CSVMapField mf = map.field(fieldnames.at(row));

        QCheckBox *check = new QCheckBox(_fields);
        if(!mf.isEmpty())
          check->setChecked(mf.isKey());
        _fields->setCellWidget(row, 0, check);

        _fields->setItem(row, 1, new QTableWidgetItem(fieldnames.at(row)));
        if (record.isEmpty())
        {
          _fields->setItem(row, 2,
                           new QTableWidgetItem(QVariant::typeToName(mf.type())));
          _fields->setItem(row, 3, new QTableWidgetItem(tr("Unknown")));
        }
        else
        {
          _fields->setItem(row, 2,
                           new QTableWidgetItem(QVariant::typeToName(record.field(row).type())));
          _fields->setItem(row, 3, new QTableWidgetItem(
                           (record.field(row).requiredStatus() == QSqlField::Required) ? tr("Yes") :
                           (record.field(row).requiredStatus() == QSqlField::Optional) ? tr("No")  :
                           tr("Unknown")));
        }

        QComboBox *actcombo = new QComboBox(_fields);
        actcombo->addItems(CSVMapField::actionList());
        if (! mf.isEmpty())
          actcombo->setCurrentIndex(mf.action());
        _fields->setCellWidget(row, 4, actcombo);

        QSpinBox *colspinner = new QSpinBox(_fields);
        colspinner->setRange(1, 999);
        colspinner->setPrefix(tr("Column "));
        if(!mf.isEmpty())
          colspinner->setValue(mf.column());
        _fields->setCellWidget(row, 5, colspinner);

        QComboBox *nullcombo = new QComboBox(_fields);
        nullcombo->addItems(CSVMapField::ifNullList());
        if (! mf.isEmpty())
          nullcombo->setCurrentIndex(mf.ifNullAction());
        _fields->setCellWidget(row, 6, nullcombo);

        QSpinBox *altspinner = new QSpinBox(_fields);
        altspinner->setRange(1, 999);
        altspinner->setPrefix(tr("Column "));
        if (! mf.isEmpty())
          altspinner->setValue(mf.columnAlt());
        _fields->setCellWidget(row, 7, altspinner);

        QComboBox *altnullcombo = new QComboBox(_fields);
        altnullcombo->addItems(CSVMapField::ifNullList(TRUE));
        if (! mf.isEmpty())
          altnullcombo->setCurrentIndex(mf.ifNullActionAlt());
        _fields->setCellWidget(row, 8, altnullcombo);

        _fields->setItem(row, 9, new QTableWidgetItem(mf.valueAlt()));

        RowController *control = new RowController(_fields, row, colspinner);
        control->setAction(actcombo);
        control->setColumn(colspinner);
        control->setIfNull(nullcombo);
        control->setAltColumn(altspinner);
        control->setAltIfNull(altnullcombo);
        control->setAltValue(_fields->item(row, 9));
        control->finishSetup();
      }
    }
    else
    {
      _selectedMap = QString::null;
      _table->setTitle(tr("Table: "));
      _table->setEnabled(FALSE);
    }
  }
  else
    _msghandler->message(QtCriticalMsg, tr("No Database"),
                         tr("Could not get the database connection."));
}
bool SqlDbBackend::save( Object *object )
{
	assert( object );
	bool update;
	QSqlRecord *record;
	QSqlCursor cursor( object->classInfo()->name() );

	if ( object->oid() == 0 ) {
		object->setOid( newOid() );
		cursor.select();
		record = cursor.primeInsert();
		update = false;
	} else {
		cursor.select( "to_number( " + oidFieldName() + ", '9999999999G0') = " + oidToString( object->oid() ) );
		if ( ! cursor.next() ) {
			cursor.select();
			record = cursor.primeInsert();
			update = false;
		} else {
			record = cursor.primeUpdate();
			update = true;
		}
	}

	// We don't mark any field as generated. So at first, none
	// would be included in the INSERT/UPDATE. Then we must make sure
	// we set the generated flag to each property field.
	// Note that this is necesary as we want relation fields to take their
	// default values when inserted.
	for ( uint i = 0; i < record->count(); ++i ) {
		record->setGenerated( i, false );
	}

	record->setValue( oidFieldName(), object->oid() );
	record->setGenerated( oidFieldName(), true );
	record->setValue( sequenceFieldName(), newSeq() );
	record->setGenerated( sequenceFieldName(), true );

	PropertiesIterator pIt( object->propertiesBegin() );
	PropertiesIterator pEnd( object->propertiesEnd() );
	Property prop;
	for ( ; pIt != pEnd; ++pIt ) {
		prop = pIt.data();
		if ( prop.readOnly() || ! record->contains( prop.name() ) )
			continue;

		if ( prop.type() == QVariant::Pixmap ) {
			QByteArray img;
			QBuffer buffer( img );
			buffer.open( IO_WriteOnly );
			prop.value().toPixmap().save( &buffer, "PNG" );
			record->setValue( prop.name(), img );
//		} else if( prop.type() == QVariant::List ){
//			QByteArray pin;
//			QDataStream stream( pin, IO_ReadWrite );
//			stream << prop.value();
//			record->setValue( prop.name(), stream );
		} else {
			record->setValue( prop.name(), prop.value() );
		}
		record->setGenerated( prop.name(), true );
	}

	if ( update ) {
		if (! cursor.update() ) {
			kdDebug() << k_funcinfo << " -> " << cursor.lastError().text() << endl;
			kdDebug() << k_funcinfo << " -> " << cursor.executedQuery() << endl;
			ERROR( "Update failed" );
		}
	} else {
		if ( ! cursor.insert() ) {
			kdDebug() << k_funcinfo << " -> " << cursor.lastError().text() << endl;
			kdDebug() << k_funcinfo << " -> " << cursor.executedQuery() << endl;
			ERROR( "Insert failed" );
		}
	}
	return true;
}
Example #7
0
/*******************************************************************
  Ensures that all tables exist and are properly formatted.
  Fails otherwise.
*******************************************************************/
bool prepareDatabase( ConnectionInfo xInfo )
{
	// write connection info to the global space for future connections to use
	DB::connectionInfo = xInfo;

	QSqlDatabase* db;
	dbLock.lock();
	if( !dbStore.contains(QThread::currentThreadId()) ){
		db = new QSqlDatabase();
		*db = QSqlDatabase::addDatabase("QMYSQL", QString::number(QThread::currentThreadId()));
		db->setHostName(DB::connectionInfo.host);
		db->setDatabaseName(DB::connectionInfo.dbname);
		db->setUserName(DB::connectionInfo.user);
		db->setPassword(DB::connectionInfo.password);
		dbStore.insert(QThread::currentThreadId(), db);

		// make sure the database exists and the credentials are good
		if( !db->open() ){
			qCritical() << "Could not open database";
			return false;
		}
	}
	else {
		db = dbStore[QThread::currentThreadId()];
	}
	dbLock.unlock();




	/*QString createMerges = 
		"CREATE TABLE IF NOT EXISTS merges ("
		"merge_id INT UNSIGNED, "
		"run_id INT UNSIGNED, "
		"merge_point INT UNSIGNED, "
		");";
	*/

	QString createLoops = 
		"CREATE TABLE IF NOT EXISTS loops ("
		"loop_id BIGINT UNSIGNED NOT NULL, "
		"length INT UNSIGNED, "
		"instance_cnt INT UNSIGNED, "
			
		"PRIMARY KEY (loop_id)"
		") ENGINE=InnoDB;";

	QString createSimulations = 
		"CREATE TABLE IF NOT EXISTS simulations ("
		"sim_id BIGINT UNSIGNED NOT NULL, "
		"final_state BIGINT UNSIGNED, "
		"length INT UNSIGNED, "
		"term_loop_id BIGINT UNSIGNED, "
			
		"PRIMARY KEY (sim_id)"
		") ENGINE=InnoDB;";

	// create the "states" table to contain the discrete states
	QString createStates = 
		"CREATE TABLE IF NOT EXISTS states ("
		"state_def BIGINT UNSIGNED NOT NULL, "
		"next_state BIGINT UNSIGNED, "
		"stepnum SMALLINT UNSIGNED, "
		"sim_id BIGINT UNSIGNED NOT NULL, "
		"loop_id BIGINT UNSIGNED, "
			
		"PRIMARY KEY (state_def), "
		"FOREIGN KEY (sim_id)  REFERENCES simulations(sim_id), "
		"FOREIGN KEY (loop_id) REFERENCES loops(loop_id)"
		") ENGINE=InnoDB;";
		
		
	// ensure that the tables exist (does not guarantee layout)
	QSqlQuery query(*db);
	if( !query.exec(createLoops) || !query.exec(createSimulations) || !query.exec(createStates) ){
		qCritical() << "Could not create critical table: " << query.lastError().text() << query.lastError().type();
		return false;
	}
	
	// confirm the layout of the critical tables
	QSqlRecord table = db->record("loops");
	if( !table.contains("loop_id")
		|| !table.contains("length")
		|| !table.contains("instance_cnt")
	){
		qCritical() << "Loop table is of the wrong format!";
		return false;
	}
	
	table = db->record("simulations");
	if( !table.contains("sim_id")
		|| !table.contains("final_state")
		|| !table.contains("length")
		|| !table.contains("term_loop_id")
	){
		qCritical() << "Simulations table is of the wrong format!";
		return false;
	}
	
	table = db->record("states");
	if( !table.contains("state_def")
		|| !table.contains("next_state")
		|| !table.contains("stepnum")
		|| !table.contains("sim_id")
		|| !table.contains("loop_id")
	){
		qCritical() << "State table is of the wrong format!";
		return false;
	}
	
	// leave open for main-thread db calls
	//db->close();

	return true;
}