【问题标题】:Does BIGINT auto increment work for SQLAlchemy with sqlite?BIGINT 自动增量是否适用于带有 sqlite 的 SQLAlchemy?
【发布时间】:2013-09-21 01:24:42
【问题描述】:

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

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

谢谢。

【问题讨论】:

    标签: sqlite sqlalchemy


    【解决方案1】:

    对于通过 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。

    【讨论】:

    • 指定 postgresql 和 mysql 似乎是多余的,我只使用 BigInt = BigInteger().with_variant(sqlite.INTEGER(), 'sqlite')
    • 显式比隐式好。
    • 但它已经明确地是您开始使用的BigInteger()。不管怎样。我喜欢我的方式;-)
    【解决方案2】:

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

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

    希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 2011-12-15
      • 2023-03-13
      • 2013-03-04
      • 2017-11-28
      • 1970-01-01
      • 2018-11-21
      • 2014-03-15
      • 1970-01-01
      • 2020-01-29
      相关资源
      最近更新 更多