Ejemplo n.º 1
0
    def __init__(self, connection=None):
        self._ran = []
        self._notes = []
        from config import database
        database_dict = database.DB

        self.repository = DatabaseMigrationRepository(database.DB,
                                                      'migrations')
        self.migrator = Migrator(self.repository, database.DB)
        if not connection or connection == 'default':
            connection = database.DATABASES['default']
        self.migrator.set_connection(connection)
        if not self.repository.repository_exists():
            self.repository.create_repository()

        from wsgi import container

        self.migration_directories = ['databases/migrations']
        for key, value in container.providers.items():
            if isinstance(key, str) and 'MigrationDirectory' in key:
                self.migration_directories.append(value)

        try:
            add_venv_site_packages()
        except ImportError:
            self.comment(
                'This command must be ran inside of the root of a Masonite project directory'
            )
Ejemplo n.º 2
0
def db_scope_fn(app, request):
    """ Session-wide test database """
    migrations_path = Path(__file__).parent.parent.joinpath("migrations")
    with app.app_context():
        _db.init_app(current_app)
        repo = DatabaseMigrationRepository(_db, "migrations")
        migrator = Migrator(repo, _db)
        if not migrator.repository_exists():
            repo.create_repository()
        migrator.rollback(migrations_path)
        migrator.run(migrations_path)
    def handle(self):
        sys.path.append(os.getcwd())
        try:
            add_venv_site_packages()
            from wsgi import container
        except ImportError:
            self.comment(
                'This command must be ran inside of the root of a Masonite project directory'
            )

        # Get any migration files from the Service Container
        migration_directory = ['databases/migrations']
        for key, value in container.providers.items():
            if 'MigrationDirectory' in key:
                migration_directory.append(value)

        # Load in the Orator migration system
        from orator.migrations import Migrator, DatabaseMigrationRepository
        from config import database
        repository = DatabaseMigrationRepository(database.DB, 'migrations')
        migrator = Migrator(repository, database.DB)
        if not migrator.repository_exists():
            repository.create_repository()

        # Create a new list of migrations with the correct file path instead
        migration_list = []
        for migration in migrator.get_repository().get_ran():
            for directory in migration_directory:
                if os.path.exists(os.path.join(directory, migration + '.py')):
                    migration_list.append(os.path.join(os.getcwd(), directory))
                    break

        # Rollback the migrations
        notes = []
        for migration in migrator.get_repository().get_ran():
            for migration_directory in migration_list:
                try:
                    migrator.reset(migration_directory)
                except QueryException as e:
                    raise e
                except FileNotFoundError:
                    pass

                if migrator.get_notes():
                    notes += migrator.get_notes()

        # Show notes from the migrator
        self.line('')
        for note in notes:
            if not ('Nothing to rollback.' in note):
                self.line(note)
        if not notes:
            self.info('Nothing to rollback')
Ejemplo n.º 4
0
def db(app):
    from orator.migrations import Migrator, DatabaseMigrationRepository
    db = app.extensions.db
    repository = DatabaseMigrationRepository(db, 'migrations')
    migrator = Migrator(repository, db)

    if not migrator.repository_exists():
        repository.create_repository()
    path = os.path.join(app.root_path, 'db/migrations')

    migrator.run(path)
    yield db
    migrator.rollback(path)
Ejemplo n.º 5
0
def migrate_in_memory(database_manager: DatabaseManager):
    """
    参考: https://github.com/sdispater/orator/issues/159#issuecomment-288464538
    """
    migration_repository = DatabaseMigrationRepository(database_manager,
                                                       'migrations')
    migrator = Migrator(migration_repository, database_manager)

    if not migrator.repository_exists():
        migration_repository.create_repository()

    migrations_path = Path(__file__).parents[4] / 'migrations'
    migrator.run(migrations_path)
Ejemplo n.º 6
0
    def test_rollback_migration_can_be_pretended(self):
        resolver_mock = flexmock(DatabaseManager)
        resolver_mock.should_receive("connection").and_return({})
        resolver = flexmock(DatabaseManager({}))
        connection = flexmock(Connection(None))
        connection.should_receive("get_logged_queries").twice().and_return([])
        resolver.should_receive("connection").with_args(None).and_return(
            connection)

        migrator = flexmock(
            Migrator(
                flexmock(DatabaseMigrationRepository(resolver, "migrations")),
                resolver))

        foo_migration = flexmock(MigrationStub("foo"))
        foo_migration.should_receive("get_connection").and_return(connection)
        bar_migration = flexmock(MigrationStub("bar"))
        bar_migration.should_receive("get_connection").and_return(connection)
        migrator.get_repository().should_receive("get_last").once().and_return(
            [foo_migration, bar_migration])

        migrator.should_receive("_resolve").with_args(
            os.getcwd(), "bar").once().and_return(bar_migration)
        migrator.should_receive("_resolve").with_args(
            os.getcwd(), "foo").once().and_return(foo_migration)

        migrator.rollback(os.getcwd(), True)

        self.assertTrue(foo_migration.downed)
        self.assertFalse(foo_migration.upped)
        self.assertTrue(foo_migration.downed)
        self.assertFalse(foo_migration.upped)
Ejemplo n.º 7
0
    def test_last_batch_of_migrations_can_be_rolled_back(self):
        resolver_mock = flexmock(DatabaseManager)
        resolver_mock.should_receive("connection").and_return({})
        resolver = flexmock(DatabaseManager({}))
        connection = flexmock()
        connection.should_receive("transaction").twice().and_return(connection)
        resolver.should_receive("connection").and_return(connection)

        migrator = flexmock(
            Migrator(
                flexmock(DatabaseMigrationRepository(resolver, "migrations")),
                resolver))

        foo_migration = MigrationStub("foo")
        bar_migration = MigrationStub("bar")
        migrator.get_repository().should_receive("get_last").once().and_return(
            [foo_migration, bar_migration])

        bar_mock = flexmock(MigrationStub())
        bar_mock.set_connection(connection)
        bar_mock.should_receive("down").once()
        foo_mock = flexmock(MigrationStub())
        foo_mock.set_connection(connection)
        foo_mock.should_receive("down").once()
        migrator.should_receive("_resolve").with_args(
            os.getcwd(), "bar").once().and_return(bar_mock)
        migrator.should_receive("_resolve").with_args(
            os.getcwd(), "foo").once().and_return(foo_mock)

        migrator.get_repository().should_receive("delete").once().with_args(
            bar_migration)
        migrator.get_repository().should_receive("delete").once().with_args(
            foo_migration)

        migrator.rollback(os.getcwd())
    def execute(self, i, o):
        """
        Executes the command.

        :type i: cleo.inputs.input.Input
        :type o: cleo.outputs.output.Output
        """
        super(InstallCommand, self).execute(i, o)

        database = i.get_option('database')
        repository = DatabaseMigrationRepository(self._resolver, 'migrations')

        repository.set_source(database)
        repository.create_repository()

        o.writeln(decode('<info>✓ Migration table created successfully</info>'))
Ejemplo n.º 9
0
    def handle(self):
        """
        Executes the command.
        """
        confirm = self.confirm(
            '<question>Are you sure you want to reset all of the migrations?</question> ',
            False
        )
        if not confirm:
            return

        database = self.option('database')
        repository = DatabaseMigrationRepository(self.resolver, 'migrations')

        migrator = Migrator(repository, self.resolver)

        self._prepare_database(migrator, database)

        pretend = bool(self.option('pretend'))

        path = self.option('path')

        if path is None:
            path = self._get_migration_path()

        migrator.reset(path, pretend)

        for note in migrator.get_notes():
            self.line(note)
Ejemplo n.º 10
0
    def test_rollback_migration_can_be_pretended(self):
        import orator.migrations.migrator as migrator
        d = flexmock(migrator)
        resolver_mock = flexmock(DatabaseManager)
        resolver_mock.should_receive('connection').and_return({})
        resolver = flexmock(DatabaseManager({}))
        connection = flexmock(Connection(None))
        connection.should_receive('get_logged_queries').twice().and_return([])
        resolver.should_receive('connection').with_args(None).and_return(
            connection)
        d.should_receive('dump').with_args(connection).and_return('')

        migrator = flexmock(
            Migrator(
                flexmock(DatabaseMigrationRepository(resolver, 'migrations')),
                resolver))

        foo_migration = flexmock(MigrationStub('foo'))
        foo_migration.should_receive('get_connection').and_return(connection)
        bar_migration = flexmock(MigrationStub('bar'))
        bar_migration.should_receive('get_connection').and_return(connection)
        migrator.get_repository().should_receive('get_last').once().and_return(
            [foo_migration, bar_migration])

        migrator.should_receive('_resolve').with_args(
            os.getcwd(), 'bar').once().and_return(bar_migration)
        migrator.should_receive('_resolve').with_args(
            os.getcwd(), 'foo').once().and_return(foo_migration)

        migrator.rollback(os.getcwd(), True)

        self.assertTrue(foo_migration.downed)
        self.assertFalse(foo_migration.upped)
        self.assertTrue(foo_migration.downed)
        self.assertFalse(foo_migration.upped)
Ejemplo n.º 11
0
    def test_last_batch_of_migrations_can_be_rolled_back(self):
        resolver_mock = flexmock(DatabaseManager)
        resolver_mock.should_receive('connection').and_return({})
        resolver = flexmock(DatabaseManager({}))
        connection = flexmock()
        connection.should_receive('transaction').twice().and_return(connection)
        resolver.should_receive('connection').and_return(connection)

        migrator = flexmock(
            Migrator(
                flexmock(DatabaseMigrationRepository(resolver, 'migrations')),
                resolver))

        foo_migration = MigrationStub('foo')
        bar_migration = MigrationStub('bar')
        migrator.get_repository().should_receive('get_last').once().and_return(
            [foo_migration, bar_migration])

        bar_mock = flexmock(MigrationStub())
        bar_mock.set_connection(connection)
        bar_mock.should_receive('down').once()
        foo_mock = flexmock(MigrationStub())
        foo_mock.set_connection(connection)
        foo_mock.should_receive('down').once()
        migrator.should_receive('_resolve').with_args(
            os.getcwd(), 'bar').once().and_return(bar_mock)
        migrator.should_receive('_resolve').with_args(
            os.getcwd(), 'foo').once().and_return(foo_mock)

        migrator.get_repository().should_receive('delete').once().with_args(
            bar_migration)
        migrator.get_repository().should_receive('delete').once().with_args(
            foo_migration)

        migrator.rollback(os.getcwd())
Ejemplo n.º 12
0
    def test_rollback_migration_can_be_pretended(self):
        resolver_mock = flexmock(DatabaseManager)
        resolver_mock.should_receive('connection').and_return({})
        resolver = flexmock(DatabaseManager({}))
        connection = flexmock(Connection(None))
        connection.should_receive('pretend').replace_with(
            lambda callback: callback(None))
        resolver.should_receive('connection').with_args(None).and_return(
            connection)

        migrator = flexmock(
            Migrator(
                flexmock(DatabaseMigrationRepository(resolver, 'migrations')),
                resolver))

        foo_migration = MigrationStub('foo')
        bar_migration = MigrationStub('bar')
        migrator.get_repository().should_receive('get_last').once().and_return(
            [foo_migration, bar_migration])

        bar_mock = flexmock(MigrationStub())
        bar_mock.should_receive('down').once()
        foo_mock = flexmock(MigrationStub())
        foo_mock.should_receive('down').once()
        migrator.should_receive('_resolve').with_args(
            os.getcwd(), 'bar').once().and_return(bar_mock)
        migrator.should_receive('_resolve').with_args(
            os.getcwd(), 'foo').once().and_return(foo_mock)

        migrator.rollback(os.getcwd(), True)
Ejemplo n.º 13
0
def pytest_runtest_teardown():
    from personalwebpageapi.models import db

    migrations_path = f'{os.getcwd()}/migrations'

    repository = DatabaseMigrationRepository(
        db,
        'migrations',
    )
    migrator = Migrator(repository, db)

    if not migrator.repository_exists():
        repository.create_repository()

    migrator.set_connection(db.get_default_connection())
    migrator.reset(migrations_path)
Ejemplo n.º 14
0
    def handle(self):
        """
        Executes the command.
        """
        prompt_msg = ('<question>Are you sure you want to rollback '
                      'the last migration?:</question> ')
        if not self.confirm_to_proceed(prompt_msg):
            return

        database = self.option('database')
        repository = DatabaseMigrationRepository(self.resolver, 'migrations')

        migrator = Migrator(repository, self.resolver)

        self._prepare_database(migrator, database)

        pretend = self.option('pretend')

        path = self.option('path')

        if path is None:
            path = self._get_migration_path()

        migrator.rollback(path, pretend)

        for note in migrator.get_notes():
            self.line(note)
Ejemplo n.º 15
0
    def handle(self):
        """
        Executes the command.
        """
        if not self.confirm_to_proceed(
            "<question>Are you sure you want to rollback the last migration?:</question> "
        ):
            return

        database = self.option("database")
        repository = DatabaseMigrationRepository(self.resolver, "migrations")

        migrator = Migrator(repository, self.resolver)

        self._prepare_database(migrator, database)

        pretend = self.option("pretend")

        path = self.option("path")

        if path is None:
            path = self._get_migration_path()

        migrator.rollback(path, pretend)

        for note in migrator.get_notes():
            self.line(note)
    def fire(self):
        """
        Executes the command.
        """
        dialog = self.get_helper('dialog')
        confirm = dialog.ask_confirmation(
            self.output,
            '<question>Are you sure you want to rollback the last migration?</question> ',
            False)
        if not confirm:
            return

        database = self.option('database')
        repository = DatabaseMigrationRepository(self.resolver, 'migrations')

        migrator = Migrator(repository, self.resolver)

        self._prepare_database(migrator, database)

        pretend = self.option('pretend')

        path = self.option('path')

        if path is None:
            path = self._get_migration_path()

        migrator.rollback(path, pretend)

        for note in migrator.get_notes():
            self.line(note)
Ejemplo n.º 17
0
def setup_database():
    DATABASES = {"sqlite": {"driver": "sqlite", "database": "test.db"}}

    db = DatabaseManager(DATABASES)
    Schema(db)

    Model.set_connection_resolver(db)

    repository = DatabaseMigrationRepository(db, "migrations")
    migrator = Migrator(repository, db)

    if not repository.repository_exists():
        repository.create_repository()

    migrator.reset("app/migrations")
    migrator.run("app/migrations")
Ejemplo n.º 18
0
    def __init__(self):
        """
        Initialize the Orator Migrator Class. Check if the migration table has been created. If not, Create the
        Repository
        """
        check, config = self.get_config()
        if not check:
            print("Error Occurred")
        else:
            self.manager = DatabaseManager(config=config)
            self.path = os.path.abspath('.') + "/database/migrations/"
            self.repository = DatabaseMigrationRepository(resolver=self.manager, table='migrations')

            if not self.repository.repository_exists():
                self.repository.create_repository()

            super().__init__(self.repository, self.manager)
    def test_get_next_batch_number_returns_last_batch_number_plus_one(self):
        resolver_mock = flexmock(DatabaseManager)
        resolver_mock.should_receive("connection").and_return(None)
        resolver = flexmock(resolver_mock({}))
        repo = flexmock(DatabaseMigrationRepository(resolver, "migrations"))
        repo.should_receive("get_last_batch_number").and_return(1)

        self.assertEqual(2, repo.get_next_batch_number())
Ejemplo n.º 20
0
    def __init__(self):
        self.db_directory = tempfile.TemporaryDirectory()
        self.db_file = os.path.join(self.db_directory.name, 'test.db')

        self.db_manager = DatabaseManager(self.database_configuration())

        migrations_directory = os.path.join(os.path.dirname(__file__), "..", 'migrations')

        migration_repository = DatabaseMigrationRepository(self.db_manager, "migrations")
        migration_repository.create_repository()
        migrator = Migrator(
            migration_repository,
            self.db_manager,
        )
        migrator.reset(migrations_directory)
        migrator.run(migrations_directory)

        _Model.set_connection_resolver(self.db_manager)
Ejemplo n.º 21
0
    def test_nothing_is_rolled_back_when_nothing_in_repository(self):
        resolver = flexmock(DatabaseManager)
        resolver.should_receive('connection').and_return(None)

        migrator = flexmock(
            Migrator(
                flexmock(DatabaseMigrationRepository(resolver, 'migrations')),
                resolver))

        migrator.get_repository().should_receive('get_last').once().and_return(
            [])

        migrator.rollback(os.getcwd())
Ejemplo n.º 22
0
    def execute(self, i, o):
        """
        Executes the command.

        :type i: cleo.inputs.input.Input
        :type o: cleo.outputs.output.Output
        """
        super(MigrateCommand, self).execute(i, o)

        dialog = self.get_helper('dialog')
        confirm = dialog.ask_confirmation(
            o,
            '<question>Are you sure you want to proceed with the migration?</question> ',
            False
        )
        if not confirm:
            return

        database = i.get_option('database')
        repository = DatabaseMigrationRepository(self._resolver, 'migrations')

        migrator = Migrator(repository, self._resolver)

        self._prepare_database(migrator, database, i, o)

        pretend = i.get_option('pretend')

        path = i.get_option('path')

        if path is None:
            path = self._get_migration_path()

        migrator.run(path, pretend)

        for note in migrator.get_notes():
            o.writeln(note)

        # If the "seed" option has been given, we will rerun the database seed task
        # to repopulate the database.
        if i.get_option('seed'):
            options = [
                ('--database', database),
                ('--config', i.get_option('config')),
                ('-n', True)
            ]

            if i.get_option('seed-path'):
                options.append(('--path', i.get_option('seed-path')))

            self.call('db:seed', options, o)
    def handle(self):
        """
        Executes the command
        """
        database = self.option('database')
        repository = DatabaseMigrationRepository(self.resolver, 'migrations')

        repository.set_source(database)
        repository.create_repository()

        self.info('Migration table created successfully')
Ejemplo n.º 24
0
    def execute(self, i, o):
        """
        Executes the command.

        :type i: cleo.inputs.input.Input
        :type o: cleo.outputs.output.Output
        """
        super(StatusCommand, self).execute(i, o)

        database = i.get_option('database')
        repository = DatabaseMigrationRepository(self._resolver, 'migrations')

        migrator = Migrator(repository, self._resolver)

        if not migrator.repository_exists():
            return o.writeln('<error>No migrations found</error>')

        self._prepare_database(migrator, database, i, o)

        path = i.get_option('path')

        if path is None:
            path = self._get_migration_path()

        ran = migrator.get_repository().get_ran()

        migrations = []
        for migration in migrator._get_migration_files(path):
            if migration in ran:
                migrations.append(
                    ['<fg=cyan>%s</>' % migration, '<info>Yes</info>'])
            else:
                migrations.append(
                    ['<fg=cyan>%s</>' % migration, '<fg=red>No</>'])

        if migrations:
            table = self.get_helper('table')
            table.set_headers(['Migration', 'Ran?'])
            table.set_rows(migrations)
            table.render(o)
        else:
            return o.writeln('<error>No migrations found</error>')

        for note in migrator.get_notes():
            o.writeln(note)
Ejemplo n.º 25
0
    def test_migrations_are_run_up_when_outstanding_migrations_exist(self):
        import orator.migrations.migrator as migrator
        d = flexmock(migrator)
        resolver_mock = flexmock(DatabaseManager)
        resolver_mock.should_receive('connection').and_return({})
        resolver = flexmock(DatabaseManager({}))
        connection = flexmock()
        connection.should_receive('transaction').twice().and_return(connection)
        resolver.should_receive('connection').and_return(connection)
        d.should_receive('dump').with_args(connection).and_return('')

        migrator = flexmock(
            Migrator(
                flexmock(DatabaseMigrationRepository(resolver, 'migrations')),
                resolver))

        g = flexmock(glob)
        g.should_receive('glob').with_args(
            os.path.join(os.getcwd(), '[0-9]*_*.py')).and_return([
                os.path.join(os.getcwd(), '2_bar.py'),
                os.path.join(os.getcwd(), '1_foo.py'),
                os.path.join(os.getcwd(), '3_baz.py')
            ])

        migrator.get_repository().should_receive('get_ran').once().and_return(
            ['1_foo'])
        migrator.get_repository().should_receive(
            'get_next_batch_number').once().and_return(1)
        migrator.get_repository().should_receive('log').once().with_args(
            '2_bar', 1)
        migrator.get_repository().should_receive('log').once().with_args(
            '3_baz', 1)
        bar_mock = flexmock(MigrationStub())
        bar_mock.set_connection(connection)
        bar_mock.should_receive('up').once()
        baz_mock = flexmock(MigrationStub())
        baz_mock.set_connection(connection)
        baz_mock.should_receive('up').once()
        migrator.should_receive('_resolve').with_args(
            os.getcwd(), '2_bar').once().and_return(bar_mock)
        migrator.should_receive('_resolve').with_args(
            os.getcwd(), '3_baz').once().and_return(baz_mock)

        migrator.run(os.getcwd())
Ejemplo n.º 26
0
    def test_migrations_are_run_up_directly_if_transactional_is_false(self):
        resolver_mock = flexmock(DatabaseManager)
        resolver_mock.should_receive("connection").and_return({})
        resolver = flexmock(DatabaseManager({}))
        connection = flexmock()
        connection.should_receive("transaction").never()
        resolver.should_receive("connection").and_return(connection)

        migrator = flexmock(
            Migrator(
                flexmock(DatabaseMigrationRepository(resolver, "migrations")),
                resolver))

        g = flexmock(glob)
        g.should_receive("glob").with_args(
            os.path.join(os.getcwd(), "[0-9]*_*.py")).and_return([
                os.path.join(os.getcwd(), "2_bar.py"),
                os.path.join(os.getcwd(), "1_foo.py"),
                os.path.join(os.getcwd(), "3_baz.py"),
            ])

        migrator.get_repository().should_receive("get_ran").once().and_return(
            ["1_foo"])
        migrator.get_repository().should_receive(
            "get_next_batch_number").once().and_return(1)
        migrator.get_repository().should_receive("log").once().with_args(
            "2_bar", 1)
        migrator.get_repository().should_receive("log").once().with_args(
            "3_baz", 1)
        bar_mock = flexmock(MigrationStub())
        bar_mock.transactional = False
        bar_mock.set_connection(connection)
        bar_mock.should_receive("up").once()
        baz_mock = flexmock(MigrationStub())
        baz_mock.transactional = False
        baz_mock.set_connection(connection)
        baz_mock.should_receive("up").once()
        migrator.should_receive("_resolve").with_args(
            os.getcwd(), "2_bar").once().and_return(bar_mock)
        migrator.should_receive("_resolve").with_args(
            os.getcwd(), "3_baz").once().and_return(baz_mock)

        migrator.run(os.getcwd())
Ejemplo n.º 27
0
    def test_get_last_migrations(self):
        resolver_mock = flexmock(DatabaseManager)
        resolver_mock.should_receive('connection').and_return(None)
        resolver = flexmock(resolver_mock({}))
        repo = flexmock(DatabaseMigrationRepository(resolver, 'migrations'))
        connection = flexmock(Connection(None))
        query = flexmock(QueryBuilder(connection, None, None))
        repo.should_receive('get_last_batch_number').and_return(1)
        repo.get_connection_resolver().should_receive('connection').with_args(
            None).and_return(connection)
        repo.get_connection().should_receive('table').once().with_args(
            'migrations').and_return(query)
        query.should_receive('where').once().with_args('batch',
                                                       1).and_return(query)
        query.should_receive('order_by').once().with_args(
            'migration', 'desc').and_return(query)
        query.should_receive('get').once().and_return('foo')

        self.assertEqual('foo', repo.get_last())
Ejemplo n.º 28
0
    def test_migrations_are_run_up_directly_if_transactional_is_false(self):
        resolver_mock = flexmock(DatabaseManager)
        resolver_mock.should_receive('connection').and_return({})
        resolver = flexmock(DatabaseManager({}))
        connection = flexmock()
        connection.should_receive('transaction').never()
        resolver.should_receive('connection').and_return(connection)

        migrator = flexmock(
            Migrator(
                flexmock(DatabaseMigrationRepository(resolver, 'migrations')),
                resolver))

        g = flexmock(glob)
        g.should_receive('glob').with_args(
            os.path.join(os.getcwd(), '[0-9]*_*.py')).and_return([
                os.path.join(os.getcwd(), '2_bar.py'),
                os.path.join(os.getcwd(), '1_foo.py'),
                os.path.join(os.getcwd(), '3_baz.py')
            ])

        migrator.get_repository().should_receive('get_ran').once().and_return(
            ['1_foo'])
        migrator.get_repository().should_receive(
            'get_next_batch_number').once().and_return(1)
        migrator.get_repository().should_receive('log').once().with_args(
            '2_bar', 1)
        migrator.get_repository().should_receive('log').once().with_args(
            '3_baz', 1)
        bar_mock = flexmock(MigrationStub())
        bar_mock.transactional = False
        bar_mock.set_connection(connection)
        bar_mock.should_receive('up').once()
        baz_mock = flexmock(MigrationStub())
        baz_mock.transactional = False
        baz_mock.set_connection(connection)
        baz_mock.should_receive('up').once()
        migrator.should_receive('_resolve').with_args(
            os.getcwd(), '2_bar').once().and_return(bar_mock)
        migrator.should_receive('_resolve').with_args(
            os.getcwd(), '3_baz').once().and_return(baz_mock)

        migrator.run(os.getcwd())
    def test_get_last_migrations(self):
        resolver_mock = flexmock(DatabaseManager)
        resolver_mock.should_receive("connection").and_return(None)
        resolver = flexmock(resolver_mock({}))
        repo = flexmock(DatabaseMigrationRepository(resolver, "migrations"))
        connection = flexmock(Connection(None))
        query = flexmock(QueryBuilder(connection, None, None))
        repo.should_receive("get_last_batch_number").and_return(1)
        repo.get_connection_resolver().should_receive("connection").with_args(
            None).and_return(connection)
        repo.get_connection().should_receive("table").once().with_args(
            "migrations").and_return(query)
        query.should_receive("where").once().with_args("batch",
                                                       1).and_return(query)
        query.should_receive("order_by").once().with_args(
            "migration", "desc").and_return(query)
        query.should_receive("get").once().and_return("foo")

        self.assertEqual("foo", repo.get_last())
    def fire(self):
        """
        Executes the command.
        """
        dialog = self.get_helper('dialog')
        confirm = dialog.ask_confirmation(
            self.output,
            '<question>Are you sure you want to proceed with the migration?</question> ',
            False)
        if not confirm:
            return

        database = self.option('database')
        repository = DatabaseMigrationRepository(self.resolver, 'migrations')

        migrator = Migrator(repository, self.resolver)

        self._prepare_database(migrator, database)

        pretend = self.option('pretend')

        path = self.option('path')

        if path is None:
            path = self._get_migration_path()

        migrator.run(path, pretend)

        for note in migrator.get_notes():
            self.line(note)

        # If the "seed" option has been given, we will rerun the database seed task
        # to repopulate the database.
        if self.option('seed'):
            options = [('--database', database), ('-n', True)]

            if self.get_definition().has_option('config'):
                options.append(('--config', self.option('config')))

            if self.option('seed-path'):
                options.append(('--path', self.option('seed-path')))

            self.call('db:seed', options)
Ejemplo n.º 31
0
    def test_nothing_is_done_when_no_migrations_outstanding(self):
        resolver_mock = flexmock(DatabaseManager)
        resolver_mock.should_receive('connection').and_return(None)
        resolver = flexmock(DatabaseManager({}))

        migrator = flexmock(
            Migrator(
                flexmock(DatabaseMigrationRepository(resolver, 'migrations')),
                resolver))

        g = flexmock(glob)
        g.should_receive('glob').with_args(
            os.path.join(os.getcwd(), '[0-9]*_*.py')).and_return(
                [os.path.join(os.getcwd(), '1_foo.py')])

        migrator.get_repository().should_receive('get_ran').once().and_return(
            ['1_foo'])

        migrator.run(os.getcwd())