Skip to content

Commit 03bfe9b

Browse files
committedJun 10, 2017
Use uuid instead of timestamp when generating layer ids
Timestamps can result in duplicate layer ids when layers are created rapidly or in different threads. Fix #14390
1 parent 326e442 commit 03bfe9b

File tree

2 files changed

+24
-5
lines changed

2 files changed

+24
-5
lines changed
 

‎src/core/qgsmaplayer.cpp

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@
1616
***************************************************************************/
1717

1818

19-
#include <QDateTime>
2019
#include <QDir>
2120
#include <QDomDocument>
2221
#include <QDomElement>
@@ -56,7 +55,6 @@ QgsMapLayer::QgsMapLayer( QgsMapLayer::LayerType type,
5655
: mValid( false ) // assume the layer is invalid
5756
, mDataSource( source )
5857
, mLayerOrigName( lyrname ) // store the original name
59-
, mID( QLatin1String( "" ) )
6058
, mLayerType( type )
6159
, mBlendMode( QPainter::CompositionMode_SourceOver ) // Default to normal blending
6260
, mLegend( nullptr )
@@ -65,12 +63,13 @@ QgsMapLayer::QgsMapLayer( QgsMapLayer::LayerType type,
6563
// Set the display name = internal name
6664
mLayerName = capitalizeLayerName( mLayerOrigName );
6765

68-
mShortName = QLatin1String( "" );
6966
//mShortName.replace( QRegExp( "[\\W]" ), "_" );
7067

7168
// Generate the unique ID of this layer
72-
QDateTime dt = QDateTime::currentDateTime();
73-
mID = lyrname + dt.toString( QStringLiteral( "yyyyMMddhhmmsszzz" ) );
69+
QString uuid = QUuid::createUuid().toString();
70+
// trim { } from uuid
71+
mID = lyrname + '_' + uuid.mid( 1, uuid.length() - 2 );
72+
7473
// Tidy the ID up to avoid characters that may cause problems
7574
// elsewhere (e.g in some parts of XML). Replaces every non-word
7675
// character (word characters are the alphabet, numbers and

‎tests/src/python/test_qgsmaplayer.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,26 @@
2525

2626
class TestQgsMapLayer(unittest.TestCase):
2727

28+
def testUniqueId(self):
29+
"""
30+
Test that layers created quickly with same name get a unique ID
31+
"""
32+
33+
# make 1000 layers quickly
34+
layers = []
35+
for i in range(1000):
36+
layer = QgsVectorLayer(
37+
'Point?crs=epsg:4326&field=name:string(20)',
38+
'test',
39+
'memory')
40+
layers.append(layer)
41+
42+
# make sure all ids are unique
43+
ids = set()
44+
for l in layers:
45+
self.assertFalse(l.id() in ids)
46+
ids.add(l.id())
47+
2848
def copyLayerViaXmlReadWrite(self, source, dest):
2949
# write to xml
3050
doc = QDomDocument("testdoc")

0 commit comments

Comments
 (0)
Please sign in to comment.