2

I have a column in an alembic revision for update_time to show when the Column is updated.

Currently I have tried:

sa.Column('update_time', sa.dialects.mysql.DATETIME(fsp=3), nullable=False, server_default=str(datetime.utcnow()), onupdate=str(datetime.utcnow()), server_onupdate=str(datetime.utcnow()))

I have also tried:

sa.Column('test_time', sa.DateTime(), server_default=sa.func.now(), server_onupdate=sa.func.now(), onupdate=sa.func.now())

When the database is built is gets the utcnow() time fine as a DateTime.

However, when I update the column via the command line in mysql, the Column stays the same timestamp.

How do I get the timestamp to update?

Jonas M.
  • 312
  • 1
  • 3
  • 11
William Ross
  • 3,568
  • 7
  • 42
  • 73

1 Answers1

6

Got it working with:

from sqlalchemy import text
from sqlalchemy.dialects.mysql import TIMESTAMP

sa.Column('update_time', TIMESTAMP(), nullable=False, server_default=text('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'))
Jonas M.
  • 312
  • 1
  • 3
  • 11
William Ross
  • 3,568
  • 7
  • 42
  • 73
  • for people trying this, there's a caveat, it might not work for all databases. at the time of writing, postgresql 15 doesn't support this. detail on this answer: https://stackoverflow.com/a/75538105/1835157 – user1835157 Aug 16 '23 at 12:20