feat: 工参属性全部由 OpenCode 同一条 SQL 导出;即席查询表没有时间列时不加时间条件

即席查询的 4G/5G 小区工参表没有日期列、4G 只有当前记录,取不到历史日工参,工参不再走即席查询。即席查询的表配置写了 time_field 而表里没有这一列时,按页面做法不带时间条件。
This commit is contained in:
2026-11-11 03:02:05 +08:00
parent 33d132d7b6
commit 688441f4a7
5 changed files with 101 additions and 230 deletions
+14 -81
View File
@@ -2,9 +2,7 @@
from __future__ import annotations
import asyncio
import json
import re
from datetime import date, datetime, timedelta
from urllib.parse import urlencode
@@ -145,7 +143,7 @@ async def export_table(
if not columns:
raise NqiError("这张表没有可导出的字段")
title = str(columns[0].get("tablename_cn") or tablename)
where = _where(columns[0], start, end, city)
where = _where(columns[0], start, end, city, timed=_has_time_column(columns))
common = {
"geographicdimension": columns[0].get("geographicdimension") or "",
"timedimension": columns[0].get("timedimension") or "",
@@ -191,79 +189,6 @@ async def export_table(
return title, columns, rows
async def export_day(
client: NqiClient,
tablename: str,
day: date,
city: str,
fields: tuple[str, ...],
*,
page_size: int = PAGE_SIZE,
pause_seconds: float = 0.3,
) -> list[dict]:
"""取一张表某一天、某个地市的指定几列。
维度有多个可选值时(如“小区,网格,地市,分公司”“天粒度”),按页面默认取第一个并去掉“粒度”。
翻页按实际返回的行数推进,平台把每页压到更少时也不会漏行;取不全就报错。
"""
await ensure_session(client)
columns = await _columns(client, tablename)
selected = [column for column in columns if column.get("columnname") in fields]
missing = set(fields) - {str(column.get("columnname")) for column in selected}
if missing:
raise NqiError(f"{tablename} 缺少字段:{'、'.join(sorted(missing))}")
head = columns[0]
common = {
"geographicdimension": _first_choice(head.get("geographicdimension")),
"timedimension": _first_choice(head.get("timedimension")).removesuffix("粒度"),
"enodebField": head.get("enodeb_field") or "",
"cgiField": head.get("cgi_field") or "",
"timeField": head.get("time_field") or "starttime",
"cellField": head.get("cell_field") or "",
"cityField": head.get("city_field") or "city",
"result": _result_json(head, selected),
"where": json.dumps(_where(head, _start(day), _end(day), city), ensure_ascii=False),
}
total, index_count = await _count(client, common)
rows: list[dict] = []
pages = 0
while len(rows) < total:
pages += 1
if pages > MAX_PAGES:
raise NqiError("数据行数超出单次导出上限")
page = await _post_json(
client,
f"{PAGE}/getTable",
{
**common,
**_column_form(selected),
"draw": pages,
"start": len(rows),
"length": page_size,
"indexcount": index_count,
"total": total,
"order[0][column]": 0,
"order[0][dir]": "desc",
"search[value]": "",
"search[regex]": "false",
},
)
data = page.get("data") if isinstance(page, dict) else None
batch = [item for item in data if isinstance(item, dict)] if isinstance(data, list) else []
if not batch:
break
rows.extend(batch)
if pause_seconds:
await asyncio.sleep(pause_seconds)
if len(rows) < total:
raise NqiError(f"{tablename} 只取到 {len(rows)} 行,应有 {total} 行")
return rows
def _first_choice(value: object) -> str:
return re.split(r"[,,.、]", str(value or ""))[0].strip()
async def _count(client: NqiClient, common: dict) -> tuple[int, str]:
"""平台出错时返回 {"stat":"0"},没有 count。不能当成 0 行。页面第一次计数总是带 indexcount=0,缺了会报错。"""
counted = await _post_json(client, f"{PAGE}/getTableCount", {**common, "indexcount": "0"})
@@ -302,12 +227,20 @@ def _field(column: dict) -> dict:
}
def _where(column: dict, start: datetime, end: datetime, city: str) -> list[dict]:
def _has_time_column(columns: list[dict]) -> bool:
"""工参这类表的配置写了 time_field,表里却没有这一列;页面这时不带时间条件,带了服务端不执行。"""
time_field = str(columns[0].get("time_field") or "starttime") if columns else ""
return any(column.get("columnname") == time_field for column in columns)
def _where(column: dict, start: datetime, end: datetime, city: str, *, timed: bool = True) -> list[dict]:
time_field = str(column.get("time_field") or "starttime")
conditions = [
{"datatype": "timestamp", "feild": time_field, "feildName": "", "symbol": ">=", "val": _stamp(start), "whereCon": "and", "query": True},
{"datatype": "timestamp", "feild": time_field, "feildName": "", "symbol": "<", "val": _stamp(end), "whereCon": "and", "query": True},
]
conditions = []
if timed:
conditions += [
{"datatype": "timestamp", "feild": time_field, "feildName": "", "symbol": ">=", "val": _stamp(start), "whereCon": "and", "query": True},
{"datatype": "timestamp", "feild": time_field, "feildName": "", "symbol": "<", "val": _stamp(end), "whereCon": "and", "query": True},
]
city_name = city.strip()
if city_name:
conditions.append(