How to find a query layer in a map document using arcpy

277
6
06-11-2021 02:03 PM
MattFrancis
New Contributor III

I have a bunch of map documents with gobs of layers in each. I have a script the goes through each map document, and each dataframe, and then inspects each layer in the dataframe. I am trying to determine if the layer is a query layer, but I do not know how to determine that.

import arcpy
import os

tfolder = r"\\tstvmmapservb\f$\ArcGIS\MXDs\NISC"
for f in os.listdir(tfolder):
    map_document = os.path.join(r"\\tstvmmapservb\f$\ArcGIS\MXDs\NISC", f)
    print("mxd: {}").format(map_document)
    mxd = arcpy.mapping.MapDocument(map_document)
    for df in arcpy.mapping.ListDataFrames(mxd, "*"):
        lyrs = arcpy.mapping.ListLayers(mxd, "", df)
        for lyr in lyrs:
            if lyr.isBroken:
                #print("{} is broken. Skipping".format(lyr.name))
                continue
            desc = arcpy.Describe(lyr)
            if desc.dataType == "GroupLayer":
                #print("{} is a group layer. Skipping".format(lyr.name))
                continue
            if desc.dataElement.dataType == "FeatureClass":
                print("{} is a feature class. Skipping".format(lyr.name))
                continue
            if lyr.supports("SERVICEPROPERTIES"):
                #print("{} is a service. Skipping".format(lyr.name))
                continue
            print(lyr)

 

0 Kudos
6 Replies
DanPatterson
MVP Honored Contributor

would "supports" "definition query" help?

Layer—ArcGIS Pro | Documentation

supports (layer_property)

DEFINITIONQUERY A layer's definition query string.

 


... sort of retired...
MattFrancis
New Contributor III

Not really; most layers have definition queries. It is similar, but I am looking for a query layer's definition, and not a layer's definition query. 

0 Kudos
DavidPike
MVP Frequent Contributor

A query layer for me in Oracle returns a '%' in the dataSource and datasetName properties.

maybe:

if '%' in lyr.datasetName:
    pass
0 Kudos
MattFrancis
New Contributor III

Thanks; I am not getting a "%" and might be getting an underscore, but looking for that character will turn up many false positives.

RandyBurton
MVP Regular Contributor

Per @DanPatterson's suggestion, if the layer supports DEFINITIONQUERY, then check the definition property for a string with length.  If it has length, the layer is using a query.

 

for lyr in lyrs:
    if lyr.supports("DEFINITIONQUERY"):
        if len(lyr.definitionQuery.strip()): # a string with length
            print lyr.name, lyr.definitionQuery

 

(My version of ArcMap allowed spaces as a definition query, so stripping them before checking length is advised.)

0 Kudos
MattFrancis
New Contributor III

Similarly, I have an XY Event Layer (In layer properties, Source tab, Data Type: XY Event Source) and desc.dataElement.dataType == "FeatureClass" is true for an XY Event Layer, though it is clearly not an SDE Feature Class. 

0 Kudos