Skip to content

Commit

Permalink
- solved issue #7550
Browse files Browse the repository at this point in the history
- implemented getPrimaryKey member function of QgsSpatiaLiteProvider
- in addFeatures, if an attribute is a primary key, its value is set to
  NULL so that sqlite generates a value automagically
  • Loading branch information
vmora committed Jul 9, 2013
1 parent e514572 commit 61062d7
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 1 deletion.
43 changes: 43 additions & 0 deletions src/providers/spatialite/qgsspatialiteprovider.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3507,6 +3507,9 @@ bool QgsSpatiaLiteProvider::addFeatures( QgsFeatureList & flist )
QString separator;
int ia, ret;


const QString primaryKey = getPrimaryKey();

if ( flist.size() == 0 )
return true;
const QgsAttributes & attributevec = flist[0].attributes();
Expand Down Expand Up @@ -3605,6 +3608,13 @@ bool QgsSpatiaLiteProvider::addFeatures( QgsFeatureList & flist )
if ( fieldname.isEmpty() || fieldname == mGeometryColumn )
continue;

// replace primary key with NULL so that sqlite will generate one for us
if ( primaryKey == fieldname )
{
v = QVariant();
assert(v.toString().isEmpty());
}

QVariant::Type type = attributeFields[i].type();
if ( v.toString().isEmpty() )
{
Expand Down Expand Up @@ -5197,3 +5207,36 @@ QGISEXTERN bool deleteLayer( const QString& dbPath, const QString& tableName, QS

return true;
}

QString QgsSpatiaLiteProvider::getPrimaryKey()
{
char **results;
int rows;
int columns;
char *errMsg = NULL;
QString sql = QString( "PRAGMA table_info(%1)" ).arg( mQuery );

int ret = sqlite3_get_table( sqliteHandle, sql.toUtf8().constData(), &results, &rows, &columns, &errMsg );
if ( ret != SQLITE_OK )
{
QgsDebugMsg( "sqlite error: " + QString::fromUtf8( errMsg ) );
}

int pkColIdx=0;
for (; (pkColIdx < columns) && (QString("pk") != results[pkColIdx]) ; pkColIdx++){}
assert(pkColIdx<columns); // we must find it

int nameIdx=0;
for (; (nameIdx < columns) && (QString("name") != results[nameIdx]) ; nameIdx++){}
assert(nameIdx<columns); // we must find it

for (int r=0; r<rows; r++)
{
if ( QString("1") == results[r*columns + pkColIdx] )
{
return QString::fromUtf8( results[r*columns + nameIdx] );
}
}

return QString();
}
1 change: 0 additions & 1 deletion tests/src/python/test_qgsspatialiteprovider.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,6 @@ def tearDown(self):
def test_SplitFeature(self):
"""Create spatialite database"""
layer = QgsVectorLayer("dbname=test.sqlite table=test_pg (geometry)", "test_pg", "spatialite")
help(QgsVectorLayer)
assert(layer.isValid())
assert(layer.hasGeometryType())
layer.startEditing()
Expand Down

0 comments on commit 61062d7

Please sign in to comment.