feat: 工参小区按制式拆成 CellData_4G、CellData_5G;即席查询补上页面必带参数
两张表列名沿用平台工参表,已有快照由迁移 0008 原样搬过去。即席查询的 result 补 tableParams、columnname,计数补 indexcount=0,缺这些服务端会返回 stat 0。
This commit is contained in:
@@ -0,0 +1,83 @@
|
||||
"""工参小区按制式拆成 CellData_4G、CellData_5G,列名沿用平台工参表,已有快照原样搬过去。"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
revision = "0008_celldata_split"
|
||||
down_revision = "0007_gongcan_snapshot"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
SHARED = ("network_type", "area", "town", "state", "cover_type", "frequency_band", "vendor", "azimuth")
|
||||
|
||||
|
||||
def _text(name: str) -> sa.Column:
|
||||
return sa.Column(name, sa.Text(), nullable=False, server_default="")
|
||||
|
||||
|
||||
def _cell_table(name: str, key: str, cell_name: str, node: str, prefix: str) -> None:
|
||||
op.create_table(
|
||||
name,
|
||||
sa.Column("id", sa.BigInteger().with_variant(sa.Integer(), "sqlite"), primary_key=True),
|
||||
sa.Column("snapshot_id", sa.Integer(), sa.ForeignKey("gongcan_snapshot.id", ondelete="CASCADE"), nullable=False),
|
||||
sa.Column(key, sa.String(64), nullable=False),
|
||||
_text(cell_name),
|
||||
_text("station_name"),
|
||||
sa.Column("latitude", sa.Float(), nullable=True),
|
||||
sa.Column("longitude", sa.Float(), nullable=True),
|
||||
_text(f"{node}_id"),
|
||||
_text(f"{node}_name"),
|
||||
*[_text(column) for column in SHARED],
|
||||
sa.UniqueConstraint("snapshot_id", key, name=f"uq_{prefix}_{key}"),
|
||||
)
|
||||
op.create_index(f"ix_{prefix}_station", name, ["snapshot_id", "station_name"])
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
_cell_table("CellData_4G", "cgi", "cell_name", "enodeb", "celldata_4g")
|
||||
_cell_table("CellData_5G", "ncgi", "nrcell_name", "gnodeb", "celldata_5g")
|
||||
shared = ", ".join(SHARED)
|
||||
op.execute(
|
||||
'insert into "CellData_4G" (snapshot_id, cgi, cell_name, station_name, latitude, longitude, enodeb_id, enodeb_name, '
|
||||
f"{shared}) select snapshot_id, cgi, cell_name, site_name, latitude, longitude, node_id, node_name, {shared} "
|
||||
"from gongcan_cell where tech = '4G'"
|
||||
)
|
||||
op.execute(
|
||||
'insert into "CellData_5G" (snapshot_id, ncgi, nrcell_name, station_name, latitude, longitude, gnodeb_id, gnodeb_name, '
|
||||
f"{shared}) select snapshot_id, cgi, cell_name, site_name, latitude, longitude, node_id, node_name, {shared} "
|
||||
"from gongcan_cell where tech = '5G'"
|
||||
)
|
||||
op.drop_index("ix_gongcan_cell_site", table_name="gongcan_cell")
|
||||
op.drop_table("gongcan_cell")
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.create_table(
|
||||
"gongcan_cell",
|
||||
sa.Column("id", sa.BigInteger().with_variant(sa.Integer(), "sqlite"), primary_key=True),
|
||||
sa.Column("snapshot_id", sa.Integer(), sa.ForeignKey("gongcan_snapshot.id", ondelete="CASCADE"), nullable=False),
|
||||
sa.Column("tech", sa.String(4), nullable=False),
|
||||
sa.Column("cgi", sa.String(64), nullable=False),
|
||||
_text("cell_name"),
|
||||
_text("site_name"),
|
||||
sa.Column("latitude", sa.Float(), nullable=True),
|
||||
sa.Column("longitude", sa.Float(), nullable=True),
|
||||
_text("node_id"),
|
||||
_text("node_name"),
|
||||
*[_text(column) for column in SHARED],
|
||||
sa.UniqueConstraint("snapshot_id", "cgi", "tech", name="uq_gongcan_cell"),
|
||||
)
|
||||
op.create_index("ix_gongcan_cell_site", "gongcan_cell", ["snapshot_id", "site_name"])
|
||||
shared = ", ".join(SHARED)
|
||||
op.execute(
|
||||
f"insert into gongcan_cell (snapshot_id, tech, cgi, cell_name, site_name, latitude, longitude, node_id, node_name, {shared}) "
|
||||
f'select snapshot_id, \'4G\', cgi, cell_name, station_name, latitude, longitude, enodeb_id, enodeb_name, {shared} from "CellData_4G"'
|
||||
)
|
||||
op.execute(
|
||||
f"insert into gongcan_cell (snapshot_id, tech, cgi, cell_name, site_name, latitude, longitude, node_id, node_name, {shared}) "
|
||||
f'select snapshot_id, \'5G\', ncgi, nrcell_name, station_name, latitude, longitude, gnodeb_id, gnodeb_name, {shared} from "CellData_5G"'
|
||||
)
|
||||
op.drop_index("ix_celldata_5g_station", table_name="CellData_5G")
|
||||
op.drop_table("CellData_5G")
|
||||
op.drop_index("ix_celldata_4g_station", table_name="CellData_4G")
|
||||
op.drop_table("CellData_4G")
|
||||
@@ -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
|
||||
|
||||
@@ -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
@@ -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="")
|
||||
|
||||
@@ -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 "",
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import asyncio
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from app.nqi import adhoc
|
||||
from app.nqi.client import NqiError
|
||||
|
||||
HEAD = {
|
||||
"tablename": "appdbv3.v_a_common_cfg_lte_cellant_d",
|
||||
"tablename_cn": "4G小区工参",
|
||||
"columnname": "cgi",
|
||||
"columnname_cn": "CGI",
|
||||
"fieldtype": "基础信息",
|
||||
"datatype": "character varying",
|
||||
"columntype": 1,
|
||||
"supporteddimension": None,
|
||||
"supportedtimedimension": None,
|
||||
}
|
||||
|
||||
|
||||
def test_result_json_carries_table_params_like_the_page():
|
||||
payload = json.loads(adhoc._result_json(HEAD, [HEAD]))
|
||||
assert list(payload) == ["result", "tableParams", "columnname"]
|
||||
assert payload["tableParams"] == {"supporteddimension": None, "supportedtimedimension": ""}
|
||||
assert payload["columnname"] == ""
|
||||
assert payload["result"][0]["feild"] == "cgi" and payload["result"][0]["table"] == HEAD["tablename"]
|
||||
|
||||
|
||||
def test_count_sends_indexcount_and_rejects_error_payload(monkeypatch):
|
||||
sent = []
|
||||
replies = [{"count": 37604, "indexcount": "0"}, {"stat": "0", "message": "null"}, {}]
|
||||
|
||||
async def fake_post(client, url, form):
|
||||
sent.append((url.rsplit("/", 1)[-1], form))
|
||||
return replies[len(sent) - 1]
|
||||
|
||||
monkeypatch.setattr(adhoc, "_post_json", fake_post)
|
||||
assert asyncio.run(adhoc._count(None, {"where": "[]"})) == (37604, "0")
|
||||
assert sent[0][0] == "getTableCount" and sent[0][1] == {"where": "[]", "indexcount": "0"}
|
||||
for _ in range(2):
|
||||
with pytest.raises(NqiError):
|
||||
asyncio.run(adhoc._count(None, {"where": "[]"}))
|
||||
@@ -25,7 +25,7 @@ from app.collect.gongcan import (
|
||||
snapshot_task_name,
|
||||
target_center,
|
||||
)
|
||||
from app.models import Base, GongcanCell, GongcanSnapshot
|
||||
from app.models import Base, CellData4G, CellData5G, GongcanSnapshot
|
||||
from app.nqi.client import NqiError
|
||||
from app.nqi.opencode import CsvTable, OpenCode
|
||||
|
||||
@@ -37,12 +37,20 @@ def cell(cgi, site, tech="4G", lat=22.0, lon=113.0, name="A", network_type="LTE"
|
||||
return {"tech": tech, "cgi": cgi, "cell_name": name, "site_name": site, "latitude": lat, "longitude": lon, "network_type": network_type}
|
||||
|
||||
|
||||
def with_target(*others):
|
||||
return [cell("t1", "T"), cell("n1", "N", tech="5G")] + [cell(f"x{i}", name) for i, name in enumerate(others)]
|
||||
def lte(cgi, site, lat=22.0):
|
||||
return {"cgi": cgi, "cell_name": f"{site}-A", "station_name": site, "latitude": lat, "longitude": 113.0, "network_type": "LTE"}
|
||||
|
||||
|
||||
def nr(ncgi, site, lat=22.0):
|
||||
return {"ncgi": ncgi, "nrcell_name": f"{site}-N", "station_name": site, "latitude": lat, "longitude": 113.0, "network_type": "NR"}
|
||||
|
||||
|
||||
def with_target():
|
||||
return {"4G": [lte("t1", "T")], "5G": [nr("n1", "N")]}
|
||||
|
||||
|
||||
def without_target():
|
||||
return [cell("n1", "N", tech="5G"), cell("o1", "O")]
|
||||
return {"4G": [lte("o1", "O")], "5G": [nr("n1", "N")]}
|
||||
|
||||
|
||||
class Clock:
|
||||
@@ -70,7 +78,7 @@ class Platform:
|
||||
|
||||
def make_store(platform, stored=None, clock=None):
|
||||
db = create_engine("sqlite://")
|
||||
Base.metadata.create_all(db, tables=[GongcanSnapshot.__table__, GongcanCell.__table__])
|
||||
Base.metadata.create_all(db, tables=[GongcanSnapshot.__table__, CellData4G.__table__, CellData5G.__table__])
|
||||
clock = clock or Clock()
|
||||
for day, cells in (stored or {}).items():
|
||||
snapshot_id = claim_snapshot(db, CITY, day, clock())
|
||||
@@ -111,13 +119,15 @@ def test_build_cells_merges_coordinates_by_cgi():
|
||||
{"cgi": "c2", "longitude": "0", "latitude": "0"},
|
||||
]
|
||||
cells = build_cells(attrs, coords, "4G")
|
||||
assert [(item["cgi"], item["cell_name"], item["site_name"], item["latitude"], item["longitude"]) for item in cells] == [
|
||||
assert [(item["cgi"], item["cell_name"], item["station_name"], item["latitude"], item["longitude"]) for item in cells] == [
|
||||
("c1", "A", "S1", 22.5, 113.1),
|
||||
("c2", "B", "S2", None, None),
|
||||
]
|
||||
assert cells[0]["node_id"] == "1" and cells[0]["tech"] == "4G" and cells[1]["network_type"] == ""
|
||||
nr = build_cells([{"ncgi": "", "cgi": "n1", "nrcell_name": "N", "gnodeb_id": "9"}], [{"ncgi": "n1", "longitude": "113", "latitude": "22"}], "5G")
|
||||
assert nr == [{**nr[0], "cgi": "n1", "cell_name": "N", "node_id": "9", "latitude": 22.0, "longitude": 113.0}]
|
||||
assert cells[0]["enodeb_id"] == "1" and cells[1]["network_type"] == ""
|
||||
assert set(cells[0]) == {"cgi", "latitude", "longitude"} | set(gongcan.ATTRIBUTES["4G"])
|
||||
rows = build_cells([{"ncgi": "", "cgi": "n1", "nrcell_name": "N", "gnodeb_id": "9"}], [{"ncgi": "n1", "longitude": "113", "latitude": "22"}], "5G")
|
||||
assert rows == [{**rows[0], "ncgi": "n1", "nrcell_name": "N", "gnodeb_id": "9", "latitude": 22.0, "longitude": 113.0}]
|
||||
assert "cgi" not in rows[0] and "enodeb_id" not in rows[0]
|
||||
|
||||
|
||||
def test_key_overlap():
|
||||
@@ -167,19 +177,20 @@ def test_snapshot_takes_attributes_from_adhoc_and_coordinates_from_opencode(monk
|
||||
oc = SnapshotOpenCode(PLATFORM_ROWS)
|
||||
cells, source = asyncio.run(fetch_snapshot(None, oc, CITY, date(2026, 11, 1)))
|
||||
assert source == "adhoc" and oc.phases == ["xy"] and oc.cleaned == [snapshot_task_name(CITY, date(2026, 11, 1))]
|
||||
assert [(item["tech"], item["site_name"], item["latitude"]) for item in cells] == [("4G", "即席站", 22.0), ("5G", "即席站", 22.0)]
|
||||
assert [(row["cgi"], row["station_name"], row["latitude"]) for row in cells["4G"]] == [("c1", "即席站", 22.0)]
|
||||
assert [(row["ncgi"], row["station_name"], row["latitude"]) for row in cells["5G"]] == [("n1", "即席站", 22.0)]
|
||||
|
||||
|
||||
def test_snapshot_falls_back_to_opencode_attributes(monkeypatch):
|
||||
adhoc_returns(monkeypatch, NqiError("即席查询没有返回行数"))
|
||||
oc = SnapshotOpenCode(PLATFORM_ROWS)
|
||||
cells, source = asyncio.run(fetch_snapshot(None, oc, CITY, date(2026, 11, 1)))
|
||||
assert source == "opencode" and oc.phases == ["attr"] and cells[0]["site_name"] == "OC站"
|
||||
assert source == "opencode" and oc.phases == ["attr"] and cells["4G"][0]["station_name"] == "OC站"
|
||||
|
||||
adhoc_returns(monkeypatch, {"4G": [{"cgi": "other"}], "5G": [{"ncgi": "n1"}]})
|
||||
mismatch = SnapshotOpenCode(PLATFORM_ROWS)
|
||||
cells, source = asyncio.run(fetch_snapshot(None, mismatch, CITY, date(2026, 11, 1)))
|
||||
assert source == "opencode" and mismatch.phases == ["xy", "attr"] and cells[0]["cgi"] == "c1"
|
||||
assert source == "opencode" and mismatch.phases == ["xy", "attr"] and cells["4G"][0]["cgi"] == "c1"
|
||||
|
||||
|
||||
def test_snapshot_rejects_empty_city(monkeypatch):
|
||||
@@ -194,10 +205,14 @@ def test_store_answers_presence_queries():
|
||||
assert store.ready_dates(CITY, date(2026, 10, 1), date(2026, 11, 1)) == [date(2026, 10, 1)]
|
||||
assert store.dates_with_target(CITY, SITE, date(2026, 1, 1), date(2027, 1, 1)) == [date(2026, 10, 1)]
|
||||
assert store.has_target(CITY, date(2026, 10, 1), Target(cgis=("zz", "t1")))
|
||||
assert store.has_target(CITY, date(2026, 11, 1), Target(cgis=("n1",)))
|
||||
assert store.has_target(CITY, date(2026, 11, 1), Target(site="N"))
|
||||
assert not store.has_target(CITY, date(2026, 11, 1), Target(cgis=("t1",)))
|
||||
assert not store.has_target("广州", date(2026, 10, 1), SITE)
|
||||
loaded = store.cells(CITY, date(2026, 10, 1))
|
||||
assert {item["cgi"] for item in loaded} == {"t1", "n1"} and loaded[0]["area"] == ""
|
||||
assert sorted((item["tech"], item["cgi"], item["cell_name"], item["site_name"]) for item in loaded) == [("4G", "t1", "T-A", "T"), ("5G", "n1", "N-N", "N")]
|
||||
assert loaded[0]["area"] == "" and loaded[0]["node_id"] == ""
|
||||
assert store.cells(CITY, date(2026, 9, 1)) == []
|
||||
|
||||
|
||||
def test_ensure_loads_once_even_when_tasks_race():
|
||||
|
||||
+33
-17
@@ -10,7 +10,7 @@
|
||||
| OpenCode 接口、提示词、导出核对 | `backend/app/nqi/opencode.py` |
|
||||
| 即席查询按天取指定列 | `backend/app/nqi/adhoc.py` 的 `export_day` |
|
||||
| 快照合并、入库、日期规则、邻站 | `backend/app/collect/gongcan.py` |
|
||||
| 表结构 | `backend/app/models.py` 的 `GongcanSnapshot`、`GongcanCell`,迁移 `0007_gongcan_snapshot` |
|
||||
| 表结构 | `backend/app/models.py` 的 `GongcanSnapshot`、`CellData4G`、`CellData5G`,迁移 `0007_gongcan_snapshot`、`0008_celldata_split` |
|
||||
|
||||
## 一份快照怎么来
|
||||
|
||||
@@ -43,20 +43,29 @@ OpenCode 那份按生效日期严格截取,是日期口径的基准;即席
|
||||
## 存储与并发
|
||||
|
||||
- `gongcan_snapshot`:每个(地市,日期)一行,唯一约束。`status` 为 `loading` / `ready` / `failed`,兼作取数锁。
|
||||
- `gongcan_cell`:快照下的小区,唯一(快照,CGI,制式),另有(快照,站点名)索引。
|
||||
- `CellData_4G`、`CellData_5G`:快照下的小区,4G 和 5G 分表,列名沿用平台工参表,以后两边结构不同也互不影响。
|
||||
PostgreSQL 里表名区分大小写,手写 SQL 要加双引号,如 `select * from "CellData_4G"`。
|
||||
|
||||
| | `CellData_4G` | `CellData_5G` |
|
||||
| --- | --- | --- |
|
||||
| 小区标识 | `cgi` | `ncgi` |
|
||||
| 小区名 | `cell_name` | `nrcell_name` |
|
||||
| 站点名 | `station_name` | `station_name` |
|
||||
| 基站 | `enodeb_id`、`enodeb_name` | `gnodeb_id`、`gnodeb_name` |
|
||||
| 其余 | `latitude`、`longitude`、`network_type`、`area`、`town`、`state`、`cover_type`、`frequency_band`、`vendor`、`azimuth` | 同左 |
|
||||
- 取数前先插入 `loading` 行,插入成功的任务负责取数;插不进的说明别人在取,每 10 秒查一次,最多等 45 分钟。
|
||||
- `loading` 超过 40 分钟没更新视为取数进程已死,下一个任务接手。
|
||||
- `failed` 冷却 10 分钟,期间别的任务直接报“刚取失败”,不反复打平台。
|
||||
- 邻站直接用库里全市快照算,不再按方框扩大范围多次导出。
|
||||
- 4G、5G 存在同一张 `gongcan_cell`,用 `tech` 区分。按 CGI 查走唯一索引(快照,CGI,制式),按站点查走(快照,站点名)索引,
|
||||
地市和日期走 `gongcan_snapshot` 的唯一索引,生产上查目标是否在某天快照里都是索引扫描。
|
||||
- 快照默认全部保留,系统不自动删除。要删时手动删 `gongcan_snapshot` 的行,`gongcan_cell` 按外键级联删除;
|
||||
- 索引:两张小区表各有唯一(快照,`cgi`/`ncgi`)和(快照,`station_name`),地市和日期走 `gongcan_snapshot` 的唯一索引。
|
||||
判断目标在不在某天快照里,按 CGI 和按站点名都只走索引。
|
||||
- 快照默认全部保留,系统不自动删除。要删时手动删 `gongcan_snapshot` 的行,两张小区表按外键级联删除;
|
||||
不要删 `status = 'loading'` 的行,那是正在取数的快照。
|
||||
- 实测江门两份快照(约 12.3 万个小区)占 52 MB,其中索引 13 MB,即每份约 26 MB。
|
||||
|
||||
## 拆除前后用哪天的工参
|
||||
|
||||
目标是一个或几个 CGI,或者一个站点名(按 `site_name` 匹配)。“今天”按北京时间。
|
||||
目标是一个或几个 CGI(4G 对 `cgi`、5G 对 `ncgi`,任一存在即算在),或者一个站点名(按 `station_name` 匹配)。“今天”按北京时间。
|
||||
|
||||
**拆除前**(取不到则该小区/站点的评估任务失败):
|
||||
|
||||
@@ -117,20 +126,27 @@ python script/download-file-all-async.py --sql "select cgi, longitude, latitude,
|
||||
导致 SQL 里的日期被换成别的日期。SQL 里一律写 `make_date(年, 月, 日)`,提示词、路径、阶段名里都不出现日期样式的数字。
|
||||
- **4G 原表没有 `starttime`**,只能按 `eff_from_date` / `eff_to_date` 取某天的状态。
|
||||
- **4G 一个 CGI 多行**(天线粒度),入库按 CGI 去重,优先保留有有效坐标的那条。
|
||||
- **即席查询数据接口暂时不可用**(2026-11-11 起):`getTableCount`、`getTable`、`searchMap` 都返回
|
||||
`{"stat":"0","message":"null"}`,按抓包的完整页面请求顺序重放、重新走 CAS 也一样;`indexSearchMap`、`getPage` 正常。
|
||||
这时快照自动改用 OpenCode 的属性。以前 `getTableCount` 出错会被当成 0 行静默返回,已改为报错。
|
||||
- 即席查询多选的维度(如“小区,网格,地市,分公司”“天粒度”)取第一个值并去掉“粒度”,这是推断,要等页面抓包确认。
|
||||
- **即席查询少一个参数就返回 `{"stat":"0","message":"null"}`**,不是平台故障。已确认页面必带、我们以前漏掉的:
|
||||
- `searchMap` 要带 `status=`(空值);
|
||||
- `getTableCount`、`getTable`、`getTableBottomInfo` 的 `result` 里,字段列表后面还有
|
||||
`"tableParams":{"supporteddimension":<表配置值>,"supportedtimedimension":<表配置值或空串>},"columnname":""`;
|
||||
- `getTableCount` 第一次总是带 `indexcount=0`。页面在结果为 0 行时会把时间放宽到表的粒度周期(周、月)再查一次,并带 `indexcount=1`。
|
||||
补上后,抓包里的“重要场景-小区月粒度”表用我们自己拼的请求能正常计数(33,342 行,与页面一致)。
|
||||
以前 `getTableCount` 出错会被当成 0 行静默返回,已改为报错。
|
||||
- **4G/5G 小区工参表在即席查询里还取不到**:带上上面的参数后,计数返回 `{}`、取数返回 0 行且 `dbTime` 为 0,
|
||||
说明服务端根本没执行查询,这两张表还要别的参数。现有抓包里没有查这两张表的请求,需要在页面上查一次并抓包对照。
|
||||
在此之前快照自动改用 OpenCode 的属性。
|
||||
|
||||
## 迁移模板工具时的字段对照
|
||||
|
||||
| 模板工具 | 快照列 |
|
||||
| --- | --- |
|
||||
| CGI | `cgi`(5G 为 NCGI) |
|
||||
| 小区名 | `cell_name` |
|
||||
| 站点名 | `site_name` |
|
||||
| 纬度 / 经度 | `latitude` / `longitude`(可能为空) |
|
||||
| 制式 | `tech`(`4G` / `5G`) |
|
||||
| 模板工具 | `CellData_4G` | `CellData_5G` |
|
||||
| --- | --- | --- |
|
||||
| CGI | `cgi` | `ncgi` |
|
||||
| 小区名 | `cell_name` | `nrcell_name` |
|
||||
| 站点名 | `station_name` | `station_name` |
|
||||
| 纬度 / 经度 | `latitude` / `longitude`(可能为空) | 同左 |
|
||||
|
||||
程序里 `GongcanStore.cells()` 把两张表合成统一字段(`tech`、`cgi`、`cell_name`、`site_name`、`node_id`、`node_name` 等)给邻站计算用。
|
||||
|
||||
入库筛选沿用模板工具规则:小区名含 `W-` 的室分小区、4G 的 NB-IoT 不参与邻站计算,邻站另外排除名称含“微小”的小区。
|
||||
目标自身是室分(`W-`)时仍然要能找到,所以快照里保留全部小区,筛选只在计算时做。
|
||||
|
||||
Reference in New Issue
Block a user