【问题标题】:Handling Redshift identity columns in SQLAlchemy处理 SQLAlchemy 中的 Redshift 标识列
【发布时间】:2015-09-17 23:22:01
【问题描述】:

我正在使用 redshift-sqlalchemy 包将 SQLAlchemy 连接到 Redshift。在 Redshift 中,我有一个简单的“公司”表:

create table if not exists companies (
    id bigint identity primary key,
    name varchar(1024) not null
);

在 SQLAlchemy 方面,我已将其映射如下:

Base = declarative_base()
class Company(Base):
    __tablename__ = 'companies'
    id = Column(BigInteger, primary_key=True)
    name = Column(String)

如果我尝试创建公司:

company = Company(name = 'Acme')
session.add(company)
session.commit()

然后我得到这个错误:

sqlalchemy.exc.StatementError: (raised as a result of Query-invoked autoflush; 
consider using a session.no_autoflush block if this flush is occurring prematurely) 
(sqlalchemy.exc.ProgrammingError) (psycopg2.ProgrammingError) 
relation "companies_id_seq" does not exist
[SQL: 'select nextval(\'"companies_id_seq"\')'] 
[SQL: u'INSERT INTO companies (id, name) 
VALUES (%(id)s, %(name)s)'] [parameters: [{'name': 'Acme'}]]

问题肯定是 SQLAlchemy 期望自动递增序列 - Postgres 和其他传统数据库的标准技术。但是 Redshift 没有序列,而是为自动生成的唯一值(不一定是连续的)提供“身份列”。关于如何使这项工作的任何建议?需要说明的是,我不关心自动递增,只需要唯一的主键值。

【问题讨论】:

标签: python sqlalchemy amazon-redshift


【解决方案1】:

就像你说的,Redshift 不支持序列,所以你可以删除这部分:

select nextval(\'"companies_id_seq"\')

您的插入语句应该是:

INSERT INTO companies 
(name)
VALUES
('Acme')

在您的表格中,您会看到“Acme”有一个具有唯一值的 id 列。您不能在 id 列中插入值,因此不要在插入语句中指定它。它将自动填充。

这里有更多解释:

http://docs.aws.amazon.com/redshift/latest/dg/c_Examples_of_INSERT_30.html

【讨论】:

  • 感谢您抽出宝贵时间回复。所以实际上你的建议是直接执行 SQL 并绕过 SQLAlchemy 提供的抽象层。这很遗憾,但可能是解决问题的唯一方法。
猜你喜欢
  • 1970-01-01
  • 2018-07-16
  • 1970-01-01
  • 1970-01-01
  • 2016-05-13
  • 2018-03-19
  • 2016-02-20
  • 2022-07-19
  • 2012-06-13
相关资源
最近更新 更多