feat: 规范标准时间字段 created_at/updated_at(Unix 秒级、元数据、trigger)
All checks were successful
技能自动化发布 / release (push) Successful in 6s
All checks were successful
技能自动化发布 / release (push) Successful in 6s
This commit is contained in:
@@ -5,6 +5,7 @@ from __future__ import annotations
|
||||
import sqlite3
|
||||
|
||||
from db.display_metadata import init_display_metadata
|
||||
from db.timestamp_columns import init_task_logs_timestamp_maintenance
|
||||
from util.runtime_paths import get_db_path
|
||||
|
||||
|
||||
@@ -27,11 +28,12 @@ def init_db() -> None:
|
||||
status TEXT NOT NULL,
|
||||
error_msg TEXT,
|
||||
result_summary TEXT,
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL
|
||||
created_at INTEGER NOT NULL DEFAULT (unixepoch()),
|
||||
updated_at INTEGER NOT NULL DEFAULT (unixepoch())
|
||||
)
|
||||
"""
|
||||
)
|
||||
init_task_logs_timestamp_maintenance(cur)
|
||||
init_display_metadata(cur)
|
||||
conn.commit()
|
||||
finally:
|
||||
|
||||
@@ -14,6 +14,8 @@ LEGACY_METADATA_TABLES = frozenset({"_schema_meta"})
|
||||
METADATA_TABLES = INTERNAL_METADATA_TABLES | LEGACY_METADATA_TABLES
|
||||
|
||||
TASK_LOGS_TABLE = "task_logs"
|
||||
DATETIME_UNIX_SECONDS = "datetime_unix_seconds"
|
||||
STANDARD_TIMESTAMP_COLUMNS = frozenset({"created_at", "updated_at"})
|
||||
|
||||
_JIANGCHANG_TABLES_DDL = """
|
||||
CREATE TABLE IF NOT EXISTS _jiangchang_tables (
|
||||
@@ -59,8 +61,24 @@ TASK_LOGS_COLUMN_METADATA: tuple[dict[str, object], ...] = (
|
||||
{"column_name": "status", "display_name": "状态", "description": "任务当前状态", "visible": 1, "searchable": 1, "editable": 1},
|
||||
{"column_name": "error_msg", "display_name": "错误信息", "description": "任务失败时的错误说明", "visible": 1, "searchable": 1, "editable": 1},
|
||||
{"column_name": "result_summary", "display_name": "结果摘要", "description": "任务执行结果摘要", "visible": 1, "searchable": 1, "editable": 1},
|
||||
{"column_name": "created_at", "display_name": "创建时间", "description": "记录创建时间", "visible": 1, "searchable": 1, "editable": 0},
|
||||
{"column_name": "updated_at", "display_name": "更新时间", "description": "记录最后更新时间", "visible": 1, "searchable": 1, "editable": 0},
|
||||
{
|
||||
"column_name": "created_at",
|
||||
"display_name": "创建时间",
|
||||
"description": "记录创建时间(Unix 秒级时间戳,数据库自动生成)",
|
||||
"visible": 1,
|
||||
"searchable": 0,
|
||||
"editable": 0,
|
||||
"display_type": DATETIME_UNIX_SECONDS,
|
||||
},
|
||||
{
|
||||
"column_name": "updated_at",
|
||||
"display_name": "更新时间",
|
||||
"description": "记录最后更新时间(Unix 秒级时间戳,自动维护)",
|
||||
"visible": 1,
|
||||
"searchable": 0,
|
||||
"editable": 0,
|
||||
"display_type": DATETIME_UNIX_SECONDS,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@@ -94,24 +112,26 @@ def upsert_column_metadata(
|
||||
visible: int = 1,
|
||||
searchable: int = 1,
|
||||
editable: int = 1,
|
||||
display_type: str | None = None,
|
||||
) -> None:
|
||||
# display_order 保留为 NULL:宿主按 PRAGMA table_info cid 展示字段,不读 display_order。
|
||||
cursor.execute(
|
||||
"""
|
||||
INSERT INTO _jiangchang_columns (
|
||||
table_name, column_name, display_name, description,
|
||||
display_order, visible, searchable, editable
|
||||
display_order, visible, searchable, editable, display_type
|
||||
)
|
||||
VALUES (?, ?, ?, ?, NULL, ?, ?, ?)
|
||||
VALUES (?, ?, ?, ?, NULL, ?, ?, ?, ?)
|
||||
ON CONFLICT(table_name, column_name) DO UPDATE SET
|
||||
display_name = excluded.display_name,
|
||||
description = excluded.description,
|
||||
display_order = NULL,
|
||||
visible = excluded.visible,
|
||||
searchable = excluded.searchable,
|
||||
editable = excluded.editable
|
||||
editable = excluded.editable,
|
||||
display_type = excluded.display_type
|
||||
""",
|
||||
(table_name, column_name, display_name, description, visible, searchable, editable),
|
||||
(table_name, column_name, display_name, description, visible, searchable, editable, display_type),
|
||||
)
|
||||
|
||||
|
||||
@@ -135,6 +155,7 @@ def seed_task_logs_display_metadata(cursor) -> None:
|
||||
visible=int(column["visible"]),
|
||||
searchable=int(column["searchable"]),
|
||||
editable=int(column["editable"]),
|
||||
display_type=str(column["display_type"]) if column.get("display_type") else None,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -8,12 +8,15 @@ import sqlite3
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
from db.display_metadata import (
|
||||
DATETIME_UNIX_SECONDS,
|
||||
METADATA_TABLES,
|
||||
STANDARD_TIMESTAMP_COLUMNS,
|
||||
TASK_LOGS_COLUMN_METADATA,
|
||||
TASK_LOGS_TABLE,
|
||||
iter_user_tables,
|
||||
list_physical_column_names,
|
||||
)
|
||||
from db.timestamp_columns import has_updated_at_trigger
|
||||
from util.constants import SKILL_SLUG
|
||||
|
||||
_TEMPLATE_PLACEHOLDER_SLUGS = frozenset({"your-skill-slug", "your_skill_slug"})
|
||||
@@ -127,6 +130,116 @@ def validate_skill_frontmatter(skill_root: str, *, allow_template_placeholders:
|
||||
return report
|
||||
|
||||
|
||||
def _quote_identifier(name: str) -> str:
|
||||
return '"' + name.replace('"', '""') + '"'
|
||||
|
||||
|
||||
def _table_column_info(cursor, table_name: str) -> dict[str, dict[str, object]]:
|
||||
cursor.execute(f"PRAGMA table_info({_quote_identifier(table_name)})")
|
||||
info: dict[str, dict[str, object]] = {}
|
||||
for row in cursor.fetchall():
|
||||
info[str(row[1])] = {
|
||||
"cid": int(row[0]),
|
||||
"name": str(row[1]),
|
||||
"type": str(row[2] or ""),
|
||||
"notnull": int(row[3] or 0),
|
||||
"dflt_value": row[4],
|
||||
"pk": int(row[5] or 0),
|
||||
}
|
||||
return info
|
||||
|
||||
|
||||
def _default_uses_unixepoch(default_value: object) -> bool:
|
||||
if default_value is None:
|
||||
return False
|
||||
text = str(default_value).strip().lower()
|
||||
return "unixepoch" in text
|
||||
|
||||
|
||||
def _expected_timestamp_display_name(column_name: str) -> str:
|
||||
if column_name == "created_at":
|
||||
return "创建时间"
|
||||
if column_name == "updated_at":
|
||||
return "更新时间"
|
||||
return ""
|
||||
|
||||
|
||||
def validate_standard_timestamp_columns(
|
||||
cursor,
|
||||
table_name: str,
|
||||
*,
|
||||
physical_columns: list[str] | None = None,
|
||||
) -> tuple[list[str], list[str]]:
|
||||
errors: list[str] = []
|
||||
warnings: list[str] = []
|
||||
ordered = physical_columns or list_physical_column_names(cursor, table_name)
|
||||
column_info = _table_column_info(cursor, table_name)
|
||||
|
||||
for column_name in STANDARD_TIMESTAMP_COLUMNS:
|
||||
if column_name not in ordered:
|
||||
continue
|
||||
|
||||
physical = column_info.get(column_name)
|
||||
if not physical:
|
||||
errors.append(f"{table_name}.{column_name} 缺少物理字段定义")
|
||||
continue
|
||||
|
||||
if "INT" not in str(physical["type"]).upper():
|
||||
errors.append(
|
||||
f"{table_name}.{column_name} 字段类型应为 INTEGER(Unix 秒级时间戳),当前为 {physical['type']!r}"
|
||||
)
|
||||
|
||||
if column_name == "created_at" and not _default_uses_unixepoch(physical["dflt_value"]):
|
||||
errors.append(
|
||||
f"{table_name}.created_at 应设置数据库默认值 DEFAULT (unixepoch()),当前默认值为 {physical['dflt_value']!r}"
|
||||
)
|
||||
if column_name == "updated_at" and not _default_uses_unixepoch(physical["dflt_value"]):
|
||||
errors.append(
|
||||
f"{table_name}.updated_at 应设置数据库初始默认值 DEFAULT (unixepoch()),当前默认值为 {physical['dflt_value']!r}"
|
||||
)
|
||||
|
||||
cursor.execute(
|
||||
"""
|
||||
SELECT display_name, display_type, editable, searchable, display_order
|
||||
FROM _jiangchang_columns
|
||||
WHERE table_name = ? AND column_name = ?
|
||||
""",
|
||||
(table_name, column_name),
|
||||
)
|
||||
meta_row = cursor.fetchone()
|
||||
if not meta_row:
|
||||
errors.append(f"{table_name}.{column_name} 缺少 _jiangchang_columns 元数据")
|
||||
continue
|
||||
|
||||
display_name, display_type, editable, searchable, display_order = meta_row
|
||||
expected_name = _expected_timestamp_display_name(column_name)
|
||||
if str(display_name or "").strip() != expected_name:
|
||||
errors.append(
|
||||
f"{table_name}.{column_name} 的 display_name 应为 {expected_name!r},当前为 {display_name!r}"
|
||||
)
|
||||
if str(display_type or "").strip() != DATETIME_UNIX_SECONDS:
|
||||
errors.append(
|
||||
f"{table_name}.{column_name} 的 display_type 应为 {DATETIME_UNIX_SECONDS!r},当前为 {display_type!r}"
|
||||
)
|
||||
if editable is None or int(editable) != 0:
|
||||
errors.append(f"{table_name}.{column_name} 的 editable 应为 0(系统时间字段不可编辑)")
|
||||
if display_order is not None:
|
||||
errors.append(f"{table_name}.{column_name} 的 display_order 应为 NULL")
|
||||
if searchable is not None and int(searchable) != 0:
|
||||
warnings.append(f"{table_name}.{column_name} 的时间字段通常不必开启 searchable")
|
||||
|
||||
if "created_at" in ordered and "updated_at" in ordered:
|
||||
if ordered.index("updated_at") < ordered.index("created_at"):
|
||||
warnings.append(f"{table_name}: updated_at 不应出现在 created_at 之前")
|
||||
|
||||
if "updated_at" in ordered and not has_updated_at_trigger(cursor, table_name):
|
||||
errors.append(
|
||||
f"{table_name}.updated_at 缺少自动维护 trigger(期望 {table_name}_set_updated_at)"
|
||||
)
|
||||
|
||||
return errors, warnings
|
||||
|
||||
|
||||
def column_order_warnings(table_name: str, ordered_names: list[str]) -> list[str]:
|
||||
warnings: list[str] = []
|
||||
if "id" in ordered_names and ordered_names.index("id") != 0:
|
||||
@@ -208,6 +321,14 @@ def validate_display_metadata(conn: sqlite3.Connection, *, check_column_order: b
|
||||
f"字段 {table_name}.{column_name} 的 display_name 应使用中文:{display_name!r}"
|
||||
)
|
||||
|
||||
ts_errors, ts_warnings = validate_standard_timestamp_columns(
|
||||
cur,
|
||||
table_name,
|
||||
physical_columns=physical_columns,
|
||||
)
|
||||
report.errors.extend(ts_errors)
|
||||
report.warnings.extend(ts_warnings)
|
||||
|
||||
cur.execute("SELECT table_name, column_name FROM _jiangchang_columns")
|
||||
for table_name, column_name in cur.fetchall():
|
||||
if table_name in METADATA_TABLES:
|
||||
|
||||
@@ -9,7 +9,6 @@ from __future__ import annotations
|
||||
from typing import Any, List, Optional, Tuple
|
||||
|
||||
from db.connection import get_conn, init_db
|
||||
from util.timeutil import now_unix
|
||||
|
||||
|
||||
def save_task_log(
|
||||
@@ -22,17 +21,16 @@ def save_task_log(
|
||||
result_summary: Optional[str] = None,
|
||||
) -> int:
|
||||
init_db()
|
||||
now = now_unix()
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO task_logs
|
||||
(task_type, target_id, input_id, input_title, status, error_msg, result_summary, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
(task_type, target_id, input_id, input_title, status, error_msg, result_summary)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(task_type, target_id, input_id, input_title or "", status, error_msg, result_summary, now, now),
|
||||
(task_type, target_id, input_id, input_title or "", status, error_msg, result_summary),
|
||||
)
|
||||
new_id = int(cur.lastrowid)
|
||||
conn.commit()
|
||||
|
||||
36
scripts/db/timestamp_columns.py
Normal file
36
scripts/db/timestamp_columns.py
Normal file
@@ -0,0 +1,36 @@
|
||||
"""标准时间字段:Unix 秒级时间戳、默认值与 updated_at 自动维护。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
STANDARD_TIMESTAMP_COLUMNS = frozenset({"created_at", "updated_at"})
|
||||
DATETIME_UNIX_SECONDS = "datetime_unix_seconds"
|
||||
TASK_LOGS_UPDATED_AT_TRIGGER = "task_logs_set_updated_at"
|
||||
|
||||
_TASK_LOGS_UPDATED_AT_TRIGGER_DDL = f"""
|
||||
CREATE TRIGGER IF NOT EXISTS {TASK_LOGS_UPDATED_AT_TRIGGER}
|
||||
AFTER UPDATE ON task_logs
|
||||
FOR EACH ROW
|
||||
BEGIN
|
||||
UPDATE task_logs
|
||||
SET updated_at = unixepoch()
|
||||
WHERE id = NEW.id AND updated_at = OLD.updated_at;
|
||||
END
|
||||
"""
|
||||
|
||||
|
||||
def init_task_logs_timestamp_maintenance(cursor) -> None:
|
||||
"""幂等创建 task_logs.updated_at 自动维护 trigger。"""
|
||||
cursor.execute(_TASK_LOGS_UPDATED_AT_TRIGGER_DDL)
|
||||
|
||||
|
||||
def has_updated_at_trigger(cursor, table_name: str) -> bool:
|
||||
trigger_name = f"{table_name}_set_updated_at"
|
||||
cursor.execute(
|
||||
"""
|
||||
SELECT 1 FROM sqlite_master
|
||||
WHERE type = 'trigger' AND name = ? AND tbl_name = ?
|
||||
LIMIT 1
|
||||
""",
|
||||
(trigger_name, table_name),
|
||||
)
|
||||
return cursor.fetchone() is not None
|
||||
Reference in New Issue
Block a user