def test_migrator_postgres(_mock_connection): """ Ensure change_fields generates queries and does not cause exception """ import peewee as pw from playhouse.db_url import connect from peewee_migrate import Migrator database = connect('postgres:///fake') migrator = Migrator(database) @migrator.create_table class User(pw.Model): name = pw.CharField() created_at = pw.DateField() assert User == migrator.orm['user'] # Date -> DateTime migrator.change_fields('user', created_at=pw.DateTimeField()) migrator.run() assert 'ALTER TABLE "user" ALTER COLUMN "created_at" TYPE TIMESTAMP' in database.cursor( ).queries # Char -> Text migrator.change_fields('user', name=pw.TextField()) migrator.run() assert 'ALTER TABLE "user" ALTER COLUMN "name" TYPE TEXT' in database.cursor( ).queries
def migrate(migrator: peewee_migrate.Migrator, _database: peewee.Database, fake=False, **_kwargs: typing.Any) -> None: if fake is True: return migrator.drop_not_null('user', 'telegram_username')
def migrate(migrator: peewee_migrate.Migrator, _database: peewee.Database, fake=False, **_kwargs: typing.Any) -> None: if fake is True: return subscription = peewee.IntegerField(default=0) migrator.add_columns(model='user', subscription=subscription)
def test_migrator_postgres(): """ Ensure change_fields generates queries and does not cause exception """ import peewee as pw from playhouse.db_url import connect from peewee_migrate import Migrator # Monkey patch psycopg2 connect import psycopg2 from .mocks import postgres psycopg2.connect = postgres.MockConnection database = connect('postgres:///fake') migrator = Migrator(database) @migrator.create_table class User(pw.Model): name = pw.CharField() created_at = pw.DateField() assert User == migrator.orm['user'] # Date -> DateTime migrator.change_fields('user', created_at=pw.DateTimeField()) migrator.run() assert 'ALTER TABLE "user" ALTER COLUMN "created_at" TYPE TIMESTAMP' in database.cursor().queries # Char -> Text migrator.change_fields('user', name=pw.TextField()) migrator.run() assert 'ALTER TABLE "user" ALTER COLUMN "name" TYPE TEXT' in database.cursor().queries
def migrate_schema(database: 'Database', from_version: int, to_version: int, migrate_dir: str = default_migrate_dir()): if from_version == to_version: return router = Router(database.db, migrate_dir, schema_version=to_version) environment = router.environment scripts = environment.scripts to_run, to_fake, downgrade = choose_scripts(scripts, from_version, to_version) if not to_run: raise NoMigrationScripts( "Cannot migrate schema from version {} to {}: " "no suitable migration scripts found".format( from_version, to_version)) with patch_peewee(database.fields, database.models): migrator = Migrator(router.database) # Teach migrator previous changes for script in to_fake: router.run_one(script, migrator, fake=True) for script in to_run: router.run_one(script, migrator, fake=False, downgrade=downgrade) version = environment.version_from_name(script) version -= 1 if downgrade else 0 database.set_user_version(version)
def test_migrator_schema(_mock_connection): import peewee as pw from playhouse.db_url import connect from peewee_migrate import Migrator database = connect('postgres:///fake') schema_name = 'test_schema' migrator = Migrator(database, schema=schema_name) def has_schema_select_query(): return database.cursor().queries[0] == 'SET search_path TO {}'.format( schema_name) @migrator.create_table class User(pw.Model): name = pw.CharField() created_at = pw.DateField() migrator.run() assert has_schema_select_query() migrator.change_fields('user', created_at=pw.DateTimeField()) migrator.run() assert has_schema_select_query()
LIST_AUGI_GENDER_VAL = [ (0, 0), (1, 1), (2, 2), (3, 3), (4, 4), ] LIST_MESSAGE_STATE = {"unread": 0, "read": 1} LIST_MESSAGE_STATE_VAL = [(0, 0), (1, 1)] chat_app_db = SqliteDatabase(os.path.join(BASE_DIR, 'database', 'chat_app.db'), pragmas={'journal_mode': 'wal'}) migrator = Migrator(chat_app_db) class BaseModel(Model): """A base model that will use our Sqlite database.""" class Meta: database = chat_app_db class ListField(TextField): def db_value(self, list_items): return ';'.join(json.dumps(item) for item in list_items) def python_value(self, data): list_items = [] if data and len(data) > 0:
import logging from peewee import (Model, DateTimeField, TextField, BigIntegerField, PeeweeException) from peewee_migrate import Migrator, Router from playhouse.sqlite_ext import RowIDField, SqliteExtDatabase from constants import GENERIC_DATE_TIME_FORMAT, EPOCH_DATE logger = logging.getLogger(__name__) database = SqliteExtDatabase('file_convert.sqlite') database.connect() migrator = Migrator(database) router = Router(database, migrate_table='migration', logger=logger) def get_current_datetime(): return datetime.now().strftime(GENERIC_DATE_TIME_FORMAT) class BaseModel(Model): rowid = RowIDField() created_at = DateTimeField(default=get_current_datetime) updated_at = DateTimeField() class Meta:
def test_migrator(): import peewee as pw from playhouse.db_url import connect from peewee_migrate import Migrator database = connect('sqlite:///:memory:') migrator = Migrator(database) @migrator.create_table class Customer(pw.Model): name = pw.CharField() assert Customer == migrator.orm['customer'] @migrator.create_table class Order(pw.Model): number = pw.CharField() uid = pw.CharField(unique=True) customer_id = pw.ForeignKeyField(Customer, column_name='customer_id') assert Order == migrator.orm['order'] migrator.run() migrator.add_columns(Order, finished=pw.BooleanField(default=False)) assert 'finished' in Order._meta.fields migrator.run() migrator.drop_columns('order', 'finished', 'customer_id', 'uid') assert 'finished' not in Order._meta.fields assert not hasattr(Order, 'customer_id') assert not hasattr(Order, 'customer_id_id') migrator.run() migrator.add_columns(Order, customer=pw.ForeignKeyField(Customer, null=True)) assert 'customer' in Order._meta.fields assert Order.customer.name == 'customer' migrator.run() assert Order.customer.name == 'customer' migrator.rename_column(Order, 'number', 'identifier') assert 'identifier' in Order._meta.fields migrator.run() migrator.drop_not_null(Order, 'identifier') assert Order._meta.fields['identifier'].null assert Order._meta.columns['identifier'].null migrator.run() migrator.add_default(Order, 'identifier', 11) assert Order._meta.fields['identifier'].default == 11 migrator.run() migrator.change_columns(Order, identifier=pw.IntegerField(default=0)) assert Order.identifier.field_type == 'INT' migrator.run() Order.create(identifier=55) migrator.sql('UPDATE "order" SET identifier = 77;') migrator.run() order = Order.get() assert order.identifier == 77 migrator.add_index(Order, 'identifier', 'customer') migrator.run() assert Order._meta.indexes assert not Order.identifier.index migrator.drop_index(Order, 'identifier', 'customer') migrator.run() assert not Order._meta.indexes migrator.remove_fields(Order, 'customer') migrator.run() assert not hasattr(Order, 'customer') migrator.add_index(Order, 'identifier', unique=True) migrator.run() assert not Order.identifier.index assert Order.identifier.unique assert Order._meta.indexes migrator.change_columns(Order, identifier=pw.IntegerField(default=0)) assert not Order._meta.indexes