Skip to content

Commit

Permalink
[Spatialite provider] prefer rowid as primary key where available
Browse files Browse the repository at this point in the history
Adapted from 1050174 without the cleanups.

fixes #14575, fixes #14626, fixes #14999
  • Loading branch information
rouault committed Jun 13, 2016
1 parent 4d1790a commit 69e3c6f
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 6 deletions.
33 changes: 27 additions & 6 deletions src/providers/spatialite/qgsspatialiteprovider.cpp
Expand Up @@ -568,6 +568,11 @@ QgsSpatiaLiteProvider::QgsSpatiaLiteProvider( QString const &uri )
return;
}

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

// retrieve version information
spatialiteVersion();

Expand Down Expand Up @@ -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;
Expand All @@ -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;
}
}
Expand Down Expand Up @@ -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 );
}
Expand Down Expand Up @@ -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 );
}
Expand Down Expand Up @@ -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
{
Expand Down
3 changes: 3 additions & 0 deletions src/providers/spatialite/qgsspatialiteprovider.h
Expand Up @@ -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 );

Expand Down

0 comments on commit 69e3c6f

Please sign in to comment.