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')
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')
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)
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)
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")
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)
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>'))
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>'))
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)
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
class Migration(Migrator): """ Handles the actions to be performed on the Migration files """ 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 run_(self, pretend): """ Run the migration file :param pretend: Determines whether to run the migration as a Simulation or not. Defaults to False :return: """ self.run(self.path, pretend=pretend) def rollback_(self, pretend): """ Roll Back the Last Migration :param pretend: Determines whether to run the migration as a Simulation or not. Defaults to False :return: int """ return self.rollback(self.path, pretend) def reset_(self, pretend): """ Reset all the migrations that have been done :param pretend: Determines whether to run the migration as a Simulation or not. Defaults to False :return: int """ return self.reset(self.path, pretend) @staticmethod @check_environment def get_config(): """ Gets the config from the os.environ. This is used to create the config dict for use by the ORM :return: str, dict """ db_type = os.getenv('DB_TYPE') db_host = os.getenv('DB_HOST') db_user = os.getenv('DB_USER') db_database = os.getenv('DB_NAME') db_password = os.getenv('DB_PASSWORD') db_prefix = os.getenv('DB_PREFIX', '') # Fix proposed by djunehor. Issue #20 check = Migration.check_packages(db_type) return check, { db_type: { 'driver': db_type.strip(), 'host': db_host.strip(), 'database': db_database.strip(), 'user': db_user.strip(), 'password': db_password.strip(), 'prefix': db_prefix.strip() } } @staticmethod def check_packages(db_name): """ Check if the driver for the user defined host is available. If it is not available, download it using PIP :param db_name: :return: """ click.echo('Checking for required Database Driver') reqs = subprocess.check_output([sys.executable, '-m', 'pip', 'freeze']) installed_packages = [r.decode().split('==')[0] for r in reqs.split()] if db_name.lower() == 'mysql': if 'PyMySQL' not in installed_packages: click.echo('Installing required Database Driver') click.echo( subprocess.check_output(["pip", "install", "pymysql"])) if db_name.lower() == 'postgresql': if 'psycopg2-binary' not in installed_packages: click.echo('Installing required Database Driver') click.echo( subprocess.check_output( ['pip', 'install', 'psycopg2-binary'])) return True