Skip to content
Permalink
Browse files

[Spatialite provider] prefer rowid as primary key where available

Adapted from 1050174 without the cleanups.

fixes #14575, fixes #14626, fixes #14999
  • Loading branch information
rouault committed Jun 13, 2016
1 parent 4d1790a commit 69e3c6f778d86d1e7d5279a90f513e337e3e2328
@@ -568,6 +568,11 @@ QgsSpatiaLiteProvider::QgsSpatiaLiteProvider( QString const &uri )
return;
}

if ( mTableBased && hasRowid() )
{
mPrimaryKey = "ROWID";
}

// retrieve version information
spatialiteVersion();

@@ -649,9 +654,6 @@ void QgsSpatiaLiteProvider::loadFieldsAbstractInterface( gaiaVectorLayerPtr lyr
fld = fld->Next;
}

mPrimaryKey.clear();
mPrimaryKeyAttrs.clear();

QString sql = QString( "PRAGMA table_info(%1)" ).arg( quotedIdentifier( mTableName ) );

char **results;
@@ -668,8 +670,10 @@ void QgsSpatiaLiteProvider::loadFieldsAbstractInterface( gaiaVectorLayerPtr lyr
if ( pk.toInt() == 0 )
continue;

if ( mPrimaryKey.isEmpty() )
if ( mPrimaryKeyAttrs.isEmpty() )
mPrimaryKey = name;
else
mPrimaryKey.clear();
mPrimaryKeyAttrs << i - 1;
}
}
@@ -766,7 +770,10 @@ void QgsSpatiaLiteProvider::loadFields()
{
// found a Primary Key column
pkCount++;
pkName = name;
if ( mPrimaryKeyAttrs.isEmpty() )
pkName = name;
else
pkName.clear();
mPrimaryKeyAttrs << i - 1;
QgsDebugMsg( "found primaryKey " + name );
}
@@ -841,7 +848,10 @@ void QgsSpatiaLiteProvider::loadFields()
if ( name == mPrimaryKey )
{
pkCount++;
pkName = name;
if ( mPrimaryKeyAttrs.isEmpty() )
pkName = name;
else
pkName.clear();
mPrimaryKeyAttrs << i - 1;
QgsDebugMsg( "found primaryKey " + name );
}
@@ -939,6 +949,17 @@ bool QgsSpatiaLiteProvider::hasTriggers()
return ( ret == SQLITE_OK && rows > 0 );
}

bool QgsSpatiaLiteProvider::hasRowid()
{
if ( attributeFields.fieldNameIndex( "ROWID" ) >= 0 )
return false;

// table without rowid column
QString sql = QString( "SELECT rowid FROM %1 WHERE 0" ).arg( quotedIdentifier( mTableName ) );
char *errMsg = nullptr;
return sqlite3_exec( sqliteHandle, sql.toUtf8(), nullptr, nullptr, &errMsg ) == SQLITE_OK;
}


QString QgsSpatiaLiteProvider::storageType() const
{
@@ -266,6 +266,9 @@ class QgsSpatiaLiteProvider: public QgsVectorDataProvider
/** Check if a table/view has any triggers. Triggers can be used on views to make them editable.*/
bool hasTriggers();

//! Check if a table has a row id (internal primary key)
bool hasRowid();

/** Convert a QgsField to work with SL */
static bool convertField( QgsField &field );

0 comments on commit 69e3c6f

Please sign in to comment.
You can’t perform that action at this time.