Create the version table and run the base script on an empty database.

        :param conn: a DB API 2 connection
17835
def init(self, conn):
        
        base = self.read_scripts()[0]['fname']
        logging.info('Creating the initial schema from %s',  base)
        apply_sql_script(conn, os.path.join(self.upgrade_dir, base))
        self.install_versioning(conn)
283016
def setup():
    
    try:
        db.bind(**config.database_config)
    except OSError:
        # Attempted to connect to a file-based database where the file didn't
        # exist
        db.bind(**config.database_config, create_db=True)

    rebuild = True

    try:
        db.generate_mapping(create_tables=True)
        with orm.db_session:
            version = GlobalConfig.get(key='schema_version')
            if version and version.int_value != SCHEMA_VERSION:
                logger.info("Existing database has schema version %d",
                            version.int_value)
            else:
                rebuild = False
    except:  # pylint:disable=bare-except
        logger.exception("Error mapping schema")

    if rebuild:
        logger.info("Rebuilding schema")
        try:
            db.drop_all_tables(with_all_data=True)
            db.create_tables()
        except:
            raise RuntimeError("Unable to upgrade schema automatically; please " +
                               "delete the existing database and try again.")

    with orm.db_session:
        if not GlobalConfig.get(key='schema_version'):
            logger.info("setting schema version to %d", SCHEMA_VERSION)
            GlobalConfig(key='schema_version',
                         int_value=SCHEMA_VERSION)
            orm.commit()
256154
def create_db(url=None):
    
    if url is None:
        url = os.environ.get("DATABASE_URL")
    parsed_url = urlparse(url)
    db_name = parsed_url.path
    db_name = db_name.strip("/")
    db = connect("postgresql://" + parsed_url.netloc)
    # check that db does not exist
    q = """SELECT 1 as exists
           FROM pg_database
           WHERE datname = '{db_name}'""".format(
        db_name=db_name
    )
    if not db.query(q).fetchone():
        # CREATE DATABASE must be run outside of a transaction
        # https://stackoverflow.com/questions/6506578/how-to-create-a-new-database-using-sqlalchemy
        conn = db.engine.connect()
        conn.execute("commit")
        conn.execute("CREATE DATABASE " + db_name)
        conn.close()
813276
def init_from_database(self, conn, database, table_name):
        
        info = conn.query('SHOW TABLE STATUS FROM `{database}` WHERE name="{table_name}"'.format(
            table_name=table_name, database=database), as_dict=True).fetchone()
        if info is None:
            if table_name == '~log':
                logger.warning('Could not create the ~log table')
                return
            else:
                raise DataJointError('The table `{database}`.`{table_name}` is not defined.'.format(
                    table_name=table_name, database=database))
        self.table_info = {k.lower(): v for k, v in info.items()}

        cur = conn.query(
            'SHOW FULL COLUMNS FROM `{table_name}` IN `{database}`'.format(
                table_name=table_name, database=database), as_dict=True)

        attributes = cur.fetchall()

        rename_map = {
            'Field': 'name',
            'Type': 'type',
            'Null': 'nullable',
            'Default': 'default',
            'Key': 'in_key',
            'Comment': 'comment'}

        fields_to_drop = ('Privileges', 'Collation')

        # rename and drop attributes
        attributes = [{rename_map[k] if k in rename_map else k: v
                       for k, v in x.items() if k not in fields_to_drop}
                      for x in attributes]

        numeric_types = {
            ('float', False): np.float64,
            ('float', True): np.float64,
            ('double', False): np.float64,
            ('double', True): np.float64,
            ('tinyint', False): np.int64,
            ('tinyint', True): np.int64,
            ('smallint', False): np.int64,
            ('smallint', True): np.int64,
            ('mediumint', False): np.int64,
            ('mediumint', True): np.int64,
            ('int', False): np.int64,
            ('int', True): np.int64,
            ('bigint', False): np.int64,
            ('bigint', True): np.uint64}

        sql_literals = ['CURRENT_TIMESTAMP']

        # additional attribute properties
        for attr in attributes:
            # process external attributes
            split_comment = attr['comment'].split(':')
            attr['is_external'] = len(split_comment) >= 3 and split_comment[1].startswith('external')
            if attr['is_external']:
                attr['comment'] = ':'.join(split_comment[2:])
                attr['type'] = split_comment[1]

            attr['nullable'] = (attr['nullable'] == 'YES')
            attr['in_key'] = (attr['in_key'] == 'PRI')
            attr['autoincrement'] = bool(re.search(r'auto_increment', attr['Extra'], flags=re.IGNORECASE))
            attr['type'] = re.sub(r'int\(\d+\)', 'int', attr['type'], count=1)   # strip size off integers
            attr['numeric'] = bool(re.match(r'(tiny|small|medium|big)?int|decimal|double|float', attr['type']))
            attr['string'] = bool(re.match(r'(var)?char|enum|date|year|time|timestamp', attr['type']))
            attr['is_blob'] = attr['is_external'] or bool(re.match(r'(tiny|medium|long)?blob', attr['type']))
            attr['database'] = database

            if attr['string'] and attr['default'] is not None and attr['default'] not in sql_literals:
                attr['default'] = '"%s"' % attr['default']

            if attr['nullable']:   # nullable fields always default to null
                attr['default'] = 'null'

            attr['sql_expression'] = None
            if not (attr['numeric'] or attr['string'] or attr['is_blob']):
                raise DataJointError('Unsupported field type {field} in `{database}`.`{table_name}`'.format(
                    field=attr['type'], database=database, table_name=table_name))
            attr.pop('Extra')

            # fill out dtype. All floats and non-nullable integers are turned into specific dtypes
            attr['dtype'] = object
            if attr['numeric']:
                is_integer = bool(re.match(r'(tiny|small|medium|big)?int', attr['type']))
                is_float = bool(re.match(r'(double|float)', attr['type']))
                if is_integer and not attr['nullable'] or is_float:
                    is_unsigned = bool(re.match('\sunsigned', attr['type'], flags=re.IGNORECASE))
                    t = attr['type']
                    t = re.sub(r'\(.*\)', '', t)    # remove parentheses
                    t = re.sub(r' unsigned$', '', t)   # remove unsigned
                    assert (t, is_unsigned) in numeric_types, 'dtype not found for type %s' % t
                    attr['dtype'] = numeric_types[(t, is_unsigned)]
        self.attributes = OrderedDict([(q['name'], Attribute(**q)) for q in attributes])

        # Read and tabulate secondary indexes
        keys = defaultdict(dict)
        for item in conn.query('SHOW KEYS FROM `{db}`.`{tab}`'.format(db=database, tab=table_name), as_dict=True):
            if item['Key_name'] != 'PRIMARY':
                keys[item['Key_name']][item['Seq_in_index']] = dict(
                    column=item['Column_name'],
                    unique=(item['Non_unique'] == 0),
                    nullable=item['Null'].lower() == 'yes')
        self.indexes = {
            tuple(item[k]['column'] for k in sorted(item.keys())):
                dict(unique=item[1]['unique'],
                     nullable=any(v['nullable'] for v in item.values()))
            for item in keys.values()}
751398
def run_migrations_online():
    

    # this callback is used to prevent an auto-migration from being generated
    # when there are no changes to the schema
    # reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html
    def process_revision_directives(context, revision, directives):
        if getattr(config.cmd_opts, 'autogenerate', False):
            script = directives[0]
            if len(script.upgrade_ops_list) >= len(bind_names) + 1:
                empty = True
                for upgrade_ops in script.upgrade_ops_list:
                    if not upgrade_ops.is_empty():
                        empty = False
                if empty:
                    directives[:] = []
                    logger.info('No changes in schema detected.')

    # for the direct-to-DB use case, start a transaction on all
    # engines, then run all migrations, then commit all transactions.
    engines = {
        '': {
            'engine': engine_from_config(
                config.get_section(config.config_ini_section),
                prefix='sqlalchemy.',
                poolclass=pool.NullPool,
            )
        }
    }
    for name in bind_names:
        engines[name] = rec = {}
        rec['engine'] = engine_from_config(
            context.config.get_section(name),
            prefix='sqlalchemy.',
            poolclass=pool.NullPool)

    for name, rec in engines.items():
        engine = rec['engine']
        rec['connection'] = conn = engine.connect()

        if USE_TWOPHASE:
            rec['transaction'] = conn.begin_twophase()
        else:
            rec['transaction'] = conn.begin()

    try:
        for name, rec in engines.items():
            logger.info("Migrating database %s" % (name or '<default>'))
            context.configure(
                connection=rec['connection'],
                upgrade_token="%s_upgrades" % name,
                downgrade_token="%s_downgrades" % name,
                target_metadata=get_metadata(name),
                process_revision_directives=process_revision_directives,
                **current_app.extensions['migrate'].configure_args
            )
            context.run_migrations(engine_name=name)

        if USE_TWOPHASE:
            for rec in engines.values():
                rec['transaction'].prepare()

        for rec in engines.values():
            rec['transaction'].commit()
    except:
        for rec in engines.values():
            rec['transaction'].rollback()
        raise
    finally:
        for rec in engines.values():
            rec['connection'].close()
702157
def db_create(database, containment='NONE', new_database_options=None, **kwargs):
    '''
    
    '''
    if containment not in ['NONE', 'PARTIAL']:
        return 'CONTAINMENT can be one of NONE and PARTIAL'
    sql = "CREATE DATABASE [{0}] CONTAINMENT = {1} ".format(database, containment)
    if new_database_options:
        sql += ' WITH ' + ', '.join(new_database_options)
    conn = None
    try:
        conn = _get_connection(**kwargs)
        conn.autocommit(True)
        # cur = conn.cursor()
        # cur.execute(sql)
        conn.cursor().execute(sql)
    except Exception as e:
        return 'Could not create the login: {0}'.format(e)
    finally:
        if conn:
            conn.autocommit(False)
            conn.close()
    return True
495114
def _migration_required(connection):
    
    stored_version = get_stored_version(connection)
    actual_version = SCHEMA_VERSION
    assert isinstance(stored_version, int)
    assert isinstance(actual_version, int)
    assert stored_version <= actual_version, \
        'Db version can not be greater than models version. Update your source code.'
    return stored_version < actual_version
1057716
def db_create():
    """"""
    try:
        migrate_api.version_control(url=db_url, repository=db_repo)
        db_upgrade()
    except DatabaseAlreadyControlledError:
        print 'ERROR: Database is already version controlled.'
776875
def execute(self, conn, app, release_version, pset_hash, output_label, global_tag, transaction = False):
        
        binds = {}
        binds["app_name"]=app
        binds["release_version"]=release_version
        binds["pset_hash"]=pset_hash
        binds["output_module_label"]=output_label
        binds["global_tag"]=global_tag

        result = self.dbi.processData(self.sql, binds, conn, transaction)

        plist = self.formatDict(result)

	if len(plist) < 1: return -1
        return plist[0]["output_mod_config_id"]
205958
def check_versions(self, conn):
        
        scripts = self.read_scripts(skip_versions=self.get_db_versions(conn))
        versions = [s['version'] for s in scripts]
        if versions:
            return ('Your database is not updated. You can update it by '
                    'running oq engine --upgrade-db which will process the '
                    'following new versions: %s' % versions)
508305
def run_syncdb():
    
    with cd(settings.FAB_SETTING('SERVER_PROJECT_ROOT')):
        if StrictVersion(django.get_version()) < StrictVersion('1.7'):
            run_workon('python{} manage.py syncdb --migrate --noinput'.format(
                PYTHON_VERSION))
        else:
            run_workon('python{} manage.py migrate'.format(PYTHON_VERSION))
1008690
function connStr(conn) {
  var conf = mergeDefaults(conn);
  var connString = conf.driver + '://' + conf.username + (conf.password ? ':' + conf.password : '') + '@' + conf.host
    + (conf.port ? ':' + conf.port : '') + '/' + conf.database;
  return connString;
}
390249
def version(user=None, password=None, host=None, port=None, database='admin', authdb=None):
    '''
    
    '''
    conn = _connect(user, password, host, port, authdb=authdb)
    if not conn:
        err_msg = "Failed to connect to MongoDB database {0}:{1}".format(host, port)
        log.error(err_msg)
        return (False, err_msg)

    try:
        mdb = pymongo.database.Database(conn, database)
        return _version(mdb)
    except pymongo.errors.PyMongoError as err:
        log.error('Listing users failed with error: %s', err)
        return six.text_type(err)
111875
def create_extension(name,
                     if_not_exists=None,
                     schema=None,
                     ext_version=None,
                     from_version=None,
                     user=None,
                     host=None,
                     port=None,
                     maintenance_db=None,
                     password=None,
                     runas=None):
    '''
    

    '''
    if if_not_exists is None:
        if_not_exists = True
    mtdata = create_metadata(name,
                             ext_version=ext_version,
                             schema=schema,
                             user=user,
                             host=host,
                             port=port,
                             maintenance_db=maintenance_db,
                             password=password,
                             runas=runas)
    installed = _EXTENSION_NOT_INSTALLED not in mtdata
    installable = is_available_extension(name,
                                         user=user,
                                         host=host,
                                         port=port,
                                         maintenance_db=maintenance_db,
                                         password=password,
                                         runas=runas)
    if installable:
        if not installed:
            args = ['CREATE EXTENSION']
            if if_not_exists:
                args.append('IF NOT EXISTS')
            args.append('"{0}"'.format(name))
            sargs = []
            if schema:
                sargs.append('SCHEMA "{0}"'.format(schema))
            if ext_version:
                sargs.append('VERSION {0}'.format(ext_version))
            if from_version:
                sargs.append('FROM {0}'.format(from_version))
            if sargs:
                args.append('WITH')
                args.extend(sargs)
            args.append(';')
            cmd = ' '.join(args).strip()
        else:
            args = []
            if schema and _EXTENSION_TO_MOVE in mtdata:
                args.append('ALTER EXTENSION "{0}" SET SCHEMA "{1}";'.format(
                    name, schema))
            if ext_version and _EXTENSION_TO_UPGRADE in mtdata:
                args.append('ALTER EXTENSION "{0}" UPDATE TO {1};'.format(
                    name, ext_version))
            cmd = ' '.join(args).strip()
        if cmd:
            _psql_prepare_and_run(
                ['-c', cmd],
                runas=runas, host=host, user=user, port=port,
                maintenance_db=maintenance_db, password=password)
    mtdata = create_metadata(name,
                             ext_version=ext_version,
                             schema=schema,
                             user=user,
                             host=host,
                             port=port,
                             maintenance_db=maintenance_db,
                             password=password,
                             runas=runas)
    ret = True
    for i in _EXTENSION_FLAGS:
        if (i in mtdata) and (i != _EXTENSION_INSTALLED):
            ret = False
    if not ret:
        log.info('Failed to create ext: %s', name)
    return ret
1295085
def what_if_I_upgrade(conn, pkg_name='openquake.server.db.schema.upgrades',
                      extract_scripts='extract_upgrade_scripts'):
    
    msg_safe_ = '\nThe following scripts can be applied safely:\n%s'
    msg_slow_ = '\nPlease note that the following scripts could be slow:\n%s'
    msg_danger_ = ('\nPlease note that the following scripts are potentially '
                   'dangerous and could destroy your data:\n%s')
    upgrader = UpgradeManager.instance(conn, pkg_name)
    applied_versions = upgrader.get_db_versions(conn)
    current_version = max(applied_versions)
    slow = []
    danger = []
    safe = []
    for script in getattr(upgrader, extract_scripts)():
        url = script['url']
        if script['version'] in applied_versions:
            continue
        elif script['version'] <= current_version:
            # you cannot apply a script with a version number lower than the
            # current db version: ensure that upgrades are strictly incremental
            raise VersionTooSmall(
                'Your database is at version %s but you want to apply %s??'
                % (current_version, script['fname']))
        elif script['flag'] == '-slow':
            slow.append(url)
        elif script['flag'] == '-danger':
            danger.append(url)
        else:  # safe script
            safe.append(url)

    if not safe and not slow and not danger:
        return 'Your database is already updated at version %s.' % \
            current_version

    header = 'Your database is at version %s.' % current_version
    msg_safe = msg_safe_ % '\n'.join(safe)
    msg_slow = msg_slow_ % '\n'.join(slow)
    msg_danger = msg_danger_ % '\n'.join(danger)
    msg = header + (msg_safe if safe else '') + (msg_slow if slow else '') \
        + (msg_danger if danger else '')
    msg += ('\nClick on the links if you want to know what exactly the '
            'scripts are doing.')
    if slow:
        msg += ('\nEven slow script can be fast if your database is small or'
                ' the upgrade affects tables that are empty.')
    if danger:
        msg += ('\nEven dangerous scripts are fine if they '
                'affect empty tables or data you are not interested in.')
    return msg
458172
def version(self, conn):
        

        command = b'version\r\n'
        response = yield from self._execute_simple_command(
            conn, command)
        if not response.startswith(const.VERSION):
            raise ClientException('Memcached version failed', response)
        version, number = response.split()
        return number
951899
def perform(self):
        
        db_versions = self.table.versions()

        version = self.version
        if (version.is_processed(db_versions) and
                not self.config.force_version == self.version.number):
            self.log(
                u'version {} is already installed'.format(version.number)
            )
            return

        self.start()
        try:
            self._perform_version(version)
        except Exception:
            if sys.version_info < (3, 4):
                msg = traceback.format_exc().decode('utf8', errors='ignore')
            else:
                msg = traceback.format_exc()
            error = u'\n'.join(self.logs + [u'\n', msg])
            self.table.record_log(version.number, error)
            raise
        self.finish()