Create a unique token.

@param string $table
@param string $col
@param integer $size
@param bool $withSpecialCharacters
@return string
@throws \Exception
485958
public function unique($table, $col, $size, $withSpecialCharacters = false)
    {
        do {
            $token = $this->random($size, $withSpecialCharacters);

            $exists = DB::table($table)->where($col, $token)->exists();
        } while ($exists);

        return $token;
    }
271830
public static function createIndex($table, $columns, $unique = false)
    {
        return Yii::$app->db->createCommand()
            ->createIndex($table .'_'.implode('-', (array) $columns) . '_idx', $table, $columns, $unique)
            ->execute();
    }
1110144
protected function alterTableAlterColumn($tableName, $colName, $colSpec)
    {

        // First, we split the column specifications into parts
        // TODO: this returns an empty array for the following string: int(11) not null auto_increment
        //		 on second thoughts, why is an auto_increment field being passed through?
        $pattern = '/^(?<definition>[\w()]+)\s?(?<null>(?:not\s)?null)?\s?(?<default>default\s[\w\']+)?\s?(?<check>check\s?[\w()\'",\s]+)?$/i';
        $matches = array();
        preg_match($pattern, $colSpec, $matches);

        // drop the index if it exists
        $alterQueries = array();

        // drop *ALL* indexes on a table before proceeding
        // this won't drop primary keys, though
        $indexes = $this->indexNames($tableName);
        $indexes = array_filter($indexes);

        foreach ($indexes as $indexName) {
            $alterQueries[] = "IF EXISTS (SELECT name FROM sys.indexes WHERE name = '$indexName' AND object_id = object_id(SCHEMA_NAME() + '.$tableName')) DROP INDEX \"$indexName\" ON \"$tableName\";";
        }

        $prefix = "ALTER TABLE \"$tableName\" ";

        // Remove the old default prior to adjusting the column.
        if ($defaultConstraintName = $this->defaultConstraintName($tableName, $colName)) {
            $alterQueries[] = "$prefix DROP CONSTRAINT \"$defaultConstraintName\";";
        }

        if (isset($matches['definition'])) {
            //We will prevent any changes being made to the ID column.  Primary key indexes will have a fit if we do anything here.
            if ($colName != 'ID') {

                // SET null / not null
                $nullFragment = empty($matches['null']) ? '' : " {$matches['null']}";
                $alterQueries[] = "$prefix ALTER COLUMN \"$colName\" {$matches['definition']}$nullFragment;";

                // Add a default back
                if (!empty($matches['default'])) {
                    $alterQueries[] = "$prefix ADD {$matches['default']} FOR \"$colName\";";
                }

                // SET check constraint (The constraint HAS to be dropped)
                if (!empty($matches['check'])) {
                    $constraint = $this->getConstraintName($tableName, $colName);
                    if ($constraint) {
                        $alterQueries[] = "$prefix DROP CONSTRAINT {$constraint};";
                    }

                    //NOTE: 'with nocheck' seems to solve a few problems I've been having for modifying existing tables.
                    $alterQueries[] = "$prefix WITH NOCHECK ADD CONSTRAINT \"{$tableName}_{$colName}_check\" {$matches['check']};";
                }
            }
        }

        return implode("\n", $alterQueries);
    }
844662
public function createTable($name, $fields, array $constraints=[], $ifNotExists=TRUE)
	{
		$existsStr = $ifNotExists ? ' IF NOT EXISTS ' : ' ';

		// Reorganize into an array indexed with column information
		// Eg $columnArray[$colname] = array(
		// 		'type' => ...,
		// 		'constraint' => ...,
		// 		'index' => ...,
		// )
		$columnArray = \arrayZipper([
			'type' => $fields,
			'constraint' => $constraints
		]);

		// Join column definitions together
		$columns = [];
		foreach($columnArray as $n => $props)
		{
			$str = $this->getDriver()->quoteIdent($n);
			$str .= isset($props['type']) ? " {$props['type']}" : "";
			$str .= isset($props['constraint']) ? " {$props['constraint']}" : "";

			$columns[] = $str;
		}

		// Generate the sql for the creation of the table
		$sql = 'CREATE TABLE'.$existsStr.$this->getDriver()->quoteTable($name).' (';
		$sql .= implode(', ', $columns);
		$sql .= ')';

		return $sql;
	}
608232
private function createIndex(Table $table, array $columns)
    {
        if (count($columns) > 0) {
            $indexPrefix = "idx_" . RdsDeliveryExecutionService::TABLE_NAME . "_";

            // Index names are limited to 63 characters in PostgreSQL (64 in MySQL)
            $indexName = substr($indexPrefix . implode("_", $columns), 0, 63);

            $table->addIndex($columns, $indexName);
        }
    }
1564
public function createIntegerColumn(string $name, int $size, bool $signed = true): IntegerColumn {
		$column = new SqliteIntegerColumn($name);
		$this->table->addColumn($column);
		return $column;
	}
297524
public function uniqueNumber($table, $column, $size, $withSpecialCharacters = false)
    {
        do {
            $token = $this->randomNumber($size, $withSpecialCharacters);

            $exists = DB::table($table)->where($column, $token)->exists();
        } while ($exists);

        return $token;
    }
20292
public function col_full_name($col, $table='', $escaped=false)
  {
    if ( \is_string($col) && ($col = trim($col)) ){
      $mcol = explode(".", str_replace("`", "", $col));
      if ( \count($mcol) > 1 ){
        $col = array_pop($mcol);
        $table = array_pop($mcol);
        $ok = 1;
      }
      else if ( !empty($table) ){
        $table = $this->table_simple_name($table);
        $col = end($mcol);
        $ok = 1;
      }
      if ( isset($ok) && bbn\str::check_name($table, $col) ){
        return $escaped ? "`".$table."`.`".$col."`" : $table.".".$col;
      }
    }
		return false;
  }
28215
private function sql_handle_col( $col, $table ) {
		global $wpdb;

		$table_sql = $this->esc_sql_ident( $table );
		$col_sql   = $this->esc_sql_ident( $col );

		$count = $wpdb->query( $wpdb->prepare( "UPDATE $table_sql SET $col_sql = REPLACE($col_sql, %s, %s);", $this->old, $this->new ) );

		return $count;
	}
752713
public function buildQuery(string $table, array $colVals): SqlParams
    {
        self::validateColValsStructure($colVals);

        $columns = $this->escapeColumns(array_keys($colVals[0]));
        $insert = "INSERT INTO {$table} (" . implode(', ', $columns) . ')';

        $valSetStr = ' (' . str_repeat('?,', count($columns) - 1) . '?),';
        $valStr = ' VALUES' . substr_replace(str_repeat($valSetStr, count($colVals)), '', -1); // remove trailing comma
        $params = array_merge(...array_map('array_values', $colVals));

        if ($this->options instanceof \PeachySQL\SqlServer\Options) {
            $selStr = '; SELECT SCOPE_IDENTITY() AS RowID;';
        } else {
            $selStr = '';
        }

        return new SqlParams($insert . $valStr . $selStr, $params);
    }
558623
public function buildTable(Schema $schema, $aliasName, $charset, $collate)
    {
        $tableName = $this->tablePrefix . $aliasName;
        $this->table = $schema->createTable($tableName);
        $this->table->addOption('alias', $aliasName);
        $this->table->addOption('charset', $charset);
        $this->table->addOption('collate', $collate);
        $this->aliasName = $aliasName;
        $this->tableName = $this->table->getName();
        $this->addColumns();
        $this->addIndexes();
        $this->setPrimaryKey();
        $this->addForeignKeyConstraints();

        return $this->table;
    }
1029885
protected function readEnabledTokenByColumnWithExpirationCheck(
        string $identifier,
        string $column,
        int $expirationInSeconds,
        string $createdAtColumn,
        array $columns = ['*']
    ): ?TokenInterface {
        try {
            $query = $this->createEnabledTokenByColumnWithExpirationCheckQuery(
                $identifier,
                $column,
                $expirationInSeconds,
                $createdAtColumn,
                $columns
            );

            $statement = $query->execute();
            $statement->setFetchMode(PDO::FETCH_CLASS, $this->getClassName());
            $result = $statement->fetch();

            return $result === false ? null : $result;
        } /** @noinspection PhpRedundantCatchClauseInspection */ catch (DBALException $exception) {
            $message = 'Reading token failed.';
            throw new RepositoryException($message, 0, $exception);
        }
    }
594189
public function create($columns, $engine = 'MyISAM', $charset = 'utf8')
    {
        $schema = $comma = $isNull = $tableKey = $type = '';

        $schema .= strtoupper(__FUNCTION__).' TABLE IF NOT EXISTS
        `'.$this->database.'`.`'.$this->tableName.'` (';
        $arrCount = count($columns);
        $i = 0;

        foreach ($columns as $key => $value) {
            $increment = (isset($value['increment'])) ? 'AUTO_INCREMENT' : '';
            if (isset($value['key'])) {
                $tableKey = strtoupper($value['key']).' ';

                if ($value['key'] == 'primary') {
                    $tableKey = 'PRIMARY KEY';
                }
            } else {
                $tableKey = '';
            }

            $isNull = (isset($value['null']) &&
                $value['null'] == true
            ) ? ' DEFAULT NULL' : ' NOT NULL';

            switch (strtolower($value['type'])) {

                case 'int':
                    $len = (isset($value['length'])) ? $value['length'] : 11;
                    list($type, $length) = $this->columnType($value['type'], $len);
                    break;
                case 'char':
                    list($type, $length) = $this->columnType($value['type'], $value['length'], 2);
                    break;
                case 'string':
                    list($type, $length) = $this->columnType('varchar', $value['length'], 200);
                    break;
                case 'text':
                    $type = 'TEXT';
                    break;
                case 'longtext':
                    $type = $value['type'];
                    break;
                case 'float':
                    list($type, $length) = $this->columnType($value['type'], $value['length'], '10,2');
                    break;
                case 'decimal':
                    list($type, $length) = $this->columnType($value['type'], $value['length'], '10,2');
                    break;
                case 'enum':
                    $length = implode('","', $value['length']);
                    $type = strtoupper($value['type']).'("'.$length.'")'.(isset($value['default']) ?  " DEFAULT '".$value['default']."'" : '');
                    break;
                case 'date':
                    $type = 'date';
                    break;
                case 'datetime':
                    $len = (isset($value['length'])) ? $value['length'] : "NOT NULL DEFAULT '0000:00:00 00:00:00'";
                    $type = strtoupper($value['type']).' '.$len;
                    $isNull = '';
                    break;
                case 'time':
                    $type = 'time';
                    break;
                case 'timestamp':
                    $len = (isset($value['length'])) ? $value['length'] : '';
                    $type = strtoupper($value['type']).' '.$len;
                    break;
            }

            $comma = ($i < $arrCount - 1) ? ',' : '';

            $schema .= '`'.$value['column'].'` '.strtoupper($type).' '
                .$increment.' '.$tableKey.PHP_EOL.$isNull.PHP_EOL;
            $schema .= $comma;

            $i++;
        }

        $schema .= ') ENGINE='.$engine.' DEFAULT  CHARSET='.$charset.';'.PHP_EOL;

        $this->schema = $schema;

        return $this;
    }
664088
public function createStringColumn(string $name, int $length, string $charset = null): StringColumn {
		$column = new CommonStringColumn($name, $length, $charset);
		$this->table->addColumn($column);
		return $column;
	}
1173031
public function specifyIdentifier($columnName, $size)
    {
        $this->identifier = $columnName;
        $this->identifierSize = $size;
        $this->setPrimaryKey($columnName);
    }
825857
protected function createTokensTable(Connection $connection, DatabaseSchemaInterface $schema): void
    {
        $manager = $connection->getSchemaManager();

        $table = new Table($schema->getTokensTable());
        $table->addColumn($schema->getTokensIdentityColumn(), Type::INTEGER)
            ->setNotnull(true)->setAutoincrement(true)->setUnsigned(true);
        $table->addColumn($schema->getTokensIsEnabledColumn(), Type::BOOLEAN)->setNotnull(true)->setDefault(true);
        $table->addColumn($schema->getTokensIsScopeModified(), Type::BOOLEAN)->setNotnull(true)->setDefault(false);
        $table->addColumn($schema->getTokensClientIdentityColumn(), Type::STRING)->setNotnull(true);
        $table->addColumn($schema->getTokensUserIdentityColumn(), Type::INTEGER)->setNotnull(false)->setUnsigned(true);
        $table->addColumn($schema->getTokensRedirectUriColumn(), Type::STRING)->setNotnull(false);
        $table->addColumn($schema->getTokensCodeColumn(), Type::STRING)->setNotnull(false);
        $table->addColumn($schema->getTokensTypeColumn(), Type::STRING)->setNotnull(false);
        $table->addColumn($schema->getTokensValueColumn(), Type::STRING)->setNotnull(false);
        $table->addColumn($schema->getTokensRefreshColumn(), Type::STRING)->setNotnull(false);
        $table->addColumn($schema->getTokensCodeCreatedAtColumn(), Type::DATETIME)->setNotnull(false);
        $table->addColumn($schema->getTokensValueCreatedAtColumn(), Type::DATETIME)->setNotnull(false);
        $table->addColumn($schema->getTokensRefreshCreatedAtColumn(), Type::DATETIME)->setNotnull(false);
        $table->setPrimaryKey([$schema->getTokensIdentityColumn()]);

        $table->addForeignKeyConstraint(
            $schema->getClientsTable(),
            [$schema->getTokensClientIdentityColumn()],
            [$schema->getClientsIdentityColumn()],
            $this->getOnDeleteCascadeConstraint()
        );

        $usersTable          = $schema->getUsersTable();
        $usersIdentityColumn = $schema->getUsersIdentityColumn();
        if ($usersTable !== null && $usersIdentityColumn !== null) {
            $table->addForeignKeyConstraint(
                $usersTable,
                [$schema->getTokensUserIdentityColumn()],
                [$usersIdentityColumn],
                $this->getOnDeleteCascadeConstraint()
            );
        }

        $manager->dropAndCreateTable($table);
    }
391057
public function create($ifNotExists = false, $charset = 'utf8', $collate = 'utf8_unicode_ci')
    {
        $query = MysqlGrammar::createDatabase($this->name, $ifNotExists, $charset, $collate);

        $this->db->setQuery($query)->execute();

        return $this;
    }