这里有一个版本,当迁移中首次出现时,它会自动创建模式(将其添加到env.py中或至少从那里导入):
import logging
from collections.abc import Iterable
from typing import Any
import alembic
import sqlalchemy.sql.base
from alembic.autogenerate.api import AutogenContext
from alembic.operations.ops import (
CreateTableOp,
ExecuteSQLOp,
UpgradeOps,
)
_logger = logging.getLogger(f"alembic.{__name__}")
class ExecuteArbitraryDDLOp(ExecuteSQLOp):
def __init__(
self,
ddl: sqlalchemy.sql.base.Executable | str,
reverse_ddl: sqlalchemy.sql.base.Executable | str,
*,
execution_options: dict[str, Any] | None = None,
) -> None:
"""A DDL Operation with both upgrade and downgrade commands."""
super().__init__(ddl, execution_options=execution_options)
self.reverse_ddl = reverse_ddl
def reverse(self) -> "ExecuteArbitraryDDLOp":
"""Return the reverse of this ExecuteArbitraryDDLOp (used for downgrades)."""
return ExecuteArbitraryDDLOp(
ddl=self.reverse_ddl, reverse_ddl=self.sqltext, execution_options=self.execution_options
)
@alembic.autogenerate.comparators.dispatch_for("schema")
def create_missing_schemas(
autogen_context: AutogenContext, upgrade_ops: UpgradeOps, schema_names: Iterable[str | None]
) -> None:
"""Creates missing schemas.
This depends on sqla/alembic to give us all existing
schemas in the schema_names argument.
"""
used_schemas = set()
for operations_group in upgrade_ops.ops:
if isinstance(operations_group, CreateTableOp) and operations_group.schema:
used_schemas.add(operations_group.schema)
existing_schemas = set(schema_names)
missing_schemas = used_schemas - existing_schemas
if missing_schemas:
for schema in missing_schemas:
_logger.info("Add migration ops for schema: %s", schema)
upgrade_ops.ops.insert(
0,
ExecuteArbitraryDDLOp(
ddl=f"CREATE SCHEMA {schema}",
reverse_ddl=f"DROP SCHEMA {schema}",
),
)
来源:
https://www.katzien.de/en/posts/2023-11-16-create-missing-schemas-in-alembic/(免责声明:本人的博客)
sqlalchemy.event
一起工作?例如,event.listen(Base.metadata, "before_create", CreateSchema("foo"))
。 - maxcountrymanmetadata = Metadata(schema=<schema-name>)
或者Base = declarative_base(schema=<schema-name>)
。 - Bin H.include_schemas=True
,alembic将会承认模式。虽然不确定为什么这个设置不是默认开启的。 - Pstrrevision --autogenerate
没有检测到并创建这些模式。我是否缺乏某些技术上的了解?(关于在哪里放置alembic_version
的问题主导了一些讨论,但这与自动生成要进入表格的模式无关。) - LondonRob