Search code examples
pythonmysqlpeewee

Set strict sql mode in peewee


I'd like to force ENUM constraints in my mySQL database. To do that, it is suggested I use "strict" sql mode. In an interactive prompt, this can be set with one of:

SET GLOBAL sql_mode = 'STRICT_ALL_TABLES';
SET SESSION sql_mode = 'STRICT_ALL_TABLES';

Or at server startup with:

 --sql-mode="STRICT_ALL_TABLES"

Or in my.cnf as:

sql-mode="STRICT_ALL_TABLES"

Is there a way to do such a thing in peewee? Perhaps by extending the Database class? Or injecting raw sql in queries?


Solution

  • Your best bet is to probably subclass MySQLDatabase and override the _connect() method, e.g.

    class StrictMySQLDatabase(MySQLDatabase):
        def _connect(self, database, **kwargs):
            conn = super(StrictMySQLDatabase, self)._connect(database, **kwargs)
            cursor = conn.cursor()
            cursor.execute("SET SESSION sql_mode = 'STRICT_ALL_TABLES';")
            return conn