feat: 工参小区按制式拆成 CellData_4G、CellData_5G;即席查询补上页面必带参数

两张表列名沿用平台工参表,已有快照由迁移 0008 原样搬过去。即席查询的 result 补 tableParams、columnname,计数补 indexcount=0,缺这些服务端会返回 stat 0。
This commit is contained in:
2026-11-11 02:30:21 +08:00
parent dcd0a87cc3
commit 33d132d7b6
8 changed files with 304 additions and 76 deletions
+61 -32
View File
@@ -15,11 +15,11 @@ from collections.abc import Awaitable, Callable
from dataclasses import dataclass
from datetime import date, datetime, timedelta, timezone
from sqlalchemy import delete, exists, insert, select, update
from sqlalchemy import delete, exists, insert, or_, select, update
from sqlalchemy.engine import Engine
from sqlalchemy.exc import IntegrityError
from app.models import GongcanCell, GongcanSnapshot, utcnow
from app.models import CellData4G, CellData5G, GongcanSnapshot, utcnow
from app.nqi import adhoc
from app.nqi.client import NqiClient, NqiError
from app.nqi.opencode import EFFECTIVE, ExportFile, OpenCode, snapshot_where, task_session
@@ -30,11 +30,13 @@ TECHS = ("4G", "5G")
ADHOC_TABLES = {"4G": "appdbv3.v_a_common_cfg_lte_cellant_d", "5G": "appdbv3.a_common_cfg_nr_cellant_d"}
PLATFORM_TABLES = {"4G": "appdbv3.a_common_cfg_lte_cellant_d", "5G": "appdbv3.a_common_cfg_nr_cellant_d"}
KEYS = {"4G": ("cgi",), "5G": ("ncgi", "cgi")}
NAMED_FIELDS = {
"4G": {"cell_name": "cell_name", "site_name": "station_name", "node_id": "enodeb_id", "node_name": "enodeb_name"},
"5G": {"cell_name": "nrcell_name", "site_name": "station_name", "node_id": "gnodeb_id", "node_name": "gnodeb_name"},
}
KEY_COLUMN = {"4G": "cgi", "5G": "ncgi"}
SHARED_FIELDS = ("network_type", "area", "town", "state", "cover_type", "frequency_band", "vendor", "azimuth")
ATTRIBUTES = {
"4G": ("cell_name", "station_name", "enodeb_id", "enodeb_name") + SHARED_FIELDS,
"5G": ("nrcell_name", "station_name", "gnodeb_id", "gnodeb_name") + SHARED_FIELDS,
}
CELL_TABLES = {"4G": CellData4G.__table__, "5G": CellData5G.__table__}
COORDS = ("longitude", "latitude")
MATCH_RATIO = 0.98
FAILED_COOLDOWN = timedelta(minutes=10)
@@ -66,7 +68,7 @@ class Target:
def attribute_columns(tech: str) -> tuple[str, ...]:
return tuple(NAMED_FIELDS[tech].values()) + SHARED_FIELDS
return ATTRIBUTES[tech]
def adhoc_fields(tech: str) -> tuple[str, ...]:
@@ -124,21 +126,38 @@ def coordinates(rows: list[dict], tech: str) -> dict[str, tuple[float, float]]:
def build_cells(attr_rows: list[dict], coord_rows: list[dict], tech: str) -> list[dict]:
"""按 CellData_4G / CellData_5G 的列名组成一行一个小区。"""
coords = coordinates(coord_rows, tech)
mapping = {**NAMED_FIELDS[tech], **{name: name for name in SHARED_FIELDS}}
cells: dict[str, dict] = {}
for row in attr_rows:
key = key_of(row, tech)
if not key or key in cells:
continue
lat, lon = coords.get(key, (None, None))
cell = {"tech": tech, "cgi": key, "latitude": lat, "longitude": lon}
for target, source in mapping.items():
cell[target] = str(row.get(source) or "").strip()
cell = {KEY_COLUMN[tech]: key, "latitude": lat, "longitude": lon}
for column in ATTRIBUTES[tech]:
cell[column] = str(row.get(column) or "").strip()
cells[key] = cell
return list(cells.values())
def unified(row, tech: str) -> dict:
"""两张表的行换成同一套字段,邻站等计算不用分制式。"""
name, site, node_id, node_name = ATTRIBUTES[tech][:4]
item = {
"tech": tech,
"cgi": row[KEY_COLUMN[tech]],
"cell_name": row[name],
"site_name": row[site],
"node_id": row[node_id],
"node_name": row[node_name],
"latitude": row["latitude"],
"longitude": row["longitude"],
}
item.update({column: row[column] for column in SHARED_FIELDS})
return item
def key_overlap(attr_rows: list[dict], coord_rows: list[dict], tech: str) -> float:
left = {key_of(row, tech) for row in attr_rows} - {""}
right = {key_of(row, tech) for row in coord_rows} - {""}
@@ -147,8 +166,8 @@ def key_overlap(attr_rows: list[dict], coord_rows: list[dict], tech: str) -> flo
return len(left & right) / len(left | right)
async def fetch_snapshot(nqi: NqiClient, oc: OpenCode, city: str, day: date, *, use_adhoc: bool = True) -> tuple[list[dict], str]:
"""从大数据平台取一份快照,返回小区列表和属性来源(adhoc / opencode)。"""
async def fetch_snapshot(nqi: NqiClient, oc: OpenCode, city: str, day: date, *, use_adhoc: bool = True) -> tuple[dict[str, list[dict]], str]:
"""从大数据平台取一份快照,返回按制式分开的小区行和属性来源(adhoc / opencode)。"""
attrs: dict[str, list[dict]] | None = None
if use_adhoc:
try:
@@ -171,14 +190,13 @@ async def fetch_snapshot(nqi: NqiClient, oc: OpenCode, city: str, day: date, *,
rows = {tech: tables[item.key].rows for tech, item in zip(TECHS, files)}
source = "adhoc" if attrs is not None else "opencode"
attrs = attrs if attrs is not None else rows
cells = [cell for tech in TECHS for cell in build_cells(attrs[tech], rows[tech], tech)]
if not any(cell["tech"] == "4G" for cell in cells) or not any(cell["tech"] == "5G" for cell in cells):
cells = {tech: build_cells(attrs[tech], rows[tech], tech) for tech in TECHS}
if not all(cells.values()):
raise GongcanError(f"{city} {day} 的工参是空的")
return cells, source
_SNAPSHOT = GongcanSnapshot.__table__
_CELL = GongcanCell.__table__
def _aware(value: datetime) -> datetime:
@@ -212,20 +230,22 @@ def claim_snapshot(engine: Engine, city: str, day: date, now: datetime) -> int |
return int(row.id) if taken.rowcount == 1 else None
def save_snapshot(engine: Engine, snapshot_id: int, cells: list[dict], source: str, now: datetime) -> None:
def save_snapshot(engine: Engine, snapshot_id: int, cells: dict[str, list[dict]], source: str, now: datetime) -> None:
with engine.begin() as connection:
connection.execute(delete(_CELL).where(_CELL.c.snapshot_id == snapshot_id))
for start in range(0, len(cells), 2000):
connection.execute(insert(_CELL), [{**cell, "snapshot_id": snapshot_id} for cell in cells[start:start + 2000]])
for tech, table in CELL_TABLES.items():
rows = cells.get(tech) or []
connection.execute(delete(table).where(table.c.snapshot_id == snapshot_id))
for start in range(0, len(rows), 2000):
connection.execute(insert(table), [{**row, "snapshot_id": snapshot_id} for row in rows[start:start + 2000]])
connection.execute(
update(_SNAPSHOT)
.where(_SNAPSHOT.c.id == snapshot_id)
.values(
status="ready",
attr_source=source,
lte_cells=sum(1 for cell in cells if cell["tech"] == "4G"),
nr_cells=sum(1 for cell in cells if cell["tech"] == "5G"),
located_cells=sum(1 for cell in cells if cell["latitude"] is not None),
lte_cells=len(cells.get("4G") or []),
nr_cells=len(cells.get("5G") or []),
located_cells=sum(1 for rows in cells.values() for row in rows if row["latitude"] is not None),
error="",
updated_at=now,
)
@@ -238,8 +258,11 @@ def fail_snapshot(engine: Engine, snapshot_id: int, error: str, now: datetime) -
def _has_target(target: Target):
condition = _CELL.c.site_name == target.site if target.site else _CELL.c.cgi.in_(target.cgis)
return exists(select(_CELL.c.id).where(_CELL.c.snapshot_id == _SNAPSHOT.c.id, condition))
found = []
for tech, table in CELL_TABLES.items():
condition = table.c.station_name == target.site if target.site else table.c[KEY_COLUMN[tech]].in_(target.cgis)
found.append(exists(select(table.c.id).where(table.c.snapshot_id == _SNAPSHOT.c.id, condition)))
return or_(*found)
def _ready(city: str, start: date, end: date):
@@ -252,7 +275,7 @@ class GongcanStore:
def __init__(
self,
engine: Engine,
loader: Callable[[str, date], Awaitable[tuple[list[dict], str]]],
loader: Callable[[str, date], Awaitable[tuple[dict[str, list[dict]], str]]],
*,
poll_seconds: float = 10.0,
wait_timeout: timedelta = timedelta(minutes=45),
@@ -278,10 +301,16 @@ class GongcanStore:
return bool(self.dates_with_target(city, target, day, day + timedelta(days=1)))
def cells(self, city: str, day: date) -> list[dict]:
columns = [column for column in _CELL.c if column.name not in ("id", "snapshot_id")]
"""当天快照里 4G、5G 的全部小区,字段见 unified。"""
with self.engine.connect() as connection:
query = select(*columns).join(_SNAPSHOT, _SNAPSHOT.c.id == _CELL.c.snapshot_id).where(*_ready(city, day, day + timedelta(days=1)))
return [dict(row._mapping) for row in connection.execute(query)]
snapshot_id = connection.execute(select(_SNAPSHOT.c.id).where(*_ready(city, day, day + timedelta(days=1)))).scalar()
if snapshot_id is None:
return []
return [
unified(row, tech)
for tech, table in CELL_TABLES.items()
for row in connection.execute(select(table).where(table.c.snapshot_id == snapshot_id)).mappings()
]
def _state(self, city: str, day: date):
with self.engine.connect() as connection:
@@ -314,13 +343,13 @@ class GongcanStore:
except BaseException as exc:
fail_snapshot(self.engine, snapshot_id, f"{type(exc).__name__}: {exc}", self.clock())
raise
logger.info("工参快照 %s %s 已入库:%s 个小区,属性来自 %s", city, day, len(cells), source)
logger.info("工参快照 %s %s 已入库:4G %s 个、5G %s 个小区,属性来自 %s", city, day, len(cells.get("4G") or []), len(cells.get("5G") or []), source)
def platform_loader(nqi: NqiClient, *, use_adhoc: bool = True) -> Callable[[str, date], Awaitable[tuple[list[dict], str]]]:
def platform_loader(nqi: NqiClient, *, use_adhoc: bool = True) -> Callable[[str, date], Awaitable[tuple[dict[str, list[dict]], str]]]:
oc = OpenCode(nqi)
async def load(city: str, day: date) -> tuple[list[dict], str]:
async def load(city: str, day: date) -> tuple[dict[str, list[dict]], str]:
return await fetch_snapshot(nqi, oc, city, day, use_adhoc=use_adhoc)
return load
+2 -1
View File
@@ -33,7 +33,8 @@ APP_TABLES = {
"collection_source",
"export_task",
"gongcan_snapshot",
"gongcan_cell",
"celldata_4g",
"celldata_5g",
}
_UNSAFE = re.compile(r"[^0-9A-Za-z_]+")
_CHUNK = 300
+37 -8
View File
@@ -101,24 +101,53 @@ class GongcanSnapshot(Base):
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
class GongcanCell(Base):
__tablename__ = "gongcan_cell"
class CellData4G(Base):
"""4G 小区工参快照,列名沿用平台 4G 工参表。"""
__tablename__ = "CellData_4G"
__table_args__ = (
UniqueConstraint("snapshot_id", "cgi", "tech", name="uq_gongcan_cell"),
Index("ix_gongcan_cell_site", "snapshot_id", "site_name"),
UniqueConstraint("snapshot_id", "cgi", name="uq_celldata_4g_cgi"),
Index("ix_celldata_4g_station", "snapshot_id", "station_name"),
)
id: Mapped[int] = mapped_column(BigInteger().with_variant(Integer, "sqlite"), primary_key=True)
snapshot_id: Mapped[int] = mapped_column(ForeignKey("gongcan_snapshot.id", ondelete="CASCADE"))
tech: Mapped[str] = mapped_column(String(4))
cgi: Mapped[str] = mapped_column(String(64))
cell_name: Mapped[str] = mapped_column(Text, default="")
site_name: Mapped[str] = mapped_column(Text, default="")
station_name: Mapped[str] = mapped_column(Text, default="")
latitude: Mapped[float | None] = mapped_column(Float, nullable=True)
longitude: Mapped[float | None] = mapped_column(Float, nullable=True)
enodeb_id: Mapped[str] = mapped_column(Text, default="")
enodeb_name: Mapped[str] = mapped_column(Text, default="")
network_type: Mapped[str] = mapped_column(Text, default="")
area: Mapped[str] = mapped_column(Text, default="")
town: Mapped[str] = mapped_column(Text, default="")
state: Mapped[str] = mapped_column(Text, default="")
cover_type: Mapped[str] = mapped_column(Text, default="")
frequency_band: Mapped[str] = mapped_column(Text, default="")
vendor: Mapped[str] = mapped_column(Text, default="")
azimuth: Mapped[str] = mapped_column(Text, default="")
class CellData5G(Base):
"""5G 小区工参快照,列名沿用平台 5G 工参表。"""
__tablename__ = "CellData_5G"
__table_args__ = (
UniqueConstraint("snapshot_id", "ncgi", name="uq_celldata_5g_ncgi"),
Index("ix_celldata_5g_station", "snapshot_id", "station_name"),
)
id: Mapped[int] = mapped_column(BigInteger().with_variant(Integer, "sqlite"), primary_key=True)
snapshot_id: Mapped[int] = mapped_column(ForeignKey("gongcan_snapshot.id", ondelete="CASCADE"))
ncgi: Mapped[str] = mapped_column(String(64))
nrcell_name: Mapped[str] = mapped_column(Text, default="")
station_name: Mapped[str] = mapped_column(Text, default="")
latitude: Mapped[float | None] = mapped_column(Float, nullable=True)
longitude: Mapped[float | None] = mapped_column(Float, nullable=True)
gnodeb_id: Mapped[str] = mapped_column(Text, default="")
gnodeb_name: Mapped[str] = mapped_column(Text, default="")
network_type: Mapped[str] = mapped_column(Text, default="")
node_id: Mapped[str] = mapped_column(Text, default="")
node_name: Mapped[str] = mapped_column(Text, default="")
area: Mapped[str] = mapped_column(Text, default="")
town: Mapped[str] = mapped_column(Text, default="")
state: Mapped[str] = mapped_column(Text, default="")
+17 -5
View File
@@ -145,7 +145,6 @@ async def export_table(
if not columns:
raise NqiError("这张表没有可导出的字段")
title = str(columns[0].get("tablename_cn") or tablename)
selected = [_field(column) for column in columns]
where = _where(columns[0], start, end, city)
common = {
"geographicdimension": columns[0].get("geographicdimension") or "",
@@ -155,7 +154,7 @@ async def export_table(
"timeField": columns[0].get("time_field") or "starttime",
"cellField": columns[0].get("cell_field") or "",
"cityField": columns[0].get("city_field") or "city",
"result": json.dumps({"result": selected}, ensure_ascii=False),
"result": _result_json(columns[0], columns),
"where": json.dumps(where, ensure_ascii=False),
}
total, index_count = await _count(client, common)
@@ -222,7 +221,7 @@ async def export_day(
"timeField": head.get("time_field") or "starttime",
"cellField": head.get("cell_field") or "",
"cityField": head.get("city_field") or "city",
"result": json.dumps({"result": [_field(column) for column in selected]}, ensure_ascii=False),
"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)
@@ -266,14 +265,27 @@ def _first_choice(value: object) -> str:
async def _count(client: NqiClient, common: dict) -> tuple[int, str]:
"""平台出错时返回 {"stat":"0"},没有 count。不能当成 0 行。"""
counted = await _post_json(client, f"{PAGE}/getTableCount", common)
"""平台出错时返回 {"stat":"0"},没有 count。不能当成 0 行。页面第一次计数总是带 indexcount=0,缺了会报错。"""
counted = await _post_json(client, f"{PAGE}/getTableCount", {**common, "indexcount": "0"})
if not isinstance(counted, dict) or "count" not in counted:
message = counted.get("message") if isinstance(counted, dict) else ""
raise NqiError(f"即席查询没有返回行数{f':{message}' if message and message != 'null' else ''}")
return int(counted.get("count") or 0), str(counted.get("indexcount") or "0")
def _result_json(head: dict, columns: list[dict]) -> str:
"""页面在字段列表后还带 tableParams 和 columnname,缺了服务端返回 {"stat":"0","message":"null"}。"""
payload = {
"result": [_field(column) for column in columns],
"tableParams": {
"supporteddimension": head.get("supporteddimension"),
"supportedtimedimension": head.get("supportedtimedimension") or "",
},
"columnname": "",
}
return json.dumps(payload, ensure_ascii=False)
def _field(column: dict) -> dict:
return {
"feildtype": column.get("fieldtype") or "",