Create the table
@return boolean
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()
    }
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));
            }
        }
    }
1133965
protected function createTables()
    {
        $this->createTable(TokensRecord::tableName(), [
            'id' => $this->primaryKey(),
            'accessToken' => $this->text()->notNull(),
            'refreshToken' => $this->text(),
            'providerId' => $this->integer()->notNull(),
            'values' => $this->text(),
            'enabled' => $this->boolean(),
            'dateExpires' => $this->dateTime(),
            'dateUpdated' => $this->dateTime()->notNull(),
            'dateCreated' => $this->dateTime()->notNull(),
            'uid' => $this->uid()
        ]);

        $this->createTable(ProviderRecord::tableName(), [
            'id' => $this->primaryKey(),
            'handle' => $this->string()->notNull(),
            'clientId' => $this->string(ProviderRecord::CLIENT_ID_LENGTH)->notNull(),
            'clientSecret' => $this->string(ProviderRecord::CLIENT_SECRET_LENGTH),
            'scopes' => $this->string(),
            'class' => $this->string()->notNull(),
            'settings' => $this->text(),
            'enabled' => $this->boolean(),
            'dateUpdated' => $this->dateTime()->notNull(),
            'dateCreated' => $this->dateTime()->notNull(),
            'uid' => $this->uid()
        ]);
    }
25835
protected function createTable()
    {
        if ($this->db->getTableSchema($this->tableName) === null) {
            $this->db->createCommand()
                ->createTable($this->tableName, [
                    'id' => 'pk',
                    'created_at' => 'integer',
                    'updated_at' => 'integer',
                    'data' => 'binary',
                ])->execute();
            $this->db->getTableSchema($this->tableName, true);
        }
    }
821759
public static function create()
    {
        // load session config
        \Config::load('session', true);

        if (\Config::get('session.driver') != 'db')
        {
            // prompt the user to confirm they want to remove the table.
            $continue = \Cli::prompt(\Cli::color('Your current driver type is not set db. Would you like to continue and add the sessions table anyway?', 'yellow'), array('y','n'));

            if ($continue === 'n')
            {
                return \Cli::color('Database sessions table was not created.', 'red');
            }
        }

        if (\DBUtil::table_exists(\Config::get('session.db.table')))
        {
            return \Cli::write('Session table already exists.');
        }

        // create the session table using the table name from the config file
        \DBUtil::create_table(\Config::get('session.db.table'), array(
            'session_id'   => array('constraint' => 40, 'type' => 'varchar'),
            'previous_id'  => array('constraint' => 40, 'type' => 'varchar'),
            'user_agent'   => array('type' => 'text', 'null' => false),
            'ip_hash'      => array('constraint' => 32, 'type' => 'char'),
            'created'      => array('constraint' => 10, 'type' => 'int', 'unsigned' => true),
            'updated'      => array('constraint' => 10, 'type' => 'int', 'unsigned' => true),
            'payload'      => array('type' => 'longtext'),
        ), array('session_id'), false, 'InnoDB', \Config::get('db.default.charset'));

        // make previous_id a unique_key. speeds up query and prevents duplicate id's
        \DBUtil::create_index(\Config::get('session.db.table'), 'previous_id', 'previous_id', 'unique');

        if (\Config::get('session.driver') === 'db')
        {
            // return success message.
            return \Cli::color('Success! Your session table has been created!', 'green');
        }
        else
        {
            // return success message notifying that the driver is not db.
            return \Cli::color('Success! Your session table has been created! Your current session driver type is set to '.\Config::get('session.driver').'. In order to use the table you just created to manage your sessions, you will need to set your driver type to "db" in your session config file.', 'green');
        }
    }
255703
public function table()
    {
        return $this->database ? $this->laravel['db']->connection($this->database)->table(config('database.migrations')) : $this->laravel['db']->table(config('database.migrations'));
    }
267889
public function create()
    {
        $dir = $this->Folder->pwd();

        if (is_dir($dir) && is_writable($dir) && !$this->exists() && touch($this->path)) {
            return true;
        }

        return false;
    }
928105
function tablesCreation()
    {
        $this->checkPiwikIsNotInstalled();

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

        if ($this->getParam('deleteTables')) {
            Manager::getInstance()->clearPluginsInstalledConfig();
            Db::dropAllTables();
            $view->existingTablesDeleted = true;
        }

        $tablesInstalled = DbHelper::getTablesInstalled();
        $view->tablesInstalled = '';

        if (count($tablesInstalled) > 0) {

            // we have existing tables
            $view->tablesInstalled     = implode(', ', $tablesInstalled);
            $view->someTablesInstalled = true;

            $self = $this;
            Access::doAsSuperUser(function () use ($self, $tablesInstalled, $view) {
                Access::getInstance();
                if ($self->hasEnoughTablesToReuseDb($tablesInstalled) &&
                    count(APISitesManager::getInstance()->getAllSitesId()) > 0 &&
                    count(APIUsersManager::getInstance()->getUsers()) > 0
                ) {
                    $view->showReuseExistingTables = true;
                }
            });
        } else {

            DbHelper::createTables();
            DbHelper::createAnonymousUser();
            DbHelper::recordInstallVersion();

            $this->updateComponents();

            Updater::recordComponentSuccessfullyUpdated('core', Version::VERSION);

            $view->tablesCreated = true;
            $view->showNextStep = true;
        }

        return $view->render();
    }
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 ) ) );
		}
	}
1299146
public function construct()
	{
		switch ($this->arguments->getOpt(4))
		{
			case 'for':
				$prefix = App::get('db')->getPrefix();
				$tables = App::get('db')->getTableList();

				if (!$table = $this->arguments->getOpt(5))
				{
					$this->output->error('Please specify the table for which a migration is being created');
				}
				else if (!in_array($table, $tables))
				{
					$this->output->error('Table does not exist');
				}

				$this->addReplacement('description', "creating table {$table}")
					 ->addReplacement('table_name', str_replace($prefix, '#__', $table))
					 ->addReplacement('up', '$^create.table^$')
					 ->addReplacement('down', '$^drop.table^$')
					 ->addReplacement('create_table', $this->showCreateTable($table));
				break;

			default:
				$this->addReplacement('description', '...')
					 ->addReplacement('up', '')
					 ->addReplacement('down', '');
				break;
		}

		// Determine our base path
		$base       = $this->arguments->getOpt('app') ? PATH_APP : PATH_CORE;
		$installDir = trim($this->arguments->getOpt('install-dir'));
		if ($installDir && strlen($installDir) > 0)
		{
			if (substr($installDir, 0, 1) == DS)
			{
				$base = rtrim($installDir, DS);
			}
			else
			{
				$base .= DS . trim($installDir, DS);
			}
		}

		// Install directory is migrations folder within base
		$installDir = $base . DS . 'migrations';

		// Extension
		$extension = null;
		if ($this->arguments->getOpt('e') || $this->arguments->getOpt('extension'))
		{
			$extension = ($this->arguments->getOpt('e')) ? $this->arguments->getOpt('e') : $this->arguments->getOpt('extension');

			if ($extension != 'core' && !$this->isValidExtension($extension, $base) && !$this->arguments->getOpt('i'))
			{
				$this->output->error("Error: the extension provided ({$extension}) does not appear to be valid.");
			}
		}
		else
		{
			$this->output->error("Error: an extension should be provided.");
		}

		// Editor
		$editor = null;
		if ($this->arguments->getOpt('editor'))
		{
			$editor = $this->arguments->getOpt('editor');
		}
		else
		{
			$editor = (getenv('EDITOR')) ? getenv('EDITOR') : 'vi';
		}

		// Create filename varient of extension
		$ext = '';
		if (!preg_match('/core/i', $extension))
		{
			$parts = explode('_', $extension);
			foreach ($parts as $part)
			{
				$ext .= ucfirst($part);
			}
		}
		else
		{
			$ext = 'Core';
		}

		// Craft file/classname
		$classname   = 'Migration' . with(new Date('now'))->format("YmdHis") . $ext;
		$destination = $installDir . DS . $classname . '.php';

		$this->addTemplateFile("{$this->getType()}.tmpl", $destination)
			 ->addReplacement('class_name', $classname)
			 ->make();

		// Open in editor
		system("{$editor} {$destination} > `tty`");
	}
382270
public function make()
    {
        // empty table to start
        $table = [];
        // get the max length of each column in the table
        $field_lengths = $this->maxMultidimensionalArrayStringSize($this->data);
        // get the length of a row by mocking up a row
        $row_length = $this->calculateRowLength($field_lengths, $this->seperator_padding, $this->seperator);
        // get the top and bottom of the table
        $book_end = $this->su->fill($row_length, $this->header_character);
        // get the row that appears below the header row to seperate it from the other rows
        $below_header = $this->su->fill($row_length, $this->below_header_character);
        // add the top $book_end
        $table[] = $book_end;
        // loop over each 'row' in our array
        for ($i = 0; $i < count($this->data); $i++) {
            // line starts as just the left most seperator
            $line = $this->seperator . $this->su->fill($this->seperator_padding);
            // loop over each 'field' aka column in our row
            for ($j = 0; $j < count($this->data[$i]); $j++) {
                // format the fields such that they have a max length of the biggest field in this column
                // and add the additional padding, then pass this to the formatter method and append it to
                // the line and then add the seperator
                $line .= $this->su->{$this->formatter}($this->data[$i][$j], $field_lengths[$j]) . $this->su->fill($this->seperator_padding) . $this->seperator . $this->su->fill($this->seperator_padding);
            }
            // add the new line to the table
            $table[] = $line;
            // if this was the first row we will add a $below_header row to break it up
            if ($i == 0) {
                $table[] = $below_header;
            }
        }
        // add the bottom book end to the table
        $table[] = $book_end;
        // set the table data on the instance
        $this->table = $table;
        return $this;
    }
937017
public function createJoinTable()
    {
        if ($this->joinTableExists() === true) {
            return;
        }

        $q = 'CREATE TABLE \''.$this->joinTable().'\' (
            target_type VARCHAR(255),
            target_id VARCHAR(255),
            target_property VARCHAR(255),
            attachment_type VARCHAR(255),
            attachment_id VARCHAR(255),
            created DATETIME
        )';
        $this->logger->debug($q);
        $this->source()->db()->query($q);
    }
480290
private function create()
	{
		// Add any automatic fields
		$this->parseAutomatics('initiate');
		$data = $this->getTableColumnsOnly();
		return $this->query->push($this->getTableName(), $data);
	}
1026552
final public function create() {

		$app = Application::getInstance();
		$class = get_called_class();
		
		if (!$this->areKeysPopulated() and !$this->db->isAutoIncrement(static::TABLE_NAME)) {
			$app->logEvent('The object’s ' . implode(', ', $this->keyProperties) . ' properties must be populated in order to create a ' . $class . ' record');
			return FALSE;
		}
		
		// hook for tasks to be executed before creation
		$this->beforeCreate();
		
		// get list of class property names
		$props = array_keys(static::getBinds());
		
		// insert the object as db record
		$dbObj = $this->prepareData($props);
		$res = $this->db->insertObject(static::TABLE_NAME, $dbObj);

		// get last insert id if not compound key
		if (!static::hasCompoundKey()) {

			$lastInsertId = $this->db->getLastInsertId();
		
			$key = $this->keyProperties[0];
			
			if ('int' == $this->getPropertyType($key)) {
				$this->{$key} = (int)$lastInsertId;
			} else {
				$this->{$key} = $lastInsertId;
			}
			
		}

		// set logs
		$keyParts = array();
			
		foreach ($this->keyProperties as $prop) {
			$keyParts[] = $prop . '=' . $this->{$prop};
		}
		
		// log as application event
		$app->logEvent('Created a new ' . $class . ' object with ' . implode(', ' , $keyParts));
		
		// hook for tasks to be executed after creation
		$this->afterCreate();
		
		return (bool)$res;
	
	}
818841
protected function createTable()
    {
        $template = file_get_contents(dirname(__FILE__) . '/TableSchema.sql');
        $this->pdo->query(sprintf($template, $this->table));
    }
695777
public function createTable(): void
    {
        // connect if we are not yet
        $conn = $this->getConnection();
        $driver = $this->getDriver();

        if ($conn instanceof Connection) {
            $schema = new Schema();
            $table = $schema->createTable($this->table);
            $table->addColumn($this->idCol, 'string', ['length' => 64]);
            $table->addColumn($this->tokenCol, 'string', ['length' => 44]);
            $table->addColumn($this->expirationCol, 'integer', ['unsigned' => true]);
            $table->setPrimaryKey([$this->idCol]);

            foreach ($schema->toSql($conn->getDatabasePlatform()) as $sql) {
                $conn->exec($sql);
            }

            return;
        }

        switch ($driver) {
            case 'mysql':
                $sql = "CREATE TABLE $this->table ($this->idCol VARCHAR(64) NOT NULL PRIMARY KEY, $this->tokenCol VARCHAR(44) NOT NULL, $this->expirationCol INTEGER UNSIGNED NOT NULL) COLLATE utf8_bin, ENGINE = InnoDB";
                break;
            case 'sqlite':
                $sql = "CREATE TABLE $this->table ($this->idCol TEXT NOT NULL PRIMARY KEY, $this->tokenCol TEXT NOT NULL, $this->expirationCol INTEGER)";
                break;
            case 'pgsql':
                $sql = "CREATE TABLE $this->table ($this->idCol VARCHAR(64) NOT NULL PRIMARY KEY, $this->tokenCol VARCHAR(64) NOT NULL, $this->expirationCol INTEGER)";
                break;
            case 'oci':
                $sql = "CREATE TABLE $this->table ($this->idCol VARCHAR2(64) NOT NULL PRIMARY KEY, $this->tokenCol VARCHAR2(64) NOT NULL, $this->expirationCol INTEGER)";
                break;
            case 'sqlsrv':
                $sql = "CREATE TABLE $this->table ($this->idCol VARCHAR(64) NOT NULL PRIMARY KEY, $this->tokenCol VARCHAR(64) NOT NULL, $this->expirationCol INTEGER)";
                break;
            default:
                throw new \DomainException(sprintf('Creating the lock table is currently not implemented for PDO driver "%s".', $driver));
        }

        $conn->exec($sql);
    }
842178
public function create () : bool
	{
        $dbObject 	= Database::getInstance();
		$attributes = $this->sanitizedAttributes();
		$sqlQuery	= "INSERT INTO ".static::$tableName." (";
		$sqlQuery  .= join(", ", array_keys($attributes));
	  	$sqlQuery  .= ") VALUES ('";
		$sqlQuery  .= join("', '", array_values($attributes));
		$sqlQuery  .= "')";
		$result 	= $dbObject->query($sqlQuery);
    	$this->id 	= $dbObject->insertId();
    	return ($result) ? TRUE : FALSE;
	}