如何使用Sqlalchemy创建序列并将该特定序列添加到表中?

时间:2018-12-19 13:05:49

标签: python postgresql sqlalchemy alembic

rollback.py :

def write_to_db(dataset_id):
    try:
        initialize_datamodels()
        EpdUmpPushRollback = datamodels.relational_tables.EpdUmpPushRollback
        with session_scope() as session:
            epdumppushrollback_obj = EpdUmpPushRollback()
            epdumppushrollback_obj.dataset_id = dataset_id
            epdumppushrollback_obj.record_id = ''
            epdumppushrollback_obj.operator_name = 'vis'
            epdumppushrollback_obj.activation_flag = 'active'
            epdumppushrollback_obj.record_creation_time = now()
            epdumppushrollback_obj.start_time = now()
            session.add(epdumppushrollback_obj)
            session.flush()

    except Exception as e:
        #err = "Error in updating the table epd_ump_push_rollback "
        #_log.exception(err)
        _log.exception("Error in updating the table {}".format(e))

table.py :

"""epd_ump_push_rollback_table

Revision ID: 4e4d99a8e544
Revises: c010f4d4b319
Create Date: 2018-12-19 18:04:30.271380

"""
from alembic import op
from sqlalchemy import Column, String, INTEGER, VARCHAR, NVARCHAR, TIMESTAMP, \
    Enum, ForeignKey, Sequence, MetaData

# revision identifiers, used by Alembic.
revision = '4e4d99a8e544'
down_revision = '2396e1b7de5c'
branch_labels = None
depends_on = None

meta = MetaData()
seq_obj = Sequence('record_id_seq', metadata=meta)


def upgrade():
    activation_flag_state = Enum('active', 'inactive', name="activation_flag_state")

    op.create_table('epd_ump_push_rollback',
                    Column('dataset_id', String, ForeignKey('epd_ip_dataset.dataset_id'),
                           primary_key=True),
                    Column('record_id', INTEGER, seq_obj, server_default=seq_obj.next_value(),
                           primary_key=True),
                    Column('operator_name', String, nullable=False),
                    Column('activation_flag', activation_flag_state, nullable=False),
                    Column('record_creation_time', TIMESTAMP),
                    Column('start_time', TIMESTAMP),
                    Column('end_time', TIMESTAMP))


def downgrade():
    op.drop_table('epd_ump_push_rollback')
    op.execute('DROP type activation_flag_state')

说明:

rollback.py文件中,我正在写入db。我正在使用db(postgresql)with session_scope() as session:进行会话。我正在创建表EpdUmpPushRollback的对象,并适当设置这些值。 record_id列应作为我在table.py中定义的序列生成,并且我正在使用alembic将架构升级到具有表EpdUmpPushRollback的新架构。

我现在有两个问题。

  1. 对于我们已定义顺序的列,是否必须使用pdumppushrollback_obj.record_id = ''添加,还是必须自动添加?
  2. 序列的名称是什么,每当我尝试在表中添加任何条目时,都会引发此错误。
  

错误:sqlalchemy.exc.ProgrammingError:(psycopg2.ProgrammingError)   “ record_id_seq”不是序列[SQL:'INSERT INTO   epd_ump_push_rollback(dataset_id,operator_name,activation_flag,   record_creation_time,start_time,end_time)VALUES(%(dataset_id)s,   %(operator_name)s,%(activation_flag)s,now(),now(),%(end_time)s)   返回epd_ump_push_rollback.record_id'] [参数:   {'dataset_id':'20181221_1200_mno','operator_name':'vis',   'activation_flag':'活动','end_time':无}]]

2 个答案:

答案 0 :(得分:0)

我已经遇到了这个问题,为了解决这个问题,我创建了序列,因此您可以尝试以下postgres语句:

CREATE SEQUENCE record_id_seq
   START WITH 1
   INCREMENT BY 1
   NO MINVALUE
   NO MAXVALUE
   CACHE 1;

答案 1 :(得分:0)

线

seq_obj = Sequence('record_id_seq', metadata=meta)

还不够。 您需要在 upgrade() 中的表创建上方添加:

op.execute(schema.CreateSequence(seq_obj))

此外,downgrade() 函数中需要放置序列