SelectByAttribute.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. """
  2. ***************************************************************************
  3. SelectByAttribute.py
  4. ---------------------
  5. Date : May 2010
  6. Copyright : (C) 2010 by Michael Minn
  7. Email : pyqgis at michaelminn dot com
  8. ***************************************************************************
  9. * *
  10. * This program is free software; you can redistribute it and/or modify *
  11. * it under the terms of the GNU General Public License as published by *
  12. * the Free Software Foundation; either version 2 of the License, or *
  13. * (at your option) any later version. *
  14. * *
  15. ***************************************************************************
  16. """
  17. __author__ = 'Michael Minn'
  18. __date__ = 'May 2010'
  19. __copyright__ = '(C) 2010, Michael Minn'
  20. from qgis.PyQt.QtCore import QVariant
  21. from qgis.core import (QgsExpression,
  22. QgsVectorLayer,
  23. QgsProcessing,
  24. QgsProcessingException,
  25. QgsProcessingAlgorithm,
  26. QgsProcessingParameterVectorLayer,
  27. QgsProcessingParameterField,
  28. QgsProcessingParameterEnum,
  29. QgsProcessingParameterString,
  30. QgsProcessingOutputVectorLayer)
  31. from processing.algs.qgis.QgisAlgorithm import QgisAlgorithm
  32. class SelectByAttribute(QgisAlgorithm):
  33. INPUT = 'INPUT'
  34. FIELD = 'FIELD'
  35. OPERATOR = 'OPERATOR'
  36. VALUE = 'VALUE'
  37. METHOD = 'METHOD'
  38. OUTPUT = 'OUTPUT'
  39. OPERATORS = ['=',
  40. '<>',
  41. '>',
  42. '>=',
  43. '<',
  44. '<=',
  45. 'begins with',
  46. 'contains',
  47. 'is null',
  48. 'is not null',
  49. 'does not contain'
  50. ]
  51. STRING_OPERATORS = ['begins with',
  52. 'contains',
  53. 'does not contain']
  54. def tags(self):
  55. return self.tr('select,attribute,value,contains,null,field').split(',')
  56. def group(self):
  57. return self.tr('Vector selection')
  58. def groupId(self):
  59. return 'vectorselection'
  60. def __init__(self):
  61. super().__init__()
  62. def flags(self):
  63. return super().flags() | QgsProcessingAlgorithm.FlagNoThreading | QgsProcessingAlgorithm.FlagNotAvailableInStandaloneTool
  64. def initAlgorithm(self, config=None):
  65. self.operators = ['=',
  66. '≠',
  67. '>',
  68. '≥',
  69. '<',
  70. '≤',
  71. self.tr('begins with'),
  72. self.tr('contains'),
  73. self.tr('is null'),
  74. self.tr('is not null'),
  75. self.tr('does not contain')
  76. ]
  77. self.methods = [self.tr('creating new selection'),
  78. self.tr('adding to current selection'),
  79. self.tr('removing from current selection'),
  80. self.tr('selecting within current selection')]
  81. self.addParameter(QgsProcessingParameterVectorLayer(self.INPUT,
  82. self.tr('Input layer'),
  83. types=[QgsProcessing.TypeVector]))
  84. self.addParameter(QgsProcessingParameterField(self.FIELD,
  85. self.tr('Selection attribute'),
  86. parentLayerParameterName=self.INPUT))
  87. self.addParameter(QgsProcessingParameterEnum(self.OPERATOR,
  88. self.tr('Operator'), self.operators, defaultValue=0))
  89. self.addParameter(QgsProcessingParameterString(self.VALUE,
  90. self.tr('Value'),
  91. optional=True))
  92. self.addParameter(QgsProcessingParameterEnum(self.METHOD,
  93. self.tr('Modify current selection by'),
  94. self.methods,
  95. defaultValue=0))
  96. self.addOutput(QgsProcessingOutputVectorLayer(self.OUTPUT, self.tr('Selected (attribute)')))
  97. def name(self):
  98. return 'selectbyattribute'
  99. def displayName(self):
  100. return self.tr('Select by attribute')
  101. def processAlgorithm(self, parameters, context, feedback):
  102. layer = self.parameterAsVectorLayer(parameters, self.INPUT, context)
  103. fieldName = self.parameterAsString(parameters, self.FIELD, context)
  104. operator = self.OPERATORS[self.parameterAsEnum(parameters, self.OPERATOR, context)]
  105. value = self.parameterAsString(parameters, self.VALUE, context)
  106. fields = layer.fields()
  107. idx = layer.fields().lookupField(fieldName)
  108. if idx < 0:
  109. raise QgsProcessingException(self.tr("Field '{}' was not found in layer").format(fieldName))
  110. fieldType = fields[idx].type()
  111. if fieldType != QVariant.String and operator in self.STRING_OPERATORS:
  112. op = ''.join('"%s", ' % o for o in self.STRING_OPERATORS)
  113. raise QgsProcessingException(
  114. self.tr('Operators {0} can be used only with string fields.').format(op))
  115. field_ref = QgsExpression.quotedColumnRef(fieldName)
  116. quoted_val = QgsExpression.quotedValue(value)
  117. if operator == 'is null':
  118. expression_string = f'{field_ref} IS NULL'
  119. elif operator == 'is not null':
  120. expression_string = f'{field_ref} IS NOT NULL'
  121. elif operator == 'begins with':
  122. expression_string = f"{field_ref} LIKE '{value}%'"
  123. elif operator == 'contains':
  124. expression_string = f"{field_ref} LIKE '%{value}%'"
  125. elif operator == 'does not contain':
  126. expression_string = f"{field_ref} NOT LIKE '%{value}%'"
  127. else:
  128. expression_string = f'{field_ref} {operator} {quoted_val}'
  129. method = self.parameterAsEnum(parameters, self.METHOD, context)
  130. if method == 0:
  131. behavior = QgsVectorLayer.SetSelection
  132. elif method == 1:
  133. behavior = QgsVectorLayer.AddToSelection
  134. elif method == 2:
  135. behavior = QgsVectorLayer.RemoveFromSelection
  136. elif method == 3:
  137. behavior = QgsVectorLayer.IntersectSelection
  138. expression = QgsExpression(expression_string)
  139. if expression.hasParserError():
  140. raise QgsProcessingException(expression.parserErrorString())
  141. layer.selectByExpression(expression_string, behavior)
  142. return {self.OUTPUT: parameters[self.INPUT]}