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

在本地 SQLite 3.53.1 实测临时表 CTAS、ALTER/DROP、目录隐藏与多会话隔离销毁

PYTHONWindows x64、CPython 3.12.14、内置 sqlite3(SQLite 3.53.1)本地离线关系语义验证环境(全程内存库或临时目录运行,未连接外部 MySQL 服务端)。explore-temporary-tables.py
explore-temporary-tables.py162 行
"""Offline SQLite verifier for MySQL Chapter 26: Temporary Tables."""
import json
import sqlite3
import sys
import tempfile
from pathlib import Path


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()

    # 1. CREATE TEMPORARY TABLE explicit schema & CTAS (AS SELECT)
    cur.executescript(
        """
        CREATE TABLE orders (
            order_id INT,
            customer_id INT,
            order_date TEXT
        );
        INSERT INTO orders VALUES
            (999, 1, '2022-12-20'),
            (1000, 2, '2023-01-02');

        CREATE TEMPORARY TABLE SalesSummary (
            product_name VARCHAR(50) NOT NULL,
            total_sales REAL NOT NULL DEFAULT 0.00,
            avg_unit_price REAL NOT NULL DEFAULT 0.00,
            total_units_sold INT NOT NULL DEFAULT 0
        );
        INSERT INTO SalesSummary (product_name, total_sales, avg_unit_price, total_units_sold)
        VALUES ('cucumber', 100.25, 90.0, 2);

        CREATE TEMPORARY TABLE temp_orders AS
        SELECT * FROM orders WHERE order_date >= '2023-01-01';
        INSERT INTO temp_orders (order_id, customer_id, order_date)
        VALUES (1001, 1, '2023-01-05');
        """
    )
    sales_rows = [list(r) for r in cur.execute("SELECT * FROM SalesSummary").fetchall()]
    temp_order_rows = [
        list(r) for r in cur.execute("SELECT * FROM temp_orders ORDER BY order_id").fetchall()
    ]
    case1 = make_case(
        "temp_table_create_crud_and_ctas",
        "Verify explicit CREATE TEMPORARY TABLE and CREATE TEMPORARY TABLE ... AS SELECT with INSERT/SELECT",
        {
            "sales_summary": [["cucumber", 100.25, 90.0, 2]],
            "temp_orders": [[1000, 2, "2023-01-02"], [1001, 1, "2023-01-05"]],
        },
        {
            "sales_summary": sales_rows,
            "temp_orders": temp_order_rows,
        },
    )

    # 2. ALTER TABLE and manual DROP TABLE on temporary table
    cur.execute("ALTER TABLE temp_orders ADD COLUMN note TEXT DEFAULT 'ok'")
    altered_cols = [r[1] for r in cur.execute("PRAGMA table_info(temp_orders)").fetchall()]
    cur.execute("DROP TABLE IF EXISTS temp_orders")
    query_after_drop_failed = False
    try:
        cur.execute("SELECT * FROM temp_orders")
    except sqlite3.OperationalError:
        query_after_drop_failed = True

    case2 = make_case(
        "temp_table_alter_and_drop",
        "Verify ALTER TABLE adds column to temporary table and DROP TABLE immediately removes it",
        {
            "altered_cols": ["order_id", "customer_id", "order_date", "note"],
            "query_after_drop_failed": True,
        },
        {
            "altered_cols": altered_cols,
            "query_after_drop_failed": query_after_drop_failed,
        },
    )

    # 3. Temporary table absent from main schema catalog (analogous to SHOW TABLES)
    main_tables = [
        r[0] for r in cur.execute("SELECT name FROM sqlite_master WHERE type='table'").fetchall()
    ]
    temp_tables = [
        r[0] for r in cur.execute("SELECT name FROM sqlite_temp_master WHERE type='table'").fetchall()
    ]
    case3 = make_case(
        "temp_table_hidden_from_main_schema",
        "Verify SalesSummary is hidden from main sqlite_master (like SHOW TABLES) and isolated in temp catalog",
        {
            "in_main_schema": False,
            "in_temp_schema": True,
        },
        {
            "in_main_schema": "SalesSummary" in main_tables,
            "in_temp_schema": "SalesSummary" in temp_tables,
        },
    )
    conn.close()

    # 4. Session isolation and auto-destroy on disconnect (using isolated TemporaryDirectory)
    with tempfile.TemporaryDirectory() as tmp:
        db_path = Path(tmp) / "session_isolation.sqlite"
        c1 = sqlite3.connect(db_path)
        c2 = sqlite3.connect(db_path)
        c1.execute("CREATE TABLE persistent_tbl (id INT)")
        c1.commit()
        c1.execute("CREATE TEMPORARY TABLE session_only (v TEXT)")
        c1.execute("INSERT INTO session_only VALUES ('private')")
        c1_sees = c1.execute("SELECT v FROM session_only").fetchone()[0]

        c2_blocked = False
        try:
            c2.execute("SELECT * FROM session_only")
        except sqlite3.OperationalError:
            c2_blocked = True
        c1.close()
        c2.close()

        c3 = sqlite3.connect(db_path)
        destroyed_after_close = False
        try:
            c3.execute("SELECT * FROM session_only")
        except sqlite3.OperationalError:
            destroyed_after_close = True
        c3.close()

    case4 = make_case(
        "temp_table_session_isolation",
        "Verify temporary table is visible only to creator session and auto-destroyed when session closes",
        {
            "creator_sees": "private",
            "other_session_blocked": True,
            "destroyed_after_close": True,
        },
        {
            "creator_sees": c1_sees,
            "other_session_blocked": c2_blocked,
            "destroyed_after_close": destroyed_after_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-temporary-tables-lab/explore-temporary-tables.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-temporary-tables.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、内置 sqlite3(SQLite 3.53.1)本地离线关系语义验证环境(全程内存库或临时目录运行,未连接外部 MySQL 服务端)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:MySQL

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

下载课程关联工程包:MySQL

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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