Returns Phinx type by SQL type

@param string $sqlTypeDef SQL type

@returns array Phinx type
17684
public function getPhinxType($sqlTypeDef)
    {
        if (!preg_match('/^([\w]+)(\(([\d]+)*(,([\d]+))*\))*$/', $sqlTypeDef, $matches)) {
            throw new \RuntimeException('Column type ' . $sqlTypeDef . ' is not supported');
        }

        $limit = null;
        $precision = null;
        $type = $matches[1];
        if (count($matches) > 2) {
            $limit = $matches[3] ?: null;
        }
        if (count($matches) > 4) {
            $precision = $matches[5];
        }
        switch ($matches[1]) {
            case 'varchar':
                $type = static::PHINX_TYPE_STRING;
                if ($limit === 255) {
                    $limit = null;
                }
                break;
            case 'char':
                $type = static::PHINX_TYPE_CHAR;
                if ($limit === 255) {
                    $limit = null;
                }
                if ($limit === 36) {
                    $type = static::PHINX_TYPE_UUID;
                }
                break;
            case 'int':
                $type = static::PHINX_TYPE_INTEGER;
                if ($limit === 11) {
                    $limit = null;
                }
                break;
            case 'bigint':
                if ($limit === 11) {
                    $limit = null;
                }
                $type = static::PHINX_TYPE_BIG_INTEGER;
                break;
            case 'blob':
                $type = static::PHINX_TYPE_BINARY;
                break;
        }
        if ($type === 'tinyint') {
            if ($matches[3] === 1) {
                $type = static::PHINX_TYPE_BOOLEAN;
                $limit = null;
            }
        }

        $this->getSqlType($type);

        return [
            'name' => $type,
            'limit' => $limit,
            'precision' => $precision,
        ];
    }
288186
protected function getColumnSqlDefinition(Column $column)
    {
        $buffer = [];
        if ($column->isIdentity()) {
            $buffer[] = $column->getType() === 'biginteger' ? 'BIGSERIAL' : 'SERIAL';
        } else {
            $sqlType = $this->getSqlType($column->getType(), $column->getLimit());
            $buffer[] = \strtoupper($sqlType['name']);
            // integers cant have limits in postgres
            if (static::PHINX_TYPE_DECIMAL === $sqlType['name'] && ($column->getPrecision() || $column->getScale())) {
                $buffer[] = \sprintf(
                    '(%s, %s)',
                    $column->getPrecision() ?: $sqlType['precision'],
                    $column->getScale() ?: $sqlType['scale']
                );
            } elseif ($sqlType['name'] === 'geography') {
                // geography type must be written with geometry type and srid, like this: geography(POLYGON,4326)
                $buffer[] = \sprintf(
                    '(%s,%s)',
                    \strtoupper($sqlType['type']),
                    $sqlType['srid']
                );
            } elseif (!\in_array($sqlType['name'], ['integer', 'smallint', 'bigint'], true)) {
                if ($column->getLimit() || isset($sqlType['limit'])) {
                    $buffer[] = sprintf('(%s)', $column->getLimit() ?: $sqlType['limit']);
                }
            }

            $timeTypes = [
                'time',
                'timestamp',
            ];
            if (in_array($sqlType['name'], $timeTypes) && $column->isTimezone()) {
                $buffer[] = strtoupper('with time zone');
            }
        }

        $buffer[] = $column->isNull() ? 'NULL' : 'NOT NULL';

        if (null !== $column->getDefault()) {
            $buffer[] = $this->getDefaultValueDefinition($column->getDefault());
        }

        return implode(' ', $buffer);
    }
1086303
private function sqlsrvtype2moodletype($sqlsrv_type) {
        $type = null;

        switch (strtoupper($sqlsrv_type)) {
          case 'BIT':
           $type = 'L';
           break;

          case 'INT':
          case 'SMALLINT':
          case 'INTEGER':
          case 'BIGINT':
           $type = 'I';
           break;

          case 'DECIMAL':
          case 'REAL':
          case 'FLOAT':
           $type = 'N';
           break;

          case 'VARCHAR':
          case 'NVARCHAR':
           $type = 'C';
           break;

          case 'TEXT':
          case 'NTEXT':
          case 'VARCHAR(MAX)':
          case 'NVARCHAR(MAX)':
           $type = 'X';
           break;

          case 'IMAGE':
          case 'VARBINARY':
          case 'VARBINARY(MAX)':
           $type = 'B';
           break;

          case 'DATETIME':
           $type = 'D';
           break;
         }

        if (!$type) {
            throw new dml_exception('invalidsqlsrvnativetype', $sqlsrv_type);
        }
        return $type;
    }
293768
protected function getDoctrineColumnType($type)
	{
		$type = strtolower($type);

		switch ($type) {
			case 'biginteger':
				$type = 'bigint';
				break;
			case 'smallinteger':
				$type = 'smallint';
				break;
			case 'mediumtext':
			case 'longtext':
				$type = 'text';
				break;
		}

		return Type::getType($type);
	}
1371669
function generateTableSQL( $tableName, $tableDef, $params, $asArray, $separateTypes = false )
    {
        $diffFriendly = isset( $params['diff_friendly'] ) ? $params['diff_friendly'] : false;
        $mysqlCompatible = isset( $params['compatible_sql'] ) ? $params['compatible_sql'] : false;

        if ( $asArray )
        {
            if ( $separateTypes )
            {
                $sqlList = array( 'tables' => array() );
            }
            else
            {
                $sqlList = array();
            }
        }

        $sql = '';
        $skip_pk = false;
        $sql_fields = array();
        $sql .= "CREATE TABLE $tableName (\n";

        $fields = $tableDef['fields'];

        foreach ( $fields as $field_name => $field_def )
        {
            $sql_fields[] = '  ' . eZMysqlSchema::generateFieldDef( $field_name, $field_def, $skip_pk_flag, $params );
            if ( $skip_pk_flag )
            {
                $skip_pk = true;
            }
        }

        // Make sure the order is as defined by 'offset'
        $indexes = $tableDef['indexes'];

        // We need to add all keys in table definition
        foreach ( $indexes as $index_name => $index_def )
        {
            $sql_fields[] = ( $diffFriendly ? '' : '  ' ) . eZMysqlSchema::generateAddIndexSql( $tableName, $index_name, $index_def, $params, true );
        }
        $sql .= join( ",\n", $sql_fields );
        $sql .= "\n)";

        // Add some extra table options if they are required
        $extraOptions = array();
        if ( isset( $params['table_type'] ) and $params['table_type'] )
        {
            $typeName = $this->tableStorageTypeName( $params['table_type'] );
            if ( $typeName )
            {
                $extraOptions[] = "ENGINE=" . $typeName;
            }
        }
        if ( isset( $params['table_charset'] ) and $params['table_charset'] )
        {
            $charsetName = $this->tableCharsetName( $params['table_charset'] );
            if ( $charsetName )
            {
                $extraOptions[] = "DEFAULT CHARACTER SET " . $charsetName;
            }
        }
        if ( isset( $tableDef['options'] ) )
        {
            foreach( $tableDef['options'] as $optionType => $optionValue )
            {
                $optionText = $this->generateTableOption( $tableName, $tableDef, $optionType, $optionValue, $params );
                if ( $optionText )
                    $extraOptions[] = $optionText;
            }
        }

        if ( count( $extraOptions ) > 0 )
        {
            $sql .= " " . implode( $diffFriendly ? "\n" : " ", $extraOptions );
        }

        if ( $asArray )
        {
            if ( $separateTypes )
            {
                $sqlList['tables'][] = $sql;
            }
            else
            {
                $sqlList[] = $sql;
            }
        }
        else
        {
            $sql .= ";\n";

            if ( $mysqlCompatible )
            {
                $sql .= "\n\n\n";
            }
        }

        return $asArray ? $sqlList : $sql;
    }
436118
def getTypeInfo(self, sql_type):  # nopep8
        
        fut = self._run_operation(self._impl.getTypeInfo, sql_type)
        return fut
1015627
private function getAlterColumnClausesSQL(ColumnDiff $columnDiff)
    {
        $column = $columnDiff->column->toArray();

        $alterClause = 'ALTER COLUMN ' . $columnDiff->column->getQuotedName($this);

        if ($column['columnDefinition']) {
            return [$alterClause . ' ' . $column['columnDefinition']];
        }

        $clauses = [];

        if ($columnDiff->hasChanged('type') ||
            $columnDiff->hasChanged('length') ||
            $columnDiff->hasChanged('precision') ||
            $columnDiff->hasChanged('scale') ||
            $columnDiff->hasChanged('fixed')
        ) {
            $clauses[] = $alterClause . ' SET DATA TYPE ' . $column['type']->getSQLDeclaration($column, $this);
        }

        if ($columnDiff->hasChanged('notnull')) {
            $clauses[] = $column['notnull'] ? $alterClause . ' SET NOT NULL' : $alterClause . ' DROP NOT NULL';
        }

        if ($columnDiff->hasChanged('default')) {
            if (isset($column['default'])) {
                $defaultClause = $this->getDefaultValueDeclarationSQL($column);

                if ($defaultClause) {
                    $clauses[] = $alterClause . ' SET' . $defaultClause;
                }
            } else {
                $clauses[] = $alterClause . ' DROP DEFAULT';
            }
        }

        return $clauses;
    }
276553
protected function getMySQLColumnType($columnData)
    {
        $type = $columnData['COLUMN_TYPE'];
        $pattern = '/^[a-z]+/';
        $match = null;
        preg_match($pattern, $type, $match);

        return $match[0];
    }
91957
protected function columnTypeToHintType($type) {
		if (static::$typeMap === null) {
			static::$typeMap = (array)Configure::read('IdeHelper.typeMap') + static::$typeMapDefaults;
		}

		if (isset(static::$typeMap[$type])) {
			return static::$typeMap[$type];
		}

		return null;
	}
1353420
private function mergeTableDefs(array $tableDef, array $alterDef) {
        $result = $tableDef;

        if ($this->findPrimaryKeyIndex($alterDef['add']['indexes'])) {
            $remove = null;
            foreach ($result['indexes'] as $i => $index) {
                if ($index['type'] === Db::INDEX_PK) {
                    $remove = $i;
                }
            }
            if ($remove !== null) {
                unset($result['indexes'][$i]);
            }
        }

        $result['columns'] = array_merge($result['columns'], $alterDef['def']['columns']);
        $result['indexes'] = array_merge($result['indexes'], $alterDef['add']['indexes']);

        return $result;
    }
701542
public function getTypeQuery()
    {

        switch( true ) {

            case $this->name === 'timestamp':
            case $this->name === 'bool':

                return $this->name;

            case $this->isEnum(): // enum's behave like strings

                return $this->name;

            case $this->name === 'bpchar': // "blank-padded char", the internal name of the 'character' data type
            case $this->name === 'text':

                return 'text';

            case $this->name === 'int2':
            case $this->name === 'int4':
            case $this->name === 'int8':

                return 'int';

            default:

                return $this->name;
                throw new \UnexpectedValueException( "type::pgTypeToQueryValidateType doesnt know about type `{$type}`" );

        }

    }
112340
protected function getPhinxColumnEncoding(string $phinxType, array $attributes, array $columnData): array
    {
        $allowedTypes = [
            AdapterInterface::PHINX_TYPE_CHAR,
            AdapterInterface::PHINX_TYPE_STRING,
            AdapterInterface::PHINX_TYPE_TEXT,
        ];
        if (!in_array($phinxType, $allowedTypes)) {
            return $attributes;
        }

        if (!empty($columnData['CHARACTER_SET_NAME'])) {
            $attributes['encoding'] = $columnData['CHARACTER_SET_NAME'];
        }

        return $attributes;
    }
336444
public function getTables($dbType, $dbDescription)
    {
        $db = $this->_connect($dbType, $dbDescription);
        return $db->listTables();
    }
1044630
protected function getPhinxColumnOptions($phinxType, $columnData, $columns)
    {
        $attributes = [];

        $attributes = $this->getPhinxColumnOptionsNull($attributes, $columnData);

        // default value
        $attributes = $this->getPhinxColumnOptionsDefault($attributes, $columnData);

        // For timestamp columns:
        $attributes = $this->getPhinxColumnOptionsTimestamp($attributes, $columnData);

        // limit / length
        $attributes = $this->getPhinxColumnOptionsLimit($attributes, $columnData);

        // numeric attributes
        $attributes = $this->getPhinxColumnOptionsNumeric($attributes, $columnData);

        // enum values
        if ($phinxType === 'enum') {
            $attributes = $this->getOptionEnumValue($attributes, $columnData);
        }

        // Collation
        $attributes = $this->getPhinxColumnCollation($phinxType, $attributes, $columnData);

        // Encoding
        $attributes = $this->getPhinxColumnEncoding($phinxType, $attributes, $columnData);

        // Comment
        $attributes = $this->getPhinxColumnOptionsComment($attributes, $columnData);

        // after: specify the column that a new column should be placed after
        $attributes = $this->getPhinxColumnOptionsAfter($attributes, $columnData, $columns);

        // @todo
        // update set an action to be triggered when the row is updated (use with CURRENT_TIMESTAMP)
        //
        // For foreign key definitions:
        // update set an action to be triggered when the row is updated
        // delete set an action to be triggered when the row is deleted

        $result = '[' . implode(', ', $attributes) . ']';

        return $result;
    }
1230818
public function convertDiffToDDL( ezcDbSchemaDiff $dbSchemaDiff )
    {
        $this->diffSchema = $dbSchemaDiff;

        // reset queries
        $this->queries = array();
        $this->context = array();

        $this->generateDiffSchemaAsSql();
        return $this->queries;
    }
145070
public function getConditionSql(array $sql, array $where, string $conditionType): array
    {
        if (empty($where)) {
            return $sql;
        }
        foreach ($where as $index => $item) {
            if ($item instanceof RawExp) {
                if ($index == 0) {
                    $sql[] = $conditionType . ' ' . $item->getValue();
                    continue;
                }
                $sql[] = $item->getValue();
                continue;
            }
            [$type, $conditions] = $item;
            if (!$index) {
                $whereType = $conditionType;
            } else {
                $whereType = strtoupper($type);
            }
            if ($conditions[0] instanceof RawExp) {
                $sql[] = $whereType . ' ' . $conditions[0]->getValue();
                continue;
            }
            [$leftField, $operator, $rightField] = $conditions;
            $leftField = $this->quoter->quoteName($leftField);
            [$rightField, $operator] = $this->getRightFieldValue($rightField, $operator);

            $sql[] = sprintf('%s %s %s %s', $whereType, $leftField, $operator, $rightField);
        }

        return $sql;
    }
785216
public static function detect_pod_field_from_sql_data_type( $sql_field ) {

		$sql_field = strtolower( $sql_field );

		$field_to_field_map = array(
			'tinyint'    => 'number',
			'smallint'   => 'number',
			'mediumint'  => 'number',
			'int'        => 'number',
			'bigint'     => 'number',
			'float'      => 'number',
			'double'     => 'number',
			'decimal'    => 'number',
			'date'       => 'date',
			'datetime'   => 'datetime',
			'timestamp'  => 'datetime',
			'time'       => 'time',
			'year'       => 'date',
			'varchar'    => 'text',
			'text'       => 'paragraph',
			'mediumtext' => 'paragraph',
			'longtext'   => 'paragraph'
		);

		return ( array_key_exists( $sql_field, $field_to_field_map ) ) ? $field_to_field_map[ $sql_field ] : 'paragraph';
	}