"""Offline SQLite verifier for MySQL Chapter 28: Database metadata & catalog inspection."""
import json
import sqlite3
import sys
def make_case(name: str, summary: str, expected, actual) -> dict:
return {
"name": name,
"summary": summary,
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main() -> None:
conn = sqlite3.connect(":memory:")
cur = conn.cursor()
cur.execute("PRAGMA foreign_keys = ON")
cur.executescript(
"""
CREATE TABLE departments (
dept_id INTEGER PRIMARY KEY,
dept_name VARCHAR(50) NOT NULL
);
CREATE TABLE employees (
emp_id INTEGER PRIMARY KEY,
emp_name VARCHAR(50) NOT NULL,
dept_id INTEGER NOT NULL,
email VARCHAR(100) UNIQUE,
CONSTRAINT fk_emp_dept FOREIGN KEY (dept_id) REFERENCES departments (dept_id)
);
CREATE INDEX idx_emp_dept ON employees (dept_id);
INSERT INTO departments VALUES (1, 'Engineering'), (2, 'Product');
INSERT INTO employees VALUES
(101, 'Alice', 1, 'alice@example.com'),
(102, 'Bob', 1, 'bob@example.com'),
(103, 'Carol', 2, 'carol@example.com');
"""
)
# 1. Database list, table list, column metadata, CREATE SQL, and row count
dbs = [r[1] for r in cur.execute("PRAGMA database_list").fetchall()]
tables = sorted(
r[0]
for r in cur.execute(
"SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'"
).fetchall()
)
emp_cols = [
{"name": r[1], "type": r[2], "notnull": bool(r[3]), "pk": bool(r[5])}
for r in cur.execute("PRAGMA table_info(employees)").fetchall()
]
create_sql = cur.execute(
"SELECT sql FROM sqlite_master WHERE type='table' AND name='employees'"
).fetchone()[0]
row_count = cur.execute("SELECT COUNT(*) FROM employees").fetchone()[0]
case1 = make_case(
"catalog_tables_columns_ddl",
"Verify database_list, sqlite_master tables/DDL, PRAGMA table_info columns, and COUNT(*)",
{
"dbs": ["main"],
"tables": ["departments", "employees"],
"emp_col_names": ["emp_id", "emp_name", "dept_id", "email"],
"ddl_has_fk": True,
"row_count": 3,
},
{
"dbs": dbs,
"tables": tables,
"emp_col_names": [c["name"] for c in emp_cols],
"ddl_has_fk": "FOREIGN KEY (dept_id) REFERENCES departments (dept_id)" in create_sql,
"row_count": row_count,
},
)
# 2. Index and foreign key metadata (counterpart of SHOW INDEX & KEY_COLUMN_USAGE)
idx_names = sorted(
r[1]
for r in cur.execute("PRAGMA index_list(employees)").fetchall()
if not r[1].startswith("sqlite_")
)
fk_rows = [
{"table": r[2], "from": r[3], "to": r[4]}
for r in cur.execute("PRAGMA foreign_key_list(employees)").fetchall()
]
case2 = make_case(
"catalog_indexes_and_foreign_keys",
"Verify index and foreign-key metadata via PRAGMA index_list and foreign_key_list",
{
"indexes": ["idx_emp_dept"],
"foreign_keys": [{"table": "departments", "from": "dept_id", "to": "dept_id"}],
},
{
"indexes": idx_names,
"foreign_keys": fk_rows,
},
)
# 3. Affected rows count after INSERT/UPDATE/DELETE (counterpart of mysqli_affected_rows / DBI do)
cur.execute("UPDATE employees SET dept_id = 2 WHERE dept_id = 1")
updated_count = cur.rowcount
sql_changes = cur.execute("SELECT changes()").fetchone()[0]
cur.execute("DELETE FROM employees WHERE emp_id = 103")
deleted_count = cur.rowcount
case3 = make_case(
"affected_rows_metadata",
"Verify cursor.rowcount and SELECT changes() accurately report affected rows for DML",
{
"updated_count": 2,
"sql_changes": 2,
"deleted_count": 1,
},
{
"updated_count": updated_count,
"sql_changes": sql_changes,
"deleted_count": deleted_count,
},
)
# 4. Engine version and runtime configuration variables
ver = cur.execute("SELECT sqlite_version()").fetchone()[0]
fk_enabled = cur.execute("PRAGMA foreign_keys").fetchone()[0]
encoding = cur.execute("PRAGMA encoding").fetchone()[0]
case4 = make_case(
"engine_version_and_pragmas",
"Verify engine version string and configuration PRAGMA queries (counterpart of VERSION()/SHOW VARIABLES)",
{
"version_matches": True,
"foreign_keys_enabled": 1,
"encoding": "UTF-8",
},
{
"version_matches": ver == sqlite3.sqlite_version,
"foreign_keys_enabled": fk_enabled,
"encoding": encoding,
},
)
conn.close()
payload = {
"version": f"CPython {sys.version.split()[0]} / SQLite {sqlite3.sqlite_version} (offline MySQL verifier)",
"cases": [case1, case2, case3, case4],
}
print(json.dumps(payload, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14、内置 sqlite3(SQLite 3.53.1)本地离线关系语义验证环境(全程内存库或临时目录运行,未连接外部 MySQL 服务端)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、内置 sqlite3(SQLite 3.53.1)本地离线关系语义验证环境(全程内存库或临时目录运行,未连接外部 MySQL 服务端)。
入口文件:projects/mysql-database-info-lab/explore-database-info.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-database-info.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、内置 sqlite3(SQLite 3.53.1)本地离线关系语义验证环境(全程内存库或临时目录运行,未连接外部 MySQL 服务端)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联41章) · 含当前章节或实例 · mbskycom202612a1590.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1599.zip