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

运行同库/跨库 renameCollection、目标冲突与 dropTarget 覆盖及 dbAdmin 权限校验

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-renamecollection.py
explore-renamecollection.py155 行
"""Offline MongoDB adminCommand renameCollection, cross-DB move & RBAC verifier (Ch14 renamecollection)."""
import json

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


class OfflineRenameServer:
    def __init__(self):
        self.dbs = {
            "test": {
                "oldCollection": {
                    "docs": [{"_id": 1, "name": "alpha"}, {"_id": 2, "name": "beta"}],
                    "indexes": ["_id_", "name_1"],
                }
            },
            "production": {
                "existingTarget": {
                    "docs": [{"_id": 99, "name": "legacy"}],
                    "indexes": ["_id_"],
                }
            },
        }
        self.user_roles = {
            "admin_user": {("test", "dbAdmin"), ("production", "dbOwner")},
            "app_rw_user": {("test", "readWrite"), ("production", "readWrite")},
        }

    def has_rename_perm(self, user: str, src_db: str, dst_db: str) -> bool:
        roles = self.user_roles.get(user, set())
        ok_src = any(db == src_db and r in ("dbAdmin", "dbOwner") for db, r in roles)
        ok_dst = any(db == dst_db and r in ("dbAdmin", "dbOwner") for db, r in roles)
        return ok_src and ok_dst

    def admin_rename_collection(self, user: str, src_ns: str, dst_ns: str, drop_target: bool = False):
        src_db, src_col = src_ns.split(".", 1)
        dst_db, dst_col = dst_ns.split(".", 1)
        if not self.has_rename_perm(user, src_db, dst_db):
            return {"ok": 0, "errmsg": "Unauthorized: requires dbAdmin or dbOwner"}
        if src_col not in self.dbs.get(src_db, {}):
            return {"ok": 0, "errmsg": "Source namespace does not exist"}
        dst_bucket = self.dbs.setdefault(dst_db, {})
        if dst_col in dst_bucket:
            if not drop_target:
                return {"ok": 0, "errmsg": "target namespace exists"}
            del dst_bucket[dst_col]
        dst_bucket[dst_col] = self.dbs[src_db].pop(src_col)
        return {"ok": 1}


def case_same_db_rename_collection():
    srv = OfflineRenameServer()
    res = srv.admin_rename_collection("admin_user", "test.oldCollection", "test.newCollection")
    cols = sorted(srv.dbs["test"].keys())
    moved = srv.dbs["test"]["newCollection"]
    actual = {
        "ok": res["ok"],
        "test_collections": cols,
        "preserved_doc_count": len(moved["docs"]),
        "preserved_indexes": moved["indexes"],
    }
    expected = {
        "ok": 1,
        "test_collections": ["newCollection"],
        "preserved_doc_count": 2,
        "preserved_indexes": ["_id_", "name_1"],
    }
    return {
        "name": "same_db_rename_collection",
        "summary": "验证同库重命名 test.oldCollection -> test.newCollection 完整保留文档与索引。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_cross_db_rename_collection():
    srv = OfflineRenameServer()
    res = srv.admin_rename_collection("admin_user", "test.oldCollection", "production.newCollection")
    actual = {
        "ok": res["ok"],
        "test_collections": sorted(srv.dbs["test"].keys()),
        "prod_collections": sorted(srv.dbs["production"].keys()),
        "moved_indexes": srv.dbs["production"]["newCollection"]["indexes"],
    }
    expected = {
        "ok": 1,
        "test_collections": [],
        "prod_collections": ["existingTarget", "newCollection"],
        "moved_indexes": ["_id_", "name_1"],
    }
    return {
        "name": "cross_db_rename_collection",
        "summary": "验证跨库重命名 test.oldCollection -> production.newCollection 迁移集合文档与索引。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_target_conflict_and_drop_target():
    srv = OfflineRenameServer()
    conflict = srv.admin_rename_collection("admin_user", "test.oldCollection", "production.existingTarget", drop_target=False)
    override = srv.admin_rename_collection("admin_user", "test.oldCollection", "production.existingTarget", drop_target=True)
    actual = {
        "conflict_ok": conflict["ok"],
        "conflict_msg": conflict["errmsg"],
        "override_ok": override["ok"],
        "new_target_doc_ids": [d["_id"] for d in srv.dbs["production"]["existingTarget"]["docs"]],
    }
    expected = {
        "conflict_ok": 0,
        "conflict_msg": "target namespace exists",
        "override_ok": 1,
        "new_target_doc_ids": [1, 2],
    }
    return {
        "name": "target_conflict_and_drop_target",
        "summary": "验证目标集合已存在时默认 dropTarget:false 报错,设为 true 后覆盖目标集合。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_rename_rbac_permission_check():
    srv = OfflineRenameServer()
    denied = srv.admin_rename_collection("app_rw_user", "test.oldCollection", "test.newCollection")
    allowed = srv.admin_rename_collection("admin_user", "test.oldCollection", "test.newCollection")
    actual = {
        "rw_user_denied": denied["ok"] == 0,
        "admin_user_allowed": allowed["ok"] == 1,
    }
    expected = {"rw_user_denied": True, "admin_user_allowed": True}
    return {
        "name": "rename_rbac_permission_check",
        "summary": "验证执行 renameCollection 需具备 dbAdmin/dbOwner 权限,普通 readWrite 用户被拒绝。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_same_db_rename_collection(),
        case_cross_db_rename_collection(),
        case_target_conflict_and_drop_target(),
        case_rename_rbac_permission_check(),
    ]
    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-renamecollection-lab/explore-renamecollection.py

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

下载课程关联工程包:MongoDB

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

下载课程关联工程包:MongoDB

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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