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

运行算术/比较/三值逻辑/按位四大运算符及 COMPANY 7 行过滤实测

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-operators.py
explore-operators.py174 行
"""PostgreSQL 运算符离线实验:实测算术、比较、三值逻辑与按位运算符,并在内存 SQLite COMPANY 7 行样本上核对过滤结果。"""
import json
import math
import platform
import sqlite3


def build_company_7() -> sqlite3.Connection:
    conn = sqlite3.connect(":memory:")
    conn.executescript(
        """
        CREATE TABLE COMPANY (
            ID      INT PRIMARY KEY NOT NULL,
            NAME    TEXT            NOT NULL,
            AGE     INT             NOT NULL,
            ADDRESS CHAR(50),
            SALARY  REAL
        );
        INSERT INTO COMPANY (ID, NAME, AGE, ADDRESS, SALARY) VALUES
            (1, 'Paul',  32, 'California', 20000),
            (2, 'Allen', 25, 'Texas',      15000),
            (3, 'Teddy', 23, 'Norway',     20000),
            (4, 'Mark',  25, 'Rich-Mond',  65000),
            (5, 'David', 27, 'Texas',      85000),
            (6, 'Kim',   22, 'South-Hall', 45000),
            (7, 'James', 24, 'Houston',    10000);
        """
    )
    return conn


def run() -> dict:
    conn = build_company_7()
    cases = []

    # Case 1: Arithmetic operators (+, -, *, /, %, ^, |/, ||/, !, !!)
    sq_arith = conn.execute("SELECT 2+3, 2-3, 2*3, 3/2, 3%2, 10/5, 12%5;").fetchone()
    exp1 = {
        "add": 5, "sub": -1, "mul": 6, "div_3_2": 1, "mod_3_2": 1,
        "div_10_5": 2, "mod_12_5": 2,
        "pow_2_3": 8, "sqrt_25": 5.0, "cbrt_27": 3.0, "fact_5": 120,
    }
    act1 = {
        "add": sq_arith[0], "sub": sq_arith[1], "mul": sq_arith[2],
        "div_3_2": sq_arith[3], "mod_3_2": sq_arith[4],
        "div_10_5": sq_arith[5], "mod_12_5": sq_arith[6],
        "pow_2_3": 2 ** 3, "sqrt_25": math.sqrt(25.0),
        "cbrt_27": round(math.cbrt(27.0), 10), "fact_5": math.factorial(5),
    }
    cases.append(
        {
            "name": "arithmetic_operators_evaluation",
            "summary": "验证四则与取模运算符(SQLite 实测)及指数、开方、立方根与阶乘语义",
            "expected": exp1,
            "actual": act1,
            "passed": act1 == exp1,
        }
    )

    # Case 2: Comparison operators on a=10, b=20 and COMPANY table
    cmp_ab = conn.execute("SELECT (10=20), (10!=20), (10<>20), (10>20), (10<20), (10>=20), (10<=20);").fetchone()
    gt_50k = [r[0] for r in conn.execute("SELECT NAME FROM COMPANY WHERE SALARY > 50000 ORDER BY ID;").fetchall()]
    eq_20k = [r[0] for r in conn.execute("SELECT NAME FROM COMPANY WHERE SALARY = 20000 ORDER BY ID;").fetchall()]
    ne_bang = [r[0] for r in conn.execute("SELECT NAME FROM COMPANY WHERE SALARY != 20000 ORDER BY ID;").fetchall()]
    ne_ang = [r[0] for r in conn.execute("SELECT NAME FROM COMPANY WHERE SALARY <> 20000 ORDER BY ID;").fetchall()]
    ge_65k = [r[0] for r in conn.execute("SELECT NAME FROM COMPANY WHERE SALARY >= 65000 ORDER BY ID;").fetchall()]
    exp2 = {
        "cmp_10_20": [0, 1, 1, 0, 1, 0, 1],
        "gt_50000": ["Mark", "David"],
        "eq_20000": ["Paul", "Teddy"],
        "ne_20000_bang": ["Allen", "Mark", "David", "Kim", "James"],
        "ne_20000_angle": ["Allen", "Mark", "David", "Kim", "James"],
        "ge_65000": ["Mark", "David"],
    }
    act2 = {
        "cmp_10_20": list(cmp_ab),
        "gt_50000": gt_50k,
        "eq_20000": eq_20k,
        "ne_20000_bang": ne_bang,
        "ne_20000_angle": ne_ang,
        "ge_65000": ge_65k,
    }
    cases.append(
        {
            "name": "comparison_operators_on_company",
            "summary": "验证 7 个比较运算符在常量与 7 行 COMPANY 样本上的过滤结果",
            "expected": exp2,
            "actual": act2,
            "passed": act2 == exp2,
        }
    )

    # Case 3: Three-valued logic truth tables (AND, OR, NOT)
    pairs = [("1", "1"), ("1", "0"), ("1", "NULL"), ("0", "0"), ("0", "NULL"), ("NULL", "NULL")]
    and_or_rows = []
    for a, b in pairs:
        res_and, res_or = conn.execute(f"SELECT ({a} AND {b}), ({a} OR {b});").fetchone()
        and_or_rows.append([res_and, res_or])
    not_rows = [conn.execute(f"SELECT NOT {a};").fetchone()[0] for a in ("1", "0", "NULL")]
    exp3 = {
        "and_or": [[1, 1], [0, 1], [None, 1], [0, 0], [0, None], [None, None]],
        "not": [0, 1, None],
    }
    act3 = {"and_or": and_or_rows, "not": not_rows}
    cases.append(
        {
            "name": "logical_three_valued_truth_tables",
            "summary": "在 SQLite 中完整实测 TRUE/FALSE/NULL 三值逻辑下 AND、OR、NOT 真值表",
            "expected": exp3,
            "actual": act3,
            "passed": act3 == exp3,
        }
    )

    # Case 4: Logical operators on COMPANY (AND, OR, IS NOT NULL)
    and_names = [
        r[0] for r in conn.execute(
            "SELECT NAME FROM COMPANY WHERE AGE >= 25 AND SALARY >= 6500 ORDER BY ID;"
        ).fetchall()
    ]
    or_count = conn.execute("SELECT COUNT(*) FROM COMPANY WHERE AGE >= 25 OR SALARY >= 6500;").fetchone()[0]
    not_null_count = conn.execute("SELECT COUNT(*) FROM COMPANY WHERE SALARY IS NOT NULL;").fetchone()[0]
    conn.execute("INSERT INTO COMPANY VALUES (8, 'Guest', 30, 'Remote', NULL);")
    not_null_after_guest = conn.execute("SELECT COUNT(*) FROM COMPANY WHERE SALARY IS NOT NULL;").fetchone()[0]
    exp4 = {
        "age_ge_25_and_salary_ge_6500": ["Paul", "Allen", "Mark", "David"],
        "or_count_on_7": 7,
        "not_null_on_7": 7,
        "not_null_excludes_null_row": 7,
    }
    act4 = {
        "age_ge_25_and_salary_ge_6500": and_names,
        "or_count_on_7": or_count,
        "not_null_on_7": not_null_count,
        "not_null_excludes_null_row": not_null_after_guest,
    }
    cases.append(
        {
            "name": "logical_operators_on_company",
            "summary": "实测 COMPANY 表上 AND、OR 与 IS NOT NULL 组合条件并验证空薪资行被过滤",
            "expected": exp4,
            "actual": act4,
            "passed": act4 == exp4,
        }
    )

    # Case 5: Bitwise operators (&, |, #, ~, <<, >>) on A=60, B=13
    bits = conn.execute("SELECT (60 | 13), (60 & 13), (~60), (60 << 2), (60 >> 2);").fetchone()
    xor_val = 60 ^ 13  # PostgreSQL uses '#' for integer bitwise XOR
    conn.close()
    exp5 = {"or": 61, "and": 12, "not": -61, "shl2": 240, "shr2": 15, "xor_pg_hash": 49}
    act5 = {
        "or": bits[0], "and": bits[1], "not": bits[2],
        "shl2": bits[3], "shr2": bits[4], "xor_pg_hash": xor_val,
    }
    cases.append(
        {
            "name": "bitwise_operators_evaluation",
            "summary": "实测 A=60、B=13 的按位或/与/取反/左移/右移及 PostgreSQL 按位异或 # 运算结果",
            "expected": exp5,
            "actual": act5,
            "passed": act5 == exp5,
        }
    )

    return {
        "version": f"CPython {platform.python_version()} / SQLite {sqlite3.sqlite_version} (offline PostgreSQL verifier)",
        "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/postgresql-operators-lab/explore-operators.py

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

下载课程关联工程包:PostgreSQL

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

下载课程关联工程包:PostgreSQL

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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