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

在本地 SQLite 3.53.1 实测 AUTOINCREMENT 自增、删行不复用、起始值 100 与重排重建

PYTHONWindows x64、CPython 3.12.14、内置 sqlite3(SQLite 3.53.1)本地离线关系语义验证环境(全程内存库或临时目录运行,未连接外部 MySQL 服务端)。explore-using-sequences.py
explore-using-sequences.py141 行
"""Offline SQLite verifier for MySQL Chapter 29: Sequences & AUTO_INCREMENT."""
import json
import sqlite3
import sys


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. AUTOINCREMENT with omitted id & explicit NULL id + last_insert_rowid()
    cur.executescript(
        """
        CREATE TABLE insect (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            name VARCHAR(30) NOT NULL,
            date DATE NOT NULL,
            origin VARCHAR(30) NOT NULL
        );
        INSERT INTO insect (id, name, date, origin) VALUES
            (NULL, 'housefly', '2001-09-10', 'kitchen'),
            (NULL, 'millipede', '2001-09-10', 'driveway'),
            (NULL, 'grasshopper', '2001-09-10', 'front yard');
        """
    )
    cur.execute(
        "INSERT INTO insect (name, date, origin) VALUES ('moth', '2001-09-14', 'windowsill')"
    )
    last_id = cur.execute("SELECT last_insert_rowid()").fetchone()[0]
    rows = [list(r) for r in cur.execute("SELECT id, name FROM insect ORDER BY id").fetchall()]
    case1 = make_case(
        "autoincrement_insert_and_last_id",
        "Verify AUTOINCREMENT assigns 1..4 for NULL/omitted ids and last_insert_rowid() returns 4",
        {
            "rows": [[1, "housefly"], [2, "millipede"], [3, "grasshopper"], [4, "moth"]],
            "last_id": 4,
        },
        {
            "rows": rows,
            "last_id": last_id,
        },
    )

    # 2. Deleted highest id is not reused; sequence counter advances monotonically
    cur.execute("DELETE FROM insect WHERE id = 4")
    seq_before = cur.execute(
        "SELECT seq FROM sqlite_sequence WHERE name = 'insect'"
    ).fetchone()[0]
    cur.execute(
        "INSERT INTO insect (name, date, origin) VALUES ('beetle', '2001-09-15', 'garden')"
    )
    next_id = cur.lastrowid
    case2 = make_case(
        "autoincrement_deleted_id_not_reused",
        "Verify deleting id=4 keeps sequence watermark at 4 and next insert receives id=5",
        {
            "seq_before_next_insert": 4,
            "next_assigned_id": 5,
        },
        {
            "seq_before_next_insert": seq_before,
            "next_assigned_id": next_id,
        },
    )

    # 3. Custom starting sequence value 100 (counterpart of AUTO_INCREMENT = 100)
    cur.execute(
        """
        CREATE TABLE orders_seq (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            label TEXT NOT NULL
        )
        """
    )
    cur.execute("INSERT INTO sqlite_sequence (name, seq) VALUES ('orders_seq', 99)")
    cur.execute("INSERT INTO orders_seq (label) VALUES ('first_order')")
    cur.execute("INSERT INTO orders_seq (label) VALUES ('second_order')")
    seq_100_rows = [
        list(r) for r in cur.execute("SELECT id, label FROM orders_seq ORDER BY id").fetchall()
    ]
    case3 = make_case(
        "autoincrement_custom_start_100",
        "Verify custom initial sequence value produces sequential IDs 100 and 101",
        [[100, "first_order"], [101, "second_order"]],
        seq_100_rows,
    )

    # 4. Resetting and re-compacting sequence IDs (counterpart of DROP id + ADD id AUTO_INCREMENT)
    cur.execute("DELETE FROM insect WHERE id IN (2, 3)")
    ids_with_gaps = [r[0] for r in cur.execute("SELECT id FROM insect ORDER BY id").fetchall()]
    cur.executescript(
        """
        CREATE TABLE insect_rebuilt (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            name VARCHAR(30) NOT NULL,
            date DATE NOT NULL,
            origin VARCHAR(30) NOT NULL
        );
        INSERT INTO insect_rebuilt (name, date, origin)
        SELECT name, date, origin FROM insect ORDER BY id;
        DROP TABLE insect;
        ALTER TABLE insect_rebuilt RENAME TO insect;
        """
    )
    rebuilt_rows = [
        list(r) for r in cur.execute("SELECT id, name FROM insect ORDER BY id").fetchall()
    ]
    case4 = make_case(
        "autoincrement_reset_renumbering",
        "Verify rebuilding table re-sequences surviving rows with gaps [1, 5] into contiguous [1, 2]",
        {
            "ids_with_gaps": [1, 5],
            "rebuilt_rows": [[1, "housefly"], [2, "beetle"]],
        },
        {
            "ids_with_gaps": ids_with_gaps,
            "rebuilt_rows": rebuilt_rows,
        },
    )

    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-using-sequences-lab/explore-using-sequences.py

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

下载课程关联工程包:MySQL

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

下载课程关联工程包:MySQL

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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