"""SQL NOW() / CURRENT_TIMESTAMP 离线实验:验证确定性时间戳投影、CURRENT_TIMESTAMP 格式规范及方言差异。"""
import json
import platform
import re
import sqlite3
def seed_websites(conn: sqlite3.Connection) -> None:
conn.executescript(
"""
CREATE TABLE websites (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
url TEXT NOT NULL,
alexa INTEGER NOT NULL,
country TEXT NOT NULL
);
INSERT INTO websites (id, name, url, alexa, country) VALUES
(1, 'Google', 'https://www.google.com/', 1, 'USA'),
(2, '淘宝', 'https://www.taobao.com/', 13, 'CN'),
(3, '蓝色天空', 'http://www.mbsky.com/', 4689, 'CN'),
(4, '微博', 'http://weibo.com/', 20, 'CN'),
(5, 'Facebook', 'https://www.facebook.com/', 3, 'USA'),
(7, 'stackoverflow', 'http://stackoverflow.com/', 0, 'IND');
"""
)
def run() -> dict:
conn = sqlite3.connect(":memory:")
seed_websites(conn)
cases = []
# Case 1: Deterministic fixed reference timestamp projection alongside websites rows
fixed_ts = "2026-05-15 08:30:45"
cur1 = conn.execute(
"SELECT name, url, datetime(?) AS date FROM websites ORDER BY id;",
(fixed_ts,),
)
cols1 = [d[0] for d in cur1.description]
rows1 = [list(r) for r in cur1.fetchall()]
exp1 = {
"columns": ["name", "url", "date"],
"row_count": 6,
"first_row": ["Google", "https://www.google.com/", "2026-05-15 08:30:45"],
"last_row": ["stackoverflow", "http://stackoverflow.com/", "2026-05-15 08:30:45"],
"all_rows_share_timestamp": True,
}
act1 = {
"columns": cols1,
"row_count": len(rows1),
"first_row": rows1[0],
"last_row": rows1[-1],
"all_rows_share_timestamp": all(r[2] == fixed_ts for r in rows1),
}
cases.append(
{
"name": "deterministic_timestamp_projection",
"summary": "使用确定性基准时间 2026-05-15 08:30:45 验证 websites 查询附带日期时间列",
"expected": exp1,
"actual": act1,
"passed": act1 == exp1,
}
)
# Case 2: Live CURRENT_TIMESTAMP / datetime('now') format validation (no wall-clock drift)
ts_iso_re = re.compile(r"^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$")
d_iso_re = re.compile(r"^\d{4}-\d{2}-\d{2}$")
cur_ts, dt_now, cur_date = conn.execute(
"SELECT CURRENT_TIMESTAMP, datetime('now'), CURRENT_DATE;"
).fetchone()
exp2 = {
"current_timestamp_matches_iso": True,
"datetime_now_matches_iso": True,
"current_date_matches_iso": True,
"ts_length": 19,
"date_length": 10,
}
act2 = {
"current_timestamp_matches_iso": bool(ts_iso_re.match(cur_ts)),
"datetime_now_matches_iso": bool(ts_iso_re.match(dt_now)),
"current_date_matches_iso": bool(d_iso_re.match(cur_date)),
"ts_length": len(cur_ts),
"date_length": len(cur_date),
}
cases.append(
{
"name": "current_timestamp_format_check",
"summary": "校验 SQLite 标准 CURRENT_TIMESTAMP、datetime('now') 与 CURRENT_DATE 返回 ISO-8601 格式",
"expected": exp2,
"actual": act2,
"passed": act2 == exp2,
}
)
# Case 3: Deterministic date arithmetic & dialect check (NOW() is MySQL/Access/PG, not SQLite)
arith = conn.execute(
"SELECT datetime('2026-05-15 08:30:45', '+8 hours'), date('2026-05-15 08:30:45', '+7 days');"
).fetchone()
now_err = None
try:
conn.execute("SELECT NOW();")
except sqlite3.OperationalError as exc:
now_err = str(exc)
exp3 = {
"plus_8_hours": "2026-05-15 16:30:45",
"plus_7_days": "2026-05-22",
"sqlite_has_no_now": True,
}
act3 = {
"plus_8_hours": arith[0],
"plus_7_days": arith[1],
"sqlite_has_no_now": bool(now_err and "no such function" in now_err.lower()),
}
cases.append(
{
"name": "date_modifiers_and_now_dialect",
"summary": "验证确定性日期偏移计算(+8 hours / +7 days)并核实 SQLite 不内置 MySQL 的 NOW()",
"expected": exp3,
"actual": act3,
"passed": act3 == exp3,
}
)
conn.close()
return {
"version": f"CPython {platform.python_version()} / SQLite {sqlite3.sqlite_version}",
"cases": cases,
}
if __name__ == "__main__":
print(json.dumps(run(), ensure_ascii=False, indent=2))
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/sql-func-now-lab/explore-func-now.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-func-now.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联67章) · 含当前章节或实例 · mbskycom202612a1523.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1550.zip