def test_topological_missing_item():
    foo = Role("foo", in_roles=["bar"])

    with pytest.raises(ValueError) as e:
        topological_sort([foo])

    assert "bar" in str(e.value)
    assert "missing" in str(e.value).lower()
def test_topological_sort_cycle_simple():
    with pytest.raises(ValueError) as e:
        topological_sort([
            Role("foo", in_roles=["bar"]),
            Role("bar", in_roles=["bar"]),
        ])
    assert "bar, foo" in str(e.value)
    assert "cyclical" in str(e.value).lower()
def test_topological_sort_duplicate():
    with pytest.raises(ValueError) as e:
        topological_sort([
            Role("foo"),
            Role("foo"),
            Role("bar"),
        ])
    assert "foo" in str(e.value)
    assert "duplicate" in str(e.value).lower()
def compare_roles(autogen_context, upgrade_ops, schemas):
    roles = autogen_context.metadata.info.get("roles")
    if not roles:
        return

    roles_by_name = {r.name: r for r in roles.roles}

    select_roles = "SELECT rolname FROM pg_roles"
    existing_roles = {
        role
        for role, *_ in autogen_context.connection.execute(
            select_roles).fetchall() if not role.startswith("pg_")
    }

    expected_role_names = set(r.name for r in roles.roles)
    new_role_names = expected_role_names - existing_roles
    removed_role_names = existing_roles - expected_role_names

    new_roles = [roles_by_name[role] for role in new_role_names]

    for role in topological_sort(new_roles):
        upgrade_ops.ops.append(CreateRoleOp(role))

    # TODO: Role update DDL

    if not roles.ignore_unspecified:
        # XXX: This probably needs to take role dependencies into account, and
        #      figure out an order which wont fail.
        for role in removed_role_names:
            upgrade_ops.ops.append(DropRoleOp(Role(role)))
def test_topological_sort_simple():
    foo = Role("foo", in_roles=["bar"])
    bar = Role("bar")
    result = topological_sort([foo, bar])

    expected_result = [bar, foo]
    assert expected_result == result
def test_topological_sort_no_deps():
    foo = Role("foo")
    bar = Role("bar")
    result = topological_sort([foo, bar])

    expected_result = [bar, foo]
    assert expected_result == result
def test_topological_fork():
    foo = Role("foo", in_roles=["bar"])
    bax = Role("bax", in_roles=["bar"])
    bar = Role("bar", in_roles=["baz"])
    baz = Role("baz")
    result = topological_sort([foo, baz, bar, bax])

    expected_result = [baz, bar, foo, bax]
    assert expected_result == result
Example #8
0
def listen(metadata):
    schemas = metadata.info["schemas"]
    for schema in schemas:
        event.listen(
            metadata,
            "before_create",
            schema_ddl(schema),
        )

    roles = metadata.info["roles"]
    for role in topological_sort(roles):
        event.listen(
            metadata,
            "after_create",
            role_ddl(role),
        )