clones the specific database

@param $main_db  string
@param $clone_db string

@return bool
@throws DatabaseException
@throws \Exception
548085
public function clone_database($main_db = null, $clone_db = null)
    {

        if (empty($this->db)) {
            throw new DatabaseException('Clone or Main database not connected');
        }

        if (empty($main_db) || empty($clone_db)) {
            throw new DatabaseException('clone names havent been set');
        }

        $sql    = "SHOW CREATE DATABASE `$main_db`";
        $result = $this->fetch_assoc($this->query($sql));

        $create_sql = str_replace($main_db, $clone_db, $result['Create Database']);

        if (empty($create_sql)) {
            throw new DatabaseException('Create database statement is empty!');
        }

        return $this->query($create_sql);
    }
709870
public function setDBO(&$db)
	{
		// Make sure the new database object is a Database.
		if (!($db instanceof \Hubzero\Database\Driver))
		{
			return false;
		}

		$this->_db = &$db;

		return true;
	}
218560
def replicate_to(other_db, continuous = false, create_target = false, doc_ids = nil)
      replicate(other_db, continuous, :source => name, :create_target => create_target, :doc_ids => doc_ids)
    end
975356
public static function process_foreign_keys($foreign_keys, $db = null)
	{
		if ( ! is_array($foreign_keys))
		{
			throw new \Database_Exception('Foreign keys on create_table() must be specified as an array');
		}

		$fk_list = array();

		foreach($foreign_keys as $definition)
		{
			// some sanity checks
			if (empty($definition['key']))
			{
				throw new \Database_Exception('Foreign keys on create_table() must specify a foreign key name');
			}
			if ( empty($definition['reference']))
			{
				throw new \Database_Exception('Foreign keys on create_table() must specify a foreign key reference');
			}
			if (empty($definition['reference']['table']) or empty($definition['reference']['column']))
			{
				throw new \Database_Exception('Foreign keys on create_table() must specify a reference table and column name');
			}

			$sql = '';
			! empty($definition['constraint']) and $sql .= " CONSTRAINT ".\DB::quote_identifier($definition['constraint']);
			$sql .= " FOREIGN KEY (".\DB::quote_identifier($definition['key']).')';
			$sql .= " REFERENCES ".\DB::quote_identifier(\DB::table_prefix($definition['reference']['table'], static::$connection)).' (';
			if (is_array($definition['reference']['column']))
			{
				$sql .= implode(', ', \DB::quote_identifier($definition['reference']['column']));
			}
			else
			{
				$sql .= \DB::quote_identifier($definition['reference']['column']);
			}
			$sql .= ')';
			! empty($definition['on_update']) and $sql .= " ON UPDATE ".$definition['on_update'];
			! empty($definition['on_delete']) and $sql .= " ON DELETE ".$definition['on_delete'];

			$fk_list[] = "\n\t".ltrim($sql);
		}

		return ', '.implode(',', $fk_list);
	}
174923
public function getDB($db = null)
    {
        if (null !== $db && !($db instanceof DB))
            throw new InvalidTypeException("Invalid database");
        return $db ?: $this->_source_db ?: DI::getInjector()->getInstance(DB::class);
    }
548684
public static function getDatabase()
	{
		//get the database settings from global space
        global $database;

        //create instance of database class
        $instance = new BaseDb($database['default'], $database[$database['default']]);

        //get connection instance and make attempt to connect to the database
        $instance = $instance->initialize()->connect();

		return $instance; 

	}
161892
def create_db(name, **client_args):
    '''
    
    '''
    if db_exists(name, **client_args):
        log.info('DB \'%s\' already exists', name)
        return False

    client = _client(**client_args)
    client.create_database(name)

    return True
416801
public static function make()
    {
        $class = str_replace(
            'DatabaseManager',
            ucfirst(config('database.default')).'Database',
            self::class
        );

        try {
            return new self(new $class());
        } catch (\Exception $e) {
            return new self(new MysqlDatabase());
        }
    }
344857
public function duplicate()
    {
        $class = get_class($this);
        $new_wrapper = new $class();

        foreach ($this->getArray() as $object) {
            $object->setDatabase($this->db);
            $duplicate_object = $object->duplicate();
            $duplicate_object->setDatabase($this->db);
            $new_wrapper->add($duplicate_object);
        }

        $new_wrapper->setDatabase($this->db);

        return $new_wrapper;
    }
214522
public function main()
    {
        $clone = $this->getFactoryInstance('log');

        if ($this->repository === '') {
            $project = $this->getProject();
            $dir = $project->getProperty('application.startdir');
        } else {
            $dir = $this->repository;
        }
        $clone->setCwd($dir);

        if ($this->maxCount !== null) {
            $max = filter_var($this->maxCount, FILTER_VALIDATE_INT);
            if ($max) {
                $max = (int) $this->maxCount;
            }
            if (!$max || (int) $this->maxCount <= 0) {
                throw new BuildException("maxcount should be a positive integer.");
            }
            $clone->setLimit('' . $this->maxCount);
        }

        if ($this->format !== null) {
            $clone->setTemplate($this->format);
        }

        if ($this->revision !== '') {
            $clone->setRev($this->revision);
        }

        try {
            $this->log("Executing: " . $clone->asString(), Project::MSG_INFO);
            $output = $clone->execute();
            if ($this->outputProperty !== null) {
                $this->project->setProperty($this->outputProperty, $output);
            } else {
                if ($output !== '') {
                    $this->log(PHP_EOL . $output);
                }
            }
        } catch (Exception $ex) {
            $msg = $ex->getMessage();
            $p = strpos($msg, 'hg returned:');
            if ($p !== false) {
                $msg = substr($msg, $p + 13);
            }
            throw new BuildException($msg);
        }
    }
1151183
private function _ifExistsDatabaseIni ($database_block)
    {
        // DB_INI_FILE 定数が設定されているかどうか
        if (! defined('DB_INI_FILE')) {
            throw new \Exception('Is not defined database.ini constant!');
        }

        // database.iniファイルが存在するかどうか
        if (! file_exists(DB_INI_FILE)) {
            throw new \Exception('Is not exists database.ini file!');
        }


        $this->ini_data = parse_ini_file(DB_INI_FILE, true)[$database_block];
        if (! $this->ini_data) {
            throw new \Exception('Is not found '.$database_block.' block!');
        }
    }
812112
def set_database(self, db):
        '''
        
        '''
        # This can not be imported globally due to circular import
        from .database import Database
        assert isinstance(db, Database), "database must be database.Database instance"
        self._database = db
1269617
public boolean create() throws DBException
    {
        boolean bSuccess = true;
        this.setResultSet(null, DBConstants.SQL_CREATE_TYPE);
        ResultSet resultSet = (ResultSet)this.getResultSet();
        if (resultSet == null)
        {
            Map<String,Object> properties = this.getDatabase().getProperties();
            String strAltSecondaryIndex = (String)this.getDatabase().getProperties().get(SQLParams.ALT_SECONDARY_INDEX);
            try   {
                int iFirstIndex = 0;
                Record record = this.getRecord();
                StringBuilder sql = new StringBuilder();
                sql.append("CREATE TABLE ");
                sql.append(record.makeTableNames(true));
                sql.append(" (");
                for (int iIndex = 0; iIndex < record.getFieldCount(); iIndex++)
                {
                    BaseField field = record.getField(iIndex);
                    if (field.isVirtual())
                        continue;
                    String strType = field.getSQLType(true, properties);
                    if (field instanceof CounterField)
                        if (this.getDatabase().isAutosequenceSupport())
                        {
                            String strCounterType = (String)this.getDatabase().getProperties().get(SQLParams.AUTO_SEQUENCE_TYPE);
                            if (strCounterType != null)
                                strType = strCounterType;
                            String strAutoseqExtra = (String)this.getDatabase().getProperties().get(SQLParams.AUTO_SEQUENCE_EXTRA);
                            if (strAutoseqExtra != null)
                                strType += strAutoseqExtra;
                            String strCounterExtra = (String)this.getDatabase().getProperties().get(SQLParams.COUNTER_EXTRA);
                            if (strCounterExtra != null)
                            {
                                strType += strCounterExtra;
                                iFirstIndex = 1;    // No need to build primary index
                            }
                        }
                    if (iIndex > 0)
                        sql.append(", ");
                    if (DBConstants.TRUE.equals(this.getDatabase().getProperties().get(SQLParams.NO_NULL_KEY_SUPPORT)))
                        this.checkNullableKey(field, strAltSecondaryIndex != null); // Set the key to not nullable for create.
                    if (!field.isNullable())
                    	if (!DBConstants.TRUE.equals(this.getDatabase().getProperties().get(SQLParams.NO_NULL_FIELD_SUPPORT)))	// Rare (or for locale dbs)
                    		strType += " NOT NULL";
                    if (strAltSecondaryIndex != null)
                        if (this.checkIndexField(field))
                            strType += ' ' + strAltSecondaryIndex;
                    sql.append(field.getFieldName(true, false)).append(' ').append(strType);
                }
                String strPrimaryKey = (String)this.getDatabase().getProperties().get(SQLParams.AUTO_SEQUENCE_PRIMARY_KEY);
                if (strPrimaryKey != null)
                    if (record.getCounterField() != null)
                        if (this.getDatabase().isAutosequenceSupport())
                {
                    sql.append(", ").append(strPrimaryKey).append(" (").append(record.getCounterField().getFieldName(true, false)).append(")");
                    iFirstIndex = 1;    // No need to build primary index
                }
                sql.append(")");
                Utility.getLogger().info(sql.toString());
                if (DBConstants.TRUE.equals((String)this.getDatabase().getProperties().get(SQLParams.NO_PREPARED_STATEMENTS_ON_CREATE)))
                    this.setStatement(null, DBConstants.SQL_CREATE_TYPE);
                if (this.getStatement(DBConstants.SQL_CREATE_TYPE) == null)
                    this.setStatement(((JdbcDatabase)this.getDatabase()).getJDBCConnection().createStatement(), DBConstants.SQL_CREATE_TYPE);
                this.getStatement(DBConstants.SQL_CREATE_TYPE).execute(sql.toString());
                // Now set up the index(es)
                sql = new StringBuilder();
                String strPrimaryKeySQL = (String)this.getDatabase().getProperties().get(SQLParams.CREATE_PRIMARY_INDEX);
                if (strPrimaryKeySQL == null)   // null=use default, If empty string, not supported.
                    strPrimaryKeySQL = "CREATE ${unique} INDEX ${keyname} ON ${table} (${fieldsandorder})";    // Default
                String strCreateIndexSQL = (String)this.getDatabase().getProperties().get(SQLParams.CREATE_INDEX);
                if (strCreateIndexSQL == null)   // null=use default, If empty string, not supported.
                    strCreateIndexSQL = strPrimaryKeySQL;    // Default
                for (int iIndex = iFirstIndex; iIndex < record.getKeyAreaCount(); iIndex++)
                {
                    KeyArea keyArea = record.getKeyArea(iIndex);
                    if ((keyArea.getUniqueKeyCode() == DBConstants.UNIQUE)
                        && (iIndex == iFirstIndex)
                            && (keyArea.getKeyFields() == 1))
                        sql = new StringBuilder(strPrimaryKeySQL);
                    else
                        sql = new StringBuilder(strCreateIndexSQL);
                    if (sql.length() == 0)
                        continue;   // Not supported.
                    boolean indexCanBeUnique = true;
                	if (DBConstants.TRUE.equals(this.getDatabase().getProperties().get(SQLParams.NO_NULL_UNIQUE_KEYS)))
                        if (iIndex > 0)
                    {	// This db considers null a valid index value and will throw a unique key error on write
                        for (int iFieldIndex = 0; iFieldIndex < keyArea.getKeyFields(); iFieldIndex++)
                        {
                            KeyField keyField = keyArea.getKeyField(iFieldIndex);
                            BaseField field = keyField.getField(DBConstants.FILE_KEY_AREA);
                            if (field.isNullable())
                            	indexCanBeUnique = false;
                        }
                    }
                    if (iIndex > 0)
                    	if (DBConstants.TRUE.equals(this.getDatabase().getProperties().get(SQLParams.NO_NULL_FIELD_SUPPORT)))	// Rare (or for locale dbs)
                    		indexCanBeUnique = false;
                    
                    if ((keyArea.getUniqueKeyCode() == DBConstants.UNIQUE) && (indexCanBeUnique))
                        sql = Utility.replace(sql, "${unique}", "UNIQUE");
                    else
                        sql = Utility.replace(sql, "${unique}", DBConstants.BLANK);
                    String strKeyName = keyArea.getKeyName();
                    String strTableNames = record.makeTableNames(true);
                    if (DBConstants.TRUE.equals(this.getDatabase().getProperties().get(SQLParams.NO_DUPLICATE_KEY_NAMES)))
                    {
                    	if (strTableNames.endsWith("_temp"))
                    		strKeyName = strTableNames.substring(0, strTableNames.length() - 5) + "_" + strKeyName;
                    	else
                    		strKeyName = strTableNames + "_" + strKeyName;
                    }
                    String strMaxKeyNameLength = (String)this.getDatabase().getProperties().get(SQLParams.MAX_KEY_NAME_LENGTH);
                    if (strMaxKeyNameLength != null)
                    {
                        int iMaxKeyNameLength = Integer.parseInt(strMaxKeyNameLength);
                        if (strKeyName.length() > iMaxKeyNameLength)
                        {
                        	strKeyName = strKeyName + (int)(Math.random() * 100000);
                            strKeyName = strKeyName.substring(strKeyName.length() - iMaxKeyNameLength);
                            while (!Character.isLetter(strKeyName.charAt(0))) {
                            	strKeyName = strKeyName.substring(1);
                            }
                        }
                    }
                    sql = Utility.replace(sql, "${keyname}", strKeyName);
                    sql = Utility.replace(sql, "${table}", strTableNames);
                    String strFields = DBConstants.BLANK;
                    String strFieldAndOrder = DBConstants.BLANK;
                    for (int iFieldIndex = 0; iFieldIndex < keyArea.getKeyFields(); iFieldIndex++)
                    {
                        KeyField keyField = keyArea.getKeyField(iFieldIndex);
                        BaseField field = keyField.getField(DBConstants.FILE_KEY_AREA);
                        if (iFieldIndex > 0)
                        {
                            strFields += ", ";
                            strFieldAndOrder += ", ";
                        }
                        strFields += field.getFieldName(true, false) + " ";
                        strFieldAndOrder += field.getFieldName(true, false) + " ";
                        if (keyField.getKeyOrder() == DBConstants.DESCENDING)
                            strFieldAndOrder += "DESC ";
                    }
                    sql = Utility.replace(sql, "${fields}", strFields);
                    sql = Utility.replace(sql, "${fieldsandorder}", strFieldAndOrder);
                    Utility.getLogger().info(sql.toString());
                    this.getStatement(DBConstants.SQL_CREATE_TYPE).execute(sql.toString());
                }
            } catch (SQLException e)    {
                throw this.getDatabase().convertError(e);
            } finally {
                if (DBConstants.TRUE.equals(this.getDatabase().getProperties().get(SQLParams.NO_PREPARED_STATEMENTS_ON_CREATE)))
                    this.setStatement(null, DBConstants.SQL_CREATE_TYPE);
            }
        }
        this.setResultSet(null, DBConstants.SQL_CREATE_TYPE);
        return bSuccess;    // Success!!!
    }
1079472
public GenericConnectionFactory cloneWith(DataSource datasource)
   {
      try
      {
         GenericConnectionFactory factory = (GenericConnectionFactory)this.clone();
         factory.dbDataSource = datasource;
         return factory;
      }
      catch (CloneNotSupportedException e)
      {
         throw new AssertionError(); // Cannot occur
      }
   }
254267
protected function duplicatePivotedRelation($relation, $relation_name, $clone) {

		// If duplicating between databases, do not duplicate relations. The related
		// instance may not exist in the other database or could have a different
		// primary key.
		if ($this->write_connection) return;

		// Loop trough current relations and attach to clone
		$relation->get()->each(function ($foreign) use ($clone, $relation_name) {
			$pivot_attributes = array_except($foreign->pivot->getAttributes(), [
				$foreign->pivot->getRelatedKey(),
				$foreign->pivot->getForeignKey(),
				$foreign->pivot->getCreatedAtColumn(),
				$foreign->pivot->getUpdatedAtColumn()
			]);
			$clone->$relation_name()->attach($foreign, $pivot_attributes);
		});
	}
103137
protected function waitForMySQLDatabaseByName($database_name)
    {
        return $this->retry(50, function () use ($database_name) {
            $this->databases = $this->fetchMySQLDatabases();
            $database = $this->getMysqlDatabaseByName($this->databases, $database_name);
            return $database['status'] == 'installed' ? $database : null;
        });
    }
43246
public function main()
    {
        $this->validate();

        $targetDatabase = $this->getTargetDatabase();

        $platform = $this->getGeneratorConfig()->getConfiguredPlatform();

        // Load the Data XML -> DB Name properties
        $map = new Properties();
        try {
            $map->load($this->getDataDbMap());
        } catch (IOException $ioe) {
            throw new BuildException("Cannot open and process the datadbmap!", $ioe);
        }

        // Parse each file in the data -> db map
        foreach ($map->keys() as $dataXMLFilename) {

            $dataXMLFile = new PhingFile($this->srcDir, $dataXMLFilename);

            // if file exists then proceed
            if ($dataXMLFile->exists()) {

                $dbname = $map->get($dataXMLFilename);

                $db = $this->getDatabase($dbname);

                if (!$db) {
                    throw new BuildException("Cannot find instantiated Database for name '$dbname' from datadbmap file.");
                }

                $db->setPlatform($platform);

                $outFile = $this->getMappedFile($dataXMLFilename);
                $sqlWriter = new FileWriter($outFile);

                $this->log("Creating SQL from XML data dump file: " . $dataXMLFile->getAbsolutePath());

                try {
                    $dataXmlParser = new XmlToDataSQL($db, $this->getGeneratorConfig(), $this->dbEncoding);
                    $dataXmlParser->transform($dataXMLFile, $sqlWriter);
                } catch (Exception $e) {
                    throw new BuildException("Exception parsing data XML: " . $e->getMessage());
                }

                // Place the generated SQL file(s)
                $p = new Properties();
                if ($this->getSqlDbMap()->exists()) {
                    $p->load($this->getSqlDbMap());
                }

                $p->setProperty($outFile->getName(), $db->getName());
                $p->store($this->getSqlDbMap(), "Sqlfile -> Database map");
            } else {
                $this->log("File '" . $dataXMLFile->getAbsolutePath() . "' in datadbmap does not exist, so skipping it.", Project::MSG_WARN);
            }
        } // foreach data xml file

    }