Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sqlAlchemy does not recognise changes to DB made outside of session

Something peculiar I've noticed is that any changes committed to the DB outside of the session (such as ones made in MySQL's Workbench) are not recognised in the sqlAlchemy session. I have to close and open a new session for sqlAlchemy to recognise it.

For example, a row I deleted manually is still fetched from sqlAlchemy.

This is how I initialise the session:

engine   = create_engine('mysql://{}:{}@{}/{}'.format(username, password, host, schema), pool_recycle=3600)
Session  = sessionmaker(bind=engine)
session  = Session()
metadata = MetaData()

How can I get sqlAlchemy to recognise them?

My sqlAlchemy version is 0.9.4 and my MySQL version is 5.5.34. We use only sqlAlchemy's Core (no ORM).

like image 589
Nobilis Avatar asked Jul 02 '15 08:07

Nobilis


People also ask

How does SQLAlchemy update data?

Update table elements in SQLAlchemy. Get the books to table from the Metadata object initialized while connecting to the database. Pass the update query to the execute() function and get all the results using fetchall() function. Use a for loop to iterate through the results.

Is there something better than SQLAlchemy?

Django, Pandas, Entity Framework, peewee, and MySQL are the most popular alternatives and competitors to SQLAlchemy.

Does SQLAlchemy automatically close connection?

connect() method returns a Connection object, and by using it in a Python context manager (e.g. the with: statement) the Connection. close() method is automatically invoked at the end of the block.

What is Autocommit in SQLAlchemy?

The “autocommit” feature is only in effect when no Transaction has otherwise been declared. This means the feature is not generally used with the ORM, as the Session object by default always maintains an ongoing Transaction .


1 Answers

To be able to read committed data from others transactions you'll need to set transaction isolation level to READ COMMITTED. For sqlalchemy and mysql:

To set isolation level using create_engine():

engine = create_engine(
    "mysql://scott:tiger@localhost/test",
    isolation_level="READ COMMITTED")

To set using per-connection execution options:

connection = engine.connect()
connection = connection.execution_options(
    isolation_level="READ COMMITTED")

source

like image 68
pavel_form Avatar answered Oct 14 '22 00:10

pavel_form