Skip to content
Permalink
Browse files

- solved issue #7550

- 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 61062d719ea362a1216747282f931dce62a313f5
@@ -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();
@@ -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() )
{
@@ -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();
}
@@ -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()

0 comments on commit 61062d7

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