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

校验 psql \l 与 \c 切库状态流转、命令行连接参数及 SQLite 多库定向查询

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-select-database.py
explore-select-database.py103 行
"""PostgreSQL 选择数据库离线实验:验证 psql 提示符、\\l 库列表字段、\\c 切库状态流转、psql 命令行直连参数及 SQLite 多库查询。"""
import json
import platform
import shlex
import sqlite3


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

    # Case 1: psql prompt & \l database list structure
    l_columns = ["Name", "Owner", "Encoding", "Collate", "Ctype", "Access privileges"]
    default_dbs = ["postgres", "testdb", "template0", "template1"]
    exp1 = {
        "superuser_prompt": "postgres=#",
        "list_columns_count": 6,
        "has_templates": True,
        "db_count": 4,
    }
    act1 = {
        "superuser_prompt": "postgres=#",
        "list_columns_count": len(l_columns),
        "has_templates": "template0" in default_dbs and "template1" in default_dbs,
        "db_count": len(default_dbs),
    }
    cases.append(
        {
            "name": "psql_prompt_and_list_databases",
            "summary": "校验 psql 提示符规则与 \\l 输出的数据库清单列及默认模板库",
            "expected": exp1,
            "actual": act1,
            "passed": act1 == exp1,
        }
    )

    # Case 2: \c dbname switching state transition
    current_db = "postgres"
    cmd = "\\c testdb"
    if cmd.startswith("\\c "):
        current_db = cmd.split()[1]
    new_prompt = f"{current_db}=#"
    exp2 = {"connected_db": "testdb", "new_prompt": "testdb=#"}
    act2 = {"connected_db": current_db, "new_prompt": new_prompt}
    cases.append(
        {
            "name": "psql_connect_switch_database",
            "summary": "验证 psql 中使用 \\c <dbname> 切换目标数据库后的提示符变化",
            "expected": exp2,
            "actual": act2,
            "passed": act2 == exp2,
        }
    )

    # Case 3: System shell psql direct connection options
    toks = shlex.split("psql -h localhost -p 5432 -U postgres testdb")
    exp3 = {"host": "localhost", "port": 5432, "user": "postgres", "dbname": "testdb"}
    act3 = {
        "host": toks[toks.index("-h") + 1],
        "port": int(toks[toks.index("-p") + 1]),
        "user": toks[toks.index("-U") + 1],
        "dbname": toks[-1],
    }
    cases.append(
        {
            "name": "cli_psql_connection_flags",
            "summary": "解析系统终端中 psql -h -p -U <dbname> 直接选库连接的命令行参数",
            "expected": exp3,
            "actual": act3,
            "passed": act3 == exp3,
        }
    )

    # Case 4: SQLite multi-database selection probe
    conn = sqlite3.connect(":memory:")
    conn.execute("ATTACH DATABASE ':memory:' AS testdb;")
    conn.execute("CREATE TABLE main.info (db TEXT);")
    conn.execute("INSERT INTO main.info VALUES ('main');")
    conn.execute("CREATE TABLE testdb.info (db TEXT);")
    conn.execute("INSERT INTO testdb.info VALUES ('testdb');")
    dbs = [r[1] for r in conn.execute("PRAGMA database_list;").fetchall()]
    selected = conn.execute("SELECT db FROM testdb.info;").fetchone()[0]
    conn.close()
    exp4 = {"databases": ["main", "testdb"], "selected_db_row": "testdb"}
    act4 = {"databases": dbs, "selected_db_row": selected}
    cases.append(
        {
            "name": "sqlite_multi_db_selection_probe",
            "summary": "在内存 SQLite 中挂载多个逻辑库并验证定向选择查询指定库表数据",
            "expected": exp4,
            "actual": act4,
            "passed": act4 == exp4,
        }
    )

    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-select-database-lab/explore-select-database.py

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

下载课程关联工程包:PostgreSQL

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

下载课程关联工程包:PostgreSQL

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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