"""检查暴雨避难场所分布图的所有动态图层是否有数据"""
import zipfile, re, os, psycopg2
TEMPLATE_PATH = r"F:\project\xian\xian_algorithm_new\app\data\template\rainfall\暴雨避难场所分布图.qgz"
z = zipfile.ZipFile(TEMPLATE_PATH)
qgs_name = [n for n in z.namelist() if n.endswith('.qgs')][0]
content = z.read(qgs_name).decode('utf-8')
maplayer_re = re.compile(r']*>(.*?)', re.DOTALL)
# 收集所有 PostgreSQL 动态图层
layers = []
for m in maplayer_re.finditer(content):
block = m.group(1)
name_m = re.search(r'([^<]+)', block)
provider_m = re.search(r']*>(\w+)', block)
ds_m = re.search(r'(.*?)', block, re.DOTALL)
provider = provider_m.group(1) if provider_m else '?'
if provider != 'postgres':
continue
name = name_m.group(1) if name_m else '?'
ds = ds_m.group(1).strip() if ds_m else ''
table_m = re.search(r'table="(\w+)"\."(\w+)"', ds)
table_key = f"{table_m.group(1)}.{table_m.group(2)}" if table_m else '?'
layers.append((name, table_key))
# 已知 GPKG 静态层
static_tables = {
'base.rivers', 'base.river', 'base.sx', 'base.sx_capital',
'base.sx_street', 'base.sx_xa_county', 'base.sx_xa_county_boundary',
'base.sx_zb_county_boundary', 'base.sx_zb_city', 'base.sx_zb_county',
'base.active_fault', 'base.traffic_expressway', 'base.traffic_provincial',
'base.traffic_railway', 'base.traffic_township', 'base.traffic_trunk_line',
}
c = psycopg2.connect(host='47.92.216.173', port=7654, user='postgres', password='zhangsan', database='xian_new')
c.autocommit = True
cur = c.cursor()
print(f"模板: 暴雨避难场所分布图")
print(f"{'图层名':20s} {'原表':40s} {'qgis有数据':10s} {'行数':>6s}")
print("-" * 85)
for name, table_key in layers:
if table_key in static_tables:
continue
schema, table = table_key.split('.', 1)
mapped_table = 'hazard_hydrops' if table == 'hazard_waterlogging' else table
try:
cur.execute(f'SELECT count(*) FROM qgis.{mapped_table}')
count = cur.fetchone()[0]
exists = "YES" if count > 0 else "EMPTY"
except:
try:
cur.execute(f'SELECT count(*) FROM {schema}.{table}')
count = cur.fetchone()[0]
exists = f"在{schema}"
except:
exists = "NO"
count = 0
marker = " <-- 无数据!" if count == 0 else ""
print(f"{name:20s} {table_key:40s} {exists:10s} {count:>6,d}{marker}")
c.close()