"""Offline Lua 5.4 semantic verification lab for Chapter 23 (database-access)."""
import json
import sqlite3
import tempfile
from pathlib import Path
VERSION = "CPython 3.12.14 offline Lua 5.4 + sqlite3(:memory:) LuaSQL semantic verifier (lua/MySQL absent)"
class SimulatedLuaSQLCursor:
def __init__(self, cur: sqlite3.Cursor):
self._cur = cur
self._cols = [d[0] for d in (cur.description or [])]
self.closed = False
def fetch(self, table: dict, mode: str = "n"):
row = self._cur.fetchone()
if row is None:
return None
table.clear()
if mode == "a":
for col, val in zip(self._cols, row):
table[col] = val
else:
for idx, val in enumerate(row, start=1):
table[idx] = val
return table
def close(self):
self._cur.close()
self.closed = True
class SimulatedLuaSQLConnection:
def __init__(self, conn: sqlite3.Connection):
self._conn = conn
self.closed = False
def execute(self, sql: str):
cur = self._conn.cursor()
cur.execute(sql)
if cur.description is not None:
return SimulatedLuaSQLCursor(cur)
self._conn.commit()
affected = cur.rowcount
cur.close()
return affected
def close(self):
self._conn.close()
self.closed = True
class SimulatedLuaSQLEnv:
def __init__(self):
self.closed = False
def connect(self, _db_name=":memory:"):
return SimulatedLuaSQLConnection(sqlite3.connect(":memory:"))
def close(self):
self.closed = True
def case_luasql_driver_ecosystem():
supported_dbs = ["ODBC", "ADO", "Oracle", "MySQL", "SQLite", "PostgreSQL"]
luarocks_pkgs = [
"luasql-sqlite3",
"luasql-postgres",
"luasql-mysql",
"luasql-sqlite",
"luasql-odbc",
]
expected = {"supported_db_count": 6, "driver_pkg_count": 5, "all_prefixed_luasql": True}
actual = {
"supported_db_count": len(supported_dbs),
"driver_pkg_count": len(luarocks_pkgs),
"all_prefixed_luasql": all(p.startswith("luasql-") for p in luarocks_pkgs),
}
return {
"name": "luasql_driver_ecosystem",
"summary": "核对 LuaSQL 支持的 6 类数据库及 LuaRocks 5 项常用驱动包安装命令",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_luasql_env_conn_cursor_fetch_export():
# Offline in-memory SQLite simulates LuaSQL env -> conn -> cur:fetch({}, "a") -> file:write -> close
env = SimulatedLuaSQLEnv()
conn = env.connect(":memory:")
conn.execute("CREATE TABLE role (id INTEGER PRIMARY KEY, name TEXT NOT NULL)")
conn.execute("INSERT INTO role (id, name) VALUES (1, 'admin'), (2, 'editor'), (3, 'guest')")
cur = conn.execute("SELECT id, name FROM role ORDER BY id")
row = cur.fetch({}, "a")
written_lines = []
with tempfile.TemporaryDirectory() as tmp:
out_file = Path(tmp) / "role.txt"
with out_file.open("w", encoding="utf-8") as fh:
while row is not None:
line = "%d %s\n" % (row["id"], row["name"])
fh.write(line)
written_lines.append(line.strip())
row = cur.fetch(row, "a")
file_content = out_file.read_text(encoding="utf-8")
cur.close()
conn.close()
env.close()
expected = {
"exported_rows": ["1 admin", "2 editor", "3 guest"],
"file_line_count": 3,
"all_resources_closed": True,
}
actual = {
"exported_rows": written_lines,
"file_line_count": len(file_content.splitlines()),
"all_resources_closed": cur.closed and conn.closed and env.closed,
}
return {
"name": "luasql_env_conn_cursor_fetch_export",
"summary": "使用内存 SQLite 离线模拟 LuaSQL env/conn/cur:fetch({}, \"a\") 查询并导出至临时 role.txt 及完整关闭",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_fetch_numeric_vs_alpha_mode():
env = SimulatedLuaSQLEnv()
conn = env.connect(":memory:")
conn.execute("CREATE TABLE item (id INTEGER, title TEXT)")
conn.execute("INSERT INTO item VALUES (10, 'LuaGuide')")
c1 = conn.execute("SELECT id, title FROM item")
row_n = c1.fetch({}, "n")
c1.close()
c2 = conn.execute("SELECT id, title FROM item")
row_a = c2.fetch({}, "a")
c2.close()
conn.close()
env.close()
expected = {
"numeric_mode_1based": {1: 10, 2: "LuaGuide"},
"alpha_mode_named": {"id": 10, "title": "LuaGuide"},
}
actual = {"numeric_mode_1based": row_n, "alpha_mode_named": row_a}
return {
"name": "fetch_numeric_vs_alpha_mode",
"summary": "对比 cur:fetch({}, \"n\") 1-based 数字下标模式与 cur:fetch({}, \"a\") 列名关联表模式",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_luasql_driver_ecosystem(),
case_luasql_env_conn_cursor_fetch_export(),
case_fetch_numeric_vs_alpha_mode(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14 离线 Lua 5.4 语义验证器(本机未安装原生 lua/luac 解释器)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14 离线 Lua 5.4 语义验证器(本机未安装原生 lua/luac 解释器)。
入口文件:projects/lua-database-access-lab/explore-database-access.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-database-access.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 Lua 5.4 语义验证器(本机未安装原生 lua/luac 解释器)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2514.zip
课程关联工程包(登记关联23章) · 含当前章节或实例 · mbskycom202612a2510.zip