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

运行 SQLite 3.53 普通索引查询计划、唯一索引约束与复合索引实测

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-create-index.py
explore-create-index.py144 行
"""SQL CREATE INDEX 离线实验:在内存 SQLite 中验证普通索引、唯一索引、复合索引及查询计划。"""
import json
import platform
import sqlite3


def run() -> dict:
    conn = sqlite3.connect(":memory:")
    conn.executescript(
        """
        CREATE TABLE Persons (
            P_Id INTEGER PRIMARY KEY,
            LastName TEXT NOT NULL,
            FirstName TEXT NOT NULL,
            Address TEXT,
            City TEXT
        );
        INSERT INTO Persons (P_Id, LastName, FirstName, Address, City) VALUES
            (1, 'Hansen', 'Ola', 'Timoteivn 10', 'Sandnes'),
            (2, 'Svendson', 'Tove', 'Borgvn 23', 'Sandnes'),
            (3, 'Pettersen', 'Kari', 'Storgt 20', 'Stavanger'),
            (4, 'Hansen', 'Nils', 'Fjordvn 5', 'Oslo');

        CREATE TABLE Users (
            UserId INTEGER PRIMARY KEY,
            Email TEXT NOT NULL
        );
        """
    )

    cases = []

    # Case 1: Simple non-unique index & EXPLAIN QUERY PLAN
    plan_before = conn.execute(
        "EXPLAIN QUERY PLAN SELECT FirstName FROM Persons WHERE LastName = 'Hansen';"
    ).fetchall()[0][3]
    conn.execute("CREATE INDEX PIndex ON Persons (LastName);")
    idx_list = conn.execute("PRAGMA index_list(Persons);").fetchall()
    pindex_info = next(r for r in idx_list if r[1] == "PIndex")
    plan_after = conn.execute(
        "EXPLAIN QUERY PLAN SELECT FirstName FROM Persons WHERE LastName = 'Hansen';"
    ).fetchall()[0][3]
    conn.execute(
        "INSERT INTO Persons (P_Id, LastName, FirstName, Address, City) VALUES (5, 'Hansen', 'Erik', 'Bakkevn 8', 'Bergen');"
    )
    hansen_count = conn.execute(
        "SELECT COUNT(*) FROM Persons WHERE LastName = 'Hansen';"
    ).fetchone()[0]

    exp1 = {
        "scan_before_index": True,
        "uses_pindex_after": True,
        "is_unique": 0,
        "duplicate_lastname_count": 3,
    }
    act1 = {
        "scan_before_index": "SCAN Persons" in plan_before,
        "uses_pindex_after": "USING INDEX PIndex" in plan_after,
        "is_unique": pindex_info[2],
        "duplicate_lastname_count": hansen_count,
    }
    cases.append(
        {
            "name": "create_simple_index_and_query_plan",
            "summary": "验证 CREATE INDEX 允许重复值并使查询计划从全表 SCAN 转为索引 SEARCH",
            "expected": exp1,
            "actual": act1,
            "passed": act1 == exp1,
        }
    )

    # Case 2: CREATE UNIQUE INDEX blocks duplicates
    conn.execute("CREATE UNIQUE INDEX UQ_Email ON Users (Email);")
    uq_list = conn.execute("PRAGMA index_list(Users);").fetchall()
    uq_info = next(r for r in uq_list if r[1] == "UQ_Email")
    conn.execute("INSERT INTO Users (UserId, Email) VALUES (1, 'ola@example.com');")
    conn.execute("INSERT INTO Users (UserId, Email) VALUES (2, 'tove@example.com');")
    dup_error = None
    try:
        conn.execute("INSERT INTO Users (UserId, Email) VALUES (3, 'ola@example.com');")
    except sqlite3.IntegrityError as exc:
        dup_error = str(exc)

    exp2 = {
        "is_unique": 1,
        "valid_rows": 2,
        "duplicate_rejected": True,
    }
    act2 = {
        "is_unique": uq_info[2],
        "valid_rows": conn.execute("SELECT COUNT(*) FROM Users;").fetchone()[0],
        "duplicate_rejected": dup_error is not None and "UNIQUE" in dup_error,
    }
    cases.append(
        {
            "name": "create_unique_index_constraint",
            "summary": "验证 CREATE UNIQUE INDEX 在插入重复索引键值时抛出 UNIQUE 约束异常",
            "expected": exp2,
            "actual": act2,
            "passed": act2 == exp2,
        }
    )

    # Case 3: Composite multi-column index
    conn.execute("DROP INDEX PIndex;")
    conn.execute("CREATE INDEX PIndex ON Persons (LastName, FirstName);")
    comp_cols = [r[2] for r in conn.execute("PRAGMA index_info(PIndex);").fetchall()]
    comp_plan = conn.execute(
        "EXPLAIN QUERY PLAN SELECT City FROM Persons WHERE LastName = 'Hansen' AND FirstName = 'Ola';"
    ).fetchall()[0][3]
    city_hit = conn.execute(
        "SELECT City FROM Persons WHERE LastName = 'Hansen' AND FirstName = 'Ola';"
    ).fetchone()[0]

    exp3 = {
        "indexed_columns": ["LastName", "FirstName"],
        "uses_composite_index": True,
        "matched_city": "Sandnes",
    }
    act3 = {
        "indexed_columns": comp_cols,
        "uses_composite_index": "USING INDEX PIndex" in comp_plan,
        "matched_city": city_hit,
    }
    cases.append(
        {
            "name": "create_composite_index_multi_column",
            "summary": "验证在 LastName 与 FirstName 上创建复合索引并命中联合过滤查询",
            "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-create-index-lab/explore-create-index.py

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

下载课程关联工程包:SQL

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

下载课程关联工程包:SQL

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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