Parses a Blob column to its SQL representation

@param Column\Blob $column
@return string
196370
protected function _getBlobColumn(Column\Blob $column)
    {
        return sprintf(
            '%s BLOB%s%s',
            $column->getName(),
            $this->_columnLength($column),
            $this->_nullableColumn($column)
        );
    }
412067
protected function getColumnSqlDefinition(Column $column)
    {
        $sqlType = $this->getSqlType($column->getType());
        $def = '';
        $def .= strtoupper($sqlType['name']);
        if ($column->getPrecision() && $column->getScale()) {
            $def .= '(' . $column->getPrecision() . ',' . $column->getScale() . ')';
        }
        $limitable = in_array(strtoupper($sqlType['name']), $this->definitionsWithLimits);
        if (($column->getLimit() || isset($sqlType['limit'])) && $limitable) {
            $def .= '(' . ($column->getLimit() ?: $sqlType['limit']) . ')';
        }
        if (($values = $column->getValues()) && is_array($values)) {
            $def .= " CHECK({$column->getName()} IN ('" . implode("', '", $values) . "'))";
        }

        $default = $column->getDefault();

        $def .= ($column->isNull() || is_null($default)) ? ' NULL' : ' NOT NULL';
        $def .= $this->getDefaultValueDefinition($default);
        $def .= ($column->isIdentity()) ? ' PRIMARY KEY AUTOINCREMENT' : '';

        if ($column->getUpdate()) {
            $def .= ' ON UPDATE ' . $column->getUpdate();
        }

        $def .= $this->getCommentDefinition($column);

        return $def;
    }
880934
protected function parseSortColumn($column)
    {
        // Parse column specification, considering possible ansi sql quoting
        // Note that table prefix is allowed, but discarded
        if (preg_match('/^("?(?<table>[^"\s]+)"?\\.)?"?(?<column>[^"\s]+)"?(\s+(?<direction>((asc)|(desc))(ending)?))?$/i', $column, $match)) {
            $table = $match['table'];
            $column = $match['column'];
        } else {
            throw new InvalidArgumentException("Invalid sort() column");
        }
        return array($table, $column);
    }
355170
protected function parseFile($file)
    {
        $this->file    = $file;
        // When running as a PHAR, copy the SQLite database
        // to a temporary file. Required as the SQLite3 driver
        // does not support streams (and it can"t, see #55154).
        if (!strncasecmp(__FILE__, 'phar://', 7)) {
            $this->file = tempnam(
                sys_get_temp_dir(),
                'Wordlists'
            );
            copy($file, $this->file);
        }

        $this->db   = new \PDO('sqlite:' . $this->file);
        $metadata   = $this->db->query(
            'SELECT type, value '.
            'FROM metadata '.
            'ORDER BY type ASC, id ASC'
        );
        foreach ($metadata as $row) {
            if (!array_key_exists($row['type'], $this->metadata)) {
                continue;
            }
            if (is_array($this->metadata[$row['type']])) {
                $this->metadata[$row['type']][] = $row['value'];
            } else {
                $this->metadata[$row['type']] = $row['value'];
            }
        }

        // Try to create a collator for the given locale.
        $this->collator = new \Collator(
            str_replace('-', '_', $this->metadata['locale'])
        );
        // -127 = U_USING_DEFAULT_WARNING
        // -128 = U_USING_FALLBACK_WARNING.
        //    0 = U_ZERO_ERROR (no error).
        if (!in_array(intl_get_error_code(), array(-127, -128, 0))) {
            throw new \Erebot\InvalidValueException(
                "Invalid locale (".$this->metadata['locale']."): ".
                intl_get_error_message()
            );
        }
        // Ignore differences in case, accents and punctuation.
        $this->collator->setStrength(\Collator::PRIMARY);

        $this->countQuery = $this->db->prepare(
            'SELECT COUNT(1) '.
            'FROM words'
        );

        $this->getQuery = $this->db->prepare(
            'SELECT value '.
            'FROM words '.
            'ORDER BY sortkey ASC '.
            'LIMIT 1 OFFSET :offset'
        );

        $this->existsQuery = $this->db->prepare(
            'SELECT value '.
            'FROM words '.
            'WHERE sortkey = :key '.
            'LIMIT 1'
        );
    }
1211234
protected function mapColumnTypeToFieldType(Column $column)
    {
        foreach ($this->typesMap as $type => $classes) {
            if (in_array($typeClass = $this->columnType($column), $classes, true)) {
                if ('StringType' === $typeClass) {
                    if (connection('mysql') && null === $column->getLength()) {
                        return 'radio';
                    }
                }

                return $type;
            }
        }

        return 'text';
    }
762062
protected function getAccessorLazyLoadSnippet(Column $column)
    {
        if ($column->isLazyLoad()) {
            $clo = $column->getLowercasedName();
            $defaultValueString = 'null';
            $def = $column->getDefaultValue();
            if ($def !== null && !$def->isExpression()) {
                $defaultValueString = $this->getDefaultValueString($column);
            }

            return "
        if (!\$this->{$clo}_isLoaded && \$this->{$clo} === {$defaultValueString} && !\$this->isNew()) {
            \$this->load{$column->getPhpName()}(\$con);
        }
";
        }

        return '';
    }
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);
    }
1055581
public function select(string $column, string ...$columns)
    {
        $instance = $this->selectQueryInstance();

        $instance->selectQuery()->columns($column, ...$columns);

        return $instance;
    }
894996
final public function field($column)
    {
        $key = $column;
        if (strpos($column, '.') !== false) {
            list(, $key) = explode('.', $column);
        }
        $key = str_replace('`', '', $key);
        $this->select($column);
        $info = $this->get();
        if (!isset($info[$key])) {
            throw  new Exception('参数错误，您的参数只能为 field 或者 table.field的形式', Exception::CODE_PARAM_VALUE_ERROR);
        }
        return $info[$key];
    }
872940
public function getColumnMeta($column)
    {
        $fields = sqlsrv_field_metadata($this->_stmt);

        if (!$fields) {
            throw new Zend_Db_Statement_Sqlsrv_Exception('Column metadata can not be fetched');
        }

        if (!isset($fields[$column])) {
            throw new Zend_Db_Statement_Sqlsrv_Exception('Column index does not exist in statement');
        }

        return $fields[$column];
    }
870310
protected function _DefineColumn($Column) {
      if (!is_array($Column->Type) && !in_array($Column->Type, array('tinyint', 'smallint', 'mediumint', 'int', 'bigint', 'char', 'varchar', 'varbinary', 'date', 'datetime', 'mediumtext', 'longtext', 'text', 'decimal', 'numeric', 'float', 'double', 'enum', 'timestamp', 'tinyblob', 'blob', 'mediumblob', 'longblob')))
         throw new Exception(sprintf(T('The specified data type (%1$s) is not accepted for the MySQL database.'), $Column->Type));
      
      $Return = '`'.$Column->Name.'` '.$Column->Type;
      
      $LengthTypes = $this->Types('length');
      if ($Column->Length != '' && in_array(strtolower($Column->Type), $LengthTypes)) {
         if($Column->Precision != '')
            $Return .= '('.$Column->Length.', '.$Column->Precision.')';
         else
            $Return .= '('.$Column->Length.')';
      }
      if (property_exists($Column, 'Unsigned') && $Column->Unsigned) {
         $Return .= ' unsigned';
      }

      if (is_array($Column->Enum))
         $Return .= "('".implode("','", $Column->Enum)."')";

      if (!$Column->AllowNull)
         $Return .= ' not null';

      if (!(is_null($Column->Default) || $Column->Default === '') && strcasecmp($Column->Type, 'timestamp') != 0)
         $Return .= " default ".self::_QuoteValue($Column->Default);

      if ($Column->AutoIncrement)
         $Return .= ' auto_increment';

      return $Return;
   }
80083
public static function parseColumn($query, $column)
    {
        $repository = $query->getRepository();
        $description = $repository->getDescription();
        $parts = explode('.', $column, 2);
        $attribute = isset($parts[1]) ? $parts[1] : null;
        $result = array('columns' => null, 'property' => null);
        //don't check the parent properties
        if ($property = $description->getProperty($parts[0], false)) {
            if ($property->isAttribute()) {
                $result['property'] = $property;
                $result['columns'] = $property->getColumn();
            } elseif ($property->isRelationship()) {
                if ($property->isManyToOne()) {
                    //join the query for the belongs to relationship
                    $result['columns'] = $columns = $property->getColumns();
                    $result['property'] = $property;
                    if ($attribute && isset($columns[$attribute])) {
                        $result['columns'] = $columns[$attribute];
                    } elseif ($attribute) {
                        $result = self::_parseManyToOne($query, $property, $attribute);
                    }
                } elseif ($property->isManyToMany()) {
                    $result = self::_parseManyToMany($query, $property, $attribute);
                    if (!$attribute) {
                        $result['columns'] = array();
                    }
                } elseif ($property->isOneToMany()) {
                    $result = self::_parseOneToMany($query, $property, $attribute);
                }

                return $result;
            }
        } elseif (isset($query->link[$parts[0]])) {
            $query = $query->link[$parts[0]]['query'];
            $result = self::parseColumn($query, $parts[1]);
        }

        return $result;
    }
468767
public function col($column)
    {
        $values = [];
        foreach ($this->_entities as $entity) {
            if ($entity->hasAttribute($column)) $values[] = $entity->$column;
        }
        return $values;
    }
1288667
public static function blob2blob($file_id)
    {
        global $CFG, $PDOX;

        if ( isset($CFG->dataroot) && strlen($CFG->dataroot) > 0 ) return;

        // Need to deal with the post 2018-02 situation where we don't even
        // have a content column in blob_file
        try {
            $stmt = $PDOX->prepare("SELECT file_sha256
                FROM {$CFG->dbprefix}blob_file
                WHERE blob_id IS NULL AND path IS NULL AND content IS NOT NULL AND file_id = :ID");
            $stmt->execute(array(':ID' => $file_id));
            $row = $stmt->fetch(\PDO::FETCH_ASSOC);
            if ( ! $row ) return false;
        } catch(\Exception $e) { // No column for old blobs
            // error_log("Content column is not present in blob_file");
            return false;
        }

        $file_sha256 = $row['file_sha256'];

        // Do we already have it in blob_blob?
        $stmt = $PDOX->prepare("SELECT blob_id FROM {$CFG->dbprefix}blob_blob WHERE blob_sha256 = :SHA");
        $stmt->execute(array(":SHA" => $file_sha256));
        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
        if ( $row ) {
            $blob_id = $row['blob_id'];
            $stmt = $PDOX->prepare("UPDATE {$CFG->dbprefix}blob_file
                SET content=NULL, blob_id=:BID WHERE file_id = :ID");
            $stmt->execute(array(':BID' => $blob_id, ':ID' => $file_id));
            error_log("Migration fid=$file_id to existing blob_blob row $blob_id sha=$file_sha256");
            return true;
        }
        // error_log("No row for $file_sha256");

        $lob = false;
        $stmt = $PDOX->prepare("SELECT content FROM {$CFG->dbprefix}blob_file WHERE file_id = :ID");
        $stmt->execute(array(":ID" => $file_id));
        $stmt->bindColumn(1, $lob, \PDO::PARAM_LOB);
        $stmt->fetch(\PDO::FETCH_BOUND);

        if ( ! is_string($lob) ) {
            $retval = "Error: LOB is not string fid=$file_id sha=$file_sha256";
            error_log($retval);
            return $retval;
        }
        // error_log("Lob size=".strlen($lob));

        $stmt = $PDOX->prepare("INSERT INTO {$CFG->dbprefix}blob_blob
            (blob_sha256, content, created_at)
            VALUES (?, ?, NOW())");
        $stmt->bindParam(1, $file_sha256);
        $stmt->bindParam(2, $lob, \PDO::PARAM_STR);
        // $stmt->bindParam(2, $fp, \PDO::PARAM_LOB);
        $PDOX->beginTransaction();
        $stmt->execute();
        $blob_id = 0+$PDOX->lastInsertId();
        $PDOX->commit();

        // Check if it made it...
        $stmt = $PDOX->prepare("SELECT blob_id FROM {$CFG->dbprefix}blob_blob WHERE blob_sha256 = :SHA");
        $stmt->execute(array(":SHA" => $file_sha256));
        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
        if ( $row ) {
            $blob_id = $row['blob_id'];
            $stmt = $PDOX->prepare("UPDATE {$CFG->dbprefix}blob_file
                SET content=NULL, blob_id=:BID WHERE file_id = :ID");
            $stmt->execute(array(':BID' => $blob_id, ':ID' => $file_id));
            error_log("Migration fid=$file_id to new blob_blob row $blob_id sha=$file_sha256");
            return true;
        }

        // Bummer if this happens - doubtful but worth double checking.
        $retval = "Error: Could not find new blob_id=$blob_id for file_id=$file_id sha=$file_sha256";
        error_log($retval);
        return $retval;
    }
957390
protected function processColumnName(string $column, $tableIdentifier): string
    {
        $column = parent::processColumnName($column, $tableIdentifier);

        if ($tableIdentifier !== null && strpos($column, '.') === false) {
            return $tableIdentifier.'.'.$column;
        } else {
            return $column;
        }
    }
343157
protected function parseColumns(string $columns): void
    {
        // Split the columns string into individual columns
        $columns = explode(',', $columns);

        foreach ($columns as &$column) {
            if (strpos($column, '.') === false) {
                $column = "{$this->model->getSource()}.{$column}";
            } else {
                $as = str_replace('.', '_', $column);
                $column = "{$column} {$as}";
            }
        }

        $this->columns = implode(', ', $columns);
    }
891870
public function getColumnMetadata($column)
    {
        if (!$this->columnDispatch) {
            $this->buildColumnDispatch();
        }

        if (!empty($this->columnDispatch[$column])) {
            $metaData = array();

            foreach ($this->columnDispatch[$column] as $handler) {
                /**
                 * @var GridField_ColumnProvider $handler
                 */
                $columnMetaData = $handler->getColumnMetadata($this, $column);

                if (is_array($columnMetaData)) {
                    $metaData = array_merge($metaData, $columnMetaData);
                    continue;
                }

                throw new LogicException(sprintf(
                    'Non-array response from %s::getColumnMetadata().',
                    get_class($handler)
                ));
            }

            return $metaData;
        }

        throw new InvalidArgumentException(sprintf(
            'Bad column "%s"',
            $column
        ));
    }