PostgreSQL.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. # -*- coding: utf-8 -*-
  2. __author__ = 'wanger'
  3. __date__ = '2024-08-20'
  4. __copyright__ = '(C) 2024 by siwei'
  5. __revision__ = '1.0'
  6. import time
  7. from typing import Optional
  8. import os
  9. import psycopg2
  10. import uuid
  11. from ..FTP.FtpUitl import FtpOper
  12. from ..FTP.FtpConfig import *
  13. from processing.tools.FileUtils import getInputFileName
  14. class PostgreSQL:
  15. # 矢量数据元数据表
  16. Vector_Storage = "t_vector_storage"
  17. # 矢量数据服务发布表
  18. Vector_Server = "t_vector_server"
  19. # 附件表
  20. Vector_FJ = "t_vector_fj"
  21. # 字段表
  22. Vector_Field = "t_vector_field"
  23. # 平台资源目录表
  24. Portal_Zyml = "t_yzt_zyml"
  25. # 备份表后缀名
  26. BackTable = "_back"
  27. # 序列名称后缀
  28. Sequence = "_id_seq"
  29. def __init__(
  30. self,
  31. host: Optional[str] = "127.0.0.1", # default host during installation
  32. port: Optional[str] = "5432", # default port during pg installation
  33. user: Optional[str] = "postgres", # default user during pg installation
  34. password: Optional[str] = "postgres", # default password during pg installation
  35. dbname: Optional[str] = "real3d", # default dbname during pg installation
  36. schema: Optional[str] = None
  37. ):
  38. # 配置数据库连接参数并指定schema
  39. self.connparams = {
  40. "dbname": dbname,
  41. "user": user,
  42. "password": password,
  43. "host": host,
  44. "port": port,
  45. "options": "-c search_path=otherSchema," + schema if schema is not None else None
  46. }
  47. self.conn = psycopg2.connect(**self.connparams)
  48. # 创建一个游标对象
  49. self.cur = self.conn.cursor()
  50. # 执行一个查询
  51. # self.cur.execute("SELECT 省,类型 from \"XZQH3857\";")
  52. # 获取查询结果
  53. # rows = self.cur.fetchall()
  54. # 打印结果
  55. # for row in rows:
  56. # for v in row:
  57. # print(v)
  58. def execute(self, sql):
  59. # 执行一个查询
  60. self.cur.execute(sql)
  61. # 获取查询结果
  62. return self.cur.fetchall()
  63. def close(self):
  64. # 关闭游标和连接
  65. self.cur.close()
  66. self.conn.close()
  67. # 根据名称删除元数据信息
  68. def deleteVectorStorage(self, name):
  69. sql = "delete from {} where name = '{}'".format(self.Vector_Storage, name)
  70. self.cur.execute(sql)
  71. self.conn.commit()
  72. # 保存元数据信息
  73. def insertVectorStorage(self, id, name, year, xmlx, sjly, xzqh, xzqh_field, ywlx, sjlx, sjywz, glbm, table_alias):
  74. sql = "insert into {} (id, name, year, xmlx, sjly, xzqh, xzqh_field, ywlx, sjlx, sjywz, glbm, table_alias) values ('{}','{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}')".format(
  75. self.Vector_Storage, id, name, year.toString("yyyy"), xmlx, sjly, xzqh, xzqh_field, ywlx, sjlx, sjywz, glbm,
  76. table_alias)
  77. self.cur.execute(sql)
  78. self.conn.commit()
  79. # 元数据入库,参数parameters
  80. def metadataStorage(self, parameters, ssxzqh, fileliststr, ywlx, glbm, ogrLayer):
  81. record_id = ""
  82. id = uuid.uuid4().__str__()
  83. id = id.replace("-", "")
  84. # print(parameters)
  85. if (parameters.get("TABLE") is None or parameters.get("TABLE") == "") and ogrLayer is not None:
  86. record_id = parameters.get("SCHEMA") + "." + getInputFileName(ogrLayer)
  87. else:
  88. record_id = parameters.get("SCHEMA") + "." + parameters.get("TABLE")
  89. table_alias = parameters.get("TABLE_ALIAS")
  90. if table_alias != '' and table_alias is not None: # 配置表别名
  91. self.setTableAlias(table=self.getTableName(recordid=record_id),
  92. alias=table_alias)
  93. self.deleteVectorStorage(name=record_id)
  94. self.insertVectorStorage(id=id, name=record_id, year=parameters.get("VECTOR_YEAR"),
  95. xmlx=parameters.get("VECTOR_XMLX"), sjly=parameters.get("VECTOR_SJLY"),
  96. xzqh=ssxzqh, xzqh_field=parameters.get("XZQH_FIELD"),
  97. ywlx=ywlx, sjlx=parameters.get("SOURCE_TYPE"), sjywz=ogrLayer,
  98. glbm=glbm, table_alias=table_alias)
  99. # 附件上传
  100. if fileliststr is not None and fileliststr != "":
  101. self.uploadAttachment(layername=record_id, layerid=id, fileliststr=fileliststr)
  102. # 获取文件名称
  103. def getInputFileName(self, file):
  104. filename = file.split("/")[len(file.split("/")) - 1]
  105. return filename[0: filename.find(".")]
  106. # 附件上传FTP
  107. def uploadAttachment(self, layername, layerid, fileliststr):
  108. print("开始上传附件啦!!")
  109. self.ftpOper = FtpOper()
  110. self.ftpOper.ftp.connect(ftpHost, ftpPort)
  111. self.ftpOper.ftp.login(ftpUsername, ftpPassword)
  112. ftp_path = '/三亚数管/' + layername # 图层FTP目录地址
  113. if not self.ftpOper.is_exist('/三亚数管/'):
  114. self.ftpOper.makedir('三亚数管', '/', '/三亚数管/')
  115. if self.ftpOper.is_exist(ftp_path): # 已有此图层目录,则删除
  116. self.ftpOper.deletedir(ftp_path)
  117. self.ftpOper.makedir(layername, '/三亚数管/', ftp_path) # 重新创建图层目录
  118. file_paths_list = fileliststr.split(",")
  119. if len(file_paths_list):
  120. for file_path in file_paths_list:
  121. if os.path.exists(file_path):
  122. filename = os.path.basename(file_path)
  123. filenamenoexten, fileextension = os.path.splitext(filename)
  124. self.ftpOper.uploadfile(file_path, ftp_path)
  125. self.insertVectorFJ(uuid.uuid4().__str__(), layerid, layername, filename, fileextension,
  126. ftp_path + '/' + filename,
  127. file_path, self.ftpOper.ftp.host + ':' + str(self.ftpOper.ftp.port),
  128. str(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())))
  129. self.ftpOper.ftp.close()
  130. # 保存附件信息
  131. def insertVectorFJ(self, id, layerid, layername, name, fjlx, fjdz, fjwz, dldz, cjsj):
  132. sql = "insert into {} (id,layerid, layername, name, fjlx, fjdz, fjwz,dldz,cjsj) values ('{}','{}','{}', '{}', '{}', '{}', '{}', '{}', '{}')".format(
  133. self.Vector_FJ, id, layerid, layername, name, fjlx, fjdz, fjwz, dldz, cjsj)
  134. self.cur.execute(sql)
  135. self.conn.commit()
  136. # 服务发布表插入
  137. def insertVectorServer(self, id, fwqlx, sjy, fwlx, fwdz, fwmc, fwgzkj, fwys, qpfa, zymlbsm, layergroup, zoommin,
  138. zoommax, layername):
  139. # 数据库管理系统服务相关表插入
  140. sql = "insert into {} (id, fwqlx, sjy, fwlx, fwdz, fwmc, fwgzkj, fwys, qpfa, zymlbsm, layergroup, zoommin, zoommax, layername) values ('{}','{}','{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}')".format(
  141. self.Vector_Server, id, fwqlx, sjy, fwlx, fwdz, fwmc, fwgzkj, fwys, qpfa, zymlbsm, layergroup, zoommin,
  142. zoommax, layername)
  143. self.cur.execute(sql)
  144. self.conn.commit()
  145. # 平台资源目录表插入
  146. def insertPortalZymlServer(self, id, fwqlx, sjy, fwlx, fwdz, fwmc, fwgzkj, fwys, qpfa, zymlbsm, layergroup, zoommin,
  147. zoommax, layername):
  148. # 平台资源目录服务相关表插入
  149. sql = "insert into {} (bsm, name, type, pbsm, url, state, parent, server_type, fwmc, " \
  150. "fwgzkj, fwys, qpfa, layergroup, format, maximumlevel, minimumlevel) values ('{}','{}','{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}')".format(
  151. self.Portal_Zyml, id, fwmc, fwlx, zymlbsm, fwdz, '1', '0', fwqlx, layername, fwgzkj, fwys, qpfa,
  152. layergroup, 'image/png', zoommax, zoommin)
  153. self.cur.execute(sql)
  154. self.conn.commit()
  155. # 获取资源目录
  156. def getZyml(self):
  157. self.cur.execute(
  158. "select t.bsm, t.name, t.pbsm from t_yzt_zyml t where t.parent = '1' order by t.lev,t.pbsm , t.sort")
  159. rows = self.cur.fetchall()
  160. return rows
  161. # 获取行政区划
  162. def getXzqh(self):
  163. self.cur.execute(
  164. "select t.id, t.name, case when t.pid = '0' then '' else t.pid end from vector.xzqh t order by t.id")
  165. rows = self.cur.fetchall()
  166. return rows
  167. # 获取矢量数据字典类型
  168. def getVectorYwlx(self):
  169. self.cur.execute(
  170. "select distinct(t.ywlx) from t_vector_field t ")
  171. rows = self.cur.fetchall()
  172. return rows
  173. # 获取部门列表
  174. def getDeptList(self):
  175. self.cur.execute(
  176. "select dept_name from (select distinct(dept_name),dept_id from sys_dept t where t.del_flag = '0' order by t.dept_id) a")
  177. rows = self.cur.fetchall()
  178. return rows
  179. # 根据用户名称查询有权限维护的数据库表,返回别名或者表名
  180. def getManagerTables(self, username):
  181. sql = f'select t.id "id",name "name", case when t.table_alias is not null then t.table_alias else t.name end as "alias", t.ywlx "ywlx" ' \
  182. f'from {self.Vector_Storage} t where t.glbm = (select dept_name from sys_dept d where d.dept_id = (select dept_id from sys_user u where u.user_name = \'{username}\' ))'
  183. self.cur.execute(sql)
  184. rows = self.cur.fetchall()
  185. return rows
  186. # 根据业务类型和表名查询必填的字段名
  187. def getMustRequireField(self, tablename, ywlx):
  188. arr = tablename.split(".")
  189. sql = f'select lower(f.name) from {self.Vector_Field} f where f.ywlx = \'{ywlx}\' and lower(f.name) in (' \
  190. f'select column_name from information_schema.columns where table_schema = \'{arr[0]}\' and table_name = \'{arr[1]}\') and f.nullable = \'1\''
  191. self.cur.execute(sql)
  192. rows = self.cur.fetchall()
  193. fields = []
  194. for row in rows:
  195. fields.append(row[0])
  196. return fields
  197. def getAllTableField(self, tablename):
  198. arr = tablename.split(".")
  199. sql = f'select column_name from information_schema.columns where table_schema = \'{arr[0]}\' and table_name = \'{arr[1]}\' and lower(column_name) not in (\'id\',\'geom\', \'shape_leng\', \'shape_area\')'
  200. self.cur.execute(sql)
  201. rows = self.cur.fetchall()
  202. fields = []
  203. for row in rows:
  204. fields.append(row[0])
  205. return fields
  206. # 保存矢量要素
  207. def insertVectorFeature(self, tablename, fields, values, wkt, wktsrid, geomtype):
  208. arr = tablename.split(".")
  209. insertvalues = ""
  210. print(values)
  211. for value in values:
  212. if value == None:
  213. insertvalues += "null,"
  214. else:
  215. b = self.is_string(value)
  216. if b == True:
  217. insertvalues += f'\'{value}\','
  218. else:
  219. insertvalues += f'{value},'
  220. print(insertvalues)
  221. print(insertvalues[:-1])
  222. # 判断几何类型是否一致
  223. if wkt.startswith(geomtype) == False:
  224. if geomtype.startswith("MULTI"): # 转换为Multi
  225. wkt = 'MULTI' + wkt
  226. wkt = wkt.replace("((", "(((").replace("))", ")))")
  227. else:
  228. wkt = wkt.replace("(((", "((").replace(")))", "))").replace("MULTI", "")
  229. sql = f'insert into {arr[0]}."{arr[1]}" ({",".join(fields)} , geom) values ({insertvalues[:-1]} , public.st_geomfromtext( \'{wkt}\', {wktsrid}))'
  230. sql = sql.replace("None", "null")
  231. print(sql)
  232. self.cur.execute(sql)
  233. self.conn.commit()
  234. # 获取矢量数据表的坐标系
  235. def getVectorTableSrid(self, tablename):
  236. arr = tablename.split(".")
  237. sql = f'select public.st_srid(geom) from {arr[0]}."{arr[1]}" limit 1'
  238. self.cur.execute(sql)
  239. rows = self.cur.fetchall()
  240. for row in rows:
  241. return row[0]
  242. # 获取矢量数据表的空间类型
  243. def getVectorTableGeomType(self, tablename):
  244. arr = tablename.split(".")
  245. sql = f'select replace(upper(public.ST_GeometryType(geom)),\'ST_\',\'\') from {arr[0]}."{arr[1]}" limit 1'
  246. self.cur.execute(sql)
  247. rows = self.cur.fetchall()
  248. for row in rows:
  249. return row[0]
  250. def getInstersectsCount(self, tablename, tablesrid, wkts, wktsrid):
  251. arr = tablename.split(".")
  252. wktsql = ""
  253. for i in range(len(wkts)):
  254. wkt = wkts[i]
  255. if i > 0:
  256. wktsql += ' or '
  257. wktsql += f' public.st_intersects(t.geom,public.st_transform( public.st_geomfromtext( \'{wkt}\', {wktsrid}), {tablesrid} )) '
  258. sql = f'select count(1) from {arr[0]}."{arr[1]}" t where {wktsql}'
  259. self.cur.execute(sql)
  260. rows = self.cur.fetchall()
  261. for row in rows:
  262. return row[0]
  263. # 设置表的别名(基于postgresql comment)
  264. def setTableAlias(self, table, alias):
  265. sql = f'COMMENT ON TABLE {table} IS \'{alias}\''
  266. self.cur.execute(sql)
  267. self.conn.commit()
  268. # 删除备份表并创建备份表
  269. def restoreBackTable(self, tablename):
  270. arr = tablename.split(".")
  271. # 删除当前表
  272. deletesql = f'drop table if exists {arr[0]}."{arr[1]}"'
  273. self.cur.execute(deletesql)
  274. self.conn.commit()
  275. # 删除当前表序列
  276. deletesequencesql = f'drop sequence if exists {tablename}{self.Sequence}'
  277. self.cur.execute(deletesequencesql)
  278. self.conn.commit()
  279. # 恢复back表
  280. createsql = f'create table {arr[0]}."{arr[1]}" as table {arr[0]}."{arr[1]}{self.BackTable}"'
  281. self.cur.execute(createsql)
  282. self.conn.commit()
  283. # 查询数据表中id的最大值
  284. sql = f'select (max(id) + 1) from {arr[0]}."{arr[1]}"'
  285. self.cur.execute(sql)
  286. rows = self.cur.fetchall()
  287. max = 1
  288. for row in rows:
  289. max = row[0]
  290. # 创建序列
  291. addsequencesql = f'create sequence {tablename}{self.Sequence} start with {max} increment by 1 no minvalue no maxvalue cache 1'
  292. self.cur.execute(addsequencesql)
  293. self.conn.commit()
  294. # 设置id字段不能为空
  295. notnullsql = f'alter table {arr[0]}."{arr[1]}" alter column id set not null'
  296. self.cur.execute(notnullsql)
  297. self.conn.commit()
  298. # 使用序列
  299. usesequencesql = f'alter table {arr[0]}."{arr[1]}" alter column id set default nextval(\'{tablename}{self.Sequence}\')'
  300. self.cur.execute(usesequencesql)
  301. self.conn.commit()
  302. # 删除备份表并创建备份表
  303. def resetBackTable(self, tablename):
  304. arr = tablename.split(".")
  305. deletesql = f'drop table if exists {arr[0]}."{arr[1]}{self.BackTable}"'
  306. self.cur.execute(deletesql)
  307. self.conn.commit()
  308. createsql = f'create table {arr[0]}."{arr[1]}{self.BackTable}" as table {arr[0]}."{arr[1]}"'
  309. self.cur.execute(createsql)
  310. self.conn.commit()
  311. def getTableName(self, recordid):
  312. sp = recordid.split(".")
  313. res = f'"{sp[0]}"."{sp[1].lower()}"'
  314. return res
  315. # 查询数据库当前模式下有没有同名的表
  316. def checkTableName(self, schemaname, tablename):
  317. sql = f'select tablename from pg_tables t where t.schemaname = \'{schemaname}\' and t.tablename = \'{tablename}\''
  318. self.cur.execute(sql)
  319. rows = self.cur.fetchall()
  320. return len(rows) == 0
  321. # 判断数据是否为字符串
  322. def is_string(self, var):
  323. return isinstance(var, str)