Search code examples
mysqlsqlsqlalchemy

How to set DEFAULT ON UPDATE CURRENT_TIMESTAMP in mysql with sqlalchemy?


I am creating table with sqlalchemy.

user = Table('users', Metadata,
Column('datecreated', TIMESTAMP,                                  
            server_default=text('CURRENT_TIMESTAMP')),            
Column('datemodified', TIMESTAMP,                                 
               server_onupdate=text('CURRENT_TIMESTAMP')),
)

But this will not set DEFAULT ON UPDATE CURRENT_TIMESTAMP.

I checked out How do you get SQLAlchemy to override MySQL "on update CURRENT_TIMESTAMP" but that will for literal I need to wire that in create table definition.


Solution

  • If you're on MySQL 5.6 or later please scroll down for the relevant answer. Users of older versions, please read this one.


    Until MySQL 5.6. in one table, you can only have one 'automated' TIMESTAMP column.

    From: http://dev.mysql.com/doc/refman/5.5/en/timestamp.html

    For one TIMESTAMP column in a table, you can assign the current timestamp as the default value and the auto-update value. It is possible to have the current timestamp be the default value for initializing the column, for the auto-update value, or both. It is not possible to have the current timestamp be the default value for one column and the auto-update value for another column.