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)
Пример #2
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()

        while True:
            count = migrator.rollback(path, pretend)

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

            if count == 0:
                break
Пример #3
0
    def handle(self):
        """
        Executes the command.
        """
        confirm = self.confirm(
            '<question>Are you sure you want to rollback the last migration?</question> ',
            True
        )
        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)
    def fire(self):
        """
        Executes the command.
        """
        dialog = self.get_helper("dialog")
        confirm = dialog.ask_confirmation(
            self.output, "<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()

        while True:
            count = migrator.rollback(path, pretend)

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

            if count == 0:
                break
Пример #5
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 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)
    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)
Пример #8
0
    def handle(self):
        """
        Executes the command.
        """
        database = self.option('database')

        self.resolver.set_default_connection(database)

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

        migrator = Migrator(repository, self.resolver)

        if not migrator.repository_exists():
            return self.error('No migrations found')

        self._prepare_database(migrator, database)

        path = self.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</>'])
            else:
                migrations.append(['<fg=cyan>%s</>' % migration, '<fg=red>No</>'])

        if migrations:
            table = self.table(
                ['Migration', 'Ran?'],
                migrations
            )
            table.render()
        else:
            return self.error('No migrations found')

        for note in migrator.get_notes():
            self.line(note)
    def execute(self, i, o):
        """
        Executes the command.

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

        dialog = self.get_helper('dialog')
        confirm = dialog.ask_confirmation(
            o,
            '<question>Are you sure you want to reset all of the migrations?</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 = bool(i.get_option('pretend'))

        path = i.get_option('path')

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

        while True:
            count = migrator.rollback(path, pretend)

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

            if count == 0:
                break
Пример #10
0
    def test_nothing_is_rolled_back_when_nothing_in_repository(self):
        import orator.migrations.migrator as migrator
        d = flexmock(migrator)
        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())
Пример #11
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)
Пример #12
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())
Пример #13
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())
Пример #14
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())
Пример #15
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())
Пример #16
0
    def test_last_batch_of_migrations_can_be_rolled_back_directly_if_transactional_is_false(
            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').never()
        resolver.should_receive('connection').and_return(connection)
        d.should_receive('dump').with_args(connection).and_return('')

        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.transactional = False
        bar_mock.set_connection(connection)
        bar_mock.should_receive('down').once()
        foo_mock = flexmock(MigrationStub())
        foo_mock.transactional = False
        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())
Пример #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")
Пример #18
0
    def test_up_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))

        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)
        bar_mock = flexmock(MigrationStub())
        bar_mock.should_receive('get_connection').once().and_return(None)
        bar_mock.should_receive('up').once()
        baz_mock = flexmock(MigrationStub())
        baz_mock.should_receive('get_connection').once().and_return(None)
        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(), True)
Пример #19
0
    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
        for migration in migration_list:

            try:
                migrator.rollback(migration)
                for note in migrator.get_notes():
                    self.line(note)
            except Exception:
                pass
Пример #20
0
    def test_last_batch_of_migrations_can_be_rolled_back_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))

        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.transactional = False
        bar_mock.set_connection(connection)
        bar_mock.should_receive("down").once()
        foo_mock = flexmock(MigrationStub())
        foo_mock.transactional = False
        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())
Пример #21
0
    def test_up_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))

        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)
        bar_mock = flexmock(MigrationStub())
        bar_mock.should_receive("get_connection").once().and_return(connection)
        bar_mock.should_receive("up").once()
        baz_mock = flexmock(MigrationStub())
        baz_mock.should_receive("get_connection").once().and_return(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(), True)
Пример #22
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)
Пример #23
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)
Пример #24
0
    def handle(self):
        """
        Executes the command.
        """
        database = self.option('database')

        self.resolver.set_default_connection(database)

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

        migrator = Migrator(repository, self.resolver)

        if not migrator.repository_exists():
            return self.error('No migrations found')

        self._prepare_database(migrator, database)

        path = self.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</>'])
            else:
                migrations.append(
                    ['<fg=cyan>%s</>' % migration, '<fg=red>No</>'])

        if migrations:
            table = self.table(['Migration', 'Ran?'], migrations)
            table.render()
        else:
            return self.error('No migrations found')

        for note in migrator.get_notes():
            self.line(note)
Пример #25
0
class Migrations(HasColoredCommands):
    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'
            )

    def run(self):
        for directory in self.migration_directories:
            try:
                if len(self.migration_directories) > 1:
                    self.info('Migrating: {}'.format(directory))
                self.migrator.run(directory)
                self._ran.append(self.repository.get_ran())
                self._notes = self.migrator._notes
            except Exception as e:
                self.danger(str(e))

        return self

    def rollback(self):
        for directory in self.migration_directories:
            try:
                if len(self.migration_directories) > 1:
                    self.info('Migrating: {}'.format(directory))
                self.migrator.rollback(directory)
                self._ran.append(self.repository.get_ran())
                self._notes = self.migrator._notes
            except Exception as e:
                self.danger(str(e))

        return self

    def refresh(self):
        self.run()
        self.rollback()

    def reset(self):
        for directory in self.migration_directories:
            try:
                if len(self.migration_directories) > 1:
                    self.info('Migrating: {}'.format(directory))
                self.migrator.reset(directory)
                self._ran.append(self.repository.get_ran())
                self._notes = self.migrator._notes
            except Exception as e:
                self.danger(str(e))

        return self

    def ran(self):
        return self._ran