-
-
Notifications
You must be signed in to change notification settings - Fork 3k
/
qgsvectorlayerutils.cpp
302 lines (252 loc) · 10.2 KB
/
qgsvectorlayerutils.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
/***************************************************************************
qgsvectorlayerutils.cpp
-----------------------
Date : October 2016
Copyright : (C) 2016 by Nyall Dawson
Email : nyall dot dawson at gmail dot com
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "qgsvectorlayerutils.h"
#include "qgsvectordataprovider.h"
#include <QRegularExpression>
bool QgsVectorLayerUtils::valueExists( const QgsVectorLayer* layer, int fieldIndex, const QVariant& value, const QgsFeatureIds& ignoreIds )
{
if ( !layer )
return false;
QgsFields fields = layer->fields();
if ( fieldIndex < 0 || fieldIndex >= fields.count() )
return false;
QString fieldName = fields.at( fieldIndex ).name();
// build up an optimised feature request
QgsFeatureRequest request;
request.setSubsetOfAttributes( QgsAttributeList() );
request.setFlags( QgsFeatureRequest::NoGeometry );
// at most we need to check ignoreIds.size() + 1 - the feature not in ignoreIds is the one we're interested in
int limit = ignoreIds.size() + 1;
request.setLimit( limit );
request.setFilterExpression( QStringLiteral( "%1=%2" ).arg( QgsExpression::quotedColumnRef( fieldName ),
QgsExpression::quotedValue( value ) ) );
QgsFeature feat;
QgsFeatureIterator it = layer->getFeatures( request );
while ( it.nextFeature( feat ) )
{
if ( ignoreIds.contains( feat.id() ) )
continue;
return true;
}
return false;
}
QVariant QgsVectorLayerUtils::createUniqueValue( const QgsVectorLayer* layer, int fieldIndex, const QVariant& seed )
{
if ( !layer )
return QVariant();
QgsFields fields = layer->fields();
if ( fieldIndex < 0 || fieldIndex >= fields.count() )
return QVariant();
QgsField field = fields.at( fieldIndex );
if ( field.isNumeric() )
{
QVariant maxVal = layer->maximumValue( fieldIndex );
QVariant newVar( maxVal.toLongLong() + 1 );
if ( field.convertCompatible( newVar ) )
return newVar;
else
return QVariant();
}
else
{
switch ( field.type() )
{
case QVariant::String:
{
QString base;
if ( seed.isValid() )
base = seed.toString();
if ( !base.isEmpty() )
{
// strip any existing _1, _2 from the seed
QRegularExpression rx( "(.*)_\\d+" );
QRegularExpressionMatch match = rx.match( base );
if ( match.hasMatch() )
{
base = match.captured( 1 );
}
}
else
{
// no base seed - fetch first value from layer
QgsFeatureRequest req;
req.setLimit( 1 );
req.setSubsetOfAttributes( QgsAttributeList() << fieldIndex );
req.setFlags( QgsFeatureRequest::NoGeometry );
QgsFeature f;
layer->getFeatures( req ).nextFeature( f );
base = f.attribute( fieldIndex ).toString();
}
// try variants like base_1, base_2, etc until a new value found
QStringList vals = layer->uniqueStringsMatching( fieldIndex, base );
// might already be unique
if ( !base.isEmpty() && !vals.contains( base ) )
return base;
for ( int i = 1; i < 10000; ++i )
{
QString testVal = base + '_' + QString::number( i );
if ( !vals.contains( testVal ) )
return testVal;
}
// failed
return QVariant();
}
default:
// todo other types - dates? times?
return QVariant();
}
}
return QVariant();
}
bool QgsVectorLayerUtils::validateAttribute( const QgsVectorLayer* layer, const QgsFeature& feature, int attributeIndex, QStringList& errors,
QgsFieldConstraints::ConstraintStrength strength, QgsFieldConstraints::ConstraintOrigin origin )
{
if ( !layer )
return false;
if ( attributeIndex < 0 || attributeIndex >= layer->fields().count() )
return false;
QgsField field = layer->fields().at( attributeIndex );
QVariant value = feature.attribute( attributeIndex );
bool valid = true;
errors.clear();
QgsFieldConstraints constraints = field.constraints();
if ( constraints.constraints() & QgsFieldConstraints::ConstraintExpression && !constraints.constraintExpression().isEmpty()
&& ( strength == QgsFieldConstraints::ConstraintStrengthNotSet || strength == constraints.constraintStrength( QgsFieldConstraints::ConstraintExpression ) )
&& ( origin == QgsFieldConstraints::ConstraintOriginNotSet || origin == constraints.constraintOrigin( QgsFieldConstraints::ConstraintExpression ) ) )
{
QgsExpressionContext context = layer->createExpressionContext();
context.setFeature( feature );
QgsExpression expr( constraints.constraintExpression() );
valid = expr.evaluate( &context ).toBool();
if ( expr.hasParserError() )
{
errors << QObject::tr( "parser error: %1" ).arg( expr.parserErrorString() );
}
else if ( expr.hasEvalError() )
{
errors << QObject::tr( "evaluation error: %1" ).arg( expr.evalErrorString() );
}
else if ( !valid )
{
errors << QObject::tr( "%1 check failed" ).arg( constraints.constraintDescription() );
}
}
if ( constraints.constraints() & QgsFieldConstraints::ConstraintNotNull
&& ( strength == QgsFieldConstraints::ConstraintStrengthNotSet || strength == constraints.constraintStrength( QgsFieldConstraints::ConstraintNotNull ) )
&& ( origin == QgsFieldConstraints::ConstraintOriginNotSet || origin == constraints.constraintOrigin( QgsFieldConstraints::ConstraintNotNull ) ) )
{
valid = valid && !value.isNull();
if ( value.isNull() )
{
errors << QObject::tr( "value is NULL" );
}
}
if ( constraints.constraints() & QgsFieldConstraints::ConstraintUnique
&& ( strength == QgsFieldConstraints::ConstraintStrengthNotSet || strength == constraints.constraintStrength( QgsFieldConstraints::ConstraintUnique ) )
&& ( origin == QgsFieldConstraints::ConstraintOriginNotSet || origin == constraints.constraintOrigin( QgsFieldConstraints::ConstraintUnique ) ) )
{
bool alreadyExists = QgsVectorLayerUtils::valueExists( layer, attributeIndex, value, QgsFeatureIds() << feature.id() );
valid = valid && !alreadyExists;
if ( alreadyExists )
{
errors << QObject::tr( "value is not unique" );
}
}
return valid;
}
QgsFeature QgsVectorLayerUtils::createFeature( QgsVectorLayer* layer, const QgsGeometry& geometry,
const QgsAttributeMap& attributes, QgsExpressionContext* context )
{
if ( !layer )
{
return QgsFeature();
}
QgsExpressionContext* evalContext = context;
QScopedPointer< QgsExpressionContext > tempContext;
if ( !evalContext )
{
// no context passed, so we create a default one
tempContext.reset( new QgsExpressionContext() );
tempContext->appendScope( QgsExpressionContextUtils::globalScope() );
tempContext->appendScope( QgsExpressionContextUtils::projectScope() );
tempContext->appendScope( QgsExpressionContextUtils::layerScope( layer ) );
evalContext = tempContext.data();
}
QgsFields fields = layer->fields();
QgsFeature newFeature( fields );
newFeature.setValid( true );
newFeature.setGeometry( geometry );
// initialise attributes
newFeature.initAttributes( fields.count() );
for ( int idx = 0; idx < fields.count(); ++idx )
{
QVariant v;
bool checkUnique = true;
// in order of priority:
// 1. client side default expression
if ( !layer->defaultValueExpression( idx ).isEmpty() )
{
// client side default expression set - takes precedence over all. Why? Well, this is the only default
// which QGIS users have control over, so we assume that they're deliberately overriding any
// provider defaults for some good reason and we should respect that
v = layer->defaultValue( idx, newFeature, evalContext );
}
// 2. provider side default value clause
// note - not an else if deliberately. Users may return null from a default value expression to fallback to provider defaults
if ( !v.isValid() && fields.fieldOrigin( idx ) == QgsFields::OriginProvider )
{
int providerIndex = fields.fieldOriginIndex( idx );
QString providerDefault = layer->dataProvider()->defaultValueClause( providerIndex );
if ( !providerDefault.isEmpty() )
{
v = providerDefault;
checkUnique = false;
}
}
// 3. provider side default literal
// note - deliberately not using else if!
if ( !v.isValid() && fields.fieldOrigin( idx ) == QgsFields::OriginProvider )
{
int providerIndex = fields.fieldOriginIndex( idx );
v = layer->dataProvider()->defaultValue( providerIndex );
if ( v.isValid() )
{
//trust that the provider default has been sensibly set not to violate any constraints
checkUnique = false;
}
}
// 4. passed attribute value
// note - deliberately not using else if!
if ( !v.isValid() && attributes.contains( idx ) )
{
v = attributes.value( idx );
}
// last of all... check that unique constraints are respected
// we can't handle not null or expression constraints here, since there's no way to pick a sensible
// value if the constraint is violated
if ( checkUnique && fields.at( idx ).constraints().constraints() & QgsFieldConstraints::ConstraintUnique )
{
if ( QgsVectorLayerUtils::valueExists( layer, idx, v ) )
{
// unique constraint violated
QVariant uniqueValue = QgsVectorLayerUtils::createUniqueValue( layer, idx, v );
if ( uniqueValue.isValid() )
v = uniqueValue;
}
}
newFeature.setAttribute( idx, v );
}
return newFeature;
}