Create structure only if it does not exist
@param $db_name [string] database name
@return [keyed array]
db => database name
struct => table/view name
error => [int] error code
error_msg => error details
509164
public function createIfNeeded($db_name)
    {
        $this->fq_name = $db_name . $this->connection->sep() . $this->name;
        $ret = array('db'=>$db_name,'struct'=>$this->name,'error'=>0,'error_msg'=>'');
        $exists = $this->connection->tableExists($this->fq_name);
        if (!$exists && !$this->create()) {
            $ret['error'] = 1;
            $ret['error_msg'] = $this->connection->error($db_name);
            $reflect = new \ReflectionClass($this);
            $ret['query'] = $reflect->getName() . '::create()';
        }

        return $ret;
    }
1070366
public function use_database($db_name)
    {
        if (!$this->connection) {
            $this->last_error_id = "db_server_conn_error";
            return false;
        }
        
        $this->db_name = $db_name;
        
        $db_name = $this->escape($db_name);
        
        if (!$this->execute_query("USE " . $db_name)) {
            $this->last_error = $this->sys_get_errors();
            $this->last_error_id = "db_not_exists_error";
            return false;
        }
        
        return true;
    }
1053296
def get_or_create(self, db_name):
        
        if not db_name in self:
            res = self.resource.put(db_name)
            if not res[0] == 201:
                raise RuntimeError(
                    'Failed to create database "{}"'.format(db_name)
                )
        return self[db_name]
730210
public function createDatabase($name)
    {
        if (preg_match('@[^a-z0-9\_\$\(\)+\-]@', $name)) {
            throw new InvalidDatabasenameException(sprintf(
                'The database name %s is invalid. The database name must match the following pattern (a-z0-9_$()+-)',
                $name
            ));
        }

        if ($this->eventManager->hasListeners(Events::PRE_CREATE_DATABASE)) {
            // @codeCoverageIgnoreStart
            $this->eventManager->dispatchEvent(Events::PRE_CREATE_DATABASE, new EventArgs($this, $name));
            // @codeCoverageIgnoreEnd
        }

        $response = $this->client->request('PUT', sprintf('/%s', $name));

        if (412 === $response->getStatusCode()) {
            throw new Exception(sprintf('The database "%s" already exist', $name));
        }

        $json = (string) $response->getBody();
        $value = JSONEncoder::decode($json);

        if (isset($value['error'])) {
            throw new Exception(sprintf('[%s] Failed to create database "%s". (%s)', $value['error'], $name, $value['reason']));
        }

        $database = $this->wrapDatabase($name);

        if ($this->eventManager->hasListeners(Events::POST_CREATE_DATABASE)) {
            // @codeCoverageIgnoreStart
            $this->eventManager->dispatchEvent(Events::POST_CREATE_DATABASE, new EventArgs($database));
            // @codeCoverageIgnoreEnd
        }

        return $database;
    }
1353499
public static function connectToServers(string $db_link, array $db_settings) : array {
		$result = [
			'success' => false,
			'error' => []
		];
		// load application structure
		$application_structure = \Application::get('application.structure');
		$db_options = $db_settings;
		unset($db_options['servers']);
		// loop through available servers
		foreach ($db_settings['servers'] as $db_server) {
			$db_object = new \Db($db_link, $db_settings['submodule'], $db_settings);
			// application structure provides more data
			if (!empty($application_structure) && isset($application_structure['settings']['db'][$db_link])) {
				foreach ($application_structure['settings']['db'][$db_link] as $k => $v) {
					if (!empty($db_server[$k]) && $db_server[$k] != $v) {
						$db_server['__original_' . $k] = $db_server[$k];
					}
					$db_server[$k] = $v;
				}
			}
			// fix database issue for multi database configurations
			if (empty($db_server['dbname'])) {
				$db_server['dbname'] = \Application::get("db.{$db_link}_schema.dbname");
			}
			// try to connect
			$db_status = $db_object->connect($db_server);
			if ($db_status['success']) {
				$result['success'] = true;
				return $result;
			}
		}
		$result['error'][] = 'Unable to open db connection!';
		return $result;
	}
1312206
public function getCurrentStructure($db, $table = '')
    {
        $res = $db->getConnection()->select("SHOW TABLES LIKE '$table'");
        $tables = array();
        $result = array();
        foreach ($res as $row) {
            $tables[] = array_pop($row);
        }
        foreach ($tables as $table) {
            $table = $db->escape_string($table);

            $info = $db->getConnection()->select('DESCRIBE `' . $table . '`');
            $fields = array();
            foreach ($info as $row) {
                $field = array();
                $field['field'] = $row['Field'];
                $field['type'] = $row['Type'];
                $field['default'] = $row['Default'];
                if ($row['Extra'] === 'auto_increment') {
                    $field['autoincrement'] = true;
                } elseif ($row['Key'] === 'PRI') {
                    $field['primary'] = true;
                }
                $fields[$field['field']] = $field;
            }

            $info = $db->getConnection()->select("SELECT 
  TABLE_NAME,COLUMN_NAME,CONSTRAINT_NAME, REFERENCED_TABLE_NAME,REFERENCED_COLUMN_NAME
FROM
  INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE
  TABLE_SCHEMA = ? AND
  TABLE_NAME = ?", array($db->getDatabaseName(), $table));

            $keys = array();
            $unique = array();
            foreach ($info as $row) {
                if ($row['REFERENCED_TABLE_NAME']) {
                    $key = array();
                    $key['field'] = $row['COLUMN_NAME'];
                    $key['table'] = $row['REFERENCED_TABLE_NAME'];
                    $key['target'] = $row['REFERENCED_COLUMN_NAME'];
//                    $fields[$key['field']]['index'] = true;
                    $keys[] = $key;
                } elseif ($row['CONSTRAINT_NAME'] != 'PRIMARY') {
                    $unique[] = $row['COLUMN_NAME'];
                }
            }

            $info2 = $db->getConnection()->select("SHOW TABLE STATUS WHERE Name = ?;", array ($table));
            if ($info2 && count($info2) > 0) {
                $info2 = $info2[0];
            }

            $engine = $info2['Engine'];
            $result[$table] = array(
                'table' => $table,
                'fields' => $fields,
                'keys' => $keys,
                'unique' => $unique,
//                'engine' => $engine,
            );
        }
        return $result;
    }
172995
public function getTable($table_name)
    {
        if (!$this->tables->has('tables', $table_name))
        {
            if ($this->db !== null)
            {
                $table = $this->db->loadTable($table_name);
                $this->tables->set('tables', $table_name, $table);
            }
            else
                throw new DBException("Table $table not ofund");
        }

        return $this->tables->get('tables', $table_name);
    }
757791
static function sql_connect ( $sql_details )
	{
		try {
			$db = @new PDO(
				"mysql:host={$sql_details['host']};dbname={$sql_details['db']}",
				$sql_details['user'],
				$sql_details['pass'],
				array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION )
			);
		}
		catch (PDOException $e) {
			self::fatal(
				"An error occurred while connecting to the database. ".
				"The error reported by the server was: ".$e->getMessage()
			);
		}

		return $db;
	}
653810
public function getStructure($name = null)
    {
        $name = $name ? : $this->default;
        if (!isset($this->structures[$name])) {
            $this->structures[$name] = new Structure($this->getDbConfig($name));
        }
        return $this->structures[$name];
    }
1123257
public static function create_index($table, $index_columns, $index_name = '', $index = '', $db = null)
	{
		static $accepted_index = array('UNIQUE', 'FULLTEXT', 'SPATIAL', 'NONCLUSTERED', 'PRIMARY');

		// make sure the index type is uppercase
		$index !== '' and $index = strtoupper($index);

		if (empty($index_name))
		{
			if (is_array($index_columns))
			{
				foreach ($index_columns as $key => $value)
				{
					if (is_numeric($key))
					{
						$index_name .= ($index_name == '' ? '' : '_').$value;
					}
					else
					{
						$index_name .= ($index_name == '' ? '' : '_').str_replace(array('(', ')', ' '), '', $key);
					}
				}
			}
			else
			{
				$index_name = $index_columns;
			}
		}

		if ($index == 'PRIMARY')
		{
			$sql = 'ALTER TABLE ';
			$sql .= \DB::quote_identifier(\DB::table_prefix($table, $db ? $db : static::$connection), $db ? $db : static::$connection);
			$sql .= ' ADD PRIMARY KEY ';
			if (is_array($index_columns))
			{
				$columns = '';
				foreach ($index_columns as $key => $value)
				{
					if (is_numeric($key))
					{
						$columns .= ($columns=='' ? '' : ', ').\DB::quote_identifier($value, $db ? $db : static::$connection);
					}
					else
					{
						$columns .= ($columns=='' ? '' : ', ').\DB::quote_identifier($key, $db ? $db : static::$connection).' '.strtoupper($value);
					}
				}
				$sql .= ' ('.$columns.')';
			}
		}
		else
		{
			$sql = 'CREATE ';

			$index !== '' and $sql .= (in_array($index, $accepted_index)) ? $index.' ' : '';

			$sql .= 'INDEX ';
			$sql .= \DB::quote_identifier($index_name, $db ? $db : static::$connection);
			$sql .= ' ON ';
			$sql .= \DB::quote_identifier(\DB::table_prefix($table, $db ? $db : static::$connection), $db ? $db : static::$connection);
			if (is_array($index_columns))
			{
				$columns = '';
				foreach ($index_columns as $key => $value)
				{
					if (is_numeric($key))
					{
						$columns .= ($columns=='' ? '' : ', ').\DB::quote_identifier($value, $db ? $db : static::$connection);
					}
					else
					{
						$columns .= ($columns=='' ? '' : ', ').\DB::quote_identifier($key, $db ? $db : static::$connection).' '.strtoupper($value);
					}
				}
				$sql .= ' ('.$columns.')';
			}
			else
			{
				$sql .= ' ('.\DB::quote_identifier($index_columns, $db ? $db : static::$connection).')';
			}
		}


		return \DB::query($sql, \DB::UPDATE)->execute($db ? $db : static::$connection);
	}
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);
            }
        );
    }
297527
protected function createDatabase()
    {
        /** @var Container $container */
        $container = $this->console->container;

        $dbService = $container->get(DatabaseService::class);
        $config    = $dbService->getDbConfig();

        // Auto create database
        $name = $config['name'];

        $config['name'] = null;

        $db = $dbService->createConnection('_preset', $config->toArray());

        $db->getDatabase($name)->create(true);

        $db->select($name);

        $config['name'] = $name;
    }
744636
public static function for_table($table_name, $connection_name = parent::DEFAULT_CONNECTION)
        {
            self::_setupDb($connection_name);

            return new self($table_name, [], $connection_name);
        }
376595
@Override
	public void createDb(String dbName) {
		String dbPath = getDbPath(dbName);
		if (map.containsKey(dbPath)) {
			throw DBLogger.newUser("Database already exists: " + dbPath);
		}
		map.put(dbPath, new ArrayList<ByteBuffer>());
		
		//create files

		//DB file
		FreeSpaceManager fsm = new FreeSpaceManager();
		StorageRootInMemory root = 
				new StorageRootInMemory(dbPath, "rw", ZooConfig.getFilePageSize(), fsm);
		IOResourceProvider file = root.createChannel();
		StorageChannelOutput out = file.createWriter(false);
		fsm.initBackingIndexNew(file);

		int headerPage = out.allocateAndSeek(PAGE_TYPE.DB_HEADER, 0);
		if (headerPage != 0) {
			throw DBLogger.newFatalInternal("Header page = " + headerPage);
		}
		int rootPage1 = out.allocateAndSeek(PAGE_TYPE.ROOT_PAGE, 0);
		int rootPage2 = out.allocateAndSeek(PAGE_TYPE.ROOT_PAGE, 0);

		//header: this is written further down

		//write User data
		int userData = out.allocateAndSeek(PAGE_TYPE.USERS, 0);

		//dir for schemata
		int schemaData = out.allocateAndSeekAP(PAGE_TYPE.SCHEMA_INDEX, 0, -1);
		//ID of next page
		out.writeInt(0);
		//Schema ID / schema data (page or actual data?)
		//0 for no more schemata
		out.writeInt(0);


		//dir for indices
		int indexDirPage = out.allocateAndSeek(PAGE_TYPE.INDEX_CATALOG, 0);
		//ID of next page
		out.writeInt(0);
		//Schema ID / attribute ID / index type / Page ID
		//0 for nor more indices
		out.writeInt(0);

		//OID index
		PagedOidIndex oidIndex = new PagedOidIndex(file);
		int oidPage = file.writeIndex(oidIndex::write);

		//Free space index
		int freeSpacePg = file.writeIndex(fsm::write);
		
		//write header
		out.seekPageForWrite(PAGE_TYPE.DB_HEADER, headerPage);
		out.writeInt(DiskIO.DB_FILE_TYPE_ID);
		out.writeInt(DiskIO.DB_FILE_VERSION_MAJ);
		out.writeInt(DiskIO.DB_FILE_VERSION_MIN);
		out.writeInt(ZooConfig.getFilePageSize());
		out.writeInt(rootPage1);
		out.writeInt(rootPage2);

		writeRoot(out, rootPage1, 1, userData, oidPage, schemaData, indexDirPage, freeSpacePg, 
				fsm.getPageCount());
		writeRoot(out, rootPage2, 0, userData, oidPage, schemaData, indexDirPage, freeSpacePg, 
				fsm.getPageCount());

		file.close();
		file = null;
		root.close();
		root = null;
		out = null;


		//initial schemata
		Properties props = new ZooJdoProperties(dbName);
		PersistenceManagerFactory pmf = 
			JDOHelper.getPersistenceManagerFactory(props);
		PersistenceManager pm = pmf.getPersistenceManager();
		pm.currentTransaction().begin();

		ZooSchema schema = ZooJdoHelper.schema(pm);
		schema.addClass(PersistenceCapableImpl.class);
		schema.addClass(DBHashMap.class);
		schema.addClass(DBArrayList.class);

		pm.currentTransaction().commit();
		pm.close();
		pmf.close();
	}
834854
def createDatabase(self, name, **dbArgs) :
        ""
        dbArgs['name'] = name
        payload = json.dumps(dbArgs, default=str)
        url = self.URL + "/database"
        r = self.session.post(url, data = payload)
        data = r.json()
        if r.status_code == 201 and not data["error"] :
            db = Database(self, name)
            self.databases[name] = db
            return self.databases[name]
        else :
            raise CreationError(data["errorMessage"], r.content)
109541
def structure_names
      names = Array.new
      @structures.each do |s|
        names << s.name
      end
      return names
    end
283973
public function createDb($name)
    {
        if (isset($name) && !empty(trim($name))) {
            $sql = "CREATE DATABASE IF NOT EXISTS `{$name}`";

            return $sql;
        } else {
            return false;
        }
    }