python - 在 SQLAlchemy 中处理 Redshift 标识列

标签 python sqlalchemy amazon-redshift

我正在使用 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 没有序列,而是为自动生成的唯一值(不一定是连续的)提供“标识列”。关于如何进行这项工作的任何建议?明确地说,我不关心自动递增,只需要唯一的主键值。

最佳答案

正如您所说,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

关于python - 在 SQLAlchemy 中处理 Redshift 标识列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31150532/

相关文章:

python - 嵌套列表排序

python - 如何打印出来!在皮亚姆尔?

python - 处理与 SQLAlchemy 的事务冲突

python-3.x - 在 Alembic 后处理中修改foreignkeyconstraint模式

python - 如何插入新列和 sum(),并在我的数据框中增加、减少通知

python - 从 os.path.isfile() 函数接收 AttributeError

sqlalchemy - 如何在 Alembic 中创建 postgresql 的序列

r - 使用 dplyr 绑定(bind)数据库中的行

amazon-redshift - AWS RedShift 的沙盒版本

R:如何使用 dplyr (函数 scr_postgres)从 redshift 中的模式中选择表?