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

离线在内存 SQLite 验证查询与执行计划、CSV/JSON/INSERT 导出回导及结构差异对比

PYTHONWindows x64、CPython 3.12.14 离线 PyCharm 工程语义与配置验证器(未启动桌面端 PyCharm IDE)。explore-dbtool.py
explore-dbtool.py193 行
"""Offline Python verification lab for PyCharm Chapter 16 (dbtool)."""
import csv
import io
import json
import sqlite3

VERSION = "CPython 3.12.14 offline PyCharm workflow verifier (desktop IDE not launched)"


def _build_demo_db():
    conn = sqlite3.connect(":memory:")
    conn.execute("PRAGMA foreign_keys = ON")
    conn.executescript(
        """
        CREATE TABLE departments (
            id INTEGER PRIMARY KEY,
            name TEXT NOT NULL UNIQUE
        );
        CREATE TABLE employees (
            id INTEGER PRIMARY KEY,
            name TEXT NOT NULL,
            dept_id INTEGER NOT NULL,
            salary INTEGER NOT NULL,
            FOREIGN KEY (dept_id) REFERENCES departments(id)
        );
        INSERT INTO departments (id, name) VALUES (1, 'Platform'), (2, 'Data');
        INSERT INTO employees (id, name, dept_id, salary) VALUES
            (101, 'Lin', 1, 18000),
            (102, 'Chen', 2, 21000);
        """
    )
    return conn


def case_sqlite_query_console_and_explain():
    conn = _build_demo_db()
    rows = conn.execute(
        "SELECT e.name, d.name, e.salary FROM employees e JOIN departments d ON e.dept_id = d.id ORDER BY e.id"
    ).fetchall()
    plan_rows = conn.execute(
        "EXPLAIN QUERY PLAN SELECT e.name, d.name FROM employees e JOIN departments d ON e.dept_id = d.id"
    ).fetchall()
    # Edit data in grid & commit
    conn.execute("UPDATE employees SET salary = 19500 WHERE id = 101")
    conn.commit()
    updated_salary = conn.execute("SELECT salary FROM employees WHERE id = 101").fetchone()[0]
    conn.close()

    expected = {
        "joined_rows": [["Lin", "Platform", 18000], ["Chen", "Data", 21000]],
        "explain_has_steps": True,
        "updated_salary": 19500,
    }
    actual = {
        "joined_rows": [list(r) for r in rows],
        "explain_has_steps": len(plan_rows) >= 2,
        "updated_salary": updated_salary,
    }
    return {
        "name": "sqlite_query_console_and_explain",
        "summary": "在内存 SQLite 执行关联查询、Explain Query Plan 执行计划分析及表格数据编辑提交",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_data_export_import_and_insert_gen():
    conn = _build_demo_db()
    cur = conn.execute("SELECT id, name, dept_id, salary FROM employees ORDER BY id")
    headers = [d[0] for d in cur.description]
    rows = cur.fetchall()

    # Export CSV & JSON & SQL INSERT
    buf = io.StringIO()
    writer = csv.writer(buf, lineterminator="\n")
    writer.writerow(headers)
    writer.writerows(rows)
    csv_text = buf.getvalue()

    json_rows = [dict(zip(headers, r)) for r in rows]
    insert_sqls = [
        f"INSERT INTO employees ({', '.join(headers)}) VALUES ({r[0]}, '{r[1]}', {r[2]}, {r[3]});"
        for r in rows
    ]

    # Import CSV back into a staging table
    conn.execute("CREATE TABLE employees_copy (id INTEGER, name TEXT, dept_id INTEGER, salary INTEGER)")
    reader = csv.DictReader(io.StringIO(csv_text))
    for item in reader:
        conn.execute(
            "INSERT INTO employees_copy VALUES (?, ?, ?, ?)",
            (int(item["id"]), item["name"], int(item["dept_id"]), int(item["salary"])),
        )
    copied = conn.execute("SELECT id, name, dept_id, salary FROM employees_copy ORDER BY id").fetchall()
    conn.close()

    expected = {
        "json_count": 2,
        "insert_count": 2,
        "csv_roundtrip_match": True,
    }
    actual = {
        "json_count": len(json_rows),
        "insert_count": len(insert_sqls),
        "csv_roundtrip_match": copied == rows,
    }
    return {
        "name": "data_export_import_and_insert_gen",
        "summary": "验证查询结果导出为 CSV/JSON/INSERT 语句并从 CSV 回导到目标表的完整数据一致性",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_schema_diff_and_migration_check():
    conn_v1 = _build_demo_db()
    conn_v2 = _build_demo_db()
    conn_v2.execute("ALTER TABLE employees ADD COLUMN email TEXT")

    cols_v1 = {r[1] for r in conn_v1.execute("PRAGMA table_info(employees)").fetchall()}
    cols_v2 = {r[1] for r in conn_v2.execute("PRAGMA table_info(employees)").fetchall()}
    fks = conn_v2.execute("PRAGMA foreign_key_list(employees)").fetchall()
    conn_v1.close()
    conn_v2.close()

    added_cols = sorted(cols_v2 - cols_v1)
    fk_edges = [(fk[2], fk[3], fk[4]) for fk in fks]
    migration_tools = ["Alembic", "Django migrations", "Flask-Migrate"]
    expected = {
        "added_columns": ["email"],
        "foreign_key_edges": [["departments", "dept_id", "id"]],
        "migration_tool_count": 3,
    }
    actual = {
        "added_columns": added_cols,
        "foreign_key_edges": [list(e) for e in fk_edges],
        "migration_tool_count": len(migration_tools),
    }
    return {
        "name": "schema_diff_and_migration_check",
        "summary": "比较两版本表结构差异(Compare With)并提取外键关系图边(ER Visualization)及迁移工具清单",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_datasource_pool_and_shortcuts():
    ds_fields = {"Host": "127.0.0.1", "Port": 3306, "User": "app", "Password": "***", "Database": "analytics"}
    pool_cfg = {"max_connections": 10, "connect_timeout_sec": 15, "idle_evict_sec": 300}
    shortcuts = {
        "execute_current_sql": ("Ctrl+Enter", "⌘Enter"),
        "execute_all_sql": ("Ctrl+Shift+Enter", "⇧⌘Enter"),
        "format_sql": ("Ctrl+Alt+L", "⌥⌘L"),
        "goto_table_def": ("Ctrl+B", "⌘B"),
        "new_console_safe_shortcut": ("Ctrl+Shift+Q / 右键 New -> Query Console", "⇧⌘L / 右键 New -> Query Console"),
    }
    expected = {
        "required_ds_fields": 5,
        "pool_valid": True,
        "shortcut_count": 5,
        "avoids_windows_alt_f4_close": True,
    }
    actual = {
        "required_ds_fields": len(ds_fields),
        "pool_valid": pool_cfg["max_connections"] > 0 and pool_cfg["connect_timeout_sec"] > 0,
        "shortcut_count": len(shortcuts),
        "avoids_windows_alt_f4_close": "Alt+F4" not in shortcuts["new_console_safe_shortcut"][0],
    }
    return {
        "name": "datasource_pool_and_shortcuts",
        "summary": "核对数据源 5 项连接字段、连接池参数及 SQL 控制台快捷键(明确提示 Windows 下 Alt+F4 会关闭窗口)",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_sqlite_query_console_and_explain(),
        case_data_export_import_and_insert_gen(),
        case_schema_diff_and_migration_check(),
        case_datasource_pool_and_shortcuts(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14 离线 PyCharm 工程语义与配置验证器(未启动桌面端 PyCharm IDE)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14 离线 PyCharm 工程语义与配置验证器(未启动桌面端 PyCharm IDE)。

入口文件:projects/pycharm-dbtool-lab/explore-dbtool.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-dbtool.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14 离线 PyCharm 工程语义与配置验证器(未启动桌面端 PyCharm IDE)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:PyCharm

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

下载课程关联工程包:PyCharm

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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