BIGINT使用sqlite自动增加SQLAlchemy的工作量吗?

时间:2013-09-16 19:27:23

标签: sqlite sqlalchemy

我正在尝试使用SQLAlchemy声明一个表。我想在表格中包含一个BIGINT自动递增主键。这似乎不适用于sqlite作为数据库后端。另一方面,使用INTEGER自动递增主键可以正常工作。

我读到sqlite的ROWID是签名的bigint。但是有没有办法拥有BIGINT自动增量字段?这样我可以交换后端而不用担心数据库特定的问题(假设MySQL和Postgres支持bigint自动递增字段)。

感谢。

2 个答案:

答案 0 :(得分:15)

对于通过Google访问并且只需要解决方案的其他人,我编写了以下代码:

# SQLAlchemy does not map BigInt to Int by default on the sqlite dialect.
# It should, but it doesnt.
from sqlalchemy import BigInteger
from sqlalchemy.dialects import postgresql, mysql, sqlite

BigIntegerType = BigInteger()
BigIntegerType = BigIntegerType.with_variant(postgresql.BIGINT(), 'postgresql')
BigIntegerType = BigIntegerType.with_variant(mysql.BIGINT(), 'mysql')
BigIntegerType = BigIntegerType.with_variant(sqlite.INTEGER(), 'sqlite')

这将允许您在数据库上使用BIGINT,在运行单元测试时使用INT。

答案 1 :(得分:11)

Sqlite不允许BIGINT用作自动增量的主键。

但是,由于dynamic nature of sqlite column types,您可以制作特定于后端的列类型,并在INTEGER后端使用sqlite类型,请参阅SQLAlchemy: How to conditionally choose type for column by depending on its backend

希望有所帮助。