Home > Blockchain >  sqlalchemy session with autocommit=True does not commit
sqlalchemy session with autocommit=True does not commit

Time:12-18

I'm trying to use a session with autocommit=true to create a row in a table, and it does not seem to be working. The row is not saved to the table.

import os

import sqlalchemy
from sqlalchemy import Table
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy import Column, create_engine, String

db_hostname    = os.environ['DB_HOSTNAME']
db_username    = os.environ['DB_USERNAME']
db_password    = os.environ['DB_PASSWORD']
db_servicename = os.environ['DB_SERVICENAME']

engine_string = f"postgresql://{db_username}:{db_password}@{db_hostname}:5432/{db_servicename}"

engine = create_engine(engine_string, isolation_level='REPEATABLE READ',
    poolclass=sqlalchemy.pool.NullPool
)

base = declarative_base()

class Testing(base):
    __tablename__ = 'testing'
    name = Column(String, primary_key=True)
    comment = Column(String)

base.metadata.create_all(engine)

S1 = sessionmaker(engine)
with S1() as session:
    test1 = Testing(name="Jimmy", comment="test1")
    session.add(test1)
    session.commit()

S2 = sessionmaker(engine, autocommit=True)
with S2() as session:
    test2 = Testing(name="Johnny", comment="test2")
    session.add(test2)

In this code, the first row with name="Jimmy" and an explicit session.commit() is saved to the table.

But the second row with name="Johnny" is not saved. Specifying autocommit=True on the session appears to have no effect.

What is the cause?

CodePudding user response:

If you enable the SQLALCHEMY_WARN_20=1 environment variable you will see

RemovedIn20Warning: The Session.autocommit parameter is deprecated and will be removed in SQLAlchemy version 2.0. …

The "2.0 way" to accomplish that "autocommit" behaviour is to do

S2 = sessionmaker(engine)
with S2() as session, session.begin():
    test2 = Testing(name="Johnny", comment="test2")
    session.add(test2)
    # no explicit session.commit() required

The changes will automatically be committed when the context manager (with block) exits, provided that no errors have occurred.

  • Related