Sql Alchemy cannot run inside a transaction block
Asked Answered
C

3

9

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?

Collyrium answered 6/7, 2017 at 22:3 Comment(0)
C
34

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

conn.execution_options(isolation_level="AUTOCOMMIT").execute(query)
Cruelty answered 7/7, 2017 at 17:50 Comment(4)
If you are using sqlalchemy :session instead of :conn, see this answer below https://mcmap.net/q/1116764/-sql-alchemy-cannot-run-inside-a-transaction-blockPhillane
This has been renamed to conn.set_isolation_level("AUTOCOMMIT") - See initd.org/psycopg/docs/…Smoulder
@Smoulder That's if you're using psycopg directly. This question is about SQLAlchemy. See docs.sqlalchemy.org/en/13/dialects/…Cruelty
@Cruelty Oh yeah.. Missed that the specific question was SQLAlchemy. So my answer contains how to do it in psycopg (which looks working also)Smoulder
P
7

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
Phillane answered 15/11, 2018 at 20:0 Comment(1)
looks like set_isolation_level() is no longer in use in 2022Greasepaint
K
2

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

from sqlalchemy.orm import Session

with Session(get_engine()) as session:
    session.execute("COMMIT")
    session.execute("DROP INDEX CONCURRENTLY IF EXISTS <my_index>;")
    
Kibbutz answered 16/3, 2023 at 13:59 Comment(1)
Somehow session.commit() didn´t work but your answer worked for me. ThanksMarquee

© 2022 - 2024 — McMap. All rights reserved.