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); }
QVariant SchemaModel::data(const QModelIndex &index, int role) const { if (!index.isValid ()) { return QVariant (); } if (role == Qt::DisplayRole) { if (index.row () >= record.count ()) { return QVariant (); } QSqlField field = record.field(index.row()); switch (index.column ()) { case 0: return field.name (); case 1: return QLatin1String (QVariant::typeToName(field.type())); case 2: return field.length (); case 3: { QStringList mods; if (pindex.indexOf (field.name ()) >= 0) { mods << tr("PRIMARY KEY"); } if (field.requiredStatus () == QSqlField::Required) { mods << tr("NOT NULL"); } else if (field.requiredStatus () == QSqlField::Optional) { mods << tr ("NULL"); } if (field.isAutoValue ()) { mods << tr ("AUTO_INCREMENT"); } return mods.join(", "); } case 4: return field.defaultValue (); } } else if (role == Qt::DecorationRole) { } return QVariant (); }
QString QTDSDriver::formatValue(const QSqlField &field, bool trim) const { QString r; if (field.isNull()) r = QLatin1String("NULL"); else if (field.type() == QVariant::DateTime) { if (field.value().toDateTime().isValid()){ r = field.value().toDateTime().toString(QLatin1String("yyyyMMdd hh:mm:ss")); r.prepend(QLatin1String("'")); r.append(QLatin1String("'")); } else r = QLatin1String("NULL"); } else if (field.type() == QVariant::ByteArray) { QByteArray ba = field.value().toByteArray(); QString res; static const char hexchars[] = "0123456789abcdef"; for (int i = 0; i < ba.size(); ++i) { uchar s = (uchar) ba[i]; res += QLatin1Char(hexchars[s >> 4]); res += QLatin1Char(hexchars[s & 0x0f]); } r = QLatin1String("0x") + res; } else {
void Browser::showMetaData(const QString &t) { QSqlRecord rec = connectionWidget->currentDatabase().record(t); QStandardItemModel *model = new QStandardItemModel(table); model->insertRows(0, rec.count()); model->insertColumns(0, 7); model->setHeaderData(0, Qt::Horizontal, "Fieldname"); model->setHeaderData(1, Qt::Horizontal, "Type"); model->setHeaderData(2, Qt::Horizontal, "Length"); model->setHeaderData(3, Qt::Horizontal, "Precision"); model->setHeaderData(4, Qt::Horizontal, "Required"); model->setHeaderData(5, Qt::Horizontal, "AutoValue"); model->setHeaderData(6, Qt::Horizontal, "DefaultValue"); for (int i = 0; i < rec.count(); ++i) { QSqlField fld = rec.field(i); model->setData(model->index(i, 0), fld.name()); model->setData(model->index(i, 1), fld.typeID() == -1 ? QString(QVariant::typeToName(fld.type())) : QString("%1 (%2)").arg(QVariant::typeToName(fld.type())).arg(fld.typeID())); model->setData(model->index(i, 2), fld.length()); model->setData(model->index(i, 3), fld.precision()); model->setData(model->index(i, 4), fld.requiredStatus() == -1 ? QVariant("?") : QVariant(bool(fld.requiredStatus()))); model->setData(model->index(i, 5), fld.isAutoValue()); model->setData(model->index(i, 6), fld.defaultValue()); } table->setModel(model); table->setEditTriggers(QAbstractItemView::NoEditTriggers); updateActions(); }
bool DatabaseDialog::tablesDoNext() { m_databaseStatus->setText( i18n("Retrieving meta data of tables...") ); QStringList tables; { Q3ListViewItem * item = (Q3CheckListItem *) m_tableView->firstChild(); for (; item; item = item->nextSibling()) { if (((Q3CheckListItem * ) item)->isOn()) { tables.append(((Q3CheckListItem * ) item)->text()); } } } if (tables.empty()) { KMessageBox::error( this, i18n("You have to select at least one table.") ); return false; } m_columnView->clear(); QSqlRecord info; for (int i = 0; i < (int) tables.size(); ++i) { info = m_dbConnection.record( tables[i] ); for (int j = 0; j < (int) info.count(); ++j) { QString name = info.fieldName(j); Q3CheckListItem * checkItem = new Q3CheckListItem( m_columnView, name, Q3CheckListItem::CheckBox ); checkItem->setOn(false); m_columnView->insertItem( checkItem ); checkItem->setText( 1, tables[i] ); QSqlField field = info.field(name); checkItem->setText( 2, QVariant::typeToName(field.type()) ); } } m_columnView->setSorting(1, true); m_columnView->sort(); m_columnView->setSorting( -1 ); setValid(m_columns, true); return true; }
QDebug operator<<(QDebug dbg, const QSqlField &f) { dbg.nospace() << "QSqlField(" << f.name() << ", " << QMetaType::typeName(f.type()); if (f.length() >= 0) dbg.nospace() << ", length: " << f.length(); if (f.precision() >= 0) dbg.nospace() << ", precision: " << f.precision(); if (f.requiredStatus() != QSqlField::Unknown) dbg.nospace() << ", required: " << (f.requiredStatus() == QSqlField::Required ? "yes" : "no"); dbg.nospace() << ", generated: " << (f.isGenerated() ? "yes" : "no"); if (f.typeID() >= 0) dbg.nospace() << ", typeID: " << f.typeID(); if (!f.defaultValue().isNull()) dbg.nospace() << ", auto-value: \"" << f.defaultValue() << '\"'; dbg.nospace() << ')'; return dbg.space(); }
QDebug operator<<(QDebug dbg, const QSqlField &f) { #ifndef Q_BROKEN_DEBUG_STREAM dbg.nospace() << "QSqlField(" << f.name() << ", " << QVariant::typeToName(f.type()); if (f.length() >= 0) dbg.nospace() << ", length: " << f.length(); if (f.precision() >= 0) dbg.nospace() << ", precision: " << f.precision(); if (f.requiredStatus() != QSqlField::Unknown) dbg.nospace() << ", required: " << (f.requiredStatus() == QSqlField::Required ? "yes" : "no"); dbg.nospace() << ", generated: " << (f.isGenerated() ? "yes" : "no"); if (f.typeID() >= 0) dbg.nospace() << ", typeID: " << f.typeID(); if (!f.defaultValue().isNull()) dbg.nospace() << ", auto-value: \"" << f.defaultValue() << '\"'; dbg.nospace() << ')'; return dbg.space(); #else qWarning("This compiler doesn't support streaming QSqlField to QDebug"); return dbg; Q_UNUSED(f); #endif }
int Q3SqlCursor::applyPrepared(const QString& q, bool invalidate) { int ar = 0; QSqlQuery* sql = 0; if (invalidate) { sql = (QSqlQuery*)this; d->lastAt = QSql::BeforeFirst; } else { sql = d->query(); } if (!sql) return 0; if (invalidate || sql->lastQuery() != q) { if (!sql->prepare(q)) return 0; } int cnt = 0; int fieldCount = (int)count(); for (int j = 0; j < fieldCount; ++j) { const QSqlField f = d->editBuffer.field(j); if (d->editBuffer.isGenerated(j)) { if (f.type() == QVariant::ByteArray) sql->bindValue(cnt, f.value(), QSql::In | QSql::Binary); else sql->bindValue(cnt, f.value()); cnt++; } } if (sql->exec()) { ar = sql->numRowsAffected(); } return ar; }
bool QgsDb2GeometryColumns::populateLayerProperty( QgsDb2LayerProperty &layer ) { if ( !mQuery.isActive() || !mQuery.next() ) { return false; } layer.schemaName = mQuery.value( 0 ).toString().trimmed(); layer.tableName = mQuery.value( 1 ).toString().trimmed(); layer.geometryColName = mQuery.value( 2 ).toString().trimmed(); layer.type = mQuery.value( 3 ).toString(); if ( mQuery.value( 4 ).isNull() ) { layer.srid.clear(); layer.srsName.clear(); } else { layer.srid = mQuery.value( 4 ).toString(); layer.srsName = mQuery.value( 5 ).toString(); } layer.extents = QStringLiteral( "0 0 0 0" ); // no extents if ( ENV_LUW == mEnvironment ) { if ( !mQuery.value( 6 ).isNull() ) // Don't get values if null { layer.extents = QString( mQuery.value( 6 ).toString() + ' ' + mQuery.value( 7 ).toString() + ' ' + mQuery.value( 8 ).toString() + ' ' + mQuery.value( 9 ).toString() ).trimmed(); } } QgsDebugMsg( QStringLiteral( "layer: %1.%2(%3) type='%4' srid='%5' srsName='%6'" ) .arg( layer.schemaName, layer.tableName, layer.geometryColName, layer.type, layer.srid, layer.srsName ) ); QgsDebugMsg( "Extents: '" + layer.extents + "'" ); layer.pkCols = QStringList(); // Use the Qt functionality to get the primary key information // to set the FID column. // We can only use the primary key if it only has one column and // the type is Integer or BigInt. QString table = QStringLiteral( "%1.%2" ).arg( layer.schemaName, layer.tableName ); QSqlIndex pk = mDatabase.primaryIndex( table ); if ( pk.count() == 1 ) { QSqlField pkFld = pk.field( 0 ); QVariant::Type pkType = pkFld.type(); if ( ( pkType == QVariant::Int || pkType == QVariant::LongLong ) ) { QString fidColName = pk.fieldName( 0 ); layer.pkCols.append( fidColName ); QgsDebugMsg( "pk is: " + fidColName ); } } else { QgsDebugMsg( "Warning: table primary key count is " + QString::number( pk.count() ) ); } layer.pkColumnName = layer.pkCols.size() > 0 ? layer.pkCols.at( 0 ) : QString(); return true; }
/*! Returns a string representation of the \a field value for the database. This is used, for example, when constructing INSERT and UPDATE statements. The default implementation returns the value formatted as a string according to the following rules: \list \i If \a field is character data, the value is returned enclosed in single quotation marks, which is appropriate for many SQL databases. Any embedded single-quote characters are escaped (replaced with two single-quote characters). If \a trimStrings is true (the default is false), all trailing whitespace is trimmed from the field. \i If \a field is date/time data, the value is formatted in ISO format and enclosed in single quotation marks. If the date/time data is invalid, "NULL" is returned. \i If \a field is \link QByteArray bytearray\endlink data, and the driver can edit binary fields, the value is formatted as a hexadecimal string. \i For any other field type, toString() is called on its value and the result of this is returned. \endlist \sa QVariant::toString() */ QString QSqlDriver::formatValue(const QSqlField &field, bool trimStrings) const { const QLatin1String nullTxt("NULL"); QString r; if (field.isNull()) r = nullTxt; else { switch (field.type()) { case QVariant::Int: case QVariant::UInt: if (field.value().type() == QVariant::Bool) r = field.value().toBool() ? QLatin1String("1") : QLatin1String("0"); else r = field.value().toString(); break; #ifndef QT_NO_DATESTRING case QVariant::Date: if (field.value().toDate().isValid()) r = QLatin1Char('\'') + field.value().toDate().toString(Qt::ISODate) + QLatin1Char('\''); else r = nullTxt; break; case QVariant::Time: if (field.value().toTime().isValid()) r = QLatin1Char('\'') + field.value().toTime().toString(Qt::ISODate) + QLatin1Char('\''); else r = nullTxt; break; case QVariant::DateTime: if (field.value().toDateTime().isValid()) r = QLatin1Char('\'') + field.value().toDateTime().toString(Qt::ISODate) + QLatin1Char('\''); else r = nullTxt; break; #endif case QVariant::String: case QVariant::Char: { QString result = field.value().toString(); if (trimStrings) { int end = result.length(); while (end && result.at(end-1).isSpace()) /* skip white space from end */ end--; result.truncate(end); } /* escape the "'" character */ result.replace(QLatin1Char('\''), QLatin1String("''")); r = QLatin1Char('\'') + result + QLatin1Char('\''); break; } case QVariant::Bool: if (field.value().toBool()) r = QLatin1String("1"); else r = QLatin1String("0"); break; case QVariant::ByteArray : { if (hasFeature(BLOB)) { QByteArray ba = field.value().toByteArray(); QString res; static const char hexchars[] = "0123456789abcdef"; for (int i = 0; i < ba.size(); ++i) { uchar s = (uchar) ba[i]; res += QLatin1Char(hexchars[s >> 4]); res += QLatin1Char(hexchars[s & 0x0f]); } r = QLatin1Char('\'') + res + QLatin1Char('\''); break; } } default: r = field.value().toString(); break; } } return r; }
void ODBC_Connection::LoadTableColumns(QTreeWidgetItem *item) { for (int i = 0, count = item->childCount(); i < count; i++) item->removeChild(item->child(0)); QString sTableName = item->text(0); if (m_db.isOpen()) { if (!m_db.tables().contains(sTableName)) // if it isnt a table, return return; // set wait cursor QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); QApplication::processEvents(); Logging::getInstance()->WriteLog(INFORMATION, QString("Retrieving tableinfo for table \"%1\" of connection \"%2\"...").arg(sTableName, m_sConnectionName)); bool bTableWarningShown = false; QSqlRecord records = m_db.record(sTableName); QSqlField field; QSqlIndex index = m_db.primaryIndex(sTableName); QString sName; QSqlQuery query; QString sTypeName; QString sLength; QString sNullable; for (int i = 0, count = records.count(); i < count; i++) { field = records.field(i); sName = field.name(); query = m_db.exec(QString("SELECT DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, NUMERIC_PRECISION, IS_NULLABLE FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME = '%1' AND TABLE_NAME = '%2'").arg(sName, sTableName)); if (query.next()) { sTypeName = query.value(0).toString(); sLength = query.value(1).toString() != "0" ? query.value(1).toString() : query.value(2).toString(); sNullable = query.value(3).toString(); query.finish(); } else { if (!bTableWarningShown) { Logging::getInstance()->WriteLog(WARNING, QString("Couldn't retrieve fieldinfo for table \"%1\" of connection \"%2\", database INFORMATION_SCHEMA.COLUMNS doesn't exist, starting fallback to manual type detection").arg(sTableName, m_sConnectionName)); #ifdef _DEBUG qDebug() << QString("Couldn't retrieve fieldinfo for table \"%1\" of connection \"%2\", database INFORMATION_SCHEMA.COLUMNS doesn't exist, starting fallback to manual type detection").arg(sTableName, m_sConnectionName); #endif bTableWarningShown = true; } sTypeName = QVariant::typeToName(field.type()); sLength = QString().setNum(field.length()); sNullable = (field.requiredStatus() == 1 ? "YES" : "NO"); } bool isPrimaryKey = index.contains(sName) ? true : false; QTreeWidgetItem *pItem = new QTreeWidgetItem(); if (isPrimaryKey) { pItem->setText(0, QString("%1 (PS, %2(%3), %4)").arg(sName, sTypeName, sLength, (sNullable == "YES" ? "NULL" : "NOT NULL"))); pItem->setIcon(0, QIcon(":/ODBC_Query/Resources/primary_key.png")); } else { pItem->setText(0, QString("%1 (%2(%3), %4)").arg(sName, sTypeName, sLength, (sNullable == "YES" ? "NULL" : "NOT NULL"))); pItem->setIcon(0, QIcon(":/ODBC_Query/Resources/row.png")); } item->addChild(pItem); } m_ui.TableTreeWidget->expandItem(item); Logging::getInstance()->WriteLog(INFORMATION, QString("Tableinfo for table \"%1\" of connection \"%2\" retrieved").arg(sTableName, m_sConnectionName)); } else { Logging::getInstance()->WriteLog(ERR, QString("Couldn't retrieve tableinfo for table \"%1\" of connection \"%2\", connection isn't open").arg(sTableName, m_sConnectionName)); #ifdef _DEBUG qDebug() << QString("Couldn't retrieve tableinfo for table \"%1\" of connection \"%2\", connection isn't open").arg(sTableName, m_sConnectionName); #endif } // set back to arrow cursor QApplication::restoreOverrideCursor(); }
void Browser::ExportMysql( QString qx ) { QString tta; QString cfileName = QFileDialog::getSaveFileName(this, "Export MYSQL locale format text",QString(setter.value("lastdirDir").toString()), "*.sql"); bool ok; QString newtablename = QInputDialog::getText(this, tr("You like mysql insert on new table name?"),tr("TableName:"), QLineEdit::Normal,runningtable, &ok); QString msgDB =tr("<p>Append create table command? mysql</p>"); int removeyes = QMessageBox::question(this, tr("Please confirm!"),msgDB, tr("&Yes"), tr("&No"), QString(),8888,9999); QString responder = QString::number(removeyes); if (cfileName.size() > 0) { QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); if (!cfileName.endsWith(".sql")) { cfileName = cfileName+".sql"; } QString dirsave = cfileName.left(cfileName.lastIndexOf("/"))+"/"; setter.setValue("lastdirDir",dirsave); dlg = new QProgressDialog(this,Qt::Popup); dlg->setLabelText (tr("Export table \"%1\"").arg( runningtable )); dlg->setCancelButton(0); QStringList cvslines; QStringList Fname; QStringList Fvalue; cvslines.append(QString("### Created on %1 ###").arg(_PROGRAM_TITLE_)); cvslines.append(QString("### Export from %1 ###").arg(UmanTimeFromUnix(QTime_Null()))); cvslines.append(QString("### Remove comment line if other application not support! ###")); QSqlQuery query(qx,connectionWidget->currentDatabase()); QSqlRecord rec = query.record(); bool window = false; if (responder =="0") { if (runningdriver == "qmysql") { window = OSWinServer(); QString dtabi = SqlCreateTable(runningtable); if (newtablename.size() > 0 ) { if (window) { dtabi.replace("`"+runningtable.toUpper()+"`","`"+newtablename.toUpper()+"`"); } else { dtabi.replace("`"+runningtable+"`","`"+newtablename+"`"); } } cvslines.append(dtabi); } else { cvslines.append(StructureMYSQLTable(rec)); cvslines.append(QString("### Manual rewrite if is from odbc export! ###")); } } if (newtablename.size() > 0 ) { runningtable = newtablename; } bool suppoaffect; int sumcol = rec.count(); int sumrow = query.numRowsAffected(); int recnum = 0; /* QProgressDialog *dlg; */ int pasero = 0; if (sumrow < 1) { suppoaffect = false; sumrow = 1000; } else { suppoaffect = true; } while (query.next()) { recnum++; /* count fake lines */ emit displaystatus(recnum,sumrow); Fvalue.clear(); Fname.clear(); for(int i=0;i<sumcol;i++){ bool oknr; QSqlField fld = rec.field(i); QString value =""; QString typeoffield = QString(QVariant::typeToName(fld.type())); if (typeoffield != "QByteArray") { value = Strsqltrimmed(query.value(i).toString()); } else { value = Strsqltrimmed(query.value(i).toString()); } int vnummer = value.toInt(&oknr); QString fname = Strcsvtrimmed(rec.fieldName(i)); if (oknr) { Fvalue.append(value); } else if (value.isEmpty()) { Fvalue.append("NULL"); } else { Fvalue.append(QString("'%1'").arg(value)); } } QString Dvalue = Fvalue.join(","); if (window) { cvslines.append(QString("REPLACE INTO `%1` VALUES (%2);").arg(runningtable.toUpper()).arg(Dvalue)); } else { cvslines.append(QString("REPLACE INTO `%1` VALUES (%2);").arg(runningtable).arg(Dvalue)); } if (!suppoaffect) { if (recnum == 1001) { recnum = 0; pasero++; dlg->setLabelText (tr("Export table \"%1\" %2x1000 !numRowsAffected").arg( runningtable ).arg(pasero)); } } } QString contentxt = cvslines.join("\n"); ///////////QTextCodec *setcurrentcodec; //////////setcurrentcodec = QTextCodec::codecForMib(106); /* utf8 */ QFile f( cfileName ); if ( f.open( QFile::WriteOnly | QFile::Text ) ) { QTextStream sw( &f ); /////////sw.setCodec(setcurrentcodec); sw << contentxt; f.close(); if (dlg->isVisible ()) { dlg->close(); } } else { if (dlg->isVisible ()) { dlg->close(); } QApplication::restoreOverrideCursor(); QMessageBox::information(this, tr("Error!"),tr("Unable to save to file %1").arg(cfileName)); } QApplication::restoreOverrideCursor(); } }
static QString copy_sql_table(const QString &table_name, const QSqlRecord &dest_rec, qfs::Connection &from_conn, qfs::Connection &to_conn) { qfLogFuncFrame() << table_name; qfInfo() << "Copying table:" << table_name; if(!to_conn.tableExists(table_name)) { qfWarning() << "Destination table" << table_name << "doesn't exist!"; return QString(); } qfs::Query from_q(from_conn); if(!from_q.exec(QString("SELECT * FROM %1").arg(table_name))) { qfWarning() << "Source table" << table_name << "doesn't exist!"; return QString(); } const QSqlRecord src_rec = from_q.record(); // copy only fields which can be found in both records QSqlRecord rec; for (int i = 0; i < dest_rec.count(); ++i) { QString fld_name = dest_rec.fieldName(i); if(src_rec.indexOf(fld_name) >= 0) { qfDebug() << fld_name << "\t added to imported fields since it is present in both databases"; rec.append(dest_rec.field(i)); } } auto *sqldrv = to_conn.driver(); QString qs = sqldrv->sqlStatement(QSqlDriver::InsertStatement, table_name, rec, true); qfDebug() << qs; qfs::Query to_q(to_conn); if(!to_q.prepare(qs)) { return QString("Cannot prepare insert table SQL statement, table: %1.").arg(table_name); } bool has_id_int = false; while(from_q.next()) { if(table_name == QLatin1String("config")) { if(from_q.value(0).toString() == QLatin1String("db.version")) continue; } for (int i = 0; i < rec.count(); ++i) { QSqlField fld = rec.field(i); QString fld_name = fld.name(); //qfDebug() << "copy:" << fld_name << from_q.value(fld_name); QVariant v = from_q.value(fld_name); v.convert(rec.field(i).type()); if(!has_id_int && (fld.type() == QVariant::Int || fld.type() == QVariant::UInt || fld.type() == QVariant::LongLong || fld.type() == QVariant::ULongLong) && fld_name == QLatin1String("id")) { // probably ID INT AUTO_INCREMENT //max_id = qMax(max_id, v.toInt()); has_id_int = true; } to_q.addBindValue(v); } if(!to_q.exec()) return QString("SQL Error: %1").arg(to_q.lastError().text()); } if(has_id_int && to_conn.driverName().endsWith(QLatin1String("PSQL"), Qt::CaseInsensitive)) { // set sequence current value when importing to PSQL qfInfo() << "updating seq number table:" << table_name; if(!to_q.exec("SELECT pg_catalog.setval(pg_get_serial_sequence(" QF_SARG(table_name) ", 'id'), MAX(id)) FROM " QF_CARG(table_name), !qf::core::Exception::Throw)) { return QString("Cannot update sequence counter, table: %1.").arg(table_name); } } return QString(); }
bool DatabaseDialog::tablesDoNext() { m_databaseStatus->setText(i18n("Retrieving meta data of tables...")); QStringList tables; { for (int i = 0; i < m_tableView->count(); ++i) { QListWidgetItem* item = m_tableView->item(i); if (item->checkState() == Qt::Checked) { tables.append(item->text()); } } } if (tables.empty()) { KMessageBox::error(this, i18n("You have to select at least one table.")); return false; } m_columnView->clear(); QSqlRecord info; for (int i = 0; i < (int) tables.size(); ++i) { info = m_dbConnection.record(tables[i]); for (int j = 0; j < (int) info.count(); ++j) { QString name = info.fieldName(j); QSqlField field = info.field(name); QTreeWidgetItem * checkItem = new QTreeWidgetItem(QStringList() << name << tables[i] << QVariant::typeToName(field.type())); checkItem->setFlags(checkItem->flags() | Qt::ItemIsUserCheckable); checkItem->setCheckState(0, Qt::Unchecked); m_columnView->addTopLevelItem(checkItem); } } m_columnView->sortItems(1, Qt::AscendingOrder); setValid(m_columns, true); return true; }
// loadFields() gets the type from the field record void QgsDb2Provider::loadFields() { mAttributeFields.clear(); //mDefaultValues.clear(); QString table = QString( "%1.%2" ).arg( mSchemaName, mTableName ); // Use the Qt functionality to get the fields and their definitions. QSqlRecord r = mDatabase.record( table ); int fieldCount = r.count(); for ( int i = 0; i < fieldCount; i++ ) { QSqlField f = r.field( i ); int typeID = f.typeID(); // seems to be DB2 numeric type id (standard?) QString sqlTypeName = db2TypeName( typeID ); QVariant::Type sqlType = f.type(); QgsDebugMsg( QString( "name: %1; length: %2; sqlTypeID: %3; sqlTypeName: %4" ) .arg( f.name() ).arg( f.length() ).arg( QString::number( typeID ), sqlTypeName ) ); if ( f.name() == mGeometryColName ) continue; // Got this with uri, just skip if ( sqlType == QVariant::String ) { mAttributeFields.append( QgsField( f.name(), sqlType, sqlTypeName, f.length() ) ); } else if ( sqlType == QVariant::Double ) { mAttributeFields.append( QgsField( f.name(), sqlType, sqlTypeName, f.length(), f.precision() ) ); } else { mAttributeFields.append( QgsField( f.name(), sqlType, sqlTypeName ) ); } if ( !f.defaultValue().isNull() ) { mDefaultValues.insert( i, f.defaultValue() ); } // Hack to get primary key since the primaryIndex function above doesn't work // on z/OS. Pick first integer column. if ( mFidColName.length() == 0 && ( sqlType == QVariant::LongLong || sqlType == QVariant::Int ) ) { mFidColName = f.name(); } } }