Create database tables if necessary

@return null
162407
public static function install()
    {
        global $PPHP;
        $db = $PPHP['db'];

        echo "    Installing emails...";
        $db->begin();
        $db->exec(
            "
            CREATE TABLE IF NOT EXISTS 'emails' (
                id          INTEGER PRIMARY KEY AUTOINCREMENT,
                sender      INTEGER NOT NULL DEFAULT '0',
                isSent      BOOL NOT NULL DEFAULT '0',
                modified    TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
                contextType VARCHAR(64) DEFAULT NULL,
                contextId   INTEGER DEFAULT NULL,
                mailfrom    INTEGER NOT NULL DEFAULT '0',
                recipients  VARCHAR(255) NOT NULL DEFAULT '',
                ccs         VARCHAR(255) NOT NULL DEFAULT '',
                bccs        VARCHAR(255) NOT NULL DEFAULT '',
                subject     TEXT NOT NULL DEFAULT '',
                html        TEXT NOT NULL DEFAULT '',
                files       BLOB,
                FOREIGN KEY(sender) REFERENCES users(id)
            )
            "
        );
        $db->commit();
        echo "    done!\n";
    }
439300
public function create_database($database) {
		$query = 'CREATE DATABASE ' . $this->quote_identifier($database);
		$statement = $this->get_statement($query);

		$statement->execute();
	}
1163533
public function createSQL()
	{
		try {

			$lines = array();

			$indices = array();

			$columns = $this->columns;

			$template = "CREATE TABLE %s (\n%s,\n%s\n) ENGINE=%s DEFAULT CHARSET=%s;";

			foreach ($this->columns as $column_name => $column)
			{

				//$column_name = $column["name"];//set the column name

				$data_type = $column["type"];//set the column data type

				$length = $column["length"];//set the lenght of the data type

				if ($column["primary"])	$indices[] = "PRIMARY KEY ({$column_name})"; //add primary key field

				if ($column["index"]) $indices[] = "KEY {$column_name} ({$column_name})"; //add index field

				switch ($data_type)
				{
					case "autonumber":

						$lines[] = "{$column_name} INT(11) NOT NULL AUTO_INCREMENT";

						break;

					case "text":

						if ($length !== null && $length <= 255)	$lines[] = "{$column_name} VARCHAR({$length}) DEFAULT NULL";

						else $lines[] = "{$column_name} text";

						break;

					case "integer":

						$lines[] = "{$column_name} INT(11) DEFAULT NULL";

						break;

					case "decimal":

						$lines[] = "{$column_name} FLOAT DEFAULT NULL";

						break;

					case "boolean":

						$lines[] = "{$column_name} TINYINT(4) DEFAULT NULL";

						break;

					case "datetime":

						$lines[] = "{$column_name} DATETIME DEFAULT NULL";

						break;

				}

			}

			$this->query_string = sprintf($template, $this->table, join(",\n", $lines), join(",\n", $indices), 'InnoDB', 'utf8');//$this->connection->character_set_name()
			
			return $this;

		} catch (MySQLException $e) {

			$e->errorShow();

		}
		
	}
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);
    }
345867
protected function createTables()
    {
        if (empty( self::$tables )) {
            throw new \Exception('Cannot create tables, as no configuration file given, or the ::$tables is not overridden.');
        }
        $client = $this->dynamoDb->getClient();

        foreach (self::$tables as $tableData) {
            $tableName = $tableData['TableName'];

            if ( ! $this->tableExists($tableName)) {
                $this->comment(sprintf('Creating table %s', $tableName));

                $client->createTable($tableData);

                $client->waitUntil('TableExists', array(
                    'TableName' => $tableName,
                ));

                $this->info(sprintf('Table "%s" created.', $tableName));
            } else {
                $this->warn(sprintf('Table "%s" already exists.', $tableName));
            }
        }
    }
828571
protected function createTable()
    {
        if ($this->db->schema->getTableSchema($this->cacheTable) === null) {
            $this->db->createCommand()
                ->createTable($this->cacheTable, [
                    'id' => 'CHAR(128) PRIMARY KEY',
                    'expire' => 'integer',
                    'data' => 'binary',
                ])->execute();
        }
    }
45069
public function createTables()
    {
        $db = $this->getDb();
        $prefixTables = $this->getTablePrefix();

        $tablesAlreadyInstalled = $this->getTablesInstalled();
        $tablesToCreate = $this->getTablesCreateSql();
        unset($tablesToCreate['archive_blob']);
        unset($tablesToCreate['archive_numeric']);

        foreach ($tablesToCreate as $tableName => $tableSql) {
            $tableName = $prefixTables . $tableName;
            if (!in_array($tableName, $tablesAlreadyInstalled)) {
                $db->query($tableSql);
            }
        }
    }
570401
protected function createTable()
	{
		try
		{
			$command=$this->db->createCommand();
			$command->createTable($this->stateTableName,array(
				$this->keyField=>'string NOT NULL',
				$this->valueField=>'text NOT NULL',
				'PRIMARY KEY ('.$this->db->quoteColumnName($this->keyField).')'
			));
		}
		catch (CDbException $e)
		{
			throw new CException(Yii::t('yii','Can\'t create state persister table. Check CREATE privilege for \'{db}\' connection user or create table manually with SQL: {sql}.',array('{db}'=>$this->dbComponent,'{sql}'=>$command->text ) ) );
		}
	}
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;
    }
9052
def _create(self):
    """"""
    from .tools import makedirs_safe

    # create directory for sql database
    makedirs_safe(os.path.dirname(self._database))

    # create all the tables
    Base.metadata.create_all(self._engine)
    logger.debug("Created new empty database '%s'" % self._database)
196415
public function createDatabases()
    {
        foreach ($this->metadataFactory->getAllMetadata() as $class) {
            if ($class->isMappedSuperclass || $class->isEmbeddedDocument) {
                continue;
            }
            $this->createDocumentDatabase($class->name);
        }
    }
341842
protected function connectDatabase()
    {
        if (!$this->databaseConfig) {
            return null;
        }

        $this->databaseConnection = ConnectionManager::create($this->databaseConfig);
    }
867531
public function actionCreate()
    {
        $model = new Dump($this->getModule()->dbList);
        if (ArrayHelper::isIn($this->db, $this->getModule()->dbList)) {
            $dbInfo = $this->getModule()->getDbInfo($this->db);
            $dumpOptions = $model->makeDumpOptions();
            if ($this->gzip) {
                $dumpOptions['isArchive'] = true;
            }
            $manager = $this->getModule()->createManager($dbInfo);
            $dumpPath = $manager->makePath($this->getModule()->path, $dbInfo, $dumpOptions);
            $dumpCommand = $manager->makeDumpCommand($dumpPath, $dbInfo, $dumpOptions);
            Yii::trace(compact('dumpCommand', 'dumpPath', 'dumpOptions'), get_called_class());
            $process = new Process($dumpCommand);
            $process->run();
            if ($process->isSuccessful()) {
                if ($this->storage) {
                    if (Yii::$app->has('backupStorage')) {
                        $dumpText = fopen($dumpPath, 'r+');
                        Yii::$app->backupStorage->writeStream(StringHelper::basename($dumpPath), $dumpText);
                        fclose($dumpText);
                    } else {
                        Console::output('Storage component is not configured.');
                    }
                }
                Console::output('Dump successfully created.');
            } else {
                Console::output('Dump failed create.');
            }
        } else {
            Console::output('Database configuration not found.');
        }
    }
39799
public function createSchema()
    {
        $query = 'CREATE TABLE IF NOT EXISTS `'.self::LIST_COLLECTION_TABLE_NAME.'` (
          `id` int NOT NULL AUTO_INCREMENT,
          `uuid` varchar(255) UNIQUE NOT NULL,
          `headers` text DEFAULT NULL,
          `created_at` TIMESTAMP NOT NULL,
          `updated_at` TIMESTAMP NOT NULL DEFAULT NOW() ON UPDATE NOW(),
          PRIMARY KEY (`id`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8;';

        $this->pdo->exec($query);

        $query2 = 'CREATE TABLE IF NOT EXISTS `'.self::LIST_ELEMENT_TABLE_NAME.'` (
          `id` int NOT NULL AUTO_INCREMENT,
          `uuid` varchar(255) NOT NULL,
          `list` varchar(255) NOT NULL,
          `body` text DEFAULT NULL,
          `created_at` TIMESTAMP NOT NULL,
          `updated_at` TIMESTAMP NOT NULL DEFAULT NOW() ON UPDATE NOW(),
          PRIMARY KEY (`id`),
          CONSTRAINT `list_foreign_key` FOREIGN KEY (`list`) REFERENCES `'.self::LIST_COLLECTION_TABLE_NAME.'`(`uuid`) ON UPDATE CASCADE ON DELETE CASCADE
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8;';

        $this->pdo->exec($query2);
    }
707651
public function runSetup()
    {
        if ($this->params->forceIsActive) {
            $this->consoleWriteLineWithIndent('Force mode active! Database will be generated', Color::YELLOW);
            
            $dbParams          = $this->getDbConnectionParams();    
            $dbConnectionCmd   = $this->getDbConnectionCmd();
            $dropDatabaseCmd   = $dbConnectionCmd . ' -e"DROP DATABASE ' . $dbParams['dbname'] . ';"';
            $createDatabaseCmd = $dbConnectionCmd . ' -e"CREATE DATABASE ' . $dbParams['dbname'] . ';"';
            $createSchemaCmd   = 'php bin/doctrine.php orm:schema-tool:create';
            
            $this->consoleWriteWithIndent('Dropping database... ');
            $output = shell_exec($dropDatabaseCmd);
            $this->consoleWriteLine('done!', Color::GREEN);
            
            $this->consoleWriteWithIndent('Creating database... ');
            $output = shell_exec($createDatabaseCmd);
            $this->consoleWriteLine('done!', Color::GREEN);
            
            $this->consoleWriteWithIndent('Creating tables... ');
            $output = shell_exec($createSchemaCmd);
            $this->consoleWriteLine('done!', Color::GREEN);
        } else {
            $this->consoleWriteLineWithIndent('Nothing to do. For database generating please use --force|-f option.', Color::YELLOW);
        }
    }
1187109
public function setTables()
    {
        foreach ($this->data['tables'] as $alias => $model) {

            // set model => alias (real table name)
            $this->builder->addFrom($model, $alias);

        }

        return null;
    }
19583
protected function createMigrationsTable()
	{
		$db = $this->_context->getDatabase();

		$sql = "SELECT name
				FROM sqlite_master
				WHERE type = 'table' AND name = :table_name";
		$migrations_table = $db->fetchValue($sql, array('table_name' => 'Migrations'));

		if ( $migrations_table !== false ) {
			return;
		}

		$sql = 'CREATE TABLE "Migrations" (
					"Name" TEXT(255,0) NOT NULL,
					"ExecutedOn" INTEGER NOT NULL,
					PRIMARY KEY("Name")
				)';
		$db->perform($sql);
	}