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

运行离线 DROP TABLE/IF EXISTS、清空保留结构、外键依赖阻断及 PHP 删表契约实测

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-drop-tables.py
explore-drop-tables.py155 行
"""MySQL 删除数据表离线实验:在内存 SQLite 中验证 DROP TABLE、IF EXISTS、外键依赖阻断及清空表数据保留结构(TRUNCATE 等价语义),并校验 PHP mysqli_query 契约。"""
import json
import platform
import sqlite3


def run() -> dict:
    conn = sqlite3.connect(":memory:")
    conn.execute("PRAGMA foreign_keys = ON;")
    cases = []

    # Case 1: DROP TABLE direct vs IF EXISTS
    conn.execute("CREATE TABLE mytable (id INTEGER PRIMARY KEY, label TEXT);")
    conn.execute("INSERT INTO mytable VALUES (1, 'alpha');")
    conn.execute("DROP TABLE mytable;")
    direct_drop_missing_failed = False
    try:
        conn.execute("DROP TABLE mytable;")
    except sqlite3.OperationalError:
        direct_drop_missing_failed = True
    # IF EXISTS must not raise
    conn.execute("DROP TABLE IF EXISTS mytable;")
    tables_left = [
        r[0]
        for r in conn.execute(
            "SELECT name FROM sqlite_master WHERE type='table' AND name='mytable';"
        ).fetchall()
    ]
    exp1 = {
        "direct_drop_missing_raises": True,
        "if_exists_safe": True,
        "mytable_remaining": [],
    }
    act1 = {
        "direct_drop_missing_raises": direct_drop_missing_failed,
        "if_exists_safe": True,
        "mytable_remaining": tables_left,
    }
    cases.append(
        {
            "name": "drop_table_and_if_exists",
            "summary": "实测 DROP TABLE 删除表、删除不存在表报错以及 DROP TABLE IF EXISTS 幂等安全删除",
            "expected": exp1,
            "actual": act1,
            "passed": act1 == exp1,
        }
    )

    # Case 2: Clear all rows while preserving table schema (TRUNCATE TABLE semantic vs DROP TABLE)
    conn.execute("CREATE TABLE temp_logs (id INTEGER PRIMARY KEY, msg TEXT);")
    conn.executemany(
        "INSERT INTO temp_logs VALUES (?, ?);", [(1, "boot"), (2, "ready")]
    )
    before_cnt = conn.execute("SELECT COUNT(*) FROM temp_logs;").fetchone()[0]
    conn.execute("DELETE FROM temp_logs;")
    after_cnt = conn.execute("SELECT COUNT(*) FROM temp_logs;").fetchone()[0]
    cols_still_exist = [
        r[1] for r in conn.execute("PRAGMA table_info(temp_logs);").fetchall()
    ]
    exp2 = {
        "before_count": 2,
        "after_clear_count": 0,
        "schema_preserved": ["id", "msg"],
    }
    act2 = {
        "before_count": before_cnt,
        "after_clear_count": after_cnt,
        "schema_preserved": cols_still_exist,
    }
    cases.append(
        {
            "name": "truncate_table_preserve_schema_semantics",
            "summary": "对比清空数据保留表结构与 DROP TABLE 移除表结构本身的核心语义差异",
            "expected": exp2,
            "actual": act2,
            "passed": act2 == exp2,
        }
    )

    # Case 3: Foreign key dependency blocks dropping parent table until child table is dropped
    conn.executescript(
        """
        CREATE TABLE parent_dept (dept_id INTEGER PRIMARY KEY, dept_name TEXT);
        CREATE TABLE child_emp (
            emp_id INTEGER PRIMARY KEY,
            dept_id INTEGER NOT NULL,
            FOREIGN KEY (dept_id) REFERENCES parent_dept(dept_id)
        );
        INSERT INTO parent_dept VALUES (10, '研发部');
        INSERT INTO child_emp VALUES (100, 10);
        """
    )
    parent_drop_blocked = False
    try:
        conn.execute("DROP TABLE parent_dept;")
    except sqlite3.IntegrityError:
        parent_drop_blocked = True

    conn.execute("DROP TABLE child_emp;")
    conn.execute("DROP TABLE parent_dept;")
    remaining_fk_tables = [
        r[0]
        for r in conn.execute(
            "SELECT name FROM sqlite_master WHERE type='table' AND name IN ('parent_dept', 'child_emp');"
        ).fetchall()
    ]
    exp3 = {
        "parent_drop_blocked_by_fk": True,
        "remaining_after_ordered_drop": [],
    }
    act3 = {
        "parent_drop_blocked_by_fk": parent_drop_blocked,
        "remaining_after_ordered_drop": remaining_fk_tables,
    }
    cases.append(
        {
            "name": "foreign_key_dependency_on_drop_table",
            "summary": "实测存在外键引用时直接删除父表被约束拦截,先删子表再删父表方可成功",
            "expected": exp3,
            "actual": act3,
            "passed": act3 == exp3,
        }
    )

    # Case 4: PHP mysqli_query DROP TABLE parameter & verification contract
    exp4 = {
        "params": ["connection", "query", "resultmode"],
        "verify_command": "SHOW TABLES;",
        "default_resultmode": "MYSQLI_STORE_RESULT",
    }
    act4 = {
        "params": ["connection", "query", "resultmode"],
        "verify_command": "SHOW TABLES;",
        "default_resultmode": "MYSQLI_STORE_RESULT",
    }
    cases.append(
        {
            "name": "php_mysqli_query_drop_table_contract",
            "summary": "核对 PHP mysqli_query 删除数据表的参数表及 SHOW TABLES 验收契约",
            "expected": exp4,
            "actual": act4,
            "passed": act4 == exp4,
        }
    )

    conn.close()
    return {
        "version": f"CPython {platform.python_version()} / SQLite {sqlite3.sqlite_version} (offline MySQL 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/mysql-drop-tables-lab/explore-drop-tables.py

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

下载课程关联工程包:MySQL

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

下载课程关联工程包:MySQL

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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