Create database tables if necessary

@return null
346244
public static function install()
    {
        global $PPHP;
        $db = $PPHP['db'];
        echo "    Installing ACL...";

        $db->begin();

        $db->exec(
            "
            CREATE TABLE IF NOT EXISTS 'acl_roles' (
                role       VARCHAR(64) NOT NULL DEFAULT '',
                action     VARCHAR(64) NOT NULL DEFAULT '*',
                objectType VARCHAR(64) NOT NULL DEFAULT '*',
                objectId   INTEGER     NOT NULL DEFAULT '0'
            )
            "
        );
        $db->exec(
            "
            CREATE UNIQUE INDEX IF NOT EXISTS idx_acl_roles
            ON acl_roles (role, action, objectType, objectId)
            "
        );
        foreach ($PPHP['config']['acl']['grant'] as $right) {
            $rightParts = preg_split('/[\s]+/', $right, null, PREG_SPLIT_NO_EMPTY);
            if (!$db->selectAtom("SELECT role FROM acl_roles WHERE role=? AND action=? AND objectType=? AND objectId='0'", $rightParts)) {
                $db->exec("INSERT INTO acl_roles VALUES (?,?,?,'0')", $rightParts);
            };
        };

        $db->exec(
            "
            CREATE TABLE IF NOT EXISTS 'acl_users' (
                userId     INTEGER     NOT NULL DEFAULT '0',
                action     VARCHAR(64) NOT NULL DEFAULT '*',
                objectType VARCHAR(64) NOT NULL DEFAULT '*',
                objectId   INTEGER     NOT NULL DEFAULT '0'
            )
            "
        );
        $db->exec(
            "
            CREATE UNIQUE INDEX IF NOT EXISTS idx_acl_users
            ON acl_users (userId, action, objectType, objectId)
            "
        );

        $db->exec(
            "
            CREATE TABLE IF NOT EXISTS 'users_roles' (
                userId     INTEGER     NOT NULL DEFAULT '0',
                role       VARCHAR(64) NOT NULL DEFAULT ''
            )
            "
        );
        $db->exec(
            "
            CREATE UNIQUE INDEX IF NOT EXISTS idx_users_roles
            ON users_roles (userId, role)
            "
        );
        if (!$db->selectAtom("SELECT userId FROM users_roles WHERE userId='1' AND role='admin'")) {
            $db->exec("INSERT INTO users_roles VALUES ('1', 'admin')");
        };

        $db->commit();
        echo "    done!\n";
    }
121888
private function setup()
    {
        $manager = $this->getConnection()->getSchemaManager();
        if ($this->tablesExist === true || $manager->tablesExist([$this->options['db_table']]) === true) {
            $this->tablesExist = true;

            return;
        }

        $schema = new Schema();
        $table = $schema->createTable($this->options['db_table']);

        $table->addColumn($this->options['db_column_feature'], 'string', ['length' => 255]);
        $table->addColumn($this->options['db_column_state'], 'boolean');

        $table->setPrimaryKey([$this->options['db_column_feature']]);

        $platform = $this->getConnection()->getDatabasePlatform();
        $queries = $schema->toSql($platform);

        foreach ($queries as $query) {
            $this->getConnection()->executeQuery($query);
        }

        $this->tablesExist = true;
    }
341842
protected function connectDatabase()
    {
        if (!$this->databaseConfig) {
            return null;
        }

        $this->databaseConnection = ConnectionManager::create($this->databaseConfig);
    }
335379
public function databaseIsEmpty()
    {
        try {
            $dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->database;
            $options = [\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES UTF8'];
            $connect = new \PDO($dsn, $this->user, $this->pass, $options);
            $connect->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);

            $command = $connect->prepare("show tables");
            $command->setFetchMode(\PDO::FETCH_ASSOC);
            $command->execute();
            return empty($command->fetchAll());

        } catch (\PDOException $e) {
            return false;
        }
    }
1231953
private function createMigrationTable()
    {
        $adapter = Database::getConnectionAdapter();
        $table = $adapter->getTablePrefix().config('database.migration');
        $generator = new SQLGenerator(
            $table,
            $adapter->getName(),
            'create'
        );

        $generator->addColumn('migration', 'string', ['unique' => true]);
        $generator->addColumn('batch', 'int');
        $generator->addColumn('created_at', 'datetime', [
            'default' => 'CURRENT_TIMESTAMP',
            'nullable' => true
        ]);

        $sql = sprintf(
            'CREATE TABLE IF NOT EXISTS %s (%s);',
            $table,
            $generator->make()
        );

        return Database::statement($sql);
    }
740568
protected function createTable()
    {
        if ($this->db->schema->getTableSchema($this->sessionTable) === null) {
            $cmd = $this->db->createCommand();
            $cmd->createTable($this->sessionTable, [
                'id' => 'CHAR(40) PRIMARY KEY',
                'expire' => 'integer',
                'data' => 'binary',
            ])->execute();
        }
    }
608976
public function actionCreate()
    {
        $stdout = '';
        foreach ($this->db->schema->getTableSchemas() as $table) {
            if ($table->name === $this->migrationTable) {
                continue;
            }
            $stdout .= static::generateCreateTable($table->name).
                static::generateColumns($table->columns, $this->db->schema->findUniqueIndexes($table)).
                static::generatePrimaryKey($table->primaryKey, $table->columns).
                static::generateTableOptions();
        }
        foreach ($this->db->schema->getTableSchemas() as $table) {
            $stdout .= $this->generateForeignKey($table);
        }
        $this->stdout($stdout);
    }
33039
private static function _get_databases(): ?databases
  {
    if ( self::check() ){
      if ( !self::$databases_obj && ($db = self::_get_db()) ){
        self::$databases_obj = new databases($db);
      }
      return self::$databases_obj;
    }
    return null;
  }
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;
    }
1090406
function databaseSetup()
    {
        $this->checkPiwikIsNotInstalled();

        $view = new View(
            '@Installation/databaseSetup',
            $this->getInstallationSteps(),
            __FUNCTION__
        );

        $view->showNextStep = false;

        $form = new FormDatabaseSetup();

        if ($form->validate()) {
            try {
                $dbInfos = $form->createDatabaseObject();

                DbHelper::checkDatabaseVersion();

                Db::get()->checkClientVersion();

                $this->createConfigFile($dbInfos);

                $this->redirectToNextStep(__FUNCTION__);
            } catch (Exception $e) {
                $view->errorMessage = Common::sanitizeInputValue($e->getMessage());
            }
        }
        $view->addForm($form);

        return $view->render();
    }
170704
function _createTable()
    {
        $this->_db->loadModule('Manager', null, true);
        $result = $this->_db->manager->createTable(
            $this->_table,
            array(
                'id'        => array('type' => $this->_types['id']),
                'logtime'   => array('type' => $this->_types['logtime']),
                'ident'     => array('type' => $this->_types['ident']),
                'priority'  => array('type' => $this->_types['priority']),
                'message'   => array('type' => $this->_types['message'])
            )
        );
        if (PEAR::isError($result)) {
            return false;
        }

        $result = $this->_db->manager->createIndex(
            $this->_table,
            'unique_id',
            array('fields' => array('id' => true), 'unique' => true)
        );
        if (PEAR::isError($result)) {
            return false;
        }

        return true;
    }
15968
public function create()
    {
        if ($this->connection->tableExists($this->fq_name)) {
            return true;
        }

        $dbms = $this->connection->dbmsName();
        $pkey = array();
        $indexes = array();
        $sql = 'CREATE TABLE '.$this->fq_name.' (';
        foreach($this->columns as $cname => $definition) {
            if (!isset($definition['type'])) {
                return false;
            }

            $sql .= $this->identifierEscape($dbms, $cname);
            $sql .= ' ' . $this->arrayToSQL($definition, $dbms);
            $sql .= ',';

            if ($this->isPrimaryKey($definition)) {
                $pkey[] = $cname;
            } elseif ($this->isIndexed($definition)) {
                $indexes[] = $cname;
            }
        }

        if (!empty($pkey)) {
            $sql .= ' PRIMARY KEY (';
            foreach($pkey as $col) {
                $sql .= $this->identifierEscape($dbms, $col).',';
            }
            $sql = substr($sql,0,strlen($sql)-1).'),';
        }
        if (!empty($indexes) && $dbms !== 'postgres9') {
            foreach($indexes as $index) {
                $sql .= ' INDEX (';
                $sql .= $this->connection->identifierEscape($index);
                $sql .= '),';
            }
        }

        $sql = rtrim($sql,',');
        $sql .= ')';
        if ($this->hasIncrement() && $dbms == 'mssql')
            $sql .= ' ON [PRIMARY]';

        $result = $this->connection->execute($sql);

        if ($result && !empty($indexes) && $dbms === 'postgres9') {
            foreach ($indexes as $index) {
                $this->connection->query("CREATE INDEX {$index}_idx ON {$this->fq_name} ({$index})");
            }
        }

        /**
          Clear out any cached definition
        */
        if ($result) {
            $this->cached_definition = false;
        }

        return ($result === false) ? false : true;

    // create()
    }
573983
public function initDatabase()
    {
        $this->call('migrate');

        if (Administrator::count() == 0) {
            $this->call('db:seed', ['--class' => \Lia\Auth\Database\AdminTablesSeeder::class]);
        }
    }
196415
public function createDatabases()
    {
        foreach ($this->metadataFactory->getAllMetadata() as $class) {
            if ($class->isMappedSuperclass || $class->isEmbeddedDocument) {
                continue;
            }
            $this->createDocumentDatabase($class->name);
        }
    }
672852
public function createDatabase()
    {
        try {
            $dsn = 'mysql:host=' . $this->host . ';';
            $options = [\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES UTF8'];
            $connect = new \PDO($dsn, $this->user, $this->pass, $options);
            $connect->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);

            $command = $connect->prepare("CREATE DATABASE {$this->database}");
            $command->execute();

        } catch (\PDOException $e) {
            return false;
        }
    }
59180
protected function _Create() {
      $PrimaryKey = array();
      $UniqueKey = array();
      $FullTextKey = array();
      $AllowFullText = TRUE;
      $Indexes = array();
      $Keys = '';
      $Sql = '';
      
      $ForceDatabaseEngine = C('Database.ForceStorageEngine');
      if ($ForceDatabaseEngine && !$this->_TableStorageEngine) {
         $this->_TableStorageEngine = $ForceDatabaseEngine;
         $AllowFullText = $this->_SupportsFulltext();
      }

      foreach ($this->_Columns as $ColumnName => $Column) {
         if ($Sql != '')
            $Sql .= ',';

         $Sql .= "\n".$this->_DefineColumn($Column);

         $ColumnKeyTypes = (array)$Column->KeyType;

         foreach ($ColumnKeyTypes as $ColumnKeyType) {
            $KeyTypeParts = explode('.', $ColumnKeyType, 2);
            $ColumnKeyType = $KeyTypeParts[0];
            $IndexGroup = GetValue(1, $KeyTypeParts, '');
            
            if ($ColumnKeyType == 'primary')
               $PrimaryKey[] = $ColumnName;
            elseif ($ColumnKeyType == 'key')
               $Indexes['FK'][$IndexGroup][] = $ColumnName;
            elseif ($ColumnKeyType == 'index')
               $Indexes['IX'][$IndexGroup][] = $ColumnName;
            elseif ($ColumnKeyType == 'unique')
               $UniqueKey[] = $ColumnName;
            elseif ($ColumnKeyType == 'fulltext' && $AllowFullText)
               $FullTextKey[] = $ColumnName;
         }
      }
      // Build primary keys
      if (count($PrimaryKey) > 0)
         $Keys .= ",\nprimary key (`".implode('`, `', $PrimaryKey)."`)";
      // Build unique keys.
      if (count($UniqueKey) > 0)
         $Keys .= ",\nunique index `".Gdn_Format::AlphaNumeric('UX_'.$this->_TableName).'` (`'.implode('`, `', $UniqueKey)."`)";
      // Build full text index.
      if (count($FullTextKey) > 0)
         $Keys .= ",\nfulltext index `".Gdn_Format::AlphaNumeric('TX_'.$this->_TableName).'` (`'.implode('`, `', $FullTextKey)."`)";
      // Build the rest of the keys.
      foreach ($Indexes as $IndexType => $IndexGroups) {
         $CreateString = ArrayValue($IndexType, array('FK' => 'key', 'IX' => 'index'));
         foreach ($IndexGroups as $IndexGroup => $ColumnNames) {
            if (!$IndexGroup) {
               foreach ($ColumnNames as $ColumnName) {
                  $Keys .= ",\n{$CreateString} `{$IndexType}_{$this->_TableName}_{$ColumnName}` (`{$ColumnName}`)";
               }
            } else {
               $Keys .= ",\n{$CreateString} `{$IndexType}_{$this->_TableName}_{$IndexGroup}` (`".implode('`, `', $ColumnNames).'`)';
            }
         }
      }

      $Sql = 'create table `'.$this->_DatabasePrefix.$this->_TableName.'` ('
         .$Sql
         .$Keys
      ."\n)";

      // Check to see if there are any fulltext columns, otherwise use innodb.
      if (!$this->_TableStorageEngine) {
         $HasFulltext = FALSE;
         foreach ($this->_Columns as $Column) {
            $ColumnKeyTypes = (array)$Column->KeyType;
            array_map('strtolower', $ColumnKeyTypes);
            if (in_array('fulltext', $ColumnKeyTypes)) {
               $HasFulltext = TRUE;
               break;
            }
         }
         if ($HasFulltext)
            $this->_TableStorageEngine = 'myisam';
         else
            $this->_TableStorageEngine = C('Database.DefaultStorageEngine', 'innodb');
         
         if (!$this->HasEngine($this->_TableStorageEngine)) {
            $this->_TableStorageEngine = 'myisam';
         }
      }
      
      if ($this->_TableStorageEngine)
         $Sql .= ' engine='.$this->_TableStorageEngine;

      if ($this->_CharacterEncoding !== FALSE && $this->_CharacterEncoding != '')
         $Sql .= ' default character set '.$this->_CharacterEncoding;
         
      if (array_key_exists('Collate', $this->Database->ExtendedProperties)) {
         $Sql .= ' collate ' . $this->Database->ExtendedProperties['Collate'];
      }
      
      $Sql .= ';';

      $Result = $this->Query($Sql);
      $this->Reset();
      
      return $Result;
   }
698610
public function database()
    {
        if (!$this->_step('license')) {
            $this->redirect(['plugin' => 'Installer', 'controller' => 'startup', 'action' => 'license']);
        }

        if (!empty($this->request->data)) {
            $dbInstaller = new DatabaseInstaller();
            if ($dbInstaller->install($this->request->data())) {
                $this->_step();
                $this->redirect(['plugin' => 'Installer', 'controller' => 'startup', 'action' => 'account']);
            } else {
                $errors = '';
                foreach ($dbInstaller->errors() as $error) {
                    $errors .= "\t<li>{$error}</li>\n";
                }
                $this->Flash->danger("<ul>\n{$errors}</ul>\n");
            }
        }

        $this->title(__d('installer', 'Database Configuration'));
    }