Skip to content
Permalink
Browse files
Fixes #45198 : Don't return default value when null
  • Loading branch information
troopa81 authored and nyalldawson committed Nov 1, 2021
1 parent d63f34a commit f5fa61a322b72ffcf3520e832ba754d2302e25a8
Showing with 42 additions and 3 deletions.
  1. +7 −3 src/core/qgsfieldformatter.cpp
  2. +35 −0 tests/src/python/test_qgsfieldformatters.py
@@ -19,7 +19,7 @@
#include "qgsfields.h"
#include "qgsvectorlayer.h"
#include "qgsvectordataprovider.h"

#include "qgsapplication.h"

QString QgsFieldFormatter::representValue( QgsVectorLayer *layer, int fieldIndex, const QVariantMap &config, const QVariant &cache, const QVariant &value ) const
{
@@ -30,13 +30,17 @@ QString QgsFieldFormatter::representValue( QgsVectorLayer *layer, int fieldIndex
if ( layer->fields().fieldOrigin( fieldIndex ) == QgsFields::OriginProvider && layer->dataProvider() )
defVal = layer->dataProvider()->defaultValueClause( layer->fields().fieldOriginIndex( fieldIndex ) );

if ( ! layer->fields().exists( fieldIndex ) )
if ( !defVal.isNull() && defVal == value )
{
return defVal;
}
else if ( value.isNull() )
{
return QgsApplication::nullRepresentation();
}
else
{
return layer->fields().at( fieldIndex ).displayString( value.isNull() ? defVal : value );
return layer->fields().at( fieldIndex ).displayString( value );
}
}

@@ -12,6 +12,7 @@


import tempfile
import os

import qgis # NOQA

@@ -23,6 +24,7 @@

from qgis.PyQt.QtCore import QCoreApplication, QLocale, QVariant
from qgis.testing import start_app, unittest
from qgis.utils import spatialite_connect
from utilities import writeShape

start_app()
@@ -599,6 +601,39 @@ def _test(layer, is_gpkg=False):
# No precision here
_test(gpkg_layer, True)

def test_representValueWithDefault(self):
"""
Check representValue behaves correctly when used on a layer which define default values
"""

dbname = os.path.join(tempfile.mkdtemp(), 'test.sqlite')
con = spatialite_connect(dbname, isolation_level=None)
cur = con.cursor()
cur.execute("BEGIN")
sql = """
CREATE TABLE test_table_default_values (
id integer primary key autoincrement,
anumber INTEGER DEFAULT 123
)
"""
cur.execute(sql)
cur.execute("COMMIT")
con.close()

vl = QgsVectorLayer(dbname + '|layername=test_table_default_values', 'test_table_default_values', 'ogr')
self.assertTrue(vl.isValid())

fieldFormatter = QgsFallbackFieldFormatter()

QLocale.setDefault(QLocale('en'))

self.assertEqual(fieldFormatter.representValue(vl, 1, {}, None, QVariant(QVariant.Int)),
'NULL')
self.assertEqual(fieldFormatter.representValue(vl, 1, {}, None, 4),
'4')
self.assertEqual(fieldFormatter.representValue(vl, 1, {}, None, "123"),
'123')


if __name__ == '__main__':
unittest.main()

0 comments on commit f5fa61a

Please sign in to comment.