DbmsAlgorithm.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. """
  2. ***************************************************************************
  3. DbmsAlgorithm.py
  4. ---------------------
  5. Date : August 2012
  6. Copyright : (C) 2012 by Victor Olaya
  7. Email : volayaf at gmail 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__ = 'Victor Olaya'
  18. __date__ = 'August 2012'
  19. __copyright__ = '(C) 2012, Victor Olaya'
  20. import os
  21. import re
  22. import numpy as np
  23. from qgis.PyQt.QtCore import QUrl, QCoreApplication
  24. from qgis.core import (QgsApplication,
  25. QgsProject,
  26. QgsVectorFileWriter,
  27. QgsProcessingFeatureSourceDefinition,
  28. QgsProcessingAlgorithm,
  29. QgsProcessingContext,
  30. QgsProcessingFeedback,
  31. QgsProviderRegistry,
  32. QgsDataSourceUri)
  33. from processing.algs.gdal.DbmsAlgorithmDialog import DbmsAlgorithmDialog
  34. from processing.algs.gdal.GdalUtils import GdalUtils
  35. from processing.tools.PostgreSQL.PostgreSQL import PostgreSQL
  36. from processing.tools.GeoServer.Geoserver import Geoserver
  37. from processing.tools.GeoServer.GeoService import GeoService
  38. from processing.tools.QGS.QgsProjectUtils import QgsProjectUtils
  39. from processing.tools.PrintUtils import getLastPrint
  40. from processing.tools.FileListPrintUtils import getFileListPrint
  41. from processing.tools.SubprocessUtils import RunSubprocess
  42. pluginPath = os.path.normpath(os.path.join(
  43. os.path.split(os.path.dirname(__file__))[0], os.pardir))
  44. class DbmsAlgorithm(QgsProcessingAlgorithm):
  45. def __init__(self):
  46. super().__init__()
  47. self.output_values = {}
  48. def icon(self):
  49. return QgsApplication.getThemeIcon("/providerGdal.svg")
  50. def tags(self):
  51. return ['ogr', 'gdal', self.commandName()]
  52. def svgIconPath(self):
  53. return QgsApplication.iconPath("providerGdal.svg")
  54. def createInstance(self, config={}):
  55. return self.__class__()
  56. def createCustomParametersWidget(self, parent):
  57. return DbmsAlgorithmDialog(self, parent=parent)
  58. def getConsoleCommands(self, parameters, context, feedback, executing=True):
  59. return None
  60. def getOgrCompatibleSource(self, parameter_name, parameters, context, feedback, executing):
  61. """
  62. Interprets a parameter as an OGR compatible source and layer name
  63. :param executing:
  64. """
  65. if not executing and parameter_name in parameters and isinstance(parameters[parameter_name],
  66. QgsProcessingFeatureSourceDefinition):
  67. # if not executing, then we throw away all 'selected features only' settings
  68. # since these have no meaning for command line gdal use, and we don't want to force
  69. # an export of selected features only to a temporary file just to show the command!
  70. parameters = {parameter_name: parameters[parameter_name].source}
  71. input_layer = self.parameterAsVectorLayer(parameters, parameter_name, context)
  72. ogr_data_path = None
  73. ogr_layer_name = None
  74. if input_layer is None or input_layer.dataProvider().name() == 'memory':
  75. if executing:
  76. # parameter is not a vector layer - try to convert to a source compatible with OGR
  77. # and extract selection if required
  78. ogr_data_path = self.parameterAsCompatibleSourceLayerPath(parameters, parameter_name, context,
  79. QgsVectorFileWriter.supportedFormatExtensions(),
  80. QgsVectorFileWriter.supportedFormatExtensions()[
  81. 0],
  82. feedback=feedback)
  83. ogr_layer_name = GdalUtils.ogrLayerName(ogr_data_path)
  84. else:
  85. # not executing - don't waste time converting incompatible sources, just return dummy strings
  86. # for the command preview (since the source isn't compatible with OGR, it has no meaning anyway and can't
  87. # be run directly in the command line)
  88. ogr_data_path = 'path_to_data_file'
  89. ogr_layer_name = 'layer_name'
  90. elif input_layer.dataProvider().name() == 'ogr':
  91. if executing and (
  92. isinstance(parameters[parameter_name], QgsProcessingFeatureSourceDefinition) and parameters[
  93. parameter_name].selectedFeaturesOnly) \
  94. or input_layer.subsetString():
  95. # parameter is a vector layer, with OGR data provider
  96. # so extract selection if required
  97. ogr_data_path = self.parameterAsCompatibleSourceLayerPath(parameters, parameter_name, context,
  98. QgsVectorFileWriter.supportedFormatExtensions(),
  99. feedback=feedback)
  100. parts = QgsProviderRegistry.instance().decodeUri('ogr', ogr_data_path)
  101. ogr_data_path = parts['path']
  102. if 'layerName' in parts and parts['layerName']:
  103. ogr_layer_name = parts['layerName']
  104. else:
  105. ogr_layer_name = GdalUtils.ogrLayerName(ogr_data_path)
  106. else:
  107. # either not using the selection, or
  108. # not executing - don't worry about 'selected features only' handling. It has no meaning
  109. # for the command line preview since it has no meaning outside of a QGIS session!
  110. ogr_data_path = GdalUtils.ogrConnectionStringAndFormatFromLayer(input_layer)[0]
  111. ogr_layer_name = GdalUtils.ogrLayerName(input_layer.dataProvider().dataSourceUri())
  112. elif input_layer.dataProvider().name().lower() == 'wfs':
  113. uri = QgsDataSourceUri(input_layer.source())
  114. baseUrl = uri.param('url').split('?')[0]
  115. ogr_data_path = f"WFS:{baseUrl}"
  116. ogr_layer_name = uri.param('typename')
  117. else:
  118. # vector layer, but not OGR - get OGR compatible path
  119. # TODO - handle "selected features only" mode!!
  120. ogr_data_path = GdalUtils.ogrConnectionStringFromLayer(input_layer)
  121. ogr_layer_name = GdalUtils.ogrLayerName(input_layer.dataProvider().dataSourceUri())
  122. return ogr_data_path, ogr_layer_name
  123. def setOutputValue(self, name, value):
  124. self.output_values[name] = value
  125. def processAlgorithm(self, parameters, context, feedback):
  126. # TODO wanger GeoServer服务发布
  127. if parameters.get("Publish_Service") is not None:
  128. zymlbsm = getLastPrint()
  129. if zymlbsm == None or zymlbsm == '':
  130. return {
  131. "Error": "资源目录未选择!"
  132. }
  133. print("zymlbsm====" + zymlbsm)
  134. layer_group_join = ""
  135. if parameters.get("LAYER_GROUP_JOIN") is not None:
  136. layer_group_join = self.groups[parameters.get("LAYER_GROUP_JOIN")]
  137. commands = self.getConsoleCommands(parameters, context, feedback, executing=True)
  138. geoSer = GeoService()
  139. result = geoSer.publishGeoService(parameters, context, feedback, commands, zymlbsm, layer_group_join)
  140. return result
  141. # === 获取gdal命令参数执行并输出log开始 ===
  142. commands = self.getConsoleCommands(parameters, context, feedback, executing=True)
  143. # if np.isin("raster2pgsql.exe", commands) or np.isin("raster2pgsql", commands):
  144. # RunSubprocess(command=' '.join(commands))
  145. # else:
  146. # GdalUtils.runGdal(commands, feedback)
  147. GdalUtils.runGdal(commands, feedback)
  148. print(commands)
  149. results = {}
  150. for o in self.outputDefinitions():
  151. if o.name() in parameters:
  152. results[o.name()] = parameters[o.name()]
  153. for k, v in self.output_values.items():
  154. results[k] = v
  155. # === 获取gdal命令参数执行并输出log结束 ===
  156. # TODO wanger 元数据入库
  157. if parameters.get("Metadata_storage") is not None and parameters.get("Metadata_storage") == True:
  158. # 所属行政区划
  159. ssxzqh = getLastPrint()
  160. print("ssxzqh====" + ssxzqh)
  161. # 获取附件列表
  162. fileliststr = getFileListPrint()
  163. pgconn = PostgreSQL(schema='base')
  164. pgconn.metadataStorage(parameters, ssxzqh, fileliststr, self.ywlxs[parameters.get("VECTOR_YWLX")],
  165. self.depts[parameters.get("VECTOR_GLBM")])
  166. pgconn.close()
  167. return results
  168. def commandName(self):
  169. parameters = {
  170. param.name(): "1"
  171. for param in self.parameterDefinitions()
  172. }
  173. context = QgsProcessingContext()
  174. feedback = QgsProcessingFeedback()
  175. name = self.getConsoleCommands(parameters, context, feedback, executing=False)[0]
  176. if name.endswith(".py"):
  177. name = name[:-3]
  178. return name
  179. def tr(self, string, context=''):
  180. if context == '':
  181. context = self.__class__.__name__
  182. return QCoreApplication.translate(context, string)