sqlalchemy - 有没有办法在 Alembic 中生成顺序修订 ID?

标签 sqlalchemy database-migration alembic

我正在使用 Alembic 作为 Python 项目的数据库迁移工具。当我运行这样的命令时:

alembic revision -m "adding a column"

...它将添加一个名为 alembic/versions/xxxxxxxxxxxx_adding_a_column.py 的新文件在哪里 xxxxxxxxxxxx是随机生成的 12 位哈希。

从使事物可读的角度来看,这有点问题,因为这意味着当查看 alembic/versions目录中,所有文件将按随机顺序出现,而不是按顺序/时间顺序出现。

Alembic 中是否有任何选项可以确保这些前缀修订 ID 是连续的?我想我可以手动重命名文件,然后更新引用,但我想知道是否已经有这样的功能。

最佳答案

听上去,您对按顺序列出的修订文件而不是按顺序排列的修订 ID 更感兴趣。前者可以在不改变如何生成修订 ID 的情况下实现。

alembic.ini 运行时生成的文件alembic init alembic有一个配置修订文件命名的部分:

# template used to generate migration files
# file_template = %%(rev)s_%%(slug)s

这是来自文档的解释:

file_template - this is the naming scheme used to generate new migration files. The value present is the default, so is commented out. Tokens available include:

  • %%(rev)s - revision id
  • %%(slug)s - a truncated string derived from the revision message
  • %%(year)d, %%(month).2d, %%(day).2d, %%(hour).2d, %%(minute).2d, %%(second).2d - components of the create date, by default datetime.datetime.now() unless the timezone configuration option is also used.


所以添加 file_template = %%(year)d-%%(month).2d-%%(day).2d_%%(rev)s_%%(slug)salembic.ini会将您的修订命名为 2018-11-15_xxxxxxxxxxxx_adding_a_column.py .

我发现了这个问题:https://bitbucket.org/zzzeek/alembic/issues/371/add-unixtime-stamp-to-start-of-versions这为我指明了正确的方向。

A comment from from that issue :

timestamps don't necessarily tell you which file is the most "recent", since branching is allowed. "alembic history" is meant to be the best source of truth on this.



因此,文件命名解决方案不能保证迁移在目录中按逻辑顺序排列(但会帮助 IMO)。可以提出相同的论点来反对具有顺序 ID。

如果您确实想指定自己的修订标识符,请使用 --rev-id 命令行上的标志。

例如。:
alembic revision -m 'a message' --rev-id=1
生成了一个名为 1_a_message.py 的文件:
"""a message

Revision ID: 1
Revises:
Create Date: 2018-11-15 13:40:31.228888

"""
from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision = '1'
down_revision = None
branch_labels = None
depends_on = None


def upgrade():
    pass


def downgrade():
    pass

因此,您绝对可以自己管理修订标识符。编写一个 bash 脚本来触发您的修订生成是微不足道的,自动传递基于日期时间的 rev_id ,例如--rev-id=<current datetime>管理目录中列出的顺序。

如果没有指定版本 ID,函数 rev_id()发现于 alembic.util.langhelpers 叫做:
def rev_id():
    return uuid.uuid4().hex[-12:]

rev_id() 的函数调用在 alembic 源代码中是硬编码的,因此如果没有对函数进行猴子修补,将很难覆盖该行为。您可以创建库的一个分支并重新定义该函数或使其调用的用于 id 生成的函数可配置。

关于sqlalchemy - 有没有办法在 Alembic 中生成顺序修订 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53303778/

相关文章:

Python:通用/模板化 getter

django - 如何将Django模型从mysql迁移到sqlite(或在任何两个数据库系统之间)?

mysql - 从 MariaDB 迁移到 MySQL

python - 使用 alembic autogenerate 时忽略模型

mysql - Alembic:在两个值之间强制执行值唯一性

sqlalchemy - 使用 Flask-SQLAlchemy 在 Alembic 自动生成迁移中未检测到任何变化

python - 使用 SQLAlchemy 在不经常使用的 Python/Flask 服务器上避免 "MySQL server has gone away"

python - 如何定义表示集合中最新对象的 SQLAlchemy 关系?

ruby-on-rails - PG::UndefinedColumn: 错误: 关系 "image_file_name"的列 "articles"不存在

python - 在 Pyramid 中存储和验证用于登录的加密密码