Created
November 1, 2013 15:09
-
-
Save passiomatic/7266859 to your computer and use it in GitHub Desktop.
A quick hack to make Peewee migrator work with MySQL - Tested against MySQL 5.1.52 on OS X.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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