"""PostgreSQL 教程总览离线实验:在内存 SQLite 中验证 ORDBMS 表、主键/外键、复合索引、触发器、事务与 JSON/全文检索基础。"""
import json
import platform
import sqlite3
def run() -> dict:
conn = sqlite3.connect(":memory:", isolation_level=None)
conn.execute("PRAGMA foreign_keys = ON;")
cases = []
# Case 1: ORDBMS tables, PK, FK & referential integrity
conn.executescript(
"""
CREATE TABLE company (
id INTEGER PRIMARY KEY NOT NULL,
name TEXT NOT NULL,
age INTEGER NOT NULL,
address TEXT,
salary REAL
);
CREATE TABLE department (
id INTEGER PRIMARY KEY NOT NULL,
dept TEXT NOT NULL,
emp_id INTEGER NOT NULL REFERENCES company(id)
);
INSERT INTO company VALUES
(1, 'Paul', 32, 'California', 20000.0),
(2, 'Allen', 25, 'Texas', 15000.0);
INSERT INTO department VALUES
(1, 'IT Billing', 1),
(2, 'Engineering', 2);
"""
)
fk_rejected = False
try:
conn.execute("INSERT INTO department VALUES (3, 'Finance', 999);")
except sqlite3.IntegrityError:
fk_rejected = True
joined = conn.execute(
"SELECT c.name, d.dept FROM company c JOIN department d ON c.id = d.emp_id ORDER BY c.id;"
).fetchall()
exp1 = {
"company_rows": 2,
"department_rows": 2,
"joined": [["Paul", "IT Billing"], ["Allen", "Engineering"]],
"orphan_fk_rejected": True,
}
act1 = {
"company_rows": conn.execute("SELECT COUNT(*) FROM company;").fetchone()[0],
"department_rows": conn.execute("SELECT COUNT(*) FROM department;").fetchone()[0],
"joined": [[r[0], r[1]] for r in joined],
"orphan_fk_rejected": fk_rejected,
}
cases.append(
{
"name": "ordbms_company_department_model",
"summary": "验证数据库、数据表、行列、主键、外键与参照完整性约束",
"expected": exp1,
"actual": act1,
"passed": act1 == exp1,
}
)
# Case 2: Composite key & B-tree index lookup
conn.executescript(
"""
CREATE TABLE enrollment (
dept_id INTEGER NOT NULL,
emp_id INTEGER NOT NULL,
role TEXT NOT NULL,
PRIMARY KEY (dept_id, emp_id)
);
CREATE INDEX idx_company_age_salary ON company(age, salary);
INSERT INTO enrollment VALUES (1, 1, 'Lead'), (2, 2, 'Engineer');
"""
)
dup_composite_rejected = False
try:
conn.execute("INSERT INTO enrollment VALUES (1, 1, 'Duplicate');")
except sqlite3.IntegrityError:
dup_composite_rejected = True
plan = [r[3] for r in conn.execute(
"EXPLAIN QUERY PLAN SELECT name FROM company WHERE age = 25 AND salary >= 10000;"
).fetchall()]
uses_index = any("idx_company_age_salary" in step for step in plan)
exp2 = {"composite_pk_unique": True, "uses_btree_index": True}
act2 = {"composite_pk_unique": dup_composite_rejected, "uses_btree_index": uses_index}
cases.append(
{
"name": "composite_key_and_index_lookup",
"summary": "验证复合主键唯一性与多列 B-Tree 索引查询计划",
"expected": exp2,
"actual": act2,
"passed": act2 == exp2,
}
)
# Case 3: Trigger + transaction savepoint rollback (local counterpart to PostgreSQL triggers & MVCC transactions)
conn.executescript(
"""
CREATE TABLE audit_log (
log_id INTEGER PRIMARY KEY AUTOINCREMENT,
emp_id INTEGER NOT NULL,
action TEXT NOT NULL
);
CREATE TRIGGER trg_company_insert AFTER INSERT ON company
BEGIN
INSERT INTO audit_log (emp_id, action) VALUES (NEW.id, 'INSERT');
END;
"""
)
conn.execute("BEGIN;")
conn.execute("INSERT INTO company VALUES (3, 'Teddy', 23, 'Norway', 20000.0);")
conn.execute("SAVEPOINT sp1;")
conn.execute("INSERT INTO company VALUES (4, 'TempUser', 20, 'Nowhere', 1000.0);")
conn.execute("ROLLBACK TO sp1;")
conn.execute("RELEASE sp1;")
conn.execute("COMMIT;")
ids_after = [r[0] for r in conn.execute("SELECT id FROM company ORDER BY id;").fetchall()]
logs = conn.execute("SELECT emp_id, action FROM audit_log ORDER BY log_id;").fetchall()
exp3 = {"company_ids": [1, 2, 3], "audit_logs": [[3, "INSERT"]]}
act3 = {"company_ids": ids_after, "audit_logs": [[r[0], r[1]] for r in logs]}
cases.append(
{
"name": "mvcc_transaction_isolation_and_trigger",
"summary": "验证 INSERT 触发器自动记录与事务保存点局部回滚的原子提交行为",
"expected": exp3,
"actual": act3,
"passed": act3 == exp3,
}
)
# Case 4: JSON & full-text search probe (offline counterpart to PostgreSQL JSONB & tsvector)
conn.executescript(
"""
CREATE TABLE pg_docs (id INTEGER PRIMARY KEY, meta TEXT NOT NULL);
INSERT INTO pg_docs VALUES
(1, '{"engine":"PostgreSQL","features":["MVCC","JSONB","FDW"]}'),
(2, '{"engine":"PostgreSQL","features":["GiST","Trigger","Rule"]}');
CREATE VIRTUAL TABLE pg_fts USING fts5(title, body);
INSERT INTO pg_fts VALUES
('MVCC', 'Multiversion concurrency control snapshot isolation'),
('FullText', 'Built-in full text search with lexemes and dictionaries');
"""
)
first_feat = conn.execute(
"SELECT json_extract(meta, '$.features[1]') FROM pg_docs WHERE id = 1;"
).fetchone()[0]
fts_hits = [r[0] for r in conn.execute(
"SELECT title FROM pg_fts WHERE pg_fts MATCH 'snapshot';"
).fetchall()]
exp4 = {"json_feature": "JSONB", "fts_matches": ["MVCC"]}
act4 = {"json_feature": first_feat, "fts_matches": fts_hits}
cases.append(
{
"name": "json_and_fts_capability_probe",
"summary": "以本地 SQLite JSON 函数与 FTS5 演示半结构化查询与全文检索概念",
"expected": exp4,
"actual": act4,
"passed": act4 == exp4,
}
)
conn.close()
return {
"version": f"CPython {platform.python_version()} / SQLite {sqlite3.sqlite_version} (offline PostgreSQL verifier)",
"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/postgresql-tutorial-lab/explore-tutorial.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-tutorial.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1669.zip
课程关联工程包(登记关联45章) · 含当前章节或实例 · mbskycom202612a1633.zip