user294318
user294318

Reputation:

How do you get SQLAlchemy to override MySQL "on update CURRENT_TIMESTAMP"

I've inherited an older database that was setup with a "on update CURRENT_TIMESTAMP" put on a field that should only describe an item's creation. With PHP I have been using "timestamp=timestamp" on UPDATE clauses, but in SQLAlchemy I can't seem to force the system to use the set timestamp.

Do I have no choice and need to update the MySQL table (millions of rows)?

foo = session.query(f).get(int(1))
ts = foo.timestamp
setattr(foo, 'timestamp', ts)
setattr(foo, 'bar', bar)
www_model.www_Session.commit()

I have also tried:

foo = session.query(f).get(int(1))
setattr(foo, 'timestamp', foo.timestamp)
setattr(foo, 'bar', bar)
www_model.www_Session.commit()

Upvotes: 3

Views: 3005

Answers (1)

Ants Aasma
Ants Aasma

Reputation: 54872

SQLAlchemy doesn't try to set the field because it thinks the value hasn't changed.

You can tell SQLAlchemy to reassign the value by specifying the onupdate attribute on the Column:

 Column('timestamp', ..., onupdate=literal_column('timestamp'))

This will result in SQLAlchemy automatically adding timestamp=timestamp to all update queries.

If you need to do it one off on an instance, you can assign the column to it:

foo.timestamp = literal_column('timestamp')
# or 
foo.timestamp = foo_tbl.c.timestamp

Upvotes: 6

Related Questions