9

I am getting a NotImplementedError: This method is not implemented for SQLAlchemy 2.0., when trying to delete a table using the delete method in SQLAlchemy v1.4.15.

from sqlalchemy import Column, Integer, MetaData, String, Table, create_engine, delete

engine = create_engine("sqlite+pysqlite:///:memory:", echo=True, future=True)
metadata = MetaData()

user = Table(
    "users", metadata, Column("id", Integer, primary_key=True), Column("name", String)
)

metadata.create_all(engine)

engine.execute(user.delete())  # leading to Traceback
# NotImplementedError: This method is not implemented for SQLAlchemy 2.0.
snakecharmerb
  • 47,570
  • 11
  • 100
  • 153
Andi
  • 3,196
  • 2
  • 24
  • 44

1 Answers1

11

engine.execute is deprecated in SQLAlchemy 1.4, and will be removed in SQLAlchemy 2.0. You need to call a connection's execute method instead:

from sqlalchemy import Column, Integer, MetaData, String, Table, create_engine, delete

# Setting future=True enforces 2.0 behaviour and disables
# legacy features. 
engine = create_engine("sqlite+pysqlite:///:memory:", echo=True, future=True)
metadata = MetaData()

user = Table(
    "users", metadata, Column("id", Integer, primary_key=True), Column("name", String)
)

metadata.create_all(engine)

stmt = delete(user)
with engine.connect() as conn:
    with conn.begin():   # Optional: start a transaction
        conn.execute(stmt)

snakecharmerb
  • 47,570
  • 11
  • 100
  • 153
  • 2
    `with engine.begin() as conn:` works, too. The difference between `with engine.connect()` and `with engine.begin()` is that absent an explicit `.commit()` the former will automatically roll back while the latter will automatically commit. – Gord Thompson May 27 '21 at 11:38