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

运行 use 惰性建库、createCollection 物化、默认 test 库写入及 dropDatabase 命名校验

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-create-database.py
explore-create-database.py168 行
"""Offline MongoDB lazy database creation, default test DB & dropDatabase verifier (Ch11 create-database)."""
import json

VERSION = "CPython 3.12.14 offline MongoDB document/query verifier (mongod absent)"


class MiniMongoInstance:
    def __init__(self):
        self.dbs = {
            "admin": {"system.version": [{"_id": "featureCompatibilityVersion"}]},
            "config": {"system.sessions": []},
            "local": {"startup_log": [{"pid": 1}]},
        }
        self.current_db = "test"

    @staticmethod
    def is_valid_db_name(name: str) -> bool:
        if not name or len(name.encode("utf-8")) > 64:
            return False
        return not any(ch in " .$/\\\x00" for ch in name)

    def use(self, name: str) -> str:
        if not self.is_valid_db_name(name):
            raise ValueError(f"Invalid database name: {name}")
        self.current_db = name
        return f"switched to db {name}"

    def show_dbs(self) -> list:
        # MongoDB only displays databases that have at least one collection/materialized storage
        return sorted(db for db, cols in self.dbs.items() if len(cols) > 0)

    def create_collection(self, col_name: str):
        self.dbs.setdefault(self.current_db, {}).setdefault(col_name, [])
        return {"ok": 1}

    def insert_one(self, col_name: str, doc: dict):
        col = self.dbs.setdefault(self.current_db, {}).setdefault(col_name, [])
        rec = dict(doc)
        rec.setdefault("_id", f"oid_{len(col) + 1}")
        col.append(rec)
        return {"acknowledged": True, "insertedId": rec["_id"]}

    def drop_database(self):
        existed = self.current_db in self.dbs
        self.dbs.pop(self.current_db, None)
        return {"dropped": self.current_db, "ok": 1} if existed else {"ok": 1}


def case_use_command_lazy_creation():
    inst = MiniMongoInstance()
    msg = inst.use("demo_db")
    cur = inst.current_db
    listed_before_write = inst.show_dbs()
    inst.insert_one("articles", {"name": "蓝色天空网"})
    listed_after_write = inst.show_dbs()
    actual = {
        "switch_msg": msg,
        "db_cmd": cur,
        "in_show_dbs_before_write": "demo_db" in listed_before_write,
        "in_show_dbs_after_write": "demo_db" in listed_after_write,
    }
    expected = {
        "switch_msg": "switched to db demo_db",
        "db_cmd": "demo_db",
        "in_show_dbs_before_write": False,
        "in_show_dbs_after_write": True,
    }
    return {
        "name": "use_command_lazy_creation",
        "summary": "验证 use 命令仅切换当前上下文,在写入首条文档前不出现在 show dbs 列表中,写入后自动落盘显现。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_explicit_collection_and_insert_materialization():
    inst = MiniMongoInstance()
    inst.use("myNewDatabase")
    res = inst.create_collection("myNewCollection")
    actual = {
        "create_ok": res["ok"] == 1,
        "db_visible": "myNewDatabase" in inst.show_dbs(),
        "collections": sorted(inst.dbs["myNewDatabase"].keys()),
    }
    expected = {
        "create_ok": True,
        "db_visible": True,
        "collections": ["myNewCollection"],
    }
    return {
        "name": "explicit_collection_and_insert_materialization",
        "summary": "验证 use 切换后调用 db.createCollection() 显式创建集合并使数据库出现在 show dbs 中。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_default_test_database_behavior():
    inst = MiniMongoInstance()
    default_name = inst.current_db
    test_before = "test" in inst.show_dbs()
    inst.insert_one("myCollection", {"name": "Alice", "age": 30})
    test_after = "test" in inst.show_dbs()
    actual = {
        "default_db": default_name,
        "test_visible_before_insert": test_before,
        "test_visible_after_insert": test_after,
        "doc_count": len(inst.dbs["test"]["myCollection"]),
    }
    expected = {
        "default_db": "test",
        "test_visible_before_insert": False,
        "test_visible_after_insert": True,
        "doc_count": 1,
    }
    return {
        "name": "default_test_database_behavior",
        "summary": "验证未执行 use 时默认落入 test 库,首次 insertOne 自动创建 test 库与集合。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_drop_database_and_naming_validation():
    inst = MiniMongoInstance()
    inst.use("myDatabase")
    inst.insert_one("c1", {"k": 1})
    drop_res = inst.drop_database()
    actual = {
        "drop_result": drop_res,
        "removed_from_show_dbs": "myDatabase" not in inst.show_dbs(),
        "reject_space_dot_dollar": [
            inst.is_valid_db_name("bad db"),
            inst.is_valid_db_name("bad.db"),
            inst.is_valid_db_name("bad$db"),
            inst.is_valid_db_name("good_db"),
        ],
    }
    expected = {
        "drop_result": {"dropped": "myDatabase", "ok": 1},
        "removed_from_show_dbs": True,
        "reject_space_dot_dollar": [False, False, False, True],
    }
    return {
        "name": "drop_database_and_naming_validation",
        "summary": "验证 db.dropDatabase() 移除当前库与集合,以及数据库名禁用空格、点号与美元符规则。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_use_command_lazy_creation(),
        case_explicit_collection_and_insert_materialization(),
        case_default_test_database_behavior(),
        case_drop_database_and_naming_validation(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

入口文件:projects/mongodb-create-database-lab/explore-create-database.py

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

下载课程关联工程包:MongoDB

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

下载课程关联工程包:MongoDB

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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