feat: 新增Metrix托管应用模式,含管理界面与容器内定时运行

- etl_app:FastAPI + NiceGUI 管理页(概览、运行记录、设置),仅 Metrix 管理员可访问,中英文与日夜间
- 设置页可配定时频率(间隔/Cron)、超时、Metrix 接口、FTP/SFTP 直连、MySQL 直连、目录与保留策略,密码只写不回显
- APScheduler 在同一容器内定时,每次运行是容器内子进程,单实例互斥、超时终止,运行记录存 SQLite、日志落盘
- main.py 抽出文件存储与数据库写入接口,新增 FTP/SFTP/MySQL 实现,脚本模式 CLI 不变
- deploy/Dockerfile、requirements-app.txt、scripts/package_metrix.py 生成应用包,README 补充说明
- 新增 tests/test_app.py,覆盖设置、运行记录、执行器、调度、身份、接口与各连接器
This commit is contained in:
2026-11-06 16:53:36 +08:00
parent ba2d3b2490
commit 96dd78baca
21 changed files with 3806 additions and 137 deletions
+262 -137
View File
@@ -94,6 +94,7 @@ CELL_DATA_FILE_RE = re.compile(r"(?P<date>20\d{6})\.xlsx$", re.IGNORECASE)
LTE_PLMN = "460-00"
DATABASE_NAME = "interference_etl"
DATABASE_TABLE = "interference_hourly_summary"
SQL_IDENTIFIER_RE = re.compile(r"[A-Za-z0-9_]{1,64}")
DEFAULT_HISTORY_ROOT = f"{DEFAULT_ROOT}/干扰历史数据"
LOCAL_CSV_ENCODING = "utf-8-sig"
HISTORY_CSV_ENCODING = "gbk"
@@ -210,6 +211,48 @@ SUMMARY_HEADER = (
"prev_nearby_fdd",
)
TABLE_COLUMNS_DDL = """
metric_time DATETIME NOT NULL COMMENT '指标开始时间',
network_type VARCHAR(16) NOT NULL DEFAULT '',
cgi VARCHAR(128) NOT NULL,
cell_name VARCHAR(255) NOT NULL,
interference_dbm DECIMAL(10,3) NOT NULL,
prev_interference_dbm DECIMAL(10,3) NULL,
longitude DECIMAL(10,6) NULL,
latitude DECIMAL(10,6) NULL,
azimuth DECIMAL(6,2) NOT NULL DEFAULT 0,
nearby_count INT NOT NULL DEFAULT 0,
nearby_26g INT NOT NULL DEFAULT 0,
nearby_700m INT NOT NULL DEFAULT 0,
nearby_tdd INT NOT NULL DEFAULT 0,
nearby_fdd INT NOT NULL DEFAULT 0,
prev_nearby_count INT NULL,
prev_nearby_26g INT NULL,
prev_nearby_700m INT NULL,
prev_nearby_tdd INT NULL,
prev_nearby_fdd INT NULL,
PRIMARY KEY (metric_time, cgi)
"""
COLUMN_MIGRATIONS = {
"network_type": "VARCHAR(16) NOT NULL DEFAULT ''",
"prev_interference_dbm": "DECIMAL(10,3) NULL",
"longitude": "DECIMAL(10,6) NULL",
"latitude": "DECIMAL(10,6) NULL",
"azimuth": "DECIMAL(6,2) NOT NULL DEFAULT 0",
"nearby_count": "INT NOT NULL DEFAULT 0",
"nearby_26g": "INT NOT NULL DEFAULT 0",
"nearby_700m": "INT NOT NULL DEFAULT 0",
"nearby_tdd": "INT NOT NULL DEFAULT 0",
"nearby_fdd": "INT NOT NULL DEFAULT 0",
"prev_nearby_count": "INT NULL",
"prev_nearby_26g": "INT NULL",
"prev_nearby_700m": "INT NULL",
"prev_nearby_tdd": "INT NULL",
"prev_nearby_fdd": "INT NULL",
}
class ProcessingError(RuntimeError):
pass
@@ -244,6 +287,16 @@ class HistoryStore(Protocol):
def upload(self, metric_time: datetime, payload: bytes) -> str: ...
class FileStorage(Protocol):
def list_dir(self, path: str) -> list[dict[str, object]]: ...
def read_bytes(self, path: str) -> bytes: ...
def make_dir(self, path: str) -> None: ...
def write_bytes(self, directory: str, filename: str, payload: bytes) -> str: ...
class MetrixApiClient:
def __init__(self, base_url: str, token: str) -> None:
if not token:
@@ -333,36 +386,33 @@ class MetrixApiClient:
class ApiSummaryStore:
def __init__(self, client: MetrixApiClient, connection_id: str) -> None:
def __init__(
self,
client: MetrixApiClient,
connection_id: str,
database: str = DATABASE_NAME,
table: str = DATABASE_TABLE,
) -> None:
if not connection_id:
raise ProcessingError("METRIX_DATABASE_CONNECTION_ID is required for database output")
self.client = client
self.connection_id = connection_id
self.table = DATABASE_TABLE
self.database = sql_identifier(database, "database")
self.table = sql_identifier(table, "table")
def latest_metric_time(self) -> datetime | None:
self._ensure_schema()
payload = self._query(
f"SELECT MAX(metric_time) AS latest_time FROM `{self.table}`",
database=DATABASE_NAME,
database=self.database,
)
rows = payload.get("rows", [])
value = rows[0].get("latest_time") if rows else None
return datetime.fromisoformat(str(value)) if value else None
def replace_latest(self, rows: list[dict[str, str]]) -> dict[str, object]:
if not rows:
raise ProcessingError("Refusing to replace database data with an empty batch")
metric_times = {datetime.strptime(row["metric_time"], "%Y-%m-%d %H:%M:%S") for row in rows}
if len(metric_times) != 1:
raise ProcessingError("Database batch must contain exactly one metric time")
metric_time = next(iter(metric_times))
latest_time = self.latest_metric_time()
if latest_time is not None and latest_time > metric_time:
raise ProcessingError(
f"Database already contains newer metric time {latest_time:%Y-%m-%d %H:%M:%S}; "
f"refusing to replace it with {metric_time:%Y-%m-%d %H:%M:%S}"
)
metric_time = batch_metric_time(rows)
ensure_not_newer(self.latest_metric_time(), metric_time)
metric_literal = f"'{metric_time:%Y-%m-%d %H:%M:%S}'"
values = ",\n".join(self._row_values(metric_literal, row) for row in rows)
@@ -373,13 +423,13 @@ class ApiSummaryStore:
START TRANSACTION;
DELETE FROM `{self.table}` WHERE metric_time = {metric_literal};
INSERT INTO `{self.table}`
(metric_time, network_type, cgi, cell_name, interference_dbm, prev_interference_dbm, longitude, latitude, azimuth, nearby_count, nearby_26g, nearby_700m, nearby_tdd, nearby_fdd, prev_nearby_count, prev_nearby_26g, prev_nearby_700m, prev_nearby_tdd, prev_nearby_fdd)
({', '.join(SUMMARY_HEADER)})
VALUES
{values};
DELETE FROM `{self.table}` WHERE metric_time <> {metric_literal};
COMMIT;
""",
"database": DATABASE_NAME,
"database": self.database,
"stop_on_error": True,
"single_session": True,
},
@@ -414,7 +464,7 @@ class ApiSummaryStore:
result: list[dict[str, str]] = []
page = 1
while True:
payload = self._query(sql, database=DATABASE_NAME, page=page, page_size=1000)
payload = self._query(sql, database=self.database, page=page, page_size=1000)
rows = payload.get("rows", [])
if not isinstance(rows, list):
raise ProcessingError("Metrix Database API returned invalid rows")
@@ -427,68 +477,24 @@ class ApiSummaryStore:
return result
page += 1
def ping(self) -> str:
payload = self.client.get_json(self._endpoint("server-info"))
if not isinstance(payload, dict):
raise ProcessingError("Metrix Database API returned invalid server info")
return str(payload.get("version") or payload.get("server_version") or "")
def _ensure_schema(self) -> None:
self._query(
f"CREATE DATABASE IF NOT EXISTS `{DATABASE_NAME}` "
"CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci"
)
self._query(
f"""
CREATE TABLE IF NOT EXISTS `{self.table}` (
metric_time DATETIME NOT NULL COMMENT '指标开始时间',
network_type VARCHAR(16) NOT NULL DEFAULT '',
cgi VARCHAR(128) NOT NULL,
cell_name VARCHAR(255) NOT NULL,
interference_dbm DECIMAL(10,3) NOT NULL,
prev_interference_dbm DECIMAL(10,3) NULL,
longitude DECIMAL(10,6) NULL,
latitude DECIMAL(10,6) NULL,
azimuth DECIMAL(6,2) NOT NULL DEFAULT 0,
nearby_count INT NOT NULL DEFAULT 0,
nearby_26g INT NOT NULL DEFAULT 0,
nearby_700m INT NOT NULL DEFAULT 0,
nearby_tdd INT NOT NULL DEFAULT 0,
nearby_fdd INT NOT NULL DEFAULT 0,
prev_nearby_count INT NULL,
prev_nearby_26g INT NULL,
prev_nearby_700m INT NULL,
prev_nearby_tdd INT NULL,
prev_nearby_fdd INT NULL,
PRIMARY KEY (metric_time, cgi)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
""",
database=DATABASE_NAME,
)
self._query(create_database_sql(self.database))
self._query(create_table_sql(self.table), database=self.database)
columns = self.client.get_json(
self._endpoint("columns"),
{"database": DATABASE_NAME, "table": self.table},
{"database": self.database, "table": self.table},
)
if not isinstance(columns, list):
raise ProcessingError("Metrix Database API returned invalid column metadata")
existing_columns = {str(item.get("name")) for item in columns if isinstance(item, dict)}
migrations = {
"network_type": "VARCHAR(16) NOT NULL DEFAULT ''",
"prev_interference_dbm": "DECIMAL(10,3) NULL",
"longitude": "DECIMAL(10,6) NULL",
"latitude": "DECIMAL(10,6) NULL",
"azimuth": "DECIMAL(6,2) NOT NULL DEFAULT 0",
"nearby_count": "INT NOT NULL DEFAULT 0",
"nearby_26g": "INT NOT NULL DEFAULT 0",
"nearby_700m": "INT NOT NULL DEFAULT 0",
"nearby_tdd": "INT NOT NULL DEFAULT 0",
"nearby_fdd": "INT NOT NULL DEFAULT 0",
"prev_nearby_count": "INT NULL",
"prev_nearby_26g": "INT NULL",
"prev_nearby_700m": "INT NULL",
"prev_nearby_tdd": "INT NULL",
"prev_nearby_fdd": "INT NULL",
}
for column, definition in migrations.items():
if column not in existing_columns:
self._query(
f"ALTER TABLE `{self.table}` ADD COLUMN `{column}` {definition}",
database=DATABASE_NAME,
)
for statement in column_migration_sql(self.table, existing_columns):
self._query(statement, database=self.database)
def _endpoint(self, action: str) -> str:
return f"/api/databases/{quote(self.connection_id, safe='')}/{action}"
@@ -530,105 +536,137 @@ class ApiSummaryStore:
) + ")"
class ApiHistoryStore:
def __init__(self, client: MetrixApiClient, storage_id: str, root: str = DEFAULT_HISTORY_ROOT) -> None:
class MetrixStorage:
def __init__(self, client: MetrixApiClient, storage_id: str) -> None:
if not storage_id:
raise ProcessingError("Metrix storage ID is required")
self.client = client
self.storage_id = storage_id
self.root = root.rstrip("/")
def exists(self, metric_time: datetime) -> bool:
directory, filename = self.target(metric_time)
base_entries = self._list_dir(self.root)
if not any(item.get("is_dir") and item.get("path") == directory for item in base_entries):
return False
return any(
not item.get("is_dir") and item.get("name") == filename and int(item.get("size") or 0) > 0
for item in self._list_dir(directory)
)
def list_dir(self, path: str) -> list[dict[str, object]]:
payload = self.client.get_json(self._endpoint("files"), {"path": path, "recursive": "false"})
if not isinstance(payload, dict) or not isinstance(payload.get("entries"), list):
raise ProcessingError("Metrix Storage API returned an invalid file list")
return payload["entries"]
def upload(self, metric_time: datetime, payload: bytes) -> str:
directory, filename = self.target(metric_time)
base_entries = self._list_dir(self.root)
if not any(item.get("is_dir") and item.get("path") == directory for item in base_entries):
response = self.client.post_json(
self._endpoint("mkdir"),
{"path": directory},
timeout=120,
)
if not isinstance(response, dict) or response.get("path") != directory:
raise ProcessingError("Metrix Storage API returned an invalid mkdir result")
response = self.client.post_file(
self._endpoint("upload"),
{"path": directory},
filename,
payload,
)
def read_bytes(self, path: str) -> bytes:
return self.client.get_bytes(self._endpoint("download"), {"path": path}, timeout=120)
def make_dir(self, path: str) -> None:
response = self.client.post_json(self._endpoint("mkdir"), {"path": path}, timeout=120)
if not isinstance(response, dict) or response.get("path") != path:
raise ProcessingError("Metrix Storage API returned an invalid mkdir result")
def write_bytes(self, directory: str, filename: str, payload: bytes) -> str:
response = self.client.post_file(self._endpoint("upload"), {"path": directory}, filename, payload)
expected_path = posixpath.join(directory, filename)
if not isinstance(response, dict) or response.get("path") != expected_path:
raise ProcessingError("Metrix Storage API returned an invalid upload result")
return expected_path
def _endpoint(self, action: str) -> str:
return f"/api/storages/{quote(self.storage_id, safe='')}/{action}"
class StorageHistoryStore:
def __init__(self, storage: FileStorage, root: str = DEFAULT_HISTORY_ROOT) -> None:
self.storage = storage
self.root = root.rstrip("/") or "/"
def exists(self, metric_time: datetime) -> bool:
directory, filename = self.target(metric_time)
if not self._has_directory(directory):
return False
return any(
not item.get("is_dir") and item.get("name") == filename and int(item.get("size") or 0) > 0
for item in self.storage.list_dir(directory)
)
def upload(self, metric_time: datetime, payload: bytes) -> str:
directory, filename = self.target(metric_time)
if not self._has_directory(directory):
self.storage.make_dir(directory)
return self.storage.write_bytes(directory, filename, payload)
def target(self, metric_time: datetime) -> tuple[str, str]:
directory = posixpath.join(self.root, metric_time.strftime("%Y-%m-%d"))
filename = f"干扰数据处理结果_{metric_time:%Y%m%d%H%M%S}.csv"
return directory, filename
def _endpoint(self, action: str) -> str:
return f"/api/storages/{quote(self.storage_id, safe='')}/{action}"
def _list_dir(self, path: str) -> list[dict[str, object]]:
payload = self.client.get_json(self._endpoint("files"), {"path": path, "recursive": "false"})
if not isinstance(payload, dict) or not isinstance(payload.get("entries"), list):
raise ProcessingError("Metrix Storage API returned an invalid file list")
return payload["entries"]
def _has_directory(self, directory: str) -> bool:
return any(item.get("is_dir") and item.get("path") == directory for item in self.storage.list_dir(self.root))
class ApiSource:
def __init__(self, client: MetrixApiClient, storage_id: str, root: str) -> None:
self.client = client
self.storage_id = storage_id
class ApiHistoryStore(StorageHistoryStore):
def __init__(self, client: MetrixApiClient, storage_id: str, root: str = DEFAULT_HISTORY_ROOT) -> None:
super().__init__(MetrixStorage(client, storage_id), root)
class StorageSource:
def __init__(
self,
storage: FileStorage,
root: str,
cell_data_directories: tuple[str, ...] | list[str] = CELL_DATA_DIRECTORIES,
) -> None:
self.storage = storage
self.root = root.rstrip("/") or "/"
self.cell_data_directories = tuple(cell_data_directories)
def candidates(self, lookback_days: int) -> list[Candidate]:
root_entries = self._list_dir(self.root)
date_dirs = sorted(
(item for item in root_entries if item.get("is_dir") and re.fullmatch(r"\d{4}-\d{2}-\d{2}", item.get("name", ""))),
key=lambda item: item["name"],
)
date_dirs = self.date_directories()
selected_dirs = date_dirs[-max(1, lookback_days) :]
result: list[Candidate] = []
for directory in selected_dirs:
for item in self._list_dir(directory["path"]):
for item in self.storage.list_dir(str(directory["path"])):
if item.get("is_dir"):
continue
candidate = parse_candidate(item["path"], int(item.get("size") or 0))
candidate = parse_candidate(str(item["path"]), int(item.get("size") or 0))
if candidate is not None:
result.append(candidate)
return result
def date_directories(self) -> list[dict[str, object]]:
return sorted(
(
item
for item in self.storage.list_dir(self.root)
if item.get("is_dir") and re.fullmatch(r"\d{4}-\d{2}-\d{2}", str(item.get("name", "")))
),
key=lambda item: str(item["name"]),
)
def download(self, path: str) -> bytes:
endpoint = f"/api/storages/{quote(self.storage_id, safe='')}/download"
return self.client.get_bytes(endpoint, {"path": path}, timeout=120)
return self.storage.read_bytes(path)
def cell_data_workbooks(self) -> list[tuple[str, bytes]]:
workbooks: list[tuple[str, bytes]] = []
for directory in CELL_DATA_DIRECTORIES:
item = select_latest_cell_data_file(self._list_dir(directory), directory)
for directory in self.cell_data_directories:
item = select_latest_cell_data_file(self.storage.list_dir(directory), directory)
path = str(item["path"])
workbooks.append((path, self.download(path)))
return workbooks
def _list_dir(self, path: str) -> list[dict[str, object]]:
endpoint = f"/api/storages/{quote(self.storage_id, safe='')}/files"
payload = self.client.get_json(endpoint, {"path": path, "recursive": "false"})
if not isinstance(payload, dict) or not isinstance(payload.get("entries"), list):
raise ProcessingError("Metrix Storage API returned an invalid file list")
return payload["entries"]
class ApiSource(StorageSource):
def __init__(
self,
client: MetrixApiClient,
storage_id: str,
root: str,
cell_data_directories: tuple[str, ...] | list[str] = CELL_DATA_DIRECTORIES,
) -> None:
super().__init__(MetrixStorage(client, storage_id), root, cell_data_directories)
class LocalSource:
def __init__(self, root: Path) -> None:
def __init__(
self,
root: Path,
cell_data_directories: tuple[str, ...] | list[str] = CELL_DATA_DIRECTORIES,
) -> None:
self.root = root.resolve()
self.cell_data_directories = tuple(cell_data_directories)
if not self.root.is_dir():
raise ProcessingError(f"Local source directory does not exist: {self.root}")
@@ -645,12 +683,12 @@ class LocalSource:
return Path(path).read_bytes()
def cell_data_workbooks(self) -> list[tuple[str, bytes]]:
directories = [self.root / Path(directory.lstrip("/")) for directory in CELL_DATA_DIRECTORIES]
directories = [self.root / Path(directory.lstrip("/")) for directory in self.cell_data_directories]
existing = [directory for directory in directories if directory.is_dir()]
if not existing:
return []
if len(existing) != len(directories):
raise ProcessingError("Local CellData source must contain all five configured directories")
raise ProcessingError("Local CellData source must contain all configured directories")
workbooks: list[tuple[str, bytes]] = []
for directory in directories:
entries = [
@@ -830,6 +868,7 @@ def process(
history: HistoryStore | None = None,
) -> Path | None:
candidates = source.candidates(lookback_days)
progress(f"scanned {len(candidates)} source archives")
metric_time, selected, missing = select_window(candidates, requested_window)
if metric_time is None:
print("status=waiting")
@@ -865,9 +904,12 @@ def process(
return None
if latest_time is not None:
previous_rows = store.rows_for_time(latest_time)
progress(f"loaded {len(previous_rows)} previous rows for {latest_time:%Y-%m-%d %H:%M:%S}")
progress(f"processing {metric_time_text}")
cell_data_workbooks = source.cell_data_workbooks()
cell_metadata = load_cell_metadata(cell_data_workbooks)
progress(f"loaded {len(cell_data_workbooks)} cell data workbooks with {len(cell_metadata)} cells")
output_key = metric_time.strftime("%Y%m%d%H%M%S")
temp_dir = output_root.resolve() / f".{output_key}.tmp-{os.getpid()}"
final_dir = output_root.resolve() / output_key
@@ -887,6 +929,8 @@ def process(
candidate = selected[source_type]
raw_zip = source.download(candidate.path)
header, rows, member_name = parse_workbook(raw_zip, source_type)
archive_name = posixpath.basename(candidate.path.replace("\\", "/"))
progress(f"{source_type}: {len(rows)} rows from {archive_name}")
csv_name = f"{source_type}_{candidate.window}.csv"
write_csv(converted_dir / csv_name, header, rows)
for row_number, row in enumerate(rows, start=2):
@@ -913,14 +957,17 @@ def process(
summary_rows.sort(key=lambda item: (item["cgi"], item["cell_name"]))
summary_name = f"interference_summary_{output_key}.csv"
write_dict_csv(temp_dir / summary_name, SUMMARY_HEADER, summary_rows)
progress(f"built {len(summary_rows)} summary rows")
if store is not None:
database_result = store.replace_latest(summary_rows)
progress(f"database updated with {database_result['inserted_rows']} rows")
if history is not None:
history_path = history.upload(
metric_time,
dict_csv_bytes(SUMMARY_HEADER, summary_rows, HISTORY_CSV_ENCODING),
)
history_result = {"enabled": True, "path": history_path}
progress("history CSV uploaded")
matched_coordinates = sum(bool(row["longitude"] and row["latitude"]) for row in summary_rows)
manifest = {
"generated_at": datetime.now(timezone.utc).isoformat(),
@@ -966,6 +1013,10 @@ def process(
return final_dir
def progress(message: str) -> None:
print(f"[{datetime.now():%H:%M:%S}] {message}", flush=True)
def summary_record(
record: dict[str, object],
source_type: str,
@@ -1139,22 +1190,96 @@ def normalize_csv_cell(value: object) -> str:
return normalize_cell(value).replace("\u00a0", " ")
def sql_identifier(value: str, field: str) -> str:
if not SQL_IDENTIFIER_RE.fullmatch(value or ""):
raise ProcessingError(f"Invalid {field} name: {value!r}")
return value
def create_database_sql(database: str) -> str:
return (
f"CREATE DATABASE IF NOT EXISTS `{sql_identifier(database, 'database')}` "
"CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci"
)
def create_table_sql(table: str) -> str:
return (
f"CREATE TABLE IF NOT EXISTS `{sql_identifier(table, 'table')}` ({TABLE_COLUMNS_DDL}) "
"ENGINE=InnoDB DEFAULT CHARSET=utf8mb4"
)
def column_migration_sql(table: str, existing_columns: set[str]) -> list[str]:
return [
f"ALTER TABLE `{sql_identifier(table, 'table')}` ADD COLUMN `{column}` {definition}"
for column, definition in COLUMN_MIGRATIONS.items()
if column not in existing_columns
]
def batch_metric_time(rows: list[dict[str, str]]) -> datetime:
if not rows:
raise ProcessingError("Refusing to replace database data with an empty batch")
metric_times = {datetime.strptime(row["metric_time"], "%Y-%m-%d %H:%M:%S") for row in rows}
if len(metric_times) != 1:
raise ProcessingError("Database batch must contain exactly one metric time")
return next(iter(metric_times))
def ensure_not_newer(latest_time: datetime | None, metric_time: datetime) -> None:
if latest_time is not None and latest_time > metric_time:
raise ProcessingError(
f"Database already contains newer metric time {latest_time:%Y-%m-%d %H:%M:%S}; "
f"refusing to replace it with {metric_time:%Y-%m-%d %H:%M:%S}"
)
def summary_row_params(row: dict[str, str]) -> tuple[object, ...]:
return (
row["metric_time"],
row["network_type"],
row["cgi"],
row["cell_name"],
parse_decimal(row["interference_dbm"], "interference_dbm"),
parse_decimal(row["prev_interference_dbm"], "prev_interference_dbm", nullable=True),
parse_decimal(row["longitude"], "longitude", nullable=True),
parse_decimal(row["latitude"], "latitude", nullable=True),
parse_decimal(row["azimuth"], "azimuth"),
int(row["nearby_count"]),
int(row["nearby_26g"]),
int(row["nearby_700m"]),
int(row["nearby_tdd"]),
int(row["nearby_fdd"]),
parse_decimal(row["prev_nearby_count"], "prev_nearby_count", nullable=True),
parse_decimal(row["prev_nearby_26g"], "prev_nearby_26g", nullable=True),
parse_decimal(row["prev_nearby_700m"], "prev_nearby_700m", nullable=True),
parse_decimal(row["prev_nearby_tdd"], "prev_nearby_tdd", nullable=True),
parse_decimal(row["prev_nearby_fdd"], "prev_nearby_fdd", nullable=True),
)
def sql_text_literal(value: str) -> str:
encoded = value.encode("utf-8").hex()
return "''" if not encoded else f"CONVERT(0x{encoded} USING utf8mb4)"
def sql_decimal_literal(value: str, field: str, nullable: bool = False) -> str:
def parse_decimal(value: str, field: str, nullable: bool = False) -> Decimal | None:
normalized = value.strip()
if not normalized and nullable:
return "NULL"
return None
try:
number = Decimal(normalized)
except InvalidOperation as exc:
raise ProcessingError(f"Invalid decimal value for {field}: {value}") from exc
if not number.is_finite():
raise ProcessingError(f"Invalid decimal value for {field}: {value}")
return format(number, "f")
return number
def sql_decimal_literal(value: str, field: str, nullable: bool = False) -> str:
number = parse_decimal(value, field, nullable)
return "NULL" if number is None else format(number, "f")
def write_csv(path: Path, header: tuple[str, ...], rows: list[tuple[object, ...]]) -> None: