蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行 SQLite 3.53 视图创建、基表更新即时同步与 DROP VIEW 保护基表实验

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-view.py
explore-view.py131 行
"""SQL 视图离线实验:在内存 SQLite 中验证 CREATE VIEW、基表更新同步反映与 DROP VIEW。"""
import json
import platform
import sqlite3


def run() -> dict:
    conn = sqlite3.connect(":memory:")
    conn.executescript(
        """
        CREATE TABLE employees (
            employee_id INTEGER PRIMARY KEY,
            first_name TEXT NOT NULL,
            last_name TEXT NOT NULL,
            salary REAL NOT NULL,
            department_id INTEGER NOT NULL
        );
        INSERT INTO employees (employee_id, first_name, last_name, salary, department_id) VALUES
            (1001, 'Lin', 'Chen', 45000, 10),
            (1002, 'Wei', 'Zhang', 55000, 20),
            (1003, 'Ming', 'Li', 72000, 20),
            (1004, 'Yan', 'Wang', 48000, 30);
        """
    )

    cases = []

    # Case 1: CREATE VIEW & SELECT from view
    conn.execute(
        """
        CREATE VIEW high_salary_employees AS
        SELECT employee_id, first_name, last_name, salary
        FROM employees
        WHERE salary > 50000;
        """
    )
    view_meta = conn.execute(
        "SELECT type, name FROM sqlite_master WHERE name = 'high_salary_employees';"
    ).fetchone()
    view_rows = conn.execute(
        "SELECT employee_id, first_name, salary FROM high_salary_employees ORDER BY employee_id;"
    ).fetchall()

    exp1 = {
        "object_meta": ["view", "high_salary_employees"],
        "initial_high_salary_rows": [[1002, "Wei", 55000.0], [1003, "Ming", 72000.0]],
    }
    act1 = {
        "object_meta": list(view_meta),
        "initial_high_salary_rows": [list(r) for r in view_rows],
    }
    cases.append(
        {
            "name": "create_and_query_view",
            "summary": "验证 CREATE VIEW 定义虚拟视图并筛选出 salary > 50000 的 2 名员工",
            "expected": exp1,
            "actual": act1,
            "passed": act1 == exp1,
        }
    )

    # Case 2: Updating base table immediately updates view query result; direct view UPDATE rejected in SQLite
    direct_update_err = None
    try:
        conn.execute("UPDATE high_salary_employees SET salary = 60000 WHERE employee_id = 1002;")
    except sqlite3.OperationalError as exc:
        direct_update_err = str(exc)

    conn.execute("UPDATE employees SET salary = 60000 WHERE employee_id = 1001;")
    updated_rows = conn.execute(
        "SELECT employee_id, first_name, salary FROM high_salary_employees ORDER BY employee_id;"
    ).fetchall()

    exp2 = {
        "direct_view_update_rejected": True,
        "updated_high_salary_rows": [
            [1001, "Lin", 60000.0],
            [1002, "Wei", 55000.0],
            [1003, "Ming", 72000.0],
        ],
    }
    act2 = {
        "direct_view_update_rejected": direct_update_err is not None and "view" in direct_update_err,
        "updated_high_salary_rows": [list(r) for r in updated_rows],
    }
    cases.append(
        {
            "name": "update_base_table_reflects_in_view",
            "summary": "验证直接 UPDATE SQLite 视图被拒,而更新基表 employees 后视图即时反映新数据(3 行)",
            "expected": exp2,
            "actual": act2,
            "passed": act2 == exp2,
        }
    )

    # Case 3: DROP VIEW IF EXISTS removes definition without affecting base table
    conn.execute("DROP VIEW IF EXISTS high_salary_employees;")
    conn.execute("DROP VIEW IF EXISTS high_salary_employees;")
    view_after = conn.execute(
        "SELECT name FROM sqlite_master WHERE type='view' AND name='high_salary_employees';"
    ).fetchall()
    base_count = conn.execute("SELECT COUNT(*) FROM employees;").fetchone()[0]

    exp3 = {
        "views_remaining": [],
        "base_table_row_count": 4,
    }
    act3 = {
        "views_remaining": view_after,
        "base_table_row_count": base_count,
    }
    cases.append(
        {
            "name": "drop_view_and_preserve_base_table",
            "summary": "验证 DROP VIEW IF EXISTS 删除视图定义且幂等,同时基表 employees 全部 4 条记录完好",
            "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-view-lab/explore-view.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-view.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:SQL

课程关联工程包(登记关联67章) · 含当前章节或实例 · mbskycom202612a1523.zip

下载课程关联工程包:SQL

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1585.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习