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

在本地临时目录实测 TSV/CSV 导出、防覆盖保护、全量与纯结构 SQL 转储及 gzip 还原

PYTHONWindows x64、CPython 3.12.14、内置 sqlite3(SQLite 3.53.1)本地离线关系语义验证环境(全程内存库或临时目录运行,未连接外部 MySQL 服务端)。explore-database-export.py
explore-database-export.py164 行
"""Offline SQLite verifier for MySQL Chapter 32: Exporting Data (CSV/TSV, SQL dump, gzip, pipe restore)."""
import csv
import gzip
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()

    cur.executescript(
        """
        CREATE TABLE users (
            id INT PRIMARY KEY,
            name TEXT NOT NULL,
            email TEXT NOT NULL
        );
        INSERT INTO users VALUES
            (1, 'Alice', 'alice@example.com'),
            (2, 'Bob, Jr.', 'bob@example.com');

        CREATE TABLE calc_tbl (a INT, b INT);
        INSERT INTO calc_tbl VALUES (3, 4), (10, 5);
        """
    )

    with tempfile.TemporaryDirectory() as tmp:
        root = Path(tmp)

        # 1. TSV and CSV export (counterpart of SELECT ... INTO OUTFILE with FIELDS/LINES TERMINATED BY)
        tsv_path = root / "users.tsv"
        csv_path = root / "users.csv"
        expr_path = root / "calc.csv"

        rows = cur.execute("SELECT id, name, email FROM users ORDER BY id").fetchall()
        with tsv_path.open("w", encoding="utf-8", newline="") as f:
            writer = csv.writer(f, delimiter="\t", lineterminator="\n")
            writer.writerows(rows)

        with csv_path.open("w", encoding="utf-8", newline="") as f:
            writer = csv.writer(f, delimiter=",", quotechar='"', quoting=csv.QUOTE_ALL, lineterminator="\r\n")
            writer.writerows(rows)

        expr_rows = cur.execute("SELECT a, b, a + b FROM calc_tbl ORDER BY a").fetchall()
        with expr_path.open("w", encoding="utf-8", newline="") as f:
            writer = csv.writer(f, delimiter=",", quotechar='"', quoting=csv.QUOTE_MINIMAL, lineterminator="\n")
            writer.writerows(expr_rows)

        csv_bytes = csv_path.read_bytes()
        expr_lines = expr_path.read_text(encoding="utf-8").splitlines()
        case1 = make_case(
            "export_csv_and_tsv_delimiters",
            "Verify TSV, quoted CRLF CSV, and computed-column CSV exports preserve delimiters and values",
            {
                "tsv_line_count": 2,
                "csv_uses_crlf": True,
                "csv_quotes_comma_field": True,
                "expr_lines": ["3,4,7", "10,5,15"],
            },
            {
                "tsv_line_count": len(tsv_path.read_text(encoding="utf-8").splitlines()),
                "csv_uses_crlf": b"\r\n" in csv_bytes,
                "csv_quotes_comma_field": '"Bob, Jr."' in csv_path.read_text(encoding="utf-8"),
                "expr_lines": expr_lines,
            },
        )

        # 2. Non-overwrite protection (analogous to MySQL SELECT ... INTO OUTFILE refusing existing files)
        overwrite_blocked = False
        try:
            with csv_path.open("x", encoding="utf-8"):
                pass
        except FileExistsError:
            overwrite_blocked = True

        case2 = make_case(
            "export_no_overwrite_safety",
            "Verify exclusive-create export guard refuses to overwrite an existing output file",
            True,
            overwrite_blocked,
        )

        # 3. Full SQL dump vs schema-only dump (counterpart of mysqldump vs mysqldump --no-data)
        full_dump_lines = list(conn.iterdump())
        schema_only_lines = [
            line for line in full_dump_lines if not line.upper().startswith("INSERT INTO")
        ]
        full_sql_path = root / "full_backup.sql"
        schema_sql_path = root / "schema_only.sql"
        full_sql_path.write_text("\n".join(full_dump_lines) + "\n", encoding="utf-8")
        schema_sql_path.write_text("\n".join(schema_only_lines) + "\n", encoding="utf-8")

        full_text = full_sql_path.read_text(encoding="utf-8")
        schema_text = schema_sql_path.read_text(encoding="utf-8")
        case3 = make_case(
            "export_sql_dump_full_and_schema_only",
            "Verify full dump contains CREATE TABLE + INSERT while schema-only (--no-data) omits INSERTs",
            {
                "full_has_create": True,
                "full_has_insert": True,
                "schema_has_create": True,
                "schema_has_insert": False,
            },
            {
                "full_has_create": "CREATE TABLE users" in full_text,
                "full_has_insert": "INSERT INTO \"users\"" in full_text,
                "schema_has_create": "CREATE TABLE users" in schema_text,
                "schema_has_insert": "INSERT INTO" in schema_text,
            },
        )

        # 4. Gzip-compressed SQL dump & pipe-style restore into fresh DB
        gz_path = root / "backup.sql.gz"
        with gzip.open(gz_path, "wt", encoding="utf-8") as gf:
            gf.write(full_text)

        with gzip.open(gz_path, "rt", encoding="utf-8") as gf:
            restored_sql = gf.read()

        target = sqlite3.connect(":memory:")
        target.executescript(restored_sql)
        restored_users = [
            list(r) for r in target.execute("SELECT id, name, email FROM users ORDER BY id").fetchall()
        ]
        target.close()

        case4 = make_case(
            "export_gzip_compressed_and_pipe_restore",
            "Verify gzip-compressed SQL dump decompresses and restores identically into a clean database",
            {
                "gzip_magic_valid": True,
                "restored_users": [[1, "Alice", "alice@example.com"], [2, "Bob, Jr.", "bob@example.com"]],
            },
            {
                "gzip_magic_valid": gz_path.read_bytes()[:2] == b"\x1f\x8b",
                "restored_users": restored_users,
            },
        )

    conn.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-database-export-lab/explore-database-export.py

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

下载课程关联工程包:MySQL

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

下载课程关联工程包:MySQL

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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