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

在本地 SQLite 3.53.1 实测 NOT NULL 对 INSERT/UPDATE 的拦截以及重建表切换非空约束

PYTHONWindows x64、CPython 3.12.14、内置 sqlite3(SQLite 3.53.1)本地离线环境。explore-notnull.py
explore-notnull.py140 行
"""Offline SQLite lab for SQL Chapter 29: NOT NULL constraint."""
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 raises_integrity(cur: sqlite3.Cursor, sql: str) -> bool:
    try:
        cur.execute(sql)
        return False
    except sqlite3.IntegrityError:
        return True


def main() -> None:
    conn = sqlite3.connect(":memory:")
    cur = conn.cursor()

    cur.execute(
        """
        CREATE TABLE Persons (
            ID int NOT NULL,
            LastName varchar(255) NOT NULL,
            FirstName varchar(255) NOT NULL,
            Age int
        );
        """
    )

    # 1. Age is nullable by default; ID/LastName/FirstName forbid NULL
    cur.execute(
        "INSERT INTO Persons (ID, LastName, FirstName, Age) VALUES (1, 'Zhang', 'Wei', NULL);"
    )
    null_lastname_blocked = raises_integrity(
        cur, "INSERT INTO Persons (ID, LastName, FirstName, Age) VALUES (2, NULL, 'Hua', 25);"
    )
    omitted_firstname_blocked = raises_integrity(
        cur, "INSERT INTO Persons (ID, LastName, Age) VALUES (3, 'Wang', 28);"
    )
    case1 = make_case(
        "default_nullable_vs_not_null",
        "Verify unspecified Age accepts NULL while NOT NULL columns reject explicit NULL or omission",
        {
            "stored_row": [1, "Zhang", "Wei", None],
            "null_lastname_blocked": True,
            "omitted_firstname_blocked": True,
        },
        {
            "stored_row": list(cur.execute("SELECT * FROM Persons WHERE ID = 1").fetchone()),
            "null_lastname_blocked": null_lastname_blocked,
            "omitted_firstname_blocked": omitted_firstname_blocked,
        },
    )

    # 2. UPDATE setting a NOT NULL column to NULL is also rejected
    update_null_blocked = raises_integrity(
        cur, "UPDATE Persons SET FirstName = NULL WHERE ID = 1;"
    )
    first_name_after = cur.execute("SELECT FirstName FROM Persons WHERE ID = 1").fetchone()[0]
    case2 = make_case(
        "update_to_null_rejected",
        "Verify NOT NULL blocks UPDATE statements that attempt to assign NULL",
        {"update_blocked": True, "firstname_preserved": "Wei"},
        {"update_blocked": update_null_blocked, "firstname_preserved": first_name_after},
    )

    # 3. Toggle NOT NULL on Age via SQLite transactional table rebuild
    age_nn_before = {r[1]: r[3] for r in cur.execute("PRAGMA table_info(Persons)").fetchall()}["Age"]
    cur.execute("UPDATE Persons SET Age = 30 WHERE ID = 1;")
    cur.executescript(
        """
        CREATE TABLE Persons_nn (
            ID int NOT NULL,
            LastName varchar(255) NOT NULL,
            FirstName varchar(255) NOT NULL,
            Age int NOT NULL
        );
        INSERT INTO Persons_nn SELECT ID, LastName, FirstName, Age FROM Persons;
        DROP TABLE Persons;
        ALTER TABLE Persons_nn RENAME TO Persons;
        """
    )
    age_nn_added = {r[1]: r[3] for r in cur.execute("PRAGMA table_info(Persons)").fetchall()}["Age"]
    age_null_blocked_after_add = raises_integrity(
        cur, "INSERT INTO Persons VALUES (2, 'Li', 'Na', NULL);"
    )

    cur.executescript(
        """
        CREATE TABLE Persons_nullable (
            ID int NOT NULL,
            LastName varchar(255) NOT NULL,
            FirstName varchar(255) NOT NULL,
            Age int NULL
        );
        INSERT INTO Persons_nullable SELECT ID, LastName, FirstName, Age FROM Persons;
        DROP TABLE Persons;
        ALTER TABLE Persons_nullable RENAME TO Persons;
        """
    )
    age_nn_dropped = {r[1]: r[3] for r in cur.execute("PRAGMA table_info(Persons)").fetchall()}["Age"]
    cur.execute("INSERT INTO Persons VALUES (2, 'Li', 'Na', NULL);")
    final_count = cur.execute("SELECT COUNT(*) FROM Persons").fetchone()[0]

    case3 = make_case(
        "sqlite_table_rebuild_toggle_notnull",
        "Verify adding and removing NOT NULL on Age via SQLite table rebuild flips PRAGMA notnull 0->1->0",
        {
            "notnull_sequence": [0, 1, 0],
            "blocked_when_added": True,
            "final_count_after_drop": 2,
        },
        {
            "notnull_sequence": [age_nn_before, age_nn_added, age_nn_dropped],
            "blocked_when_added": age_null_blocked_after_add,
            "final_count_after_drop": final_count,
        },
    )

    conn.close()
    payload = {
        "version": f"CPython {sys.version.split()[0]} / SQLite {sqlite3.sqlite_version}",
        "cases": [case1, case2, case3],
    }
    print(json.dumps(payload, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14、内置 sqlite3(SQLite 3.53.1)本地离线环境。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14、内置 sqlite3(SQLite 3.53.1)本地离线环境。

入口文件:projects/sql-notnull-lab/explore-notnull.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-notnull.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、内置 sqlite3(SQLite 3.53.1)本地离线环境。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:SQL

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

下载课程关联工程包:SQL

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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