Sql Alchemy cannot run inside a transaction block

Question:

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?

Asked By: Filipe Ferminiano

||

Answers:

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

conn.execution_options(isolation_level="AUTOCOMMIT").execute(query)
Answered By: univerio

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:[email protected]: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
Answered By: Nam G VU

Another option is to run COMMIT manually before removing or adding the index:

with Session(get_engine()) as session:
    session.execute("COMMIT")
    session.execute("DROP INDEX CONCURRENTLY IF EXISTS <my_index>;")
    
Answered By: tread