Skip to content
View on GitHub

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

Screenshot of Edit geodatabase with transactions sample

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 Geodatabase.featureTables in feature layers.
  3. If a transaction is required, begin one using Geodatabase.beginTransaction().
  4. Add one or more features to the feature table(s).
  5. 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

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, transact, transactions

Sample Code

EditGeodatabaseWithTransactionsView.swiftEditGeodatabaseWithTransactionsView.swiftEditGeodatabaseWithTransactionsView.Model.swift
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 // Copyright 2024 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 // // https://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.  import ArcGIS import SwiftUI  struct EditGeodatabaseWithTransactionsView: View {  /// The view model for the sample.  @StateObject private var model = Model()   /// The action currently being preformed.  @State private var selectedAction: Action? = .setUp   /// The text describing the status of the sample.  @State private var statusText = ""   /// The point on the map where the user tapped.  @State private var tapLocation: Point?   /// A Boolean value indicating whether a transaction is active on the geodatabase.  @State private var isInTransaction = false   /// A Boolean value indicating whether a transaction is required to add a feature.  @State private var transactionIsRequired = true   /// A Boolean value indicating whether the select feature type popover is presented.  @State private var isSelectingFeatureType = false   /// A Boolean value indicating whether the alert to end a transaction is presented.  @State private var endTransactionAlertIsPresented = false   /// The error shown in the error alert.  @State private var error: Error?   var body: some View {  MapView(map: model.map)  .onSingleTapGesture { _, mapPoint in  // Shows the select feature type popover when a feature can currently be added.  guard !transactionIsRequired || isInTransaction else { return }   tapLocation = mapPoint  isSelectingFeatureType = true  }  .task(id: selectedAction) {  guard let selectedAction else { return }   do {  switch selectedAction {  case .setUp:  try await model.setUp()  case .addFeature(let tableName, let featureTypeName):  try await model.addFeature(  tableName: tableName,  featureTypeName: featureTypeName,  point: tapLocation!  )  case .beginTransaction:  try model.geodatabase.beginTransaction()  isInTransaction = true  case .commitTransaction:  try model.geodatabase.commitTransaction()  isInTransaction = false  case .rollbackTransaction:  try model.geodatabase.rollbackTransaction()  isInTransaction = false  }   statusText = selectedAction.completionMessage  } catch GeodatabaseError.geometryOutsideReplicaExtent {  statusText = "Error: Feature geometry is outside the generate geodatabase geometry."  } catch {  self.error = error  }   self.selectedAction = nil  }  .overlay(alignment: .top) {  Text(statusText)  .multilineTextAlignment(.center)  .frame(maxWidth: .infinity, alignment: .center)  .padding(8)  .background(.regularMaterial, ignoresSafeAreaEdges: .horizontal)  }  .toolbar {  ToolbarItemGroup(placement: .bottomBar) {  Button(isInTransaction ? "End Transaction" : "Start Transaction") {  if isInTransaction {  // Presents the alert to handle the edits.  endTransactionAlertIsPresented = true  } else {  selectedAction = .beginTransaction  }  }  .disabled(!transactionIsRequired)  .popover(isPresented: $isSelectingFeatureType) {  SelectFeatureTypeView(  featureTables: model.geodatabase.featureTables  ) { tableName, featureTypeName in  selectedAction = .addFeature(  tableName: tableName,  featureTypeName: featureTypeName  )  }  .presentationDetents([.fraction(0.5)])  .frame(idealWidth: 320, idealHeight: 380)  }   Spacer()   Toggle("Requires Transaction", isOn: $transactionIsRequired)  .disabled(isInTransaction)  .onChange(of: transactionIsRequired) {  statusText = transactionIsRequired  ? "Tap Start to begin a transaction."  : "Tap on the map to add a feature."  }  }  }  .alert("Commit Edits", isPresented: $endTransactionAlertIsPresented) {  Button("Commit") {  selectedAction = .commitTransaction  }  Button("Rollback", role: .destructive) {  selectedAction = .rollbackTransaction  }  Button("Cancel", role: .cancel) {}  } message: {  Text("Commit the edits in the transaction to the geodatabase or rollback to discard them.")  }  .disabled(selectedAction == .setUp)  .errorAlert(presentingError: $error)  } }  /// An action associated with the geodatabase. private enum Action: Equatable {  /// Sets up the sample.  case setUp  /// Adds a feature of a given type to a table in the geodatabase.  case addFeature(tableName: String, featureTypeName: String)  /// Starts a transaction on the geodatabase.  case beginTransaction  /// Commits the edits in the transaction to the geodatabase.  case commitTransaction  /// Rollback the edits in the transaction from the geodatabase.  case rollbackTransaction   /// The message to display when the action successfully completes.  var completionMessage: String {  switch self {  case .setUp: "Tap Start to begin a transaction."  case .addFeature: "Added feature."  case .beginTransaction: "Transaction started."  case .commitTransaction: "Edits committed to geodatabase."  case .rollbackTransaction: "Edits discarded."  }  } }  /// A view allowing the user to select a feature type from given feature tables. private struct SelectFeatureTypeView: View {  /// The feature tables containing the feature types.  let featureTables: [ArcGISFeatureTable]   /// The action to perform when a feature type is selected and the "Done" button is pressed.  let onFeatureSelectionAction: (_ tableName: String, _ featureTypeName: String) -> Void   /// The action to dismiss the view.  @Environment(\.dismiss) private var dismiss   /// The name of the feature table selected in the picker.  @State private var selectedFeatureTableName = ""   /// The name of the feature type selected by the user.  @State private var selectedFeatureTypeName: String?   /// The feature types of the selected feature table.  private var featureTypeOptions: [FeatureType] {  let selectFeatureTable = featureTables.first { $0.tableName == selectedFeatureTableName }  return selectFeatureTable?.featureTypes ?? []  }   var body: some View {  NavigationStack {  Form {  Section("Feature Type") {  Picker("Feature Table", selection: $selectedFeatureTableName) {  ForEach(featureTables, id: \.tableName) { featureTable in  Text(featureTable.displayName)  }  }  .pickerStyle(.segmented)   Picker("Feature Type", selection: $selectedFeatureTypeName) {  ForEach(featureTypeOptions, id: \.name) { featureType in  Text(featureType.name)  .tag(featureType.name as String?)  }  }  .pickerStyle(.inline)  .labelsHidden()  }  }  .navigationTitle("New Feature")  .navigationBarTitleDisplayMode(.inline)  .toolbar {  ToolbarItem(placement: .cancellationAction) {  Button("Cancel", role: .cancel) { dismiss() }  }   ToolbarItem(placement: .confirmationAction) {  Button("Done") {  onFeatureSelectionAction(selectedFeatureTableName, selectedFeatureTypeName!)  dismiss()  }  .disabled(selectedFeatureTypeName == nil)  }  }  }  .onAppear {  selectedFeatureTableName = featureTables.first?.tableName ?? ""  }  } }  #Preview {  NavigationStack {  EditGeodatabaseWithTransactionsView()  } }

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