import arcpy
import os
def main():
# --- Tool parameters ---
gdb = arcpy.GetParameterAsText(0) # Input Geodatabase
field_name = arcpy.GetParameterAsText(1) # Field to use in query (e.g., project_number)
where_clause = arcpy.GetParameterAsText(2) # SQL clause (e.g., project_number = 'ABC' OR project_number = 'XYZ')
clear_all = arcpy.GetParameter(3) # Boolean checkbox: True = clear all definition queries
# Get current project
aprx = arcpy.mp.ArcGISProject("CURRENT")
# Walk through all feature classes in the GDB
for dirpath, dirnames, fcs in arcpy.da.Walk(gdb, datatype="FeatureClass"):
for fc in fcs:
fc_path = os.path.join(dirpath, fc)
# If not clearing → check that the field exists before applying query
if not clear_all:
if not arcpy.ListFields(fc_path, field_name):
arcpy.AddWarning(f"{field_name} not found in {fc}, skipping")
continue
# Go through all maps and layers in the project
for m in aprx.listMaps():
for lyr in m.listLayers():
if lyr.isFeatureLayer:
try:
# Match the layer's data source with this feature class path
if os.path.normcase(os.path.normpath(lyr.dataSource)) == os.path.normcase(os.path.normpath(fc_path)):
# --- CLEAR ALL option ---
if clear_all:
lyr.definitionQuery = ""
arcpy.AddMessage(f"Cleared query on {lyr.name}")
# --- APPLY QUERY option ---
else:
if where_clause:
lyr.definitionQuery = where_clause
arcpy.AddMessage(f"Applied query on {lyr.name}: {where_clause}")
else:
arcpy.AddWarning(f"No where clause provided for {lyr.name}, skipped")
except Exception as e:
arcpy.AddWarning(f"Could not update {lyr.name}: {e}")
# Save changes to project
aprx.save()
if __name__ == "__main__":
main()