Skip to content
View on GitHubSample viewer app

Use transactions to manage how changes are committed to a geodatabase.

screenshot

Use case

Transactions allow you to control how changes are added to a database. This is useful to ensure that when multiple changes are made to a database, they all succeed or fail at once. For example, you could have a business rule that both parent/guardian and student must be added to a database used for calculating school bus routes. You can use transactions to avoid breaking the business rule if you lose power while between the steps of adding the student and parent/guardian.

How to use the sample

Tap on the map to add multiple types of features. To apply edits directly, uncheck the "Requires Transaction". When using transactions, use the buttons to start editing and stop editing. When you stop editing, you can choose to commit the changes or roll them back.

How it works

  1. Create a Geodatabase using the mobile geodatabase file location.
  2. Display the GeodatabaseFeatureTable in feature layers.
  3. If a transaction is required, begin one using Geodatabase::beginTransaction().
  4. To check if a Geodatabase is in transaction use Geodatabase::isInTransaction().
  5. Add one or more features to the feature table(s).
  6. When ready, either commit the transaction to the geodatabase with Geodatabase::commitTransaction() or roll back the transaction with Geodatabase::rollbackTransaction().

Relevant API

  • Geodatabase
  • Geodatabase::beginTransaction
  • Geodatabase::commitTransaction
  • Geodatabase::isInTransaction
  • Geodatabase::rollbackTransaction
  • GeometryEditor

Offline data

This sample downloads the Save The Bay Geodatabase item from ArcGIS Online.

About the data

The mobile geodatabase contains a collection schema for wildlife sightings around Christmas Bay, TX, USA. It was created using data from the Save The Bay Feature Service.

Tags

commit, database, geodatabase, geometry editor, transact, transactions

Sample Code

EditGeodatabaseWithTransactions.cppEditGeodatabaseWithTransactions.cppEditGeodatabaseWithTransactions.hEditGeodatabaseWithTransactions.qml
Use dark colors for code blocksCopy
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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
// [WriteFile Name=EditGeodatabaseWithTransactions, Category=EditData]
// [Legal]
// Copyright 2025 Esri.

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0

// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// [Legal]

#ifdef PCH_BUILD
#include "pch.hpp"
#endif // PCH_BUILD

// sample headers
#include "EditGeodatabaseWithTransactions.h"

// ArcGIS Maps SDK headers
#include "ErrorException.h"
#include "Feature.h"
#include "FeatureLayer.h"
#include "FeatureTemplate.h"
#include "FeatureType.h"
#include "Geodatabase.h"
#include "GeodatabaseFeatureTable.h"
#include "Geometry.h"
#include "GeometryEngine.h"
#include "Graphic.h"
#include "GraphicListModel.h"
#include "GraphicsOverlay.h"
#include "GraphicsOverlayListModel.h"
#include "LayerListModel.h"
#include "Map.h"
#include "MapQuickView.h"
#include "MapTypes.h"
#include "Point.h"
#include "SimpleLineSymbol.h"
#include "SpatialReference.h"
#include "SymbolTypes.h"
#include "Viewpoint.h"

// Qt headers
#include <QException>
#include <QFuture>
#include <QFutureWatcher>
#include <QStandardPaths>
#include <QTimer>

using namespace Esri::ArcGISRuntime;

// helper method to get cross platform data path
namespace
{
  QString defaultDataPath()
  {
#ifdef Q_OS_IOS
    return QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
#else
    return QStandardPaths::writableLocation(QStandardPaths::HomeLocation);
#endif
  }
} // namespace

EditGeodatabaseWithTransactions::EditGeodatabaseWithTransactions(QObject* parent /* = nullptr */) :
  QObject(parent),
  m_map(new Map(BasemapStyle::ArcGISTopographic, this))
{
  m_extent = Envelope(-95.3035, 29.0100, -95.1053, 29.1298, SpatialReference::wgs84());
  m_map->setInitialViewpoint(Viewpoint(m_extent));

  const QString dataPath = defaultDataPath() + "/ArcGIS/Runtime/Data/geodatabase/SaveTheBay.geodatabase";

  m_geodatabase = new Geodatabase(dataPath, this);
  connect(m_geodatabase, &Geodatabase::doneLoading, this, &EditGeodatabaseWithTransactions::onGeodatabaseDoneLoading_);

  m_geodatabase->load();
}

EditGeodatabaseWithTransactions::~EditGeodatabaseWithTransactions() = default;

void EditGeodatabaseWithTransactions::init()
{
  // Register the map view for QML
  qmlRegisterType<MapQuickView>("Esri.Samples", 1, 0, "MapView");
  qmlRegisterType<EditGeodatabaseWithTransactions>("Esri.Samples", 1, 0, "EditGeodatabaseWithTransactionsSample");
}

MapQuickView* EditGeodatabaseWithTransactions::mapView() const
{
  return m_mapView;
}

bool EditGeodatabaseWithTransactions::stopEditingEnabled() const
{
  return m_stopEditingEnabled;
}

bool EditGeodatabaseWithTransactions::requireTransaction() const
{
  return m_requireTransaction;
}

bool EditGeodatabaseWithTransactions::loadingVisible() const
{
  return m_loadingVisible;
}

QStringList EditGeodatabaseWithTransactions::currentFeatureTypes() const
{
  return m_currentFeatureTypes;
}

QStringList EditGeodatabaseWithTransactions::availableTableNames() const
{
  return m_availableTableNames;
}

QString EditGeodatabaseWithTransactions::messageText() const
{
  return m_messageText;
}

QString EditGeodatabaseWithTransactions::selectedTableName() const
{
  return m_selectedTableName;
}

// Set the view (created in QML)
void EditGeodatabaseWithTransactions::setMapView(MapQuickView* mapView)
{
  if (!mapView || mapView == m_mapView)
  {
    return;
  }

  m_mapView = mapView;
  m_mapView->setMap(m_map);

  emit mapViewChanged();

  connectSignals_();
}

void EditGeodatabaseWithTransactions::connectSignals_()
{
  connect(m_mapView, &MapQuickView::mouseClicked, this, [this](QMouseEvent& mouseEvent)
  {
    if (!m_geodatabase)
    {
      return;
    }

    // Only allow adding features if transaction conditions are met
    if (m_requireTransaction && !m_geodatabase->isInTransaction())
    {
      setMessageText("Start a transaction first.");
      return;
    }

    // Get screen coordinates and emit signal to show feature type dialog
    const double screenX = mouseEvent.position().x();
    const double screenY = mouseEvent.position().y();

    emit featureTypeSelectionRequested(screenX, screenY);
  });
}

void EditGeodatabaseWithTransactions::onGeodatabaseDoneLoading_(const Error& error)
{
  if (!error.isEmpty())
  {
    setMessageText(error.message());
    setLoadingVisible_(false);
    return;
  }

  setLoadingVisible_(false);
  setMessageText("Using local geodatabase.");

  m_allFeatureTables.clear();
  m_tablesByName.clear();
  m_availableTableNames.clear();

  const int totalTablesToLoad = m_geodatabase->geodatabaseFeatureTables().size();

  // Use a shared pointer to track the count across lambda captures
  auto tablesLoadedCount = std::make_shared<int>(0);

  for (GeodatabaseFeatureTable* table : m_geodatabase->geodatabaseFeatureTables())
  {
    connect(table, &GeodatabaseFeatureTable::doneLoading, this, [this, table, totalTablesToLoad, tablesLoadedCount](const Error& error)
    {
      if (!error.isEmpty())
      {
        setMessageText(error.message());
        return;
      }

      // Store reference to the table with proper name mapping
      m_allFeatureTables.append(table);

      // Set specific display names as per the Geodatabase
      QString displayName;
      if (table->tableName() == "Save_The_Bay_Marine_Sync")
      {
        table->setDisplayName("Marine");
        displayName = "Marine";
      }
      else if (table->tableName() == "Save_The_Bay_Birds_Sync")
      {
        table->setDisplayName("Bird");
        displayName = "Bird";
      }
      else
      {
        displayName = table->displayName().isEmpty() ? table->tableName() : table->displayName();
      }

      m_tablesByName[displayName] = table;
      m_availableTableNames.append(displayName);

      // Create feature layer for the map
      if (m_mapView && m_mapView->map())
      {
        FeatureLayer* layer = new FeatureLayer(table, this);
        layer->setMinScale(0);
        layer->setMaxScale(0);
        layer->setVisible(true);
        m_mapView->map()->operationalLayers()->append(layer);
      }

      (*tablesLoadedCount)++;

      // When all tables are loaded
      if (*tablesLoadedCount == totalTablesToLoad)
      {
        onAllTablesLoaded_();
      }
    });

    table->load();
  }
}

void EditGeodatabaseWithTransactions::onAllTablesLoaded_()
{
  // Initialize with first table as default selection
  if (!m_availableTableNames.isEmpty())
  {
    m_selectedTableName = m_availableTableNames.first();
    updateFeatureTypesForTable_(m_tablesByName[m_selectedTableName]);
    emit selectedTableNameChanged();
  }

  emit availableTableNamesChanged();

  // Connect transaction status monitoring
  connect(m_geodatabase, &Geodatabase::transactionStatusChanged, this, &EditGeodatabaseWithTransactions::gdbTransactionStatusChanged_);

  // Show the extent graphic
  drawExtent_();

  // Set the map viewpoint to show the geodatabase extent
  if (m_mapView)
  {
    m_mapView->setViewpointAsync(Viewpoint(m_extent));
  }

  setMessageText("Tap Start to begin a transaction.");
}

void EditGeodatabaseWithTransactions::gdbTransactionStatusChanged_()
{
  if (!m_geodatabase)
  {
    return;
  }
  // Update UI controls based on whether the geodatabase has a current transaction
  const bool isInTransaction = m_geodatabase->isInTransaction();

  m_stopEditingEnabled = isInTransaction;

  // Update status message based on current state
  if (isInTransaction)
  {
    setMessageText("Transaction started.");
  }
  else if (m_requireTransaction)
  {
    setMessageText("Tap Start to begin a transaction.");
  }
  else
  {
    setMessageText("Tap on the map to add a feature.");
  }

  emit stopEditingEnabledChanged();
}

void EditGeodatabaseWithTransactions::setRequireTransaction(bool require)
{
  if (!m_geodatabase)
  {
    return;
  }

  if (!require && m_geodatabase->isInTransaction())
  {
    setMessageText("Stop editing to end the current transaction.");
    return;
  }

  m_requireTransaction = require;
  emit requireTransactionChanged();

  // Update status message based on requirement
  if (require)
  {
    setMessageText("Tap Start to begin a transaction.");
  }
  else
  {
    setMessageText("Tap on the map to add a feature.");
  }

  // Update control states
  const bool isInTransaction = m_geodatabase->isInTransaction();
  m_stopEditingEnabled = require && isInTransaction;

  emit stopEditingEnabledChanged();
}

void EditGeodatabaseWithTransactions::beginTransaction()
{
  if (!m_geodatabase)
  {
    return;
  }

  // Begin transaction for the geodatabase if it's not in transaction
  if (!m_geodatabase->isInTransaction())
  {
    m_geodatabase->beginTransaction();
  }
}

void EditGeodatabaseWithTransactions::stopTransaction()
{
  if (!m_geodatabase || !m_mapView)
  {
    return;
  }

  // Ask the user if they want to commit or rollback the transaction
  emit commitDialogRequested();
}

void EditGeodatabaseWithTransactions::commitTransaction()
{
  if (!m_geodatabase)
  {
    return;
  }

  // Commit the transaction to store the edits (this will also end the transaction)
  m_geodatabase->commitTransaction();
  setMessageText("Edits committed to geodatabase.");
}

void EditGeodatabaseWithTransactions::rollbackTransaction()
{
  if (!m_geodatabase)
  {
    return;
  }

  // Rollback the transaction to discard the edits (this will also end the transaction)
  m_geodatabase->rollbackTransaction();
  setMessageText("Edits discarded.");
}

void EditGeodatabaseWithTransactions::cancelTransactionCommit()
{
  // User canceled - indicate that the transaction is active
  setMessageText("Transaction started.");
}

void EditGeodatabaseWithTransactions::updateFeatureTypesForTable_(GeodatabaseFeatureTable* table)
{
  if (!table)
  {
    return;
  }

  m_currentFeatureTypes.clear();

  QStringList featureTypeNames;
  featureTypeNames.reserve(table->featureTypes().size());

  for (const FeatureType& featureType : table->featureTypes())
  {
    featureTypeNames.append(featureType.name());
  }

  featureTypeNames.sort(Qt::CaseInsensitive);
  m_currentFeatureTypes = featureTypeNames;

  emit currentFeatureTypesChanged();
}

void EditGeodatabaseWithTransactions::setSelectedTableName(const QString& tableName)
{
  if (m_selectedTableName != tableName)
  {
    m_selectedTableName = tableName;
    emit selectedTableNameChanged();

    // Update feature types for the newly selected table
    GeodatabaseFeatureTable* table = m_tablesByName.value(tableName, nullptr);
    if (table)
    {
      updateFeatureTypesForTable_(table);
    }
  }
}

void EditGeodatabaseWithTransactions::addFeatureAtLocation(const QString& tableName, const QString& featureTypeName, const QPoint& location)
{
  if (!m_mapView || !m_geodatabase)
  {
    return;
  }

  GeodatabaseFeatureTable* targetTable = m_tablesByName.value(tableName, nullptr);
  if (!targetTable)
  {
    setMessageText(QString("Table '%1' not found.").arg(tableName));
    return;
  }

  // Find the feature type
  FeatureType selectedFeatureType;
  bool foundType = false;
  for (const FeatureType& featureType : targetTable->featureTypes())
  {
    if (featureType.name() == featureTypeName)
    {
      selectedFeatureType = featureType;
      foundType = true;
      break;
    }
  }

  if (!foundType)
  {
    setMessageText(QString("Feature type '%1' not found in table '%2'.").arg(featureTypeName, tableName));
    return;
  }

  // Convert screen point to map point
  const Point mapPoint = m_mapView->screenToLocation(location.x(), location.y());
  if (mapPoint.isEmpty())
  {
    setMessageText("Invalid location clicked.");
    return;
  }

  // Convert point to WGS84 and check if point is in the extent (extent is in WGS84)
  const Geometry projectedGeometry = GeometryEngine::project(mapPoint, SpatialReference::wgs84());
  if (GeometryEngine::contains(m_extent, projectedGeometry) == false)
  {
    setMessageText("Error: Feature geometry is outside the generate geodatabase geometry.");
    return;
  }

  // Create feature using the selected type's template attributes
  QVariantMap attributes;
  if (!selectedFeatureType.templates().isEmpty())
  {
    // Use the first template's attributes if available
    attributes = selectedFeatureType.templates().at(0).prototypeAttributes();
  }

  Feature* newFeature = targetTable->createFeature(attributes, mapPoint, this);
  if (!newFeature)
  {
    setMessageText("Failed to create new feature.");
    return;
  }

  // Add the new feature to the table
  targetTable->addFeatureAsync(newFeature)
    .then(this,
          [this]()
  {
    setMessageText("Added feature.");
  })
    .onFailed(this,
              [this](const ErrorException& exception)
  {
    QString errorMsg = QString("Error adding feature: %1").arg(exception.error().message());
    setMessageText(errorMsg);
  })
    .onCanceled(this, [this]()
  {
    setMessageText("Add feature operation was canceled.");
  });
}

void EditGeodatabaseWithTransactions::updateFeatureTypesForSelectedTable(const QString& tableName)
{
  GeodatabaseFeatureTable* table = m_tablesByName.value(tableName, nullptr);
  updateFeatureTypesForTable_(table);
}

void EditGeodatabaseWithTransactions::setMessageText(const QString& message)
{
  if (m_messageText != message)
  {
    m_messageText = message;
    emit messageTextChanged();
  }
}

void EditGeodatabaseWithTransactions::setLoadingVisible_(bool visible)
{
  if (m_loadingVisible != visible)
  {
    m_loadingVisible = visible;
    emit loadingVisibleChanged();
  }
}

void EditGeodatabaseWithTransactions::drawExtent_()
{
  if (!m_mapView)
  {
    return;
  }

  // Create a graphic for the geodatabase extent
  SimpleLineSymbol* lineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle::Solid, QColor(Qt::red), 2, this);
  Graphic* extentGraphic = new Graphic(m_extent, lineSymbol, this);

  // Create a graphics overlay for the extent graphic
  GraphicsOverlay* extentOverlay = new GraphicsOverlay(this);
  extentOverlay->graphics()->append(extentGraphic);

  // Add graphics overlay to the map view
  m_mapView->graphicsOverlays()->append(extentOverlay);
}

Your browser is no longer supported. Please upgrade your browser for the best experience. See our browser deprecation post for more details.