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

在本地 SQLite 3.53.1 实测字符串、数值聚合、日期时间、流程控制与 JSON/窗口函数

PYTHONWindows x64、CPython 3.12.14、内置 sqlite3(SQLite 3.53.1)本地离线关系语义验证环境(全程内存库或临时目录运行,未连接外部 MySQL 服务端)。explore-functions.py
explore-functions.py253 行
"""Offline SQLite verifier for MySQL Chapter 34: Built-in Functions (String, Numeric, Date, Advanced, JSON/Window)."""
import json
import math
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. String functions (SQLite native + exact Python equivalents for MySQL helpers)
    s_len, s_lower, s_upper, s_sub, s_trim, s_ltrim, s_rtrim, s_rep, s_pos, s_ascii = cur.execute(
        """
        SELECT LENGTH('MBSKY'),
               LOWER('MBSKY'),
               UPPER('mbsky'),
               SUBSTR('MBSKY', 2, 3),
               TRIM('  MBSKY  '),
               LTRIM('  MBSKY'),
               RTRIM('MBSKY  '),
               REPLACE('abc', 'a', 'x'),
               INSTR('myteststring', 'st'),
               UNICODE('A')
        """
    ).fetchone()

    def substring_index(text: str, delim: str, count: int) -> str:
        parts = text.split(delim)
        if count > 0:
            return delim.join(parts[:count])
        return delim.join(parts[count:])

    mysql_str_helpers = {
        "concat_ws": "-".join(["SQL", "Tutorial", "is", "fun!"]),
        "field_c": ["a", "b", "c", "d", "e"].index("c") + 1,
        "find_in_set_c": "a,b,c,d,e".split(",").index("c") + 1,
        "format_num": f"{250500.5634:,.2f}",
        "lpad": ("xx" + "abc")[-5:],
        "rpad": ("abc" + "xx")[:5],
        "reverse": "abc"[::-1],
        "repeat": "sky" * 3,
        "sub_idx_pos": substring_index("a*b", "*", 1),
        "sub_idx_neg": substring_index("a*b", "*", -1),
        "sub_idx_nested": substring_index(substring_index("a*b*c*d*e", "*", 3), "*", -1),
    }

    case1 = make_case(
        "string_functions_core",
        "Verify SQLite native string functions and MySQL string helper semantics",
        {
            "native": [5, "mbsky", "MBSKY", "BSK", "MBSKY", "MBSKY", "MBSKY", "xbc", 5, 65],
            "helpers": {
                "concat_ws": "SQL-Tutorial-is-fun!",
                "field_c": 3,
                "find_in_set_c": 3,
                "format_num": "250,500.56",
                "lpad": "xxabc",
                "rpad": "abcxx",
                "reverse": "cba",
                "repeat": "skyskysky",
                "sub_idx_pos": "a",
                "sub_idx_neg": "b",
                "sub_idx_nested": "c",
            },
        },
        {
            "native": [s_len, s_lower, s_upper, s_sub, s_trim, s_ltrim, s_rtrim, s_rep, s_pos, s_ascii],
            "helpers": mysql_str_helpers,
        },
    )

    # 2. Numeric & aggregate functions
    cur.executescript(
        """
        CREATE TABLE products (id INT, price REAL, qty INT);
        INSERT INTO products VALUES (1, 10.0, 2), (2, 20.0, 3), (3, 30.0, 5);
        """
    )
    n_abs, n_round0, n_round2, n_div, n_mod, n_min_s, n_max_s = cur.execute(
        """
        SELECT ABS(-1),
               ROUND(1.23456),
               ROUND(345.156, 2),
               10 / 5,
               5 % 2,
               MIN(3, 12, 34, 8, 25),
               MAX(3, 12, 34, 8, 25)
        """
    ).fetchone()
    agg_avg, agg_cnt, agg_max, agg_min, agg_sum = cur.execute(
        "SELECT AVG(price), COUNT(id), MAX(price), MIN(price), SUM(qty) FROM products"
    ).fetchone()

    math_checks = {
        "ceil": math.ceil(1.5),
        "floor": math.floor(1.5),
        "pow": int(math.pow(2, 3)),
        "sqrt": int(math.sqrt(25)),
        "log10": int(math.log10(100)),
        "log2_4": int(math.log2(4)),
        "exp3_r4": round(math.exp(3), 4),
        "sin30_r1": round(math.sin(math.radians(30)), 1),
        "sign_neg": -1 if -10 < 0 else (1 if -10 > 0 else 0),
        "truncate_3": math.trunc(1.23456 * 1000) / 1000,
    }
    case2 = make_case(
        "numeric_and_aggregate_functions",
        "Verify SQLite numeric/aggregate SQL functions and standard mathematical functions",
        {
            "scalar": [1, 1.0, 345.16, 2, 1, 3, 34],
            "aggregates": [20.0, 3, 30.0, 10.0, 10],
            "math": {
                "ceil": 2,
                "floor": 1,
                "pow": 8,
                "sqrt": 5,
                "log10": 2,
                "log2_4": 2,
                "exp3_r4": 20.0855,
                "sin30_r1": 0.5,
                "sign_neg": -1,
                "truncate_3": 1.234,
            },
        },
        {
            "scalar": [n_abs, n_round0, n_round2, n_div, n_mod, n_min_s, n_max_s],
            "aggregates": [agg_avg, agg_cnt, agg_max, agg_min, agg_sum],
            "math": math_checks,
        },
    )

    # 3. Date & time functions in SQLite (counterpart to MySQL DATE_ADD, DATE_SUB, DATEDIFF, LAST_DAY, EXTRACT)
    d_add10, d_sub2, d_diff, d_last, d_year, d_month, d_day, d_time, d_add_time = cur.execute(
        """
        SELECT DATE('2017-06-15', '+10 days'),
               DATE('2017-06-15', '-2 days'),
               CAST(JULIANDAY('2001-01-01') - JULIANDAY('2001-02-02') AS INT),
               DATE('2017-06-20', 'start of month', '+1 month', '-1 day'),
               CAST(STRFTIME('%Y', '2017-06-15') AS INT),
               CAST(STRFTIME('%m', '2011-11-11 11:11:11') AS INT),
               CAST(STRFTIME('%d', '2017-06-15') AS INT),
               TIME('2020-06-15 19:30:10'),
               DATETIME('2020-06-15 09:34:21', '+2 hours', '+10 minutes', '+5 seconds')
        """
    ).fetchone()
    case3 = make_case(
        "date_time_functions_core",
        "Verify date addition/subtraction, DATEDIFF, LAST_DAY, component extraction, and time addition",
        [
            "2017-06-25",
            "2017-06-13",
            -32,
            "2017-06-30",
            2017,
            11,
            15,
            "19:30:10",
            "2020-06-15 11:44:26",
        ],
        [d_add10, d_sub2, d_diff, d_last, d_year, d_month, d_day, d_time, d_add_time],
    )

    # 4. Advanced conditional, NULL, and conversion functions
    c_case, c_cast, c_coal, c_iif, c_ifnull, c_nullif_eq, c_nullif_ne = cur.execute(
        """
        SELECT CASE WHEN 1 > 0 THEN '1 > 0' WHEN 2 > 0 THEN '2 > 0' ELSE '3 > 0' END,
               CAST('42' AS INTEGER),
               COALESCE(NULL, NULL, 'mbsky.com', 'example.org'),
               IIF(1 > 0, '正确', '错误'),
               IFNULL(NULL, 'Hello World'),
               NULLIF(25, 25),
               NULLIF(25, 30)
        """
    ).fetchone()
    case4 = make_case(
        "advanced_control_and_null_functions",
        "Verify CASE WHEN, CAST, COALESCE, IIF/IF, IFNULL, NULLIF, and binary conversion",
        {
            "sql": ["1 > 0", 42, "mbsky.com", "正确", "Hello World", None, 25],
            "bin_15": "1111",
        },
        {
            "sql": [c_case, c_cast, c_coal, c_iif, c_ifnull, c_nullif_eq, c_nullif_ne],
            "bin_15": format(15, "b"),
        },
    )

    # 5. MySQL 8.0 JSON & Window functions verified directly in SQLite 3.53.1
    j_obj, j_arr, j_ext = cur.execute(
        """
        SELECT json_object('key1', 'value1', 'key2', 'value2'),
               json_array(1, 2, 'three'),
               json_extract('{"name": "John", "age": 30}', '$.name')
        """
    ).fetchone()
    cur.executescript(
        """
        CREATE TABLE students (id INT, name TEXT, score INT);
        INSERT INTO students VALUES (1, 'Alice', 95), (2, 'Bob', 95), (3, 'Carol', 88);
        """
    )
    win_rows = [
        list(r)
        for r in cur.execute(
            """
            SELECT ROW_NUMBER() OVER (ORDER BY id) AS rn,
                   RANK() OVER (ORDER BY score DESC) AS rnk,
                   name,
                   score
            FROM students
            ORDER BY id
            """
        ).fetchall()
    ]
    case5 = make_case(
        "mysql8_json_and_window_functions",
        "Verify JSON_OBJECT, JSON_ARRAY, JSON_EXTRACT, ROW_NUMBER(), and RANK() window functions",
        {
            "json_obj": {"key1": "value1", "key2": "value2"},
            "json_arr": [1, 2, "three"],
            "json_name": "John",
            "window_rows": [[1, 1, "Alice", 95], [2, 1, "Bob", 95], [3, 3, "Carol", 88]],
        },
        {
            "json_obj": json.loads(j_obj),
            "json_arr": json.loads(j_arr),
            "json_name": j_ext,
            "window_rows": win_rows,
        },
    )

    conn.close()
    payload = {
        "version": f"CPython {sys.version.split()[0]} / SQLite {sqlite3.sqlite_version} (offline MySQL verifier)",
        "cases": [case1, case2, case3, case4, case5],
    }
    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-functions-lab/explore-functions.py

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

下载课程关联工程包:MySQL

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

下载课程关联工程包:MySQL

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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