【问题标题】:Populating an array of enums填充枚举数组
【发布时间】:2018-06-21 11:30:40
【问题描述】:

我无法从我的 Alembic 迁移中将枚举放入我的表中。

此处为 MVCE:https://pastebin.com/ng3XcKLf

(SQLAlchemy 1.2、psycopg2 2.7.3.2 和 postgres 10.1 - 需要使用您的 postgres URI 修改第 15 行)

我阅读了有关 SQLAlchemy/Postgres 和枚举数组的问题,但根据我在问题跟踪器中可以找到的内容,1.1 已解决。

有人能指出正确的方向吗?

变体 1: 尝试使用 postgres 枚举类型的属性

op.bulk_insert(permission, [{
    'name': 'ViewContent',
    'contexts': [pgpermissioncontexts.resourceType]
}])

这失败了:AttributeError: 'Enum' object has no attribute 'resourceType'

变体 2: 尝试使用底层 python 枚举的属性

op.bulk_insert(permission, [{
    'name': 'ViewContent',
    'contexts': [PermissionContexts.resourceType]
}])

sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) cols of type permissioncontexts[] but expression is of type text[] 失败

变体 3: 将字符串数组转换为枚举数组

op.bulk_insert(permission, [{
    'name': 'ViewContent',
    'contexts': sa.cast([PermissionContexts.resourceType], sa.ARRAY(pgenum))
}])

这可能有效,也可能无效 - python 进程膨胀到使用 4GB 内存,并一直在那里直到终止。

变体 4: 插入空数组

op.bulk_insert(permission, [{
    'name': 'ViewContent',
    'contexts': []
}])

这行得通,但显然没有价值。

【问题讨论】:

  • 请提供MVCE,例如this appears to work fine
  • 使用 MVCE 更新
  • 看你的要点,我认为这意味着问题出在 alembic bulk_insert () 语句上。我使用了这个,因为我将数据添加为 alembic 迁移的一部分,并且手头有 alembic 表引用。我会看看我是否可以重写它以使用 SqlAlchemy insert()s,看看它是否有效。

标签: python postgresql sqlalchemy alembic


【解决方案1】:

不幸的是枚举数组不能开箱即用,但是有一个documented workaround, 这也在this answer 中进行了描述。使用 ArrayOfEnum 而不是 ARRAY,您的变体 2 有效:

op.bulk_insert(permission, [{
    'name': 'ViewContent',
    'contexts': [PermissionContexts.resourceType],
}])

投射到ARRAY(permissioncontexts) 也应该有效,并且在不使用bulk_insert() 时也有效

op.execute(permission.insert().values({
    'name': 'ViewContent',
    'contexts': sa.cast([PermissionContexts.resourceType], ARRAY(pgpermissioncontexts)),
}))

或者当使用bulk_insert(multiinsert=False)时:

op.bulk_insert(permission, [{
    'name': 'ViewContent',
    'contexts': sa.cast([PermissionContexts.resourceType], ARRAY(pgpermissioncontexts)),
}], multiinsert=False)

alembic 或 sqlalchemy 对多参数的处理似乎存在错误。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2015-06-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-25
  • 1970-01-01
  • 2011-03-04
相关资源
最近更新 更多