2

I have a versioned database in ArcGIS and I am wondering how can I tell arcpy what version to query. The closest I have got to an answer has been building a particular connection file that specifies the version to connect to, or use ChangeVersion_management which only works on layers and views.

I can easily do that in a published map on the web using ArcGIS JS API by setting the version using layer.setGDBVersion(version)

PolyGeo
  • 65,136
  • 29
  • 109
  • 338
Mahdi
  • 635
  • 4
  • 18
  • This may help http://pro.arcgis.com/en/pro-app/tool-reference/data-management/changeversion.htm – Learner Feb 16 '16 at 17:18

2 Answers2

4

In Arcgis the dataset version is set at Workspace level. As you have mentioned in your question, you should create a connection file for that version and change the handle to the featureclass or table. something like this:

worspace = "c:/connectionFiles/version1.sde/" 
layerName = "parcel" 
fc= worpspace+layerName 
arcpy.da.SearchCursor(fc,...)

##to change the version, first we create a connection file for that version!     
arcpy.CreateArcSDEConnectionFile_management(r'c:\connectionFiles',
                                        'version2.sde',
                                        '5151',
                                        '',
                                        'toolbox',
                                        'toolbox',
                                        'SAVE_USERNAME',
                                        'SDE.DEFAULT',
                                        'SAVE_VERSION')

and you know what to do next.

Farid Cheraghi
  • 8,773
  • 1
  • 23
  • 53
3

You are on the right track. You just need to use MakeFeatureLayer to convert the feature class to a layer. I created a version and did an edit and then tried the following:

>>> arcpy.env.workspace = r'Database Connections\gisadmin.sde'
>>> arcpy.MakeFeatureLayer_management(r'Database Connections\gisadmin.sde\GISADMIN.Buildings', 'fl')
>>> arcpy.ChangeVersion_management('fl', "TRANSACTIONAL", "GISADMIN.Oli")
>>> arcpy.GetCount_management('fl')
<Result '1715'>
>>> arcpy.ChangeVersion_management('fl', "TRANSACTIONAL", "sde.DEFAULT")
<Result 'fl'>
>>> arcpy.GetCount_management('fl')
<Result '1714'>
>>> with arcpy.da.SearchCursor('fl', flds) as cur: 
...

Also, there is an advantage to starting from a pre-created connection file vs creating one in code in that the password is not visible in the connection file. You would only need to pre-create the connection file per user since you can change the version in code.

Oli
  • 336
  • 1
  • 3
  • I have seen this before but it felt so wrong to do this. I mean, I appreciate your solution, but I was looking for something under arcpy.env or a parameter passed to the the cursors. It seems to be bad architecture by ArcGIS folks. Thank you anyways. I prefer this to the making a connection on the fly as you mentioned. – Mahdi Nov 28 '14 at 07:40