def _upgrade(self): argv = [ 'upgrade', config.get('sqlalchemy.url'), ] main(argv, debug=False, repository=repository)
def take_action(self, opts): #Work-around for SQLA0.8 being incompatible with sqlalchemy-migrate import sqlalchemy sqlalchemy.exceptions = sqlalchemy.exc from migrate.versioning.shell import main sect = 'app:main' option = 'sqlalchemy.url' # get sqlalchemy.url config in app:mains conf = ConfigParser() conf.read(opts.ini) name = "migration" try: dburi = conf.get(sect, option, vars={'here': os.getcwd()}) except: print( "Unable to read config file or missing sqlalchemy.url in app:main section" ) return print("Migrations repository '%s',\ndatabase url '%s'\n" % (name, dburi)) if not opts.args: opts.args = ['help'] sys.argv[0] = sys.argv[0] + ' migrate' main(argv=opts.args, url=dburi, repository=name, name=name)
def take_action(self, opts): #Work-around for SQLA0.8 being incompatible with sqlalchemy-migrate import sqlalchemy sqlalchemy.exceptions = sqlalchemy.exc from migrate.versioning.shell import main sect = 'app:main' option = 'sqlalchemy.url' # get sqlalchemy.url config in app:mains conf = ConfigParser() conf.read(opts.ini) name = "migration" try: dburi = conf.get(sect, option, vars={'here':os.getcwd()}) except: print("Unable to read config file or missing sqlalchemy.url in app:main section") return print("Migrations repository '%s',\ndatabase url '%s'\n"%(name, dburi)) if not opts.args: opts.args = ['help'] sys.argv[0] = sys.argv[0] + ' migrate' main(argv=opts.args, url=dburi, repository=name, name=name)
def invoke_migrate_main(): # Migrate has its own args, so cannot use argparse config = get_config(sys.argv, use_argparse=False) db_url = config['db_url'] repo = config['repo'] main(repository=repo, url=db_url)
def _downgrade(self): argv = [ 'downgrade', config.get('sqlalchemy.url'), ] main(argv, debug=False, repository=repository, version=0)
def _init(self): try: argv = ['version_control', config.get('sqlalchemy.url')] main(argv, debug=False, repository=repository) except DatabaseAlreadyControlledError: print("Migration table already exist") else: print("Migration table prepared")
def parseOptions(self, options=None): if not required_imports_ok(): sys.exit(1) from migrate.versioning.shell import main # Tweak sys.argv sys.argv = sys.argv[sys.argv.index('migrate'):] main(url=db.create_engine().url, repository=UPGRADES_REPO.path) sys.exit()
def handle(self, app, prog, name, remaining_args): optional = {} repository = app.config.get('SQLALCHEMY_MIGRATE_REPOSITORY', False) if repository: optional['repository'] = repository shell.main(remaining_args, url=app.config['SQLALCHEMY_DATABASE_URI'], debug=app.config['DEBUG'], **optional)
def _check_error(self, args, code, expected, **kw): original = sys.stderr try: actual = StringIO() sys.stderr = actual try: shell.main(args, **kw) except SystemExit, e: self.assertEqual(code, e.args[0]) else:
def _check_error(self,args,code,expected,**kw): original = sys.stderr try: actual = StringIO() sys.stderr = actual try: shell.main(args,**kw) except SystemExit, e: self.assertEqual(code,e.args[0]) else:
def test_shutdown_logging(self): """Try to shutdown logging output""" repos = self.tmp_repos() result = self.env.run('migrate create %s repository_name' % repos) result = self.env.run('migrate version %s --disable_logging' % repos) self.assertEqual(result.stdout, '') result = self.env.run('migrate version %s -q' % repos) self.assertEqual(result.stdout, '') # TODO: assert logging messages to 0 shell.main(['version', repos], logging=False)
def main(url, repository): # Check if database is under version control try: db_version(url, repository) except DatabaseNotControlledError: # put database under version control version_control(url, repository) kwargs = {'url': url, 'repository': repository } shell.main(**kwargs)
def test_main(self): """Test main() function""" repos = self.tmp_repos() shell.main(['help']) shell.main(['help', 'create']) shell.main(['create', 'repo_name', '--preview_sql'], repository=repos) shell.main(['version', '--', '--repository=%s' % repos]) shell.main(['version', '-d', '--repository=%s' % repos, '--version=2']) self._check_error(['foobar'],2,'error: Invalid command foobar') self._check_error(['create', 'f', 'o', 'o'],2,'error: Too many arguments for command create: o') self._check_error(['create'],2,'error: Not enough arguments for command create: name, repository not specified') self._check_error(['create', 'repo_name'],2,'already exists', repository=repos)
def _check_error(self,args,code,expected,**kw): original = sys.stderr try: actual = cStringIO() sys.stderr = actual try: shell.main(args,**kw) except SystemExit as e: self.assertEqual(code,e.args[0]) else: self.fail('No exception raised') finally: sys.stderr = original actual = actual.getvalue() self.assertTrue(expected in actual,'%r not in:\n"""\n%s\n"""'%(expected,actual))
def test_main(self): """Test main() function""" repos = self.tmp_repos() shell.main(["help"]) shell.main(["help", "create"]) shell.main(["create", "repo_name", "--preview_sql"], repository=repos) shell.main(["version", "--", "--repository=%s" % repos]) shell.main(["version", "-d", "--repository=%s" % repos, "--version=2"]) self._check_error(["foobar"], 2, "error: Invalid command foobar") self._check_error(["create", "f", "o", "o"], 2, "error: Too many arguments for command create: o") self._check_error( ["create"], 2, "error: Not enough arguments for command create: name, repository not specified" ) self._check_error(["create", "repo_name"], 2, "already exists", repository=repos)
def setup_schema(command, conf, vars): """Place any commands to setup tutorial here""" # Load the models # <websetup.websetup.schema.before.model.import> from tutorial import model # <websetup.websetup.schema.after.model.import> # <websetup.websetup.schema.before.metadata.create_all> print "Creating tables" model.metadata.create_all(bind=config['pylons.app_globals'].sa_engine) # <websetup.websetup.schema.after.metadata.create_all> transaction.commit() from migrate.versioning.shell import main main(argv=['version_control'], url=config['sqlalchemy.url'], repository='migration', name='migration')
def _perform_appless_action(self, pluggable): repository = self._pluggable_repository(pluggable) if repository is None: return tablename = self._pluggable_tablename(pluggable) print "\n%s Migrations" % pluggable print "\tRepository '%s'" % repository print "\tVersioning Table '%s'" % tablename #disable logging, this is due to sqlalchemy-migrate bug that #causes the disable_logging option to ignored args = self.args[:1] + ['-q'] + self.args[1:] main(argv=args, url=None, repository=repository, name=pluggable, version_table=tablename, disable_logging=True)
def setup_schema(command, conf, vars): """Place any commands to setup thesis_portal here""" # Load the models # <websetup.websetup.schema.before.model.import> from thesis_portal import model # <websetup.websetup.schema.after.model.import> # <websetup.websetup.schema.before.metadata.create_all> print "Creating tables" model.metadata.create_all(bind=config['pylons.app_globals'].sa_engine) # <websetup.websetup.schema.after.metadata.create_all> transaction.commit() from migrate.versioning.shell import main main(argv=['version_control'], url=config['sqlalchemy.url'], repository='migration', name='migration')
def execute(self,shell_cmd,runshell=None): """A crude simulation of a shell command, to speed things up""" # If we get an fd, the command is already done if isinstance(shell_cmd,file) or isinstance(shell_cmd,StringIO): return shell_cmd # Analyze the command; see if we can 'fake' the shell try: # Forced to run in shell? #if runshell or '--runshell' in sys.argv: if runshell: raise Exception # Remove the command prefix if not shell_cmd.startswith(self._cmd): raise Exception cmd = shell_cmd[(len(self._cmd)+1):] params = cmd.split(' ') command = params[0] except: return super(Shell,self).execute(shell_cmd) # Redirect stdout to an object; redirect stderr to stdout fd = StringIO() orig_stdout = sys.stdout orig_stderr = sys.stderr sys.stdout = fd sys.stderr = fd # Execute this command try: try: shell.main(params) except SystemExit,e: # Simulate the exit status fd_close=fd.close def close_(): fd_close() return e.args[0] fd.close = close_ except Exception,e: # Print the exception, but don't re-raise it traceback.print_exc() # Simulate a nonzero exit status fd_close=fd.close def close_(): fd_close() return 2 fd.close = close_
def _perform_migration(self, pluggable): repository = self._pluggable_repository(pluggable) if repository is None or not os.path.exists(repository): print "%s - Pluggable does not support migrations" % pluggable return tablename = self._pluggable_tablename(pluggable) print '\n%s Migrations' % pluggable print "\tRepository '%s'" % repository print "\tDatabase '%s'" % self.dburi print "\tVersioning Table '%s'" % tablename #disable logging, this is due to sqlalchemy-migrate bug that #causes the disable_logging option to ignored args = self.args[:1] + ['-q'] + self.args[1:] main(argv=args, url=self.dburi, repository=repository, name=pluggable, version_table=tablename, disable_logging=True)
def command(self): ini = 'development.ini' sect = 'app:main' option = 'sqlalchemy.url' # get sqlalchemy.url config in app:mains curdir = os.getcwd() conf = ConfigParser.ConfigParser() conf.read(os.path.join(curdir, ini)) self.name = "migration" try: self.dburi = conf.get(sect, option, vars={'here':curdir}) except: print "you shold set sqlalchemy.url in development.ini first" print "The repository is '%s'\nThe url is '%s'"%(self.name, self.dburi) main(argv=self.args, url=self.dburi,repository=self.name, name=self.name)
def take_action(self, opts): #Work-around for SQLA0.8 being incompatible with sqlalchemy-migrate import sqlalchemy sqlalchemy.exceptions = sqlalchemy.exc from migrate.versioning.shell import main from migrate.exceptions import DatabaseAlreadyControlledError, DatabaseNotControlledError self.args = opts.args self.options = opts if len(self.args) < 2 or self.args[0] == 'help': self.args = ['help'] return main(self.args) self._setup_logging() name = pkg_resources.safe_name(self.args.pop(0)) sys.argv[0] = sys.argv[0] + ' migrate' if self.args[0] in ('create', 'script'): self._perform_appless_action(name) return # get sqlalchemy.url config in app:mains conf = ConfigParser() conf.read(opts.ini) try: sect = 'app:main' option = 'sqlalchemy.url' self.dburi = conf.get(sect, option, vars={'here': os.getcwd()}) except: print( "Unable to read config file or missing sqlalchemy.url in app:main section" ) return pluggables_to_migrate = [] if name == 'all': pluggables_to_migrate.extend(self._detect_loaded_pluggables()) else: pluggables_to_migrate.append(name) print('Migrating', ', '.join(pluggables_to_migrate)) for pluggable in pluggables_to_migrate: try: self._perform_migration(pluggable) except DatabaseAlreadyControlledError: print('Pluggable already under version control...') except DatabaseNotControlledError: print( 'Your application is not under version control for this pluggable' ) print( 'Please run the version_control command before performing any other action.' )
def setup_schema(command, conf, vars): """Place any commands to setup nimsgears here""" # Load the models # <websetup.websetup.schema.before.model.import> from nimsgears import model # <websetup.websetup.schema.after.model.import> # <websetup.websetup.schema.before.metadata.create_all> print 'Creating database tables' model.metadata.create_all(bind=config['pylons.app_globals'].sa_engine) # <websetup.websetup.schema.after.metadata.create_all> transaction.commit() from migrate.versioning.shell import main from migrate.exceptions import DatabaseAlreadyControlledError try: main(argv=['version_control'], url=config['sqlalchemy.url'], repository='migration', name='migration') except DatabaseAlreadyControlledError: print 'Database tables already exist'
def command(self): sect = 'app:main' option = 'sqlalchemy.url' # get sqlalchemy.url config in app:mains conf = ConfigParser.ConfigParser() conf.read(self.options.ini) self.name = "migration" try: self.dburi = conf.get(sect, option, vars={'here':os.getcwd()}) except: print "Unable to read config file or missing sqlalchemy.url in app:main section" return print "Migrations repository '%s',\ndatabase url '%s'\n"%(self.name, self.dburi) if not self.args: self.args = ['help'] sys.argv[0] = sys.argv[0] + ' migrate' main(argv=self.args, url=self.dburi, repository=self.name, name=self.name)
def setup_schema(command, conf, vars): """Place any commands to setup tgtodotrack here""" # Load the models # <websetup.websetup.schema.before.model.import> from tgtodotrack import model # <websetup.websetup.schema.after.model.import> # <websetup.websetup.schema.before.metadata.create_all> print "Creating tables" model.metadata.create_all(bind=config['pylons.app_globals'].sa_engine) # <websetup.websetup.schema.after.metadata.create_all> transaction.commit() from migrate.versioning.shell import main from migrate.exceptions import DatabaseAlreadyControlledError try: main(argv=['version_control'], url=config['sqlalchemy.url'], repository='migration', name='migration') except DatabaseAlreadyControlledError: print 'Database already under version control'
def command(self): ini = 'development.ini' sect = 'app:main' option = 'sqlalchemy.url' # get sqlalchemy.url config in app:mains curdir = os.getcwd() conf = ConfigParser.ConfigParser() conf.read(os.path.join(curdir, ini)) self.name = "migration" try: self.dburi = conf.get(sect, option, vars={'here': curdir}) except: print "you shold set sqlalchemy.url in development.ini first" print "The repository is '%s'\nThe url is '%s'" % (self.name, self.dburi) main(argv=self.args, url=self.dburi, repository=self.name, name=self.name)
def take_action(self, opts): #Work-around for SQLA0.8 being incompatible with sqlalchemy-migrate import sqlalchemy sqlalchemy.exceptions = sqlalchemy.exc from migrate.versioning.shell import main from migrate.exceptions import DatabaseAlreadyControlledError, DatabaseNotControlledError self.args = opts.args self.options = opts if len(self.args) < 2 or self.args[0] == 'help': self.args = ['help'] return main(self.args) self._setup_logging() name = pkg_resources.safe_name(self.args.pop(0)) sys.argv[0] = sys.argv[0] + ' migrate' if self.args[0] in ('create', 'script'): self._perform_appless_action(name) return # get sqlalchemy.url config in app:mains conf = ConfigParser() conf.read(opts.ini) try: sect = 'app:main' option = 'sqlalchemy.url' self.dburi = conf.get(sect, option, vars={'here':os.getcwd()}) except: print("Unable to read config file or missing sqlalchemy.url in app:main section") return pluggables_to_migrate = [] if name == 'all': pluggables_to_migrate.extend(self._detect_loaded_pluggables()) else: pluggables_to_migrate.append(name) print('Migrating', ', '.join(pluggables_to_migrate)) for pluggable in pluggables_to_migrate: try: self._perform_migration(pluggable) except DatabaseAlreadyControlledError: print('Pluggable already under version control...') except DatabaseNotControlledError: print('Your application is not under version control for this pluggable') print('Please run the version_control command before performing any other action.')
def command(self): sect = 'app:main' option = 'sqlalchemy.url' # get sqlalchemy.url config in app:mains conf = ConfigParser.ConfigParser() conf.read(self.options.ini) self.name = "migration" try: self.dburi = conf.get(sect, option, vars={'here': os.getcwd()}) except: print "Unable to read config file or missing sqlalchemy.url in app:main section" return print "Migrations repository '%s',\ndatabase url '%s'\n" % (self.name, self.dburi) if not self.args: self.args = ['help'] sys.argv[0] = sys.argv[0] + ' migrate' main(argv=self.args, url=self.dburi, repository=self.name, name=self.name)
#!/usr/bin/env python from migrate.versioning.shell import main if __name__ == '__main__': main(url='postgresql://*****:*****@localhost:15432/myapp', debug='True', repository='sql_alchemy')
# Copyright (c) 2013 Mirantis, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from migrate.versioning.shell import main # This should probably be a console script entry point. if __name__ == '__main__': main(debug='False', repository='.')
#!/usr/bin/env python from dotenv import load_dotenv # Load environment variables from '.env' file. load_dotenv() import os from migrate.versioning.shell import main from vsm.config import BaseConfig if __name__ == "__main__": main(repository="migrations", url=BaseConfig.SQLALCHEMY_DATABASE_URI, debug="True")
#!/usr/bin/env python from migrate.versioning.shell import main import os if __name__ == '__main__': db_url = f'postgresql://' \ f'{os.environ["DB_USER"]}:{os.environ["DB_PASSWORD"]}@{os.environ["DB_HOST"]}/{os.environ["DB_NAME"]}' main(repository='migrations', url=db_url, debug='False')
#!/usr/bin/env python from migrate.versioning.shell import main if __name__ == "__main__": main(url="sqlite:///puppies.db", debug="False", repository="puppy_repository")
#!/usr/bin/env python from migrate.versioning.shell import main if __name__ == '__main__': main(six='<module 'six' from '/home/meg/Envs/mblog2/local/lib/python2.7/site-packages/six.pyc'>')
client = boto3.client(service_name='secretsmanager', region_name=region) # Decrypted secret using the associated KMS CMK # Depending on whether the secret was a string or binary, one of these fields will be populated get_secret_value_response = client.get_secret_value(SecretId=secret_name) if 'SecretString' in get_secret_value_response: secret = get_secret_value_response['SecretString'] else: secret = get_secret_value_response['SecretBinary'].decode("utf-8") return yaml.load(secret) if 'SETTINGS' in os.environ: if os.path.isfile(os.environ['SETTINGS']): with open(os.environ['SETTINGS'], 'r') as stream: settings = yaml.load(stream)['postgres'] if 'AWS_SECRETS_SETTINGS' in os.environ: aws_secret_name = os.environ['AWS_SECRETS_SETTINGS'] aws_config = get_secret(aws_secret_name) settings = aws_config['postgres'] if __name__ == '__main__': db_url = 'postgresql://%s:5432/%s?user=%s&password=%s' % ( settings['host'], settings['database'], settings['username'], settings['password']) try: main(url=db_url, repository='db', debug='False') except DatabaseAlreadyControlledError: exit(0)
#!/usr/bin/env python from migrate.versioning.shell import main if __name__ == '__main__': main(url='sqlite:///puppyshelter.db', debug='False', repository='puppy_shelter_repo')
#!/usr/bin/env python from migrate.versioning.shell import main import config if __name__ == '__main__': d = {'host': config.SQL_HOST, 'user': config.SQL_USER, 'dbname': config.SQL_DBNAME, 'password': config.SQL_PASSWORD, 'driver': config.SQL_DRIVER, } url = '%(driver)s://%(user)s:%(password)s@%(host)s/%(dbname)s' % d main(url=url, repository='db_repo')
#!/usr/bin/env python from migrate.versioning.shell import main # pragma: no cover if __name__ == '__main__': # pragma: no cover main()
#!/usr/bin/env python from migrate.versioning.shell import main if __name__ == '__main__': main(six='<module 'six' from '/usr/lib/python2.7/site-packages/six.pyc'>')
sys.path.insert(1, os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, 'lib'))) from galaxy.model.orm.scripts import read_config_file_arg from galaxy.util.properties import load_app_properties log = logging.getLogger( __name__ ) config_file = read_config_file_arg( sys.argv, 'config/galaxy.ini', 'universe_wsgi.ini' ) if not os.path.exists( config_file ): print "Galaxy config file does not exist (hint: use '-c config.ini' for non-standard locations): %s" % config_file sys.exit( 1 ) repo = 'lib/tool_shed/galaxy_install/migrate' properties = load_app_properties( ini_file=config_file ) cp = SafeConfigParser() cp.read( config_file ) if config_file == 'config/galaxy.ini.sample' and 'GALAXY_TEST_DBURI' in os.environ: # Running functional tests. db_url = os.environ[ 'GALAXY_TEST_DBURI' ] elif "install_database_connection" in properties: db_url = properties[ "install_database_connection" ] elif "database_connection" in properties: db_url = properties[ "database_connection" ] elif "database_file" in properties: db_url = "sqlite:///%s?isolation_level=IMMEDIATE" % properties[ "database_file" ] else: db_url = "sqlite:///./database/universe.sqlite?isolation_level=IMMEDIATE" main( repository=repo, url=db_url )
#!/usr/bin/env python from migrate.versioning.shell import main main(url='sqlite:///production.db',repository='db_repo')
#!/usr/bin/env python from migrate.versioning.shell import main if __name__ == '__main__': main(six='<module 'six' from 'C:\Users\Leo\PycharmProjects\bean-counter\env\lib\site-packages\six.pyc'>')
#!/usr/bin/env python from migrate.versioning.shell import main if __name__ == "__main__": main(debug='False', repository='.')
#!/usr/bin/env python from migrate.versioning.shell import main if __name__ == '__main__': main(six='<module 'six' from '/home/scnhpl/Flask/venv/local/lib/python2.7/site-packages/six.pyc'>')
#!/usr/bin/env python3.8 from migrate.versioning.shell import main if __name__ == '__main__': main(repository='db', url='sqlite:///db/db.sqlite3', debug='False')
#!/usr/bin/env python from migrate.versioning.shell import main main(url='sqlite:///development.db', debug='False', repository='migrations_repository')
#!/usr/bin/env python # Copyright 2013 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import os from sds.db.sqlalchemy import migrate_repo from migrate.versioning.shell import main if __name__ == '__main__': main(debug='False', repository=os.path.abspath(os.path.dirname(migrate_repo.__file__)))
#!/usr/bin/env python from migrate.versioning.shell import main main(url='postgresql://*****:*****@localhost:5432/nags', debug='False', repository='database')
from migrate.versioning.shell import main if __name__ == '__matilda_cost__': main(debug='False', repository=".")
#!/usr/bin/env python from migrate.versioning.shell import main if __name__ == '__main__': main(six='<module 'six' from '/Users/koki/.virtualenvs/papylus/lib/python2.7/site-packages/six.pyc'>')
#!/usr/bin/env python from migrate.versioning.shell import main main(url='sqlite:////var/tmp/spam/db/spam.sqlite', debug='False', repository='db_versioning/')