QString Browser::StructureTable( QSqlRecord now ) { QSqlRecord rec = now; QString createtable; QString sqltipename; QStringList CreateTable; int totalcools = rec.count(); if (totalcools > 0) { /* sqlite3 table construct from odbc converter */ for (int i = 0; i < totalcools; ++i) { QSqlField fld = rec.field(i); QString name = Strtrimmed(fld.name()); QString typeoffield = QString(QVariant::typeToName(fld.type())); /* fld.isAutoValue() never true from auto_increment mysql ??? */ if (fld.requiredStatus() and i < 2 and typeoffield == "int") { sqltipename = QString("%1 INTEGER PRIMARY KEY").arg(name); } else if ( typeoffield == "double" or typeoffield == "int" ) { sqltipename = QString("%1 NUMERIC").arg(name); } else if ( typeoffield == "QByteArray") { sqltipename = QString("%1 BLOB").arg(name); } else { sqltipename = QString("%1 TEXT").arg(name); } CreateTable.append(sqltipename); ////////qDebug() << "### fieldname " << name; ///////////qDebug() << "### typeoffield " << typeoffield; } QString midlecreate = CreateTable.join(","); midlecreate.prepend(QString("CREATE TABLE %1 (").arg(runningtable)); midlecreate.append(");"); createtable = midlecreate; } return createtable; }
Login::Login(Configuracion *m_config,QWidget *parent) : QDialog(parent), ui(new Ui::Login) { this->setWindowFlags(Qt::Dialog|Qt::CustomizeWindowHint|Qt::WindowTitleHint); ui->setupUi(this); //-------------------------------------------- // Conexiones //-------------------------------------------- connect(ui->btnEmpresa,SIGNAL(clicked()),this,SLOT(btnEmpresa_clicked())); connect(ui->Crearconfiguracin,SIGNAL(clicked()),this,SLOT(Crearconfiguracion_clicked())); // TODO - Rellenar en base a fichero de empresas BD terra. // Relleno combo empresas QSqlQuery *QryEmpresas = new QSqlQuery(QSqlDatabase::database("terra")); QryEmpresas->prepare("Select * from empresas"); if(QryEmpresas->exec()) { while (QryEmpresas->next()) { QSqlRecord rEmpresa = QryEmpresas->record(); ui->cboEmpresa->addItem(rEmpresa.field("nombre").value().toString()); } } this->ui->lineUsuario->setFocus(); }
QString Cliente::Nuevocodigo_cliente() { QString codigo; double nCodigo = 1; QSqlQuery qClientes(Configuracion_global->groupDB); if(qClientes.exec("select codigo_cliente from clientes order by codigo_cliente desc limit 1")) { if (qClientes.next()) { QSqlRecord registro = qClientes.record(); codigo = registro.field("codigo_cliente").value().toString(); nCodigo = codigo.mid(Configuracion_global->cuenta_clientes.length()).toULong(); nCodigo ++; codigo = QString::number(nCodigo); } } QString codigo_nuevo; QString formato = QString("%1.0f").arg(Configuracion_global->digitos_cuentas_contables-Configuracion_global->cuenta_clientes.length()); formato.prepend("%0"); std::string _x = formato.toStdString(); codigo_nuevo.sprintf(_x.c_str(),nCodigo); codigo_nuevo.prepend(Configuracion_global->cuenta_clientes); cuenta_iva_repercutido = Configuracion_global->cuenta_iva_repercutido1 +codigo_nuevo; return codigo_nuevo; }
void QRelation::populateDictionary() { if (!isValid()) return; if (model == NULL) populateModel(); QSqlRecord record; for (int i=0; i < model->rowCount(); ++i) { record = model->record(i); dictionary[record.field(rel.indexColumn()).value().toString()] = record.field(rel.displayColumn()).value(); } m_dictInitialized = true; }
void TablePrivate::init() { Q_Q(Table); q->setTable(name); q->setEditStrategy(QSqlTableModel::OnFieldChange); q->select(); QSqlRecord columnNames = q->record(); int columnCount = columnNames.count(); columns.reserve(columnCount); for(int i = 0; i < columnCount; ++i) { Column *column = new Column(columnNames.field(i), q); column->setIndex(i); columns.append(column); columnsByName.insert(column->name(), column); } while(q->canFetchMore()) q->fetchMore(); QSqlQuery query = q->query(); int rowCount = q->rowCount(); int idIndex = q->record().indexOf(QLatin1String("id")); int id = 0; rows.reserve(rowCount); rowsById.reserve(rowCount); for(int i = 0; i < rowCount; ++i) { query.seek(i); id = query.value(idIndex).toInt(); Row *row = new Row(i, id, q); rows.append(row); rowsById.insert(id, row); } }
QSqlField QSqlRecordProto::field(int index) const { QSqlRecord *item = qscriptvalue_cast<QSqlRecord*>(thisObject()); if (item) return item->field(index); return QSqlField(); }
void AddressBook::csvExport() { QFileDialog dialog(this); QStringList fileNames; dialog.setFileMode(QFileDialog::AnyFile); dialog.setNameFilter(tr("Données CSV (*.csv)")); if (dialog.exec()) fileNames = dialog.selectedFiles(); QFile file(fileNames[0]); if (!file.open(QIODevice::WriteOnly)) QMessageBox::information(this, tr("Impossible d'ouvrir le fichier"),file.errorString()); QString data; data = "Last Name,First Name,Birthday,Home Phone,Mobile Phone,Business Phone,Business Fax,E-mail Address,Web Page,Home Address,Home City,Home Postal Code,Business Address,Business City,Business Postal Code\n"; // /!\ CETTE (ces) LIGNE(s) (et les éventuelles lignes semblables) A (ont) ETE INSPIREE(s) PAR "LA MAILING LIST QT" (disponible à l'adresse "http://lists.trolltech.com/qt-interest/2008-03/thread00073-0.html"). LE CODE REPRIS N'EST PAS DISPONIBLE A LA (aux) LIGNE(s) SUIVANTE(s) for (int row = 0; row < model->rowCount(); ++row) { QSqlRecord record = model->record(row); for (int field = 0; field < record.count(); ++field) { if(field != 0 && field != 4) { if (field > 1) data += ","; data += record.field(field).value().toString(); // } } data += "\n"; } QTextStream *output; output = new QTextStream(&file); *output << data; QMessageBox::information(this,"Exportation","L'exportation au format CSV est terminée"); }
QSqlField QSqlRecordProto::field(const QString &name) const { QSqlRecord *item = qscriptvalue_cast<QSqlRecord*>(thisObject()); if (item) return item->field(name); return QSqlField(); }
void QSqlField_snippets() { #if 0 { //! [2] QSqlField field("age", QVariant::Int); field.setValue(QPixmap()); // WRONG //! [2] } #endif { //! [3] QSqlField field("age", QVariant::Int); field.setValue(QString("123")); // casts QString to int //! [3] } { //! [4] QSqlQuery query; //! [4] //! [5] QSqlRecord record = query.record(); //! [5] //! [6] QSqlField field = record.field("country"); //! [6] } }
QDebug operator<<(QDebug dbg, const QSqlRecord &r) { dbg << "QSqlRecord(" << r.count() << ')'; for (int i = 0; i < r.count(); ++i) dbg << '\n' << QString::fromLatin1("%1:").arg(i, 2) << r.field(i) << r.value(i).toString(); return dbg; }
TSqlSchema::TSqlSchema(QObject *parent) : QObject(parent) { database = QSqlDatabase::addDatabase("QSQLITE"); database.setDatabaseName("imsit.sqlite"); if(!database.open()) { currentErrorCode = database.lastError(); qDebug() << "Error code = " << currentErrorCode.text() << endl; } QString genre = "select * from genre"; QSqlQuery currentQuery(genre); if(!currentQuery.exec()) { currentErrorCode = currentQuery.lastError(); qDebug() << "Error code = " << currentErrorCode.text() << endl; } else while(currentQuery.next()) { const QSqlRecord currentRecord = currentQuery.record(); QSqlField genre = currentRecord.field("genre"); qDebug() << genre.value().toString(); } }
QString Cliente::NuevoCodigoCliente() { Configuracion *oConfig = new Configuracion(); oConfig->CargarDatos(); QString cCodigo; QString cNum; int nCodigo; QSqlQuery *qClientes = new QSqlQuery(QSqlDatabase::database("empresa")); if(qClientes->exec("select cCodigoCliente from clientes order by cCodigoCliente desc limit 1")) { if (qClientes->next()) { QSqlRecord registro = qClientes->record(); cCodigo = registro.field("cCodigoCliente").value().toString(); nCodigo = cCodigo.toInt(); nCodigo ++; cCodigo = QString::number(nCodigo); } } if (nCodigo == 0 || nCodigo == 1) { cNum = "1"; while (cNum.length()< (oConfig->nDigitosCuentasContables - oConfig->cCuentaClientes.length()) ) { cNum.prepend("0"); } cCodigo = oConfig->cCuentaClientes + cNum; } return cCodigo; }
Column *TablePrivate::addColumn(const QString &name, const QString &sqlType, const QVariant &defaultValue) { Q_Q(Table); if(q->columnNames().contains(name, Qt::CaseInsensitive)) { qWarning() << "TablePrivate::addColumn: Duplicate column name" << name; return columnsByName.value(name); } QSqlQuery query(database->sqlDatabase()); QString queryString = QLatin1String("ALTER TABLE ")+this->name+QLatin1String(" ADD ")+name+ QLatin1String(" ")+sqlType; if(!defaultValue.toString().isEmpty()) { queryString += QLatin1String(" DEFAULT ")+defaultValue.toString(); } query.exec(queryString); checkSqlError(query); query.finish(); QSqlRecord record = database->sqlDatabase().record(this->name); QSqlField columnField = record.field(record.indexOf(name)); q->beginInsertColumns(QModelIndex(),columns.count(), columns.count()); Column *column = new Column(columnField, q); columns.append(column); columnsByName.insert(name, column); foreach(Row *row, rows) { row->addColumn(name, defaultValue); }
void TablePrivate::init() { Q_Q(Table); QSqlRecord columnNames = database->sqlDatabase().record(name); columns.reserve(columnNames.count()); for(int i = 0; i < columnNames.count(); ++i) { Column *column = new Column(columnNames.field(i), q); columns.append(column); columnsByName.insert(column->name(), column); } QSqlQuery query(database->sqlDatabase()); query.exec(QLatin1String("SELECT * FROM ")+name); rows.reserve(query.size()); rowsById.reserve(query.size()); int idIndex = query.record().indexOf(QLatin1String("id")); Q_ASSERT_X(idIndex != -1, "TablePrivate::init", "The table has no field 'id'"); int id = 0; while(query.next()) { id = query.value(idIndex).toInt(); Row *row = new Row(query, q_ptr); rows.append(row); rowsById.insert(id, row); } checkSqlError(query); query.finish(); }
IlwisObject *InternalIlwisObjectFactory::createRepresentation(const Resource& resource, const IOOptions &options) const{ QString code = resource.code(); Representation *rpr = createFromResource<Representation>(resource, options); if ( code != sUNDEF) { InternalDatabaseConnection db; QString query = QString("Select linkedtable from codes where code = '%1'").arg(code); if (db.exec(query)) { if ( db.next()){ QString table = db.value(0).toString(); if ( table == "representation"){ query = QString("Select * from representation where code='%1'").arg(code); if (db.exec(query)) { if ( db.next()){ QSqlRecord rec = db.record(); rpr->fromInternal(rec); QString relateddomain = rec.field("relateddomain").value().toString(); QString rprType = rec.field("representationtype").value().toString(); QString definition = rec.field("definition").value().toString(); QString mode = rec.field("mode").value().toString(); if ( rprType == "continuouscolor"){ rpr->colors(new ContinuousColorLookup(definition, mode)); }else if ( rprType == "palettecolor"){ rpr->colors(new PaletteColorLookUp(definition)); } if ( relateddomain == "value"){ rpr->domain(IDomain("value")); } rpr->readOnly(true); }else return 0; }else return 0; }else return 0; }else return 0; }else return 0; } return rpr; }
IlwisObject *InternalIlwisObjectFactory::createProjection(const Resource& resource, const IOOptions &options) const { QString query; QString code = resource.code(); Projection *proj = 0; if ( code == sUNDEF){ // meant for new projections which will be initialized later (e.g by the streaming connector) proj = createFromResource<Projection>(resource, options); } else if ( code != "") { InternalDatabaseConnection db; query = QString("Select * from projection where code = '%1'").arg(code); if ( db.exec(query)) { if (db.next()) { QSqlRecord rec = db.record(); const ProjectionFactory *factory = kernel()->factory<ProjectionFactory>("ProjectionFactory",resource); if ( factory) { ProjectionImplementation *projimpl = 0; if ( options.contains("proj4")) projimpl = static_cast<ProjectionImplementation *>(factory->create(resource.code(), options["proj4"].toString())); else projimpl = static_cast<ProjectionImplementation *>(factory->create(resource)); if (!projimpl) { kernel()->issues()->log(TR(ERR_COULDNT_CREATE_OBJECT_FOR_2).arg("projection", resource.name())); return 0; } proj = createFromResource<Projection>(resource, options); proj->setImplementation(projimpl); proj->fromInternal(rec); proj->setAuthority(rec.field("authority").value().toString()); proj->setWkt(rec.field("wkt").value().toString()); } else { kernel()->issues()->log(TR(ERR_COULDNT_CREATE_OBJECT_FOR_2).arg("ProjectionFactory",resource.name())); } } else { kernel()->issues()->log(TR(ERR_FIND_SYSTEM_OBJECT_1).arg(code)); } } else{ kernel()->issues()->logSql(db.lastError()); } } else { kernel()->issues()->log(TR(ERR_MISSING_CODE_FOR_SYSTEM_OBJECT)); } return proj; }
void GeodeticDatum::getFromInternal(const QString &ellips) { InternalDatabaseConnection db; QString query = "Select * from datum"; if ( db.exec(query) ){ while( db.next()){ QSqlRecord rec = db.record(); double dx = rec.field("dx").value().toDouble(); double dy = rec.field("dy").value().toDouble(); double dz = rec.field("dz").value().toDouble(); QString ellipsoid = rec.field("ellipsoid").value().toString(); // the combination of ellips-name, dx, dy and dz uniquely identifies the datum by name and area if ( ellipsoid.toLower() == ellips.toLower() && std::abs(_datumParams[dmDX] - dx) < 0.01 && std::abs(_datumParams[dmDY] - dy) < 0.01 && std::abs(_datumParams[dmDZ] - dz) < 0.01) { _datumParams[dmDX] = dx; _datumParams[dmDY] = dy; _datumParams[dmDZ] = dz; code(rec.field("code").value().toString()); name(rec.field("name").value().toString()); setArea(rec.field("area").value().toString()); setWktName(rec.field("wkt").value().toString()); setAuthority(rec.field("authority").value().toString()); return; } } } }
QVariant PeopleLookupModel::data(const QModelIndex &item, int role) const { const int column = item.column(); if (role == Qt::DisplayRole) { const QSqlRecord rec = record(item.row()); if (column == 0) { return rec.field("id").value(); } else if (column == 1) { return rec.field("name").value(); } } else if (role == Qt::UserRole) { const QSqlRecord rec = record(item.row()); return rec.field("id").value(); } return QSqlQueryModel::data(item, role); }
ChartSettingsDialog::ChartSettingsDialog(const QSqlRecord &record, QWidget *parent) : QDialog(parent), ui(new Ui::ChartSettingsDialog) { ui->setupUi(this); connect(ui->yAxisColumnComboBox, SIGNAL(currentIndexChanged(QString)), this, SIGNAL(yValuesColumnChanged(QString))); for (int i=0; i<record.count(); i++) { allColumnNames << record.fieldName(i); if ((record.field(i).type()==QVariant::Double)|| (record.field(i).type()==QVariant::Int)) { numericColumnNames << record.fieldName(i); } } ui->xAxisColumnComboBox->addItems(allColumnNames); ui->yAxisColumnComboBox->addItems(numericColumnNames); }
NumericDomain* InternalIlwisObjectFactory::createNumericDomain(const QString& code, InternalDatabaseConnection& db, const IOOptions &options, const Resource& resource) const { QString query = QString("Select * from numericdomain where code='%1'").arg(code); if (db.exec(query)) { if ( db.next()){ QSqlRecord rec = db.record(); NumericDomain *dv = createFromResource<NumericDomain>(resource, options); dv->fromInternal(rec); double vmin = rec.field("minv").value().toDouble(); double vmax = rec.field("maxv").value().toDouble(); double step = rec.field("resolution").value().toDouble(); int range_strict = rec.field("range_strict").value().toInt(); QString parent = rec.field("parent").value().toString(); db.closeConnection(); QString unit = rec.field("unit").value().toString(); if (unit == "Days"){ if ( fmod(step,1.0) == 0 && step != 0) dv->range(new TimeInterval(Time(vmin), Time(vmax))); else dv->range(new TimeInterval(Time(vmin), Time(vmax),Duration(QString("%1D").arg(step)))); }else { if ( fmod(step,1.0) == 0 && step != 0) dv->range(new NumericRange(vmin, vmax,1)); else dv->range(new NumericRange(vmin, vmax)); } dv->setStrict(range_strict ? true : false); if ( parent != "" && parent != code) { // no parenting to itself IDomain dom; dom.prepare(parent, options); if ( dom.isValid()) { dv->setParent(dom); } } return dv; }else { kernel()->issues()->log(TR(ERR_FIND_SYSTEM_OBJECT_1).arg(code)); } } return 0; }
bool db_query_widget::new_query(const QString &SQL) { lb_status->setText(tr("Sending SQL query...")); pv_SQL = SQL; le_sql->setText(pv_SQL); if(!pv_query->exec(pv_SQL)){ std::cerr << "db_query_widget::" << __FUNCTION__ << ": query execution failed" << std::endl; std::cerr << "-> " << pv_query->lastError().text().toStdString().c_str() << std::endl; lb_status->setText(tr("Query execution failed: ") + pv_query->lastError().text()); return false; } // Count num rows and columns QSqlRecord record; int row=0, col=0, i; while(pv_query->next()){ if(row >= pv_max_rows){ break; } row++; } pv_query->first(); record = pv_query->record(); col = record.count(); // Init the table pv_table->setColumnCount(col); for(i=0; i<col; i++){ QTableWidgetItem *item = new QTableWidgetItem(record.field(i).name()); pv_table->setHorizontalHeaderItem(i, item); } // Enter data pv_table->setSortingEnabled(false); pv_table->setRowCount(row); row = 0; while(pv_query->next()){ if(row >= pv_max_rows){ std::cerr << "db_query_widget::" << __FUNCTION__ << ": Maximum rows -> Aborting here" << std::endl; break; } record = pv_query->record(); // Set each column for(i=0; i<col; i++){ QTableWidgetItem *item = new QTableWidgetItem(record.value(i).toString()); pv_table->setItem(row, i, item); } row++; } pv_table->setSortingEnabled(true); pv_table->resizeRowsToContents(); pv_table->resizeColumnsToContents(); lb_status->setText(tr("Ready")); return true; }
void NMC_NameManager::AddPendingRegFunctor::operator() (const QSqlRecord& rec) { nmcrpc::NameRegistration reg(me.rpc, me.nc); const QString val = rec.field("regData").value ().toString (); std::istringstream in(val.toStdString ()); in >> reg; me.pendingRegs.push_back (reg); qDebug () << " " << QString(reg.getName ().c_str ()); }
void Factura::BorrarLineaFactura(int id_lin) { if (id_lin !=0) { QSqlQuery *qrylin_fac = new QSqlQuery(QSqlDatabase::database("empresa")); frmDecision msgBox; msgBox.Inicializar(tr("Borrar línea"),tr("Está a punto de borrar la línea de la factura"), tr("¿Desea continuar?"),"",tr("Sí"),tr("No")); int elegido = msgBox.exec(); if(elegido == 1) { qrylin_fac->prepare("Select * from lin_fac where id = :id_lin"); qrylin_fac->bindValue(":id_lin",id_lin); if (qrylin_fac->exec()) { QSqlRecord record = qrylin_fac->record(); // Reponer Artículo QSqlQuery *QArticulos = new QSqlQuery(QSqlDatabase::database("empresa")); QArticulos->prepare("update articulos set " "nUnidadesVendidas = nUnidadesVendidas -:nCantidad," "nStockReal = nStockReal - :nCantidad2, " "rAcumuladoVentas = rAcumuladoVentas + :rTotal " "where cCodigo= :cCodigo"); QArticulos->bindValue(":dUltimaVenta",QDate::currentDate()); QArticulos->bindValue(":nCantidad",record.field("nCantidad").value().toDouble()); QArticulos->bindValue(":nCantidad2",record.field("nCantidad").value().toDouble()); QArticulos->bindValue(":rTotal",record.field("rTotal").value().toDouble()); QArticulos->bindValue(":cCodigo",record.field("cCodigo").value().toString()); QArticulos->exec(); delete QArticulos; } qrylin_fac->prepare("Delete from lin_fac where id = :id_lin"); qrylin_fac->bindValue(":id_lin",id_lin); if(!qrylin_fac->exec()){ QMessageBox::critical(NULL,tr("Borrar línea"),tr("Falló el borrado de la línea de factura"),tr("&Aceptar")); } delete qrylin_fac; calcularFactura(); } } else { QMessageBox::critical(NULL,tr("Borrar Línea factura"),tr("Debe seleccionar una línea para poder borrar"),tr("OK")); } }
void DataViewer::onDatabaseItemActivated(const DatabaseItem &item) { if ((DatabaseItem::Table != item.m_type) && (DatabaseItem::View != item.m_type)) { return; } d_ptr->database = item.m_database; // for table tableShema QSqlRecord record = item.m_database.record(item.m_value); d_ptr->m_shemaModel->removeRows(0, d_ptr->m_shemaModel->rowCount()); d_ptr->m_shemaModel->insertRows(0, record.count()); for (int i = 0; i < record.count(); ++i) { QSqlField field = record.field(i); d_ptr->m_shemaModel->setData(d_ptr->m_shemaModel->index(i, 0), field.name()); d_ptr->m_shemaModel->setData(d_ptr->m_shemaModel->index(i, 1), field.type() == QVariant::Invalid ? "???" : QString(QVariant::typeToName(field.type()))); d_ptr->m_shemaModel->setData(d_ptr->m_shemaModel->index(i, 2), (field.length() < 0) ? QVariant("???") : field.length()); d_ptr->m_shemaModel->setData(d_ptr->m_shemaModel->index(i, 3), (field.precision() < 0) ? QVariant("???") : field.precision()); d_ptr->m_shemaModel->setData(d_ptr->m_shemaModel->index(i, 4), field.requiredStatus() == QSqlField::Unknown ? "???" : QVariant(bool(field.requiredStatus()))); d_ptr->m_shemaModel->setData(d_ptr->m_shemaModel->index(i, 5), field.isAutoValue()); d_ptr->m_shemaModel->setData(d_ptr->m_shemaModel->index(i, 6), field.defaultValue()); } d_ptr->m_tableShema->setModel(d_ptr->m_shemaModel.data()); d_ptr->m_tableShema->setEditTriggers(QAbstractItemView::NoEditTriggers); d_ptr->m_tableShema->resizeColumnsToContents(); d_ptr->m_tab->setTabText(::Scheme, tr(::c_schemeTable).arg(item.m_value)); // for table tableData QSqlTableModel *modelData = new QSqlTableModel(0, item.m_database); modelData->setEditStrategy(QSqlTableModel::OnRowChange); modelData->setTable(item.m_value); modelData->select(); d_ptr->m_tableData->setModel(modelData); d_ptr->m_tableData->setEditTriggers(QAbstractItemView::DoubleClicked | QAbstractItemView::EditKeyPressed); d_ptr->m_tableData->resizeColumnsToContents(); d_ptr->m_tab->setTabText(::Data, tr(::c_dataTable).arg(item.m_value)); d_ptr->m_sqlDataModel.reset(modelData); }
QString Browser::StructureMYSQLTable( QSqlRecord now ) { QSqlRecord rec = now; QString createtable; QString sqltipename, mkey; QStringList CreateTable; int totalcools = rec.count(); if (totalcools > 0) { /* sqlite3 table construct from odbc converter */ for (int i = 0; i < totalcools; ++i) { QSqlField fld = rec.field(i); QString name = Strtrimmed(fld.name()); name.toUpper(); if (name == "id") { name = "ID"; } QString typeoffield = QString(QVariant::typeToName(fld.type())); int sizefe = fld.length(); if (sizefe > 255) { sizefe = 255; } if (sizefe < 1) { sizefe = 255; } /* fld.isAutoValue() never true from auto_increment mysql ??? */ if (fld.requiredStatus() and i < 2 and typeoffield == "int") { sqltipename = QString(" `%1` INT(%2) NOT NULL auto_increment").arg(name).arg(sizefe); mkey = QString(" KEY `%1` (`%1`)").arg(name); } else if ( typeoffield == "int" ) { sqltipename = QString(" `%1` int(%2) default NULL").arg(name).arg(sizefe); } else if ( typeoffield == "double") { sqltipename = QString(" `%1` int(%2) default NULL").arg(name).arg(sizefe); } else if ( typeoffield == "QByteArray") { sqltipename = QString(" `%1` LONGBLOB default NULL").arg(name); } else { sqltipename = QString(" `%1` VARCHAR(%2) default NULL").arg(name).arg(sizefe); } CreateTable.append(sqltipename); ////////qDebug() << "### fieldname " << name; ///////////qDebug() << "### typeoffield " << typeoffield; } if (mkey.size() > 0) { CreateTable.append(mkey); } QString midlecreate = CreateTable.join(",\n"); midlecreate.prepend(QString("### mysql version 5 or > ###\nDROP TABLE IF EXISTS `%1`;\nCREATE TABLE `%1` (\n").arg(runningtable)); midlecreate.append("\n) TYPE=MyISAM;"); createtable = midlecreate; } return createtable; }
QString repr(QSqlRecord record) { QString record_str; QSqlField field; for(int i=0; i<record.count(); i++) { field = record.field(i); if (field.isNull()) record_str.append(QString("%1 = NULL, ").arg(field.name())); else record_str.append(QString("%1 = %2, ").arg(field.name(), field.value().toString())); } return record_str; }
//load a session in the database bool SessionManager::load(QString id, QMap<QString, QString>& SESS){ QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE"); db.setDatabaseName("sess.db"); if(db.open()){ //Is the session table there ? if(db.tables().indexOf("sessions") == -1){ return false; } QSqlQuery query(db); query.prepare("SELECT * from sessions WHERE id="+id); if(!query.exec()){ return false; } else{ while (query.next()){ QSqlRecord rec = query.record(); SESS.insert("id", rec.field("id").value().toString()); SESS.insert("name", rec.field("name").value().toString()); SESS.insert("hostname", rec.field("hostname").value().toString()); SESS.insert("username", rec.field("username").value().toString()); SESS.insert("password", rec.field("password").value().toString()); SESS.insert("port", rec.field("port").value().toString()); SESS.insert("type", rec.field("type").value().toString()); SESS.insert("initpath", rec.field("initpath").value().toString()); } } }else{ return false; } return true; }
/* Code for the name status functor. */ void MTCredentials::NameStatusFunctor::operator() (const QSqlRecord& rec) { if (found) qDebug () << "ERROR: Found more than one nmc_names entry for Nym " << nym.c_str () << " and cred " << cred.c_str (); found = true; const bool active = rec.field ("active").value ().toInt (); const QString name = rec.field ("name").value ().toString (); const QString updateTx = rec.field ("updateTx").value ().toString (); /* If the active flag is set but the update transaction is currently unconfirmed, mark the entry also as 'pending'. */ bool unconfirmed = false; if (active && nc.getNumberOfConfirmations (updateTx.toStdString ()) == 0) unconfirmed = true; if (!active || unconfirmed) res = tr("pending"); else { nmcrpc::NamecoinInterface::Name nm; nm = nc.queryName (name.toStdString ()); std::string nymSrc; nymSrc = opentxs::OTAPI_Wrap::It()->GetNym_SourceForID (nym); NMC_Verifier verify(nc); if (!verify.verifyCredentialHashAtSource (cred, nymSrc)) res = tr("invalid"); else if (nm.isExpired ()) res = tr("expired"); else { const int expireIn = nm.getExpireCounter (); res = tr("%1 blocks valid").arg (expireIn); } } }
QString accessHelperMove(QString MoveName, QString column) { QSqlRecord rec; bool success = accessMove(MoveName, rec); if( success ) { return rec.field(column).value().toString(); } else { return "-1"; } }
QSqlRecord Query::record() const { QSqlRecord ret = Super::record(); for(int i=0; i<ret.count(); i++) { QSqlField fld = ret.field(i); QString n = QueryBuilder::unmangleLongFieldName(fld.name()); if(n != fld.name()) { fld.setName(n); ret.replace(i, fld); } } return ret; }