Sql Alchemy cannot run inside a transaction block

2020-08-04 10:54发布

问题:

I'm trying to run a query in redshift from a python script, but I'm getting error:

sqlalchemy.exc.InternalError: (psycopg2.InternalError) ALTER EXTERNAL TABLE cannot run inside a transaction block

This is my code:

engine = create_engine(SQL_ENGINE % urlquote(REDSHIFT_PASS))
partition_date = (date.today() - timedelta(day)).strftime("%Y%m%d")
query = """alter table  {table_name} add partition (dt={date_partition}) location 's3://dft-dwh-files/raw_data/google_analytics/revenue_per_channel/{date_partition}/';""".format(date_partition=partition_date,table_name=table_name)
conn = engine.connect()
conn.execute(query).execution_options(autocommit=True)

How can I fix this?

回答1:

For PostgreSQL, you need to set the isolation level to AUTOCOMMIT, not the SQLAlchemy autocommit:

conn.execution_options(isolation_level="AUTOCOMMIT").execute(query)


回答2:

This solution works for me as using sqlalchemy :session not :conn as @univerio answer

I quote their answer here

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
engine = create_engine('postgresql+psycopg2://USER:PASSWORD@127.0.0.1:5432/DB_OR_TEMPLATE')
session = sessionmaker(bind=engine)()
session.connection().connection.set_isolation_level(0)
session.execute('CREATE DATABASE test')
session.connection().connection.set_isolation_level(1)

If you don't have any databases, you should use template1

"""Isolation level values."""
ISOLATION_LEVEL_AUTOCOMMIT     = 0
ISOLATION_LEVEL_READ_COMMITTED = 1
ISOLATION_LEVEL_SERIALIZABLE   = 2