static PyObject *meth_QSqlIndex_setCursorName(PyObject *sipSelf, PyObject *sipArgs)
{
    PyObject *sipParseErr = NULL;

    {
        const QString* a0;
        int a0State = 0;
        QSqlIndex *sipCpp;

        if (sipParseArgs(&sipParseErr, sipArgs, "BJ1", &sipSelf, sipType_QSqlIndex, &sipCpp, sipType_QString,&a0, &a0State))
        {
            Py_BEGIN_ALLOW_THREADS
            sipCpp->setCursorName(*a0);
            Py_END_ALLOW_THREADS
            sipReleaseType(const_cast<QString *>(a0),sipType_QString,a0State);

            Py_INCREF(Py_None);
            return Py_None;
        }
    }

    /* Raise an exception if the arguments couldn't be parsed. */
    sipNoMethod(sipParseErr, sipName_QSqlIndex, sipName_setCursorName, doc_QSqlIndex_setCursorName);

    return NULL;
}
Esempio n. 2
0
static QSqlIndex qGetTableInfo(QSqlQuery &q, const QString &tableName, bool onlyPIndex = false)
{
    QString schema;
    QString table(tableName);
    int indexOfSeparator = tableName.indexOf(QLatin1Char('.'));
    if (indexOfSeparator > -1) {
        schema = tableName.left(indexOfSeparator).append(QLatin1Char('.'));
        table = tableName.mid(indexOfSeparator + 1);
    }
    q.exec(QLatin1String("PRAGMA ") + schema + QLatin1String("table_info (") + _q_escapeIdentifier(table) + QLatin1String(")"));

    QSqlIndex ind;
    while (q.next()) {
        bool isPk = q.value(5).toInt();
        if (onlyPIndex && !isPk)
            continue;
        QString typeName = q.value(2).toString().toLower();
        QSqlField fld(q.value(1).toString(), qGetColumnType(typeName));
        if (isPk && (typeName == QLatin1String("integer")))
            // INTEGER PRIMARY KEY fields are auto-generated in sqlite
            // INT PRIMARY KEY is not the same as INTEGER PRIMARY KEY!
            fld.setAutoValue(true);
        fld.setRequired(q.value(3).toInt() != 0);
        fld.setDefaultValue(q.value(4));
        ind.append(fld);
    }
    return ind;
}
Esempio n. 3
0
static QSqlIndex qGetTableInfo(QSqlQuery &q, QString &tableName, bool onlyPIndex = false)
{   
    QString dbName;
    QString table(tableName);
    int indexOfSeparator = tableName.indexOf(QLatin1Char('.'));
    if (indexOfSeparator > -1) {
        dbName = tableName.left(indexOfSeparator +1 );
        table = tableName.mid(indexOfSeparator + 1);
    }
    q.exec(QLatin1String("PRAGMA ") + dbName + QLatin1String("table_info (") + _q_escapeIdentifier(table) + QLatin1String(")"));

    const int NAME_IDX = 1;
    const int TYPE_IDX = 2;
    const int NOTNULL_IDX = 3;
    const int DFLT_VALUE_IDX = 4;
    const int PK_IDX = 5;    
    
    QSqlIndex ind;
    while (q.next()) {
        bool isPk = q.value(PK_IDX).toInt();
        if (onlyPIndex && !isPk)
            continue;
        QString typeName = q.value(TYPE_IDX).toString().toLower();
        QSqlField fld(q.value(NAME_IDX).toString(), qGetColumnType(typeName));
        if (isPk && (typeName == QLatin1String("integer")))
            // INTEGER PRIMARY KEY fields are auto-generated in sqlite
            // INT PRIMARY KEY is not the same as INTEGER PRIMARY KEY!
            fld.setAutoValue(true);
        fld.setRequired(q.value(NOTNULL_IDX).toInt() != 0);
        fld.setDefaultValue(q.value(DFLT_VALUE_IDX));
        ind.append(fld);
    }
    return ind;
}
Esempio n. 4
0
static int compare_recs(const QSqlRecord* buf1, const QSqlRecord* buf2,
                         const QSqlIndex& idx)
{
    int cmp = 0;

    int i = 0;
    const QString fn(idx.field(i).name());
    const QSqlField f1 = buf1->field(fn);

    if (f1.isValid()) {
        switch (f1.type()) { // ### more types?
        case QVariant::String:
            cmp = f1.value().toString().trimmed().compare(
                          buf2->value(fn).toString().trimmed());
            break;
        default:
            if (f1.value().toDouble() < buf2->value(fn).toDouble())
                cmp = -1;
            else if (f1.value().toDouble() > buf2->value(fn).toDouble())
                cmp = 1;
        }
    }

    if (idx.isDescending(i))
        cmp = -cmp;
    return cmp;
}
Esempio n. 5
0
int Q3SqlCursor::del(bool invalidate)
{
    QSqlIndex idx = primaryIndex(false);
    if (idx.isEmpty())
        return del(qWhereClause(&d->editBuffer, d->nm, QLatin1String("and"), driver()), invalidate);
    return del(toString(primaryIndex(), &d->editBuffer, d->nm, QString(QLatin1Char('=')), QLatin1String("and")), invalidate);
}
Esempio n. 6
0
QString qOrderByClause( const QSqlIndex & i, const QString& prefix = QString::null )
{
    QString str;
    int k = i.count();
    if( k == 0 ) return QString::null;
    str = " order by " + i.toString( prefix );
    return str;
}
Esempio n. 7
0
int QSqlCursor::del( bool invalidate )
{
    QSqlIndex idx = primaryIndex( FALSE );
    if ( idx.isEmpty() )
        return del( qWhereClause( &d->editBuffer, d->nm, "and", driver() ), invalidate );
    else
	return del( toString( primaryIndex(), &d->editBuffer, d->nm,
			  "=", "and" ), invalidate );
}
Esempio n. 8
0
QString qOrderByClause(const QSqlIndex & i, const QString& prefix = QString())
{
    QString str;
    int k = i.count();
    if(k == 0)
        return QString();
    str = QLatin1String(" order by ") + i.toString(prefix);
    return str;
}
Esempio n. 9
0
QString getPrimary(QSqlDatabase &db, QString sTable)
{
  QString sPrimary = "kbrecordid";

  QSqlIndex i = db.driver()->primaryIndex(sTable);
  if (i.count()){
    sPrimary = i.fieldName(0);
  }
  return sPrimary;
}
Esempio n. 10
0
QSqlRecord* QSqlCursor::primeUpdate()
{
    // memorize the primary keys as they were before the user changed the values in editBuffer
    QSqlRecord* buf = editBuffer( TRUE );
    QSqlIndex idx = primaryIndex( FALSE );
    if ( !idx.isEmpty() )
	d->editIndex = toString( idx, buf, d->nm, "=", "and" );
    else
	d->editIndex = qWhereClause( buf, d->nm, "and", driver() );
    return buf;
}
Esempio n. 11
0
QSqlRecord* Q3SqlCursor::primeUpdate()
{
    // memorize the primary keys as they were before the user changed the values in editBuffer
    QSqlRecord* buf = editBuffer(true);
    QSqlIndex idx = primaryIndex(false);
    if (!idx.isEmpty())
        d->editIndex = toString(idx, buf, d->nm, QString(QLatin1Char('=')), QLatin1String("and"));
    else
        d->editIndex = qWhereClause(buf, d->nm, QLatin1String("and"), driver());
    return buf;
}
int TableSchema::primaryKeyIndex() const
{
    QSqlTableModel model;
    model.setTable(tablename);
    QSqlIndex index = model.primaryKey();
    if (index.isEmpty()) {
        return -1;
    }

    QSqlField fi = index.field(0);
    return model.record().indexOf(fi.name());
}
QString TableSchema::primaryKeyFieldName() const
{
    QSqlTableModel model;
    model.setTable(tablename);
    QSqlIndex index = model.primaryKey();
    if (index.isEmpty()) {
        return QString();
    }

    QSqlField fi = index.field(0);
    return fi.name();
}
Esempio n. 14
0
QSqlIndex Q3SqlCursor::index(const QStringList& fieldNames) const
{
    QSqlIndex idx;
    for (QStringList::ConstIterator it = fieldNames.begin(); it != fieldNames.end(); ++it) {
        QSqlField f = field((*it));
        if (!f.isValid()) { /* all fields must exist */
            idx.clear();
            break;
        }
        idx.append(f);
    }
    return idx;
}
Esempio n. 15
0
static bool index_matches(const Q3SqlCursor* cur, const QSqlRecord* buf,
                           const QSqlIndex& idx)
{
    bool indexEquals = false;
    for (int i = 0; i < idx.count(); ++i) {
        const QString fn(idx.field(i).name());
        if (cur->value(fn) == buf->value(fn))
            indexEquals = true;
        else {
            indexEquals = false;
            break;
        }
    }
    return indexEquals;
}
Esempio n. 16
0
bool QSqlCursor::select( const QString & filter, const QSqlIndex & sort )
{
    QString fieldList = toString( d->nm );
    if ( fieldList.isEmpty() )
	return FALSE;
    QString str= "select " + fieldList;
    str += " from " + d->nm;
    if ( !filter.isEmpty() ) {
	d->ftr = filter;
	str += " where " + filter;
    } else
	d->ftr = QString::null;
    if ( sort.count() > 0 )
	str += " order by " + sort.toString( d->nm );
    d->srt = sort;
    return exec( str );
}
Esempio n. 17
0
bool Q3SqlCursor::select(const QString & filter, const QSqlIndex & sort)
{
    QString fieldList(toString(d->nm));
    if (fieldList.isEmpty())
        return false;
    QString str(QLatin1String("select ") + fieldList);
    str += QLatin1String(" from ") + d->nm;
    if (!filter.isEmpty()) {
        d->ftr = filter;
        str += QLatin1String(" where ") + filter;
    } else
        d->ftr.clear();
    if (sort.count() > 0)
        str += QLatin1String(" order by ") + sort.toString(d->nm);
    d->srt = sort;
    return exec(str);
}
Esempio n. 18
0
void tst_QSqlDriver::primaryIndex()
{
    QFETCH_GLOBAL(QString, dbName);
    QSqlDatabase db = QSqlDatabase::database(dbName);
    CHECK_DATABASE(db);

    QString tablename(qTableName("relTEST1", __FILE__));
    //check that we can get primary index using unquoted mixed case table name
    QSqlIndex index = db.driver()->primaryIndex(tablename);
    QCOMPARE(index.count(), 1);

    if( db.driverName().startsWith("QIBASE") || db.driverName().startsWith("QOCI") || db.driverName().startsWith("QDB2"))
        QCOMPARE(index.fieldName(0), QString::fromLatin1("ID"));
    else
        QCOMPARE(index.fieldName(0), QString::fromLatin1("id"));


    //check that we can get the primary index using a quoted tablename
    if( db.driverName().startsWith("QIBASE") || db.driverName().startsWith("QOCI") || db.driverName().startsWith("QDB2"))
        tablename = tablename.toUpper();
    else if (db.driverName().startsWith("QPSQL"))
        tablename = tablename.toLower();

    if(!db.driverName().startsWith("QODBC") && !db.databaseName().contains("PostgreSql")) {
        index = db.driver()->primaryIndex(db.driver()->escapeIdentifier(tablename, QSqlDriver::TableName));
        QCOMPARE(index.count(), 1);
    }
    if( db.driverName().startsWith("QIBASE") || db.driverName().startsWith("QOCI") || db.driverName().startsWith("QDB2"))
        QCOMPARE(index.fieldName(0), QString::fromLatin1("ID"));
    else
        QCOMPARE(index.fieldName(0), QString::fromLatin1("id"));



    //check that we can not get the primary index using a quoted but incorrect table name casing
    if( db.driverName().startsWith("QIBASE") || db.driverName().startsWith("QOCI") || db.driverName().startsWith("QDB2"))
        tablename = tablename.toLower();
    else if (db.driverName().startsWith("QPSQL"))
        tablename = tablename.toUpper();

    index = db.driver()->primaryIndex(db.driver()->escapeIdentifier(tablename, QSqlDriver::TableName));
    if (tst_Databases::isMySQL(db)
      || db.driverName().startsWith("QSQLITE")
      || db.driverName().startsWith("QTDS")
      || tst_Databases::isSqlServer(db)
      || tst_Databases::isMSAccess(db))
        QCOMPARE(index.count(), 1); //mysql will always find the table name regardless of casing
    else
        QCOMPARE(index.count(), 0);
}
Esempio n. 19
0
QString QSqlCursor::toString( const QSqlIndex& i, QSqlRecord* rec, const QString& prefix,
				const QString& fieldSep, const QString& sep ) const
{
    QString filter;
    bool separator = FALSE;
    for( uint j = 0; j < i.count(); ++j ){
	if ( rec->isGenerated( j ) ) {
	    if( separator ) {
		filter += " " + sep + " " ;
	    }
	    QString fn = i.fieldName( j );
	    QSqlField* f = rec->field( fn );
	    filter += toString( prefix, f, fieldSep );
	    separator = TRUE;
	}
    }
    return filter;
}
Esempio n. 20
0
QString Q3SqlCursor::toString(const QSqlIndex& i, QSqlRecord* rec, const QString& prefix,
                                const QString& fieldSep, const QString& sep) const
{
    QString filter;
    bool separator = false;
    for(int j = 0; j < i.count(); ++j){
        if (rec->isGenerated(j)) {
            if(separator) {
                filter += QLatin1Char(' ') + sep + QLatin1Char(' ') ;
            }
            QString fn = i.fieldName(j);
            QSqlField f = rec->field(fn);
            filter += toString(prefix, &f, fieldSep);
            separator = true;
        }
    }
    return filter;
}
Esempio n. 21
0
QSqlIndex QMYSQLDriver::primaryIndex( const QString& tablename ) const
{
    QSqlIndex idx;
    if ( !isOpen() )
	return idx;
    QSqlQuery i = createQuery();
    QString stmt( "show index from %1;" );
    QSqlRecord fil = record( tablename );
    i.exec( stmt.arg( tablename ) );
    while ( i.isActive() && i.next() ) {
	if ( i.value(2).toString() == "PRIMARY" ) {
	    idx.append( *fil.field( i.value(4).toString() ) );
	    idx.setCursorName( i.value(0).toString() );
	    idx.setName( i.value(2).toString() );
	}
    }
    return idx;
}
Esempio n. 22
0
static QSqlIndex indexFromStringList(const QStringList& l, const Q3SqlCursor* cursor)
{
    QSqlIndex newSort;
    for (int i = 0; i < l.count(); ++i) {
        QString f = l[i];
        bool desc = false;
        if (f.mid(f.length()-3) == QLatin1String("ASC"))
            f = f.mid(0, f.length()-3);
        if (f.mid(f.length()-4) == QLatin1String("DESC")) {
            desc = true;
            f = f.mid(0, f.length()-4);
        }
        int dot = f.lastIndexOf(QLatin1Char('.'));
        if (dot != -1)
            f = f.mid(dot+1);
        const QSqlField field = cursor->field(f.trimmed());
        if (field.isValid())
            newSort.append(field, desc);
        else
            qWarning("QSqlIndex::indexFromStringList: unknown field: '%s'", f.latin1());
    }
    return newSort;
}
Esempio n. 23
0
//## possibly add sizeHint parameter
bool Q3SqlCursorManager::findBuffer(const QSqlIndex& idx, int atHint)
{
#ifdef QT_DEBUG_DATAMANAGER
    qDebug("Q3SqlCursorManager::findBuffer:");
#endif
    Q3SqlCursor* cur = cursor();
    if (!cur)
        return false;
    if (!cur->isActive())
        return false;
    if (!idx.count()) {
        if (cur->at() == QSql::BeforeFirst)
            cur->next();
        return false;
    }
    QSqlRecord* buf = cur->editBuffer();
    bool indexEquals = false;
#ifdef QT_DEBUG_DATAMANAGER
    qDebug(" Checking hint...");
#endif
    /* check the hint */
    if (cur->seek(atHint))
        indexEquals = index_matches(cur, buf, idx);

    if (!indexEquals) {
#ifdef QT_DEBUG_DATAMANAGER
        qDebug(" Checking current page...");
#endif
        /* check current page */
        int pageSize = 20;
        int startIdx = qMax(atHint - pageSize, 0);
        int endIdx = atHint + pageSize;
        for (int j = startIdx; j <= endIdx; ++j) {
            if (cur->seek(j)) {
                indexEquals = index_matches(cur, buf, idx);
                if (indexEquals)
                    break;
            }
        }
    }

    if (!indexEquals && cur->driver()->hasFeature(QSqlDriver::QuerySize)
         && cur->sort().count()) {
#ifdef QT_DEBUG_DATAMANAGER
        qDebug(" Using binary search...");
#endif
        // binary search based on record buffer and current sort fields
        int lo = 0;
        int hi = cur->size();
        int mid;
        if (compare_recs(buf, cur, cur->sort()) >= 0)
            lo = cur->at();
        while (lo != hi) {
            mid = lo + (hi - lo) / 2;
            if (!cur->seek(mid))
                break;
            if (index_matches(cur, buf, idx)) {
                indexEquals = true;
                break;
            }
            int c = compare_recs(buf, cur, cur->sort());
            if (c < 0) {
                hi = mid;
            } else if (c == 0) {
                // found it, but there may be duplicates
                int at = mid;
                do {
                    mid--;
                    if (!cur->seek(mid))
                        break;
                    if (index_matches(cur, buf, idx)) {
                        indexEquals = true;
                        break;
                    }
                } while (compare_recs(buf, cur, cur->sort()) == 0);

                if (!indexEquals) {
                    mid = at;
                    do {
                        mid++;
                        if (!cur->seek(mid))
                            break;
                        if (index_matches(cur, buf, idx)) {
                            indexEquals = true;
                            break;
                        }
                    } while (compare_recs(buf, cur, cur->sort()) == 0);
                }
                break;
            } else if (c > 0) {
                lo = mid + 1;
            }
        }
    }

    if (!indexEquals) {
#ifdef QT_DEBUG_DATAMANAGER
        qDebug(" Using brute search...");
#endif
#ifndef QT_NO_CURSOR
        QApplication::setOverrideCursor(Qt::WaitCursor);
#endif
        /* give up, use brute force */
        int startIdx = 0;
        if (cur->at() != startIdx) {
            cur->seek(startIdx);
        }
        for (;;) {
            indexEquals = false;
            indexEquals = index_matches(cur, buf, idx);
            if (indexEquals)
                break;
            if (!cur->next())
                break;
        }
#ifndef QT_NO_CURSOR
        QApplication::restoreOverrideCursor();
#endif
    }
#ifdef QT_DEBUG_DATAMANAGER
        qDebug(" Done, result:" + QString::number(indexEquals));
#endif
    return indexEquals;
}
Esempio n. 24
0
/*!
 *\~english
 *	Initialisation the widget on form loaded in engine.
 *\~russian
 *	Инициализация виджета при загрузке в форму инжина.
 *\~
 */
void
wDBTable::init(aDatabase *adb, aEngine *e )
{

	aLog::print(aLog::Debug, tr("wDBTable init in engine "));
//	printf("begin init wdbtable\n");
	unsigned int countField,i;
	aCfgItem o, own;
	QString str, ctype;
	QStringList lst,lstHead,lstWidth;
	int tid;
	aWidget *container = NULL;

	t_doc = rcIcon( "t_doc.png" );
        t_doc_d = rcIcon( "t_doc_d.png" );
        t_doc_t = rcIcon( "t_doc_t.png" );
        t_doc_m = rcIcon( "t_doc_m.png" );
        t_doc_tm = rcIcon( "t_doc_tm.png" );
	t_cat_e = rcIcon( "t_cat_e.png" );
        t_cat_ed = rcIcon( "t_cat_ed.png" );
	t_cat_g = rcIcon( "t_cat_g.png" );
	t_cat_gd = rcIcon( "t_cat_gd.png" );

	engine = e;
	setConfirmDelete(true);
	db = adb;
	md = &adb->cfg;
	tid = property("TableInd").toInt();
	container = aWidget::parentContainer( this );
	if ( !container )
	{
		aLog::print(aLog::Error, tr("wDBTable not in Ananas object container "));
		return; //printf("!no wDBTable parent container\n");
	}
	else
	{
		o = md->objTable( container->getId(), tid );
		if ( o.isNull() )
		{
			//debug_message("Table not found\n");
			aLog::print(aLog::Error, tr("wDBTable init meta object not found "));
		}
		ctype = container->className();
		aLog::print(aLog::Info, tr("wDBTable container type is %1 ").arg(ctype));

		setContainerType(ctype);
	}

	//o  = md->find(property("TableInd").toInt());
	if ( o.isNull() )
	{
		aLog::print(aLog::Error, tr("wDBTable init meta object not found "));
		return;
	}
	countField = numCols();
	for(i=0; i<countField;i++)
	{
		removeColumn(0);
	}
	aSQLTable *tbl = NULL;
	//printf("ctype = %s\n",( const char *) ctype );
	if ( containerType() == "wDocument" )
	{
		QString flt;
		flt = QString("idd=%1").arg(container->uid());
		aLog::print(aLog::Info, tr("wDBTable filter is %1 ").arg(flt));
		setFilter(flt);
		//TODO: fix memory leak
		tbl = new aSQLTable( o, adb );
//		printf("new table ok\n");
	//	tbl->first();

	}
	if ( containerType() == "wCatalogue" ) {
                tbl = container->table(); //new aSQLTable( o, adb );
		setFilter(QString("idg=0"));
		newDataId(0);
		tbl->append( Q3SqlFieldInfo("system_icon") );
//		tbl->setGenerated( "system_icon", false );
		tbl->setCalculated("system_icon", true );
          }
	if ( containerType() == "wJournal" ) {
		tbl = container->table(); //new aSQLTable( o, adb );
		tbl->setMode( 0 );
		tbl->append( Q3SqlFieldInfo( "system_icon" ) );
//		tbl->setGenerated( "system_icon", false );
		tbl->setCalculated( "system_icon", true );
//		tbl->append( QSqlFieldInfo( "t1" ) );
//		tbl->setGenerated( "t1", false );
//		tbl->setCalculated("t1", true );
        }
	refresh();
	cur->clear();
	setSqlCursor(tbl,true);
	refresh(RefreshColumns);
	countField = numCols();
	lst = property("DefIdList").toStringList();
	lstHead = property("DefHeaders").toStringList();
	lstWidth = property("ColWidth").toStringList();
	for ( i = 0; i < countField; i++ )
	{
		//remove all columns in wDBTable, not in sql cursor
		removeColumn( 0 );
		QString s = sqlCursor()->fieldName(i);
//		printf(">>>>s = %s\n",s.ascii());
//		if(sqlCursor()->isCalculated(s))
//		{
//			if((s.left(7)=="text_uf" && lst.findIndex(s.mid(7))!=-1) || s == "system_icon")
//			{
//				continue;
//			}
			// not calculate field, if is not contents in wDBTable
//			sqlCursor()->setCalculated(sqlCursor()->fieldName(i),false);
//		}
	}
	if ( containerType() == "wJournal" ) {
		addColumn( "system_icon", "", 20 );
		setColumnReadOnly( 0, true );
		if (md->objClass(*(container->getMDObject()))==md_journal && !((aDocJournal*) container->dataObject())->type() ) {
			// we have common journal
			// Insert journal system columns.
			addColumn( "ddate", tr("Date"), 100 );
			addColumn( "pnum", tr("Prefix"), 200 );
			addColumn( "num", tr("Number"), 100 );
		}
	}
	if ( containerType() == "wCatalogue" ) {
		addColumn( "system_icon", "", 20 );
	//	printf("set column ro\n");
		setColumnReadOnly( 0, true );
	}

	if ( containerType() == "wDocument" || containerType() == "wCatalogue" ) {

	// Задаем сортировку по индентификатору в обратном порядке для
	// табличной части документа
	// чтобы при добавлении новых позиций в список строки не скакали
	    QSqlIndex pk = sqlCursor()->primaryIndex();
	    pk.setDescending( 0, false);
	    setSort( pk );
	    sqlCursor()->select();
	    sqlCursor()->first();
	    refresh();
	}


	//refresh(RefreshColumns);
	if (md->objClass(*(container->getMDObject()))!=md_journal || ((aDocJournal*) container->dataObject())->type() ) {
		// we have not common journal
		for(i=0; i<lst.count();i++)
		{
			// assemble sql table field names
			if ( containerType() == "wJournal" )
			{
//				str = journalFieldName(lst[i].toLong());

				str = "uf"+QString::number(journalFieldId(lst[i].toLong()));
				//printf(">>>>>>ss=%s\n",str.ascii());
			}
			else
			{
				str = "uf"+lst[i];
			}
			// add defined fields
			addColumn(str,lstHead[i],lstWidth[i].toInt());
		}
	}
	refresh(RefreshAll);
	setWFieldEditor();
	aLog::print(aLog::Debug, tr("wDBTable init in engine ok"));
}
Esempio n. 25
0
/*
   SQLite dbs have no user name, passwords, hosts or ports.
   just file names.
*/
bool QSQLiteDriver::open(const QString & db, const QString &, const QString &, const QString &, int, const QString &conOpts)
{
    if (isOpen())
        close();

    if (db.isEmpty())
        return false;
    bool sharedCache = false;
    int openMode = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, timeOut=5000;
    QStringList opts=QString(conOpts).remove(QLatin1Char(' ')).split(QLatin1Char(';'));
    foreach(const QString &option, opts) {
        if (option.startsWith(QLatin1String("QSQLITE_BUSY_TIMEOUT="))) {
            bool ok;
            int nt = option.mid(21).toInt(&ok);
            if (ok)
                timeOut = nt;
        }
        if (option == QLatin1String("QSQLITE_OPEN_READONLY"))
            openMode = SQLITE_OPEN_READONLY;
        if (option == QLatin1String("QSQLITE_ENABLE_SHARED_CACHE"))
            sharedCache = true;
    }

    sqlite3_enable_shared_cache(sharedCache);

#ifndef QT_WEBOS
    if (sqlite3_open_v2(db.toUtf8().constData(), &d->access, openMode, NULL) == SQLITE_OK) {
#else // QT_WEBOS
#if SQLITE_VERSION_NUMBER >= 3005000
    if (sqlite3_open_v2(db.toUtf8().constData(), &d->access, openMode, NULL) == SQLITE_OK) {
#else
	if (sqlite3_open(db.toUtf8().constData(), &d->access) == SQLITE_OK) {
#endif
#endif // QT_WEBOS
        sqlite3_busy_timeout(d->access, timeOut);
        setOpen(true);
        setOpenError(false);
        return true;
    } else {
        setLastError(qMakeError(d->access, tr("Error opening database"),
                     QSqlError::ConnectionError));
        setOpenError(true);
        return false;
    }
}

void QSQLiteDriver::close()
{
    if (isOpen()) {
        foreach (QSQLiteResult *result, d->results)
            result->d->finalize();

        if (sqlite3_close(d->access) != SQLITE_OK)
            setLastError(qMakeError(d->access, tr("Error closing database"),
                                    QSqlError::ConnectionError));
        d->access = 0;
        setOpen(false);
        setOpenError(false);
    }
}

QSqlResult *QSQLiteDriver::createResult() const
{
    return new QSQLiteResult(this);
}

bool QSQLiteDriver::beginTransaction()
{
    if (!isOpen() || isOpenError())
        return false;

    QSqlQuery q(createResult());
    if (!q.exec(QLatin1String("BEGIN"))) {
        setLastError(QSqlError(tr("Unable to begin transaction"),
                               q.lastError().databaseText(), QSqlError::TransactionError));
        return false;
    }

    return true;
}

bool QSQLiteDriver::commitTransaction()
{
    if (!isOpen() || isOpenError())
        return false;

    QSqlQuery q(createResult());
    if (!q.exec(QLatin1String("COMMIT"))) {
        setLastError(QSqlError(tr("Unable to commit transaction"),
                               q.lastError().databaseText(), QSqlError::TransactionError));
        return false;
    }

    return true;
}

bool QSQLiteDriver::rollbackTransaction()
{
    if (!isOpen() || isOpenError())
        return false;

    QSqlQuery q(createResult());
    if (!q.exec(QLatin1String("ROLLBACK"))) {
        setLastError(QSqlError(tr("Unable to rollback transaction"),
                               q.lastError().databaseText(), QSqlError::TransactionError));
        return false;
    }

    return true;
}

QStringList QSQLiteDriver::tables(QSql::TableType type) const
{
    QStringList res;
    if (!isOpen())
        return res;

    QSqlQuery q(createResult());
    q.setForwardOnly(true);

    QString sql = QLatin1String("SELECT name FROM sqlite_master WHERE %1 "
                                "UNION ALL SELECT name FROM sqlite_temp_master WHERE %1");
    if ((type & QSql::Tables) && (type & QSql::Views))
        sql = sql.arg(QLatin1String("type='table' OR type='view'"));
    else if (type & QSql::Tables)
        sql = sql.arg(QLatin1String("type='table'"));
    else if (type & QSql::Views)
        sql = sql.arg(QLatin1String("type='view'"));
    else
        sql.clear();

    if (!sql.isEmpty() && q.exec(sql)) {
        while(q.next())
            res.append(q.value(0).toString());
    }

    if (type & QSql::SystemTables) {
        // there are no internal tables beside this one:
        res.append(QLatin1String("sqlite_master"));
    }

    return res;
}

static QSqlIndex qGetTableInfo(QSqlQuery &q, const QString &tableName, bool onlyPIndex = false)
{
    QString schema;
    QString table(tableName);
    int indexOfSeparator = tableName.indexOf(QLatin1Char('.'));
    if (indexOfSeparator > -1) {
        schema = tableName.left(indexOfSeparator).append(QLatin1Char('.'));
        table = tableName.mid(indexOfSeparator + 1);
    }
    q.exec(QLatin1String("PRAGMA ") + schema + QLatin1String("table_info (") + _q_escapeIdentifier(table) + QLatin1String(")"));

    QSqlIndex ind;
    while (q.next()) {
        bool isPk = q.value(5).toInt();
        if (onlyPIndex && !isPk)
            continue;
        QString typeName = q.value(2).toString().toLower();
        QSqlField fld(q.value(1).toString(), qGetColumnType(typeName));
        if (isPk && (typeName == QLatin1String("integer")))
            // INTEGER PRIMARY KEY fields are auto-generated in sqlite
            // INT PRIMARY KEY is not the same as INTEGER PRIMARY KEY!
            fld.setAutoValue(true);
        fld.setRequired(q.value(3).toInt() != 0);
        fld.setDefaultValue(q.value(4));
        ind.append(fld);
    }
    return ind;
}
Esempio n. 26
0
void Q3SqlCursorManager::setSort(const QSqlIndex& sort)
{
    setSort(sort.toStringList());
}
Esempio n. 27
0
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();
}
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;
}