Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A quick hack to make Peewee migrator work with MySQL - Tested against MySQL 5.1.52 on OS X.
from peewee import *
from playhouse import migrate
kwargs = dict(
host = 'localhost',
user = 'root',
passwd = '' # The legendary MySQL empty password
)
_db = MySQLDatabase('test', **kwargs)
_db.connect()
class Foo(Model):
bar = TextField()
class Meta:
database = _db
db_table = 'foo'
class NewFoo(Foo):
bar = TextField()
baz = CharField(max_length=100, default='')
class Meta:
database = _db
db_table = 'foo'
class MySQLMigrator(migrate.Migrator):
sql_add_column = 'ALTER TABLE %(table)s ADD COLUMN %(column)s'
sql_rename_column = 'ALTER TABLE %(table)s CHANGE COLUMN %(column)s %(renamed_column)s'
# sql_drop_column same as base Migrator class
# sql_rename_table same as base Migrator class
sql_null = 'ALTER TABLE %(table)s MODIFY COLUMN %(column)s'
def rename_column(self, model_class, old_name, new_name):
field = getattr(model_class, old_name)
field.db_column = new_name
self.execute(self.sql_rename_column % {
'table': self.quote(model_class._meta.db_table),
'column': old_name,
'renamed_column': self.compiler.field_sql(field)})
def set_nullable(self, model_class, field, nullable=False):
field.null = nullable
self.execute(self.sql_null % {
'table': self.quote(model_class._meta.db_table),
'column': self.compiler.field_sql(field)})
def run_tests():
models = (Foo, )
for model in models:
model.create_table(fail_silently=True)
migrator = MySQLMigrator(_db)
with _db.transaction():
migrator.add_column(NewFoo, NewFoo.baz)
migrator.set_nullable(NewFoo, NewFoo.baz, nullable=True)
migrator.rename_column(NewFoo, 'baz', 'qux')
#migrator.drop_column(NewFoo, 'qux')
#migrator.rename_table(Foo, 'newfoo')
if __name__ == '__main__':
run_tests()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment