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")
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