Change database helper
12112
public function switchDb($db_name)
    {
        $self = $this;

        return $this->app['mongo'] = $this->app->share(
            function () use ($db_name, $self) {
                return new Db($db_name, $self->client, $self->app);
            }
        );
    }
1336447
def disable(ctx):
    """"""

    if ctx.obj['username'] is None:
        log('Specify the username with "iso db user --username ..."')
        return

    change_user = ctx.obj['db'].objectmodels['user'].find_one({
        'name': ctx.obj['username']
    })

    change_user.active = False
    change_user.save()
    log('Done')
457165
function EasyMySQL(config)
{
	this.debug = config.error_debug || false;

	if(db)
		db.configure(config);
}
110994
public function upgradeDatabase()
    {
        /* add permissions lines for edit_block_name and edit_block_cache_settings */
        $ebk = Key::getByHandle('edit_block_name');
        if (!is_object($ebk)) {
            Key::add('block', 'edit_block_name', 'Edit Name', "Controls whether users can change the block's name (rarely used.).", false, false);
        }
        $ebk = Key::getByHandle('edit_block_cache_settings');
        if (!is_object($ebk)) {
            Key::add('block', 'edit_block_cache_settings', 'Edit Cache Settings', 'Controls whether users can change the block cache settings for this block instance.', false, false);
        }

        /* Add marketplace single pages */
        $this->createSinglePage('/dashboard/extend/connect', 'Connect to the Community', ['meta_keywords' => 'concrete5.org, my account, marketplace']);
        $this->createSinglePage('/dashboard/extend/themes', 'Get More Themes', ['meta_keywords' => 'buy theme, new theme, marketplace, template']);
        $this->createSinglePage('/dashboard/extend/addons', 'Get More Add-Ons', ['meta_keywords' => 'buy addon, buy add on, buy add-on, purchase addon, purchase add on, purchase add-on, find addon, new addon, marketplace']);

        /* Add auth types ("handle|name") "twitter|Twitter" and "community|concrete5.org" */
        try {
            $community = AuthenticationType::getByHandle('community');
        } catch (Exception $e) {
            $community = AuthenticationType::add('community', 'concrete5.org');
            if (is_object($community)) {
                $community->disable();
            }
        }

        try {
            $twitter = AuthenticationType::getByHandle('twitter');
        } catch (Exception $e) {
            $twitter = AuthenticationType::add('twitter', 'Twitter');
            if (is_object($twitter)) {
                $twitter->disable();
            }
        }

        /* delete customize page themes dashboard single page */
        $customize = Page::getByPath('/dashboard/pages/themes/customize');
        if (is_object($customize) && !$customize->isError()) {
            $customize->delete();
        }

        /* exclude nav from flat view in dashboard */
        $flat = Page::getByPath('/dashboard/sitemap/explore');
        if (is_object($customize) && !$customize->isError() && $this->isAttributeHandleValid(PageCategory::class, 'exclude_nav')) {
            $flat->setAttribute('exclude_nav', false);
        }
    }
202019
def reset_attribute!(attr)
      attr = database_field_name(attr)
      attributes[attr] = changed_attributes.delete(attr) if attribute_changed?(attr)
    end
656643
def table_absent(name, db):
    '''
    
    '''
    changes = {'name': name,
               'changes': {},
               'result': None,
               'comment': ''}
    conn = None
    try:
        conn = sqlite3.connect(db, detect_types=sqlite3.PARSE_DECLTYPES)
        tables = _query(conn, "SELECT sql FROM sqlite_master " +
                              " WHERE type='table' AND name=?", [name])

        if len(tables) == 1:
            if __opts__['test']:
                changes['result'] = True
                changes['comment'] = "'" + name + "' will be dropped"
            else:
                conn.execute("DROP TABLE " + name)
                conn.commit()
                changes['changes']['old'] = tables[0][0]
                changes['result'] = True
                changes['comment'] = "'" + name + "' was dropped"
        elif not tables:
            changes['result'] = True
            changes['comment'] = "'" + name + "' is already absent"
        else:
            changes['result'] = False
            changes['comment'] = "Multiple tables with the same name='" + \
                                 name + "'"

    except Exception as e:
        changes['result'] = False
        changes['comment'] = six.text_type(e)

    finally:
        if conn:
            conn.close()

    return changes
1310818
def handle(self, *args, **options):
        
        database = getattr(
                settings, 'LIQUIMIGRATE_DATABASE', options['database'])

        try:
            dbsettings = databases[database]
        except KeyError:
            raise CommandError("don't know such a connection: %s" % database)

        verbosity = int(options.get('verbosity'))

        # get driver
        driver_class = (
                options.get('driver')
                or dbsettings.get('ENGINE').split('.')[-1])
        dbtag, driver, classpath = LIQUIBASE_DRIVERS.get(
                            driver_class, (None, None, None))

        classpath = options.get('classpath') or classpath

        if driver is None:
            raise CommandError(
                "unsupported db driver '%s'\n"
                "available drivers: %s" % (
                    driver_class, ' '.join(LIQUIBASE_DRIVERS.keys())))

        # command options
        changelog_file = (
                options.get('changelog_file')
                or _get_changelog_file(options['database']))
        username = options.get('username') or dbsettings.get('USER') or ''
        password = options.get('password') or dbsettings.get('PASSWORD') or ''
        url = options.get('url') or _get_url_for_db(dbtag, dbsettings)

        command = options['command']
        cmdargs = {
            'jar': LIQUIBASE_JAR,
            'changelog_file': changelog_file,
            'username': username,
            'password': password,
            'command': command,
            'driver': driver,
            'classpath': classpath,
            'url': url,
            'args': ' '.join(args),
        }

        cmdline = "java -jar %(jar)s --changeLogFile %(changelog_file)s \
--username=%(username)s --password=%(password)s \
--driver=%(driver)s --classpath=%(classpath)s --url=%(url)s \
%(command)s %(args)s" % (cmdargs)

        if verbosity > 0:
            print("changelog file: %s" % (changelog_file,))
            print("executing: %s" % (cmdline,))

        created_models = None   # we dont know it

        if emit_pre_migrate_signal and not options.get('no_signals'):
            if django_19_or_newer:
                emit_pre_migrate_signal(
                        1, options.get('interactive'), database)
            else:
                emit_pre_migrate_signal(
                    created_models, 1, options.get('interactive'), database)

        rc = os.system(cmdline)

        if rc == 0:

            try:
                if not options.get('no_signals'):
                    if emit_post_migrate_signal:
                        if django_19_or_newer:
                            emit_post_migrate_signal(
                                0, options.get('interactive'), database)
                        else:
                            emit_post_migrate_signal(
                                created_models, 0,
                                options.get('interactive'), database)
                    elif emit_post_sync_signal:
                        emit_post_sync_signal(
                                created_models, 0,
                                options.get('interactive'), database)

                if not django_19_or_newer:
                    call_command(
                        'loaddata', 'initial_data', verbosity=1,
                        database=database)
            except TypeError:
                # singledb (1.1 and older)
                emit_post_sync_signal(
                        created_models, 0, options.get('interactive'))

                call_command(
                        'loaddata', 'initial_data', verbosity=0)
        else:
            raise CommandError('Liquibase returned an error code %s' % rc)
870628
def _setup_helper():
    """"""
    base = os.path.abspath(os.path.dirname(__file__))
    helper = os.path.join(base, "helper.sh")
    with open(helper) as fh:
        click.echo(fh.read())
218514
private void updateDOTable() throws InstallationFailedException {
        if (_db.equals(InstallOptions.INCLUDED)) {
            return; // no need to update embedded
        }
        try {
            Connection conn = getConnection();
            DatabaseMetaData dmd = conn.getMetaData();
            ResultSet rs = dmd.getTables(null, null, "do%", null);
            while (rs.next()) {
                if (rs.getString("TABLE_NAME").equals("do")) {
                    Statement stmt = conn.createStatement();
                    stmt.execute("ALTER TABLE do RENAME TO dobj");
                    System.out.println("Renamed table 'do' to 'dobj'.");
                    stmt.close();
                }
            }
            rs.close();
        } catch (Exception e) {
            throw new InstallationFailedException(e.getMessage(), e);
        }
    }
753680
def handle(self, *args, **options):
        
        router = options['router']
        dbinfo = settings.DATABASES.get(router)
        if dbinfo is None:
            raise CommandError("Unknown database router %s" % router)

        engine = dbinfo.get('ENGINE')

        user = password = database_name = database_host = database_port = ''
        if engine == 'mysql':
            (user, password, database_name, database_host, database_port) = parse_mysql_cnf(dbinfo)

        user = options['user'] or dbinfo.get('USER') or user
        password = options['password'] or dbinfo.get('PASSWORD') or password
        owner = options['owner'] or user

        database_name = options['dbname'] or dbinfo.get('NAME') or database_name
        if database_name == '':
            raise CommandError("You need to specify DATABASE_NAME in your Django settings file.")

        database_host = dbinfo.get('HOST') or database_host
        database_port = dbinfo.get('PORT') or database_port

        verbosity = options["verbosity"]
        if options['interactive']:
            confirm = input("""
You have requested a database reset.
This will IRREVERSIBLY DESTROY
ALL data in the database "%s".
Are you sure you want to do this?

Type 'yes' to continue, or 'no' to cancel: """ % (database_name,))
        else:
            confirm = 'yes'

        if confirm != 'yes':
            print("Reset cancelled.")
            return

        SQLITE_ENGINES = getattr(settings, 'DJANGO_EXTENSIONS_RESET_DB_SQLITE_ENGINES', (
            'django.db.backends.sqlite3',
            'django.db.backends.spatialite',
        ))
        MYSQL_ENGINES = getattr(settings, 'DJANGO_EXTENSIONS_RESET_DB_MYSQL_ENGINES', (
            'django.db.backends.mysql',
        ))
        POSTGRESQL_ENGINES = getattr(settings, 'DJANGO_EXTENSIONS_RESET_DB_POSTGRESQL_ENGINES', (
            'django.db.backends.postgresql',
            'django.db.backends.postgresql_psycopg2',
            'django.db.backends.postgis',
            'psqlextra.backend',
        ))

        if engine in SQLITE_ENGINES:
            try:
                logging.info("Unlinking %s database", engine)
                os.unlink(database_name)
            except OSError:
                pass

        elif engine in MYSQL_ENGINES:
            import MySQLdb as Database
            kwargs = {
                'user': user,
                'passwd': password,
            }
            if database_host.startswith('/'):
                kwargs['unix_socket'] = database_host
            else:
                kwargs['host'] = database_host

            if database_port:
                kwargs['port'] = int(database_port)

            connection = Database.connect(**kwargs)
            drop_query = 'DROP DATABASE IF EXISTS `%s`' % database_name
            utf8_support = '' if options['no_utf8_support'] else 'CHARACTER SET utf8'
            create_query = 'CREATE DATABASE `%s` %s' % (database_name, utf8_support)
            logging.info('Executing... "%s"', drop_query)
            connection.query(drop_query)
            logging.info('Executing... "%s"', create_query)
            connection.query(create_query.strip())

        elif engine in POSTGRESQL_ENGINES:
            import psycopg2 as Database  # NOQA

            conn_params = {'database': 'template1'}
            if user:
                conn_params['user'] = user
            if password:
                conn_params['password'] = password
            if database_host:
                conn_params['host'] = database_host
            if database_port:
                conn_params['port'] = database_port

            connection = Database.connect(**conn_params)
            connection.set_isolation_level(0)  # autocommit false
            cursor = connection.cursor()

            if options['close_sessions']:
                close_sessions_query = """
                    SELECT pg_terminate_backend(pg_stat_activity.pid)
                    FROM pg_stat_activity
                    WHERE pg_stat_activity.datname = '%s';
                """ % database_name
                logging.info('Executing... "%s"', close_sessions_query.strip())
                try:
                    cursor.execute(close_sessions_query)
                except Database.ProgrammingError as e:
                    logging.exception("Error: %s", str(e))

            drop_query = "DROP DATABASE \"%s\";" % database_name
            logging.info('Executing... "%s"', drop_query)
            try:
                cursor.execute(drop_query)
            except Database.ProgrammingError as e:
                logging.exception("Error: %s", str(e))

            create_query = "CREATE DATABASE \"%s\"" % database_name
            if owner:
                create_query += " WITH OWNER = \"%s\" " % owner
            create_query += " ENCODING = 'UTF8'"

            if settings.DEFAULT_TABLESPACE:
                create_query += ' TABLESPACE = %s;' % settings.DEFAULT_TABLESPACE
            else:
                create_query += ';'

            logging.info('Executing... "%s"', create_query)
            cursor.execute(create_query)

        else:
            raise CommandError("Unknown database engine %s" % engine)

        if verbosity >= 2 or options['interactive']:
            print("Reset successful.")
1030418
def get_changelog_file_for_database(database=DEFAULT_DB_ALIAS):
    """"""

    from django.conf import settings

    try:
        return settings.LIQUIMIGRATE_CHANGELOG_FILES[database]
    except AttributeError:
        if database == DEFAULT_DB_ALIAS:
            try:
                return settings.LIQUIMIGRATE_CHANGELOG_FILE
            except AttributeError:
                raise ImproperlyConfigured(
                        'Please set LIQUIMIGRATE_CHANGELOG_FILE or '
                        'LIQUIMIGRATE_CHANGELOG_FILES in your '
                        'project settings')
        else:
            raise ImproperlyConfigured(
                'LIQUIMIGRATE_CHANGELOG_FILES dictionary setting '
                'is required for multiple databases support')
    except KeyError:
        raise ImproperlyConfigured(
            "Liquibase changelog file is not set for database: %s" % database)
658712
function ChangeTableSQL($tablename, $flds, $tableoptions = false, $dropOldFlds=false)
	{
	global $ADODB_FETCH_MODE;

		$save = $ADODB_FETCH_MODE;
		$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
		if ($this->connection->fetchMode !== false) $savem = $this->connection->SetFetchMode(false);

		// check table exists
		$save_handler = $this->connection->raiseErrorFn;
		$this->connection->raiseErrorFn = '';
		$cols = $this->MetaColumns($tablename);
		$this->connection->raiseErrorFn = $save_handler;

		if (isset($savem)) $this->connection->SetFetchMode($savem);
		$ADODB_FETCH_MODE = $save;

		if ( empty($cols)) {
			return $this->CreateTableSQL($tablename, $flds, $tableoptions);
		}

		if (is_array($flds)) {
		// Cycle through the update fields, comparing
		// existing fields to fields to update.
		// if the Metatype and size is exactly the
		// same, ignore - by Mark Newham
			$holdflds = array();
			foreach($flds as $k=>$v) {
				if ( isset($cols[$k]) && is_object($cols[$k]) ) {
					// If already not allowing nulls, then don't change
					$obj = $cols[$k];
					if (isset($obj->not_null) && $obj->not_null)
						$v = str_replace('NOT NULL','',$v);
					if (isset($obj->auto_increment) && $obj->auto_increment && empty($v['AUTOINCREMENT']))
					    $v = str_replace('AUTOINCREMENT','',$v);

					$c = $cols[$k];
					$ml = $c->max_length;
					$mt = $this->MetaType($c->type,$ml);

					if (isset($c->scale)) $sc = $c->scale;
					else $sc = 99; // always force change if scale not known.

					if ($sc == -1) $sc = false;
					list($fsize, $fprec) = $this->_getSizePrec($v['SIZE']);

					if ($ml == -1) $ml = '';
					if ($mt == 'X') $ml = $v['SIZE'];
					if (($mt != $v['TYPE']) || ($ml != $fsize || $sc != $fprec) || (isset($v['AUTOINCREMENT']) && $v['AUTOINCREMENT'] != $obj->auto_increment)) {
						$holdflds[$k] = $v;
					}
				} else {
					$holdflds[$k] = $v;
				}
			}
			$flds = $holdflds;
		}


		// already exists, alter table instead
		list($lines,$pkey,$idxs) = $this->_GenFields($flds);
		// genfields can return FALSE at times
		if ($lines == null) $lines = array();
		$alter = 'ALTER TABLE ' . $this->TableName($tablename);
		$sql = array();

		foreach ( $lines as $id => $v ) {
			if ( isset($cols[$id]) && is_object($cols[$id]) ) {

				$flds = Lens_ParseArgs($v,',');

				//  We are trying to change the size of the field, if not allowed, simply ignore the request.
				// $flds[1] holds the type, $flds[2] holds the size -postnuke addition
				if ($flds && in_array(strtoupper(substr($flds[0][1],0,4)),$this->invalidResizeTypes4)
				 && (isset($flds[0][2]) && is_numeric($flds[0][2]))) {
					if ($this->debug) ADOConnection::outp(sprintf("<h3>%s cannot be changed to %s currently</h3>", $flds[0][0], $flds[0][1]));
					#echo "<h3>$this->alterCol cannot be changed to $flds currently</h3>";
					continue;
	 			}
				$sql[] = $alter . $this->alterCol . ' ' . $v;
			} else {
				$sql[] = $alter . $this->addCol . ' ' . $v;
			}
		}

		if ($dropOldFlds) {
			foreach ( $cols as $id => $v )
			    if ( !isset($lines[$id]) )
					$sql[] = $alter . $this->dropCol . ' ' . $v->name;
		}
		return $sql;
	}
1251916
function dbRequestHandler( req, res, next ) {
  /**
   * @type {Object}
   *
   * @property {Object} [db]
   * @property {Error} [db.error]
   * @property {setupDb} [db.setupDb]
   *
   * @property {boolean} [debug]
   */
  var app = req.app

  if ( app.debug ) {
    console.log( '[debug]', new Date().toGMTString(), 'dbRequestHandler()' )
  }

  if ( !app.db ) {
    return next()
  }

  if ( !app.db.error ) {
    return next()
  }

  if ( typeof app.setupDb !== 'function' ) {
    return next()
  }

  if ( typeof app.db._readyState !== 'undefined' && app.db._readyState !== 0 ) {
    return next()
  }

  console.log( '[warn]', new Date().toGMTString(), 'attempting to reconnect to mongodb://%host:%port/%database'
    .replace( '%host', app.db.host )
    .replace( '%port', app.db.port )
    .replace( '%database', app.db.name )
  )

  app.setupDb()
    .then(
      /**
       * @param {Object} db
       * @returns {*}
       */
      function ( db ) {
        app.db = db;

        return next()
      }
    )
    .catch(
      /**
       * @param {Error} err
       * @returns {*}
       */
      function ( err ) {
        if ( process.env.NODE_ENV !== 'development' ) {
          console.error( err )
          err = new DatabaseError( err.code, 'please try again later ...' )
        }

        err.statusCode = err.statusCode || 500;

        app.db = {
          error: err
        };

        return next( err )
      }
    );
}
251608
def change(self, key, value):
        """"""
        self.obj[key] = value
        self.changes.append("Updating build:{}.{}={}"
                            .format(self.obj['name'], key, value))
        return self
779033
public function upgradeDatabase()
    {
        $config = $this->app->make('config');
        $resolver = $this->app->make(Resolver::class);
        $error = null;
        try {
            list($characterSet, $collation) = $resolver
                ->setCharacterSet((string) $config->get('database.preferred_character_set'))
                ->setCollation((string) $config->get('database.preferred_collation'))
                ->resolveCharacterSetAndCollation($this->connection)
            ;
        } catch (CharacterSetCollationException $x) {
            try {
                list($characterSet, $collation) = $resolver
                    ->setCharacterSet((string) $config->get('database.fallback_character_set'))
                    ->setCollation((string) $config->get('database.fallback_collation'))
                    ->resolveCharacterSetAndCollation($this->connection)
                ;
            } catch (Exception $x) {
                $error = $x;
            }
        } catch (Throwable $x) {
            $error = $x;
        }
        if ($error !== null) {
            $this->output(t('Failed to resolve the database character set and collation: %s', $error->getMessage()));

            return;
        }
        $params = $this->connection->getParams();
        if (isset($params['character_set']) && $params['character_set'] === $characterSet && isset($params['collation']) && $params['collation'] === $collation) {
            return;
        }
        $manager = $this->app->make(Manager::class);
        try {
            $manager->apply(
                $characterSet,
                $collation,
                '',
                '',
                function ($message) {
                    $this->output($message);
                }
            );
        } catch (Exception $x) {
            $this->output(t('Failed to set character sets: %s', $x->getMessage()));
        } catch (Throwable $x) {
            $this->output(t('Failed to set character sets: %s', $x->getMessage()));
        }
    }
516591
def update(connection, silent, hgnc_file_path, hcop_file_path, low_memory):
    """"""
    database.update(connection=connection,
                    silent=silent,
                    hgnc_file_path=hgnc_file_path,
                    hcop_file_path=hcop_file_path,
                    low_memory=low_memory)
1364404
def handle_database(self):
        
        # TODO: When initdb and upgradedb are dropped we can just test
        # managedb, but for backwards compatibility we need to support
        # initdb without upgradedb and vice-versa

        if self.args.initdb or self.args.upgradedb:
            db = DbAdmin(self.dir, None, self.args, self.external)
            status = db.check()
            log.debug('OMERO database upgrade status: %s', status)
        else:
            log.warn('OMERO database check disabled')
            return DB_INIT_NEEDED

        if status == DB_INIT_NEEDED:
            if self.args.initdb:
                log.debug('Initialising OMERO database')
                db.init()
            else:
                log.error('OMERO database not found')
                raise Stop(DB_INIT_NEEDED,
                           'Install/Upgrade failed: OMERO database not found')

        elif status == DB_UPGRADE_NEEDED:
            log.warn('OMERO database exists but is out of date')
            if self.args.upgradedb:
                log.debug('Upgrading OMERO database')
                db.upgrade()
            else:
                raise Stop(
                    DB_UPGRADE_NEEDED,
                    'Pass --managedb or upgrade your OMERO database manually')

        else:
            assert status == DB_UPTODATE

        return status