Files
verify-promotion-metric-def…/scripts/db/timestamp_columns.py
chenfuqiang 04026d0372
All checks were successful
技能自动化发布 / release (push) Successful in 7s
feat: 职称评审核验助手首版 v1.0.1(verify-promotion-metric-default)
2026-09-13 16:05:20 +08:00

51 lines
1.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""标准时间字段:Unix 秒级时间戳、默认值与 updated_at 自动维护。
业务表若包含 created_at / updated_at,在 CREATE TABLE 后调用
``init_updated_at_trigger(cursor, table_name)``。模板默认不建业务表。
"""
from __future__ import annotations
STANDARD_TIMESTAMP_COLUMNS = frozenset({"created_at", "updated_at"})
DATETIME_UNIX_SECONDS = "datetime_unix_seconds"
def updated_at_trigger_name(table_name: str) -> str:
return f"{table_name}_set_updated_at"
def _quote_identifier(name: str) -> str:
return '"' + name.replace('"', '""') + '"'
def init_updated_at_trigger(cursor, table_name: str) -> None:
"""幂等创建 {table}_set_updated_at:业务字段 UPDATE 后刷新 updated_at。"""
trigger = updated_at_trigger_name(table_name)
quoted = _quote_identifier(table_name)
quoted_trigger = _quote_identifier(trigger)
cursor.execute(
f"""
CREATE TRIGGER IF NOT EXISTS {quoted_trigger}
AFTER UPDATE ON {quoted}
FOR EACH ROW
BEGIN
UPDATE {quoted}
SET updated_at = unixepoch()
WHERE id = NEW.id AND updated_at = OLD.updated_at;
END
"""
)
def has_updated_at_trigger(cursor, table_name: str) -> bool:
trigger_name = updated_at_trigger_name(table_name)
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