Class yii\sphinx\Schema
Inheritance | yii\sphinx\Schema » yii\base\BaseObject |
---|---|
Available since extension's version | 2.0 |
Source Code | https://github.com/yiisoft/yii2-sphinx/blob/master/src/Schema.php |
Schema represents the Sphinx schema information.
Public Properties
Property | Type | Description | Defined By |
---|---|---|---|
$db | yii\sphinx\Connection | The Sphinx connection | yii\sphinx\Schema |
$indexNames | string[] | All index names in the Sphinx. | yii\sphinx\Schema |
$indexSchemas | yii\sphinx\IndexSchema[] | The metadata for all indexes in the Sphinx. | yii\sphinx\Schema |
$indexTypes | array | All index types in the Sphinx in format: index name => index type. | yii\sphinx\Schema |
$queryBuilder | yii\sphinx\QueryBuilder | The query builder for this connection. | yii\sphinx\Schema |
$typeMap | array | Mapping from physical column types (keys) to abstract column types (values) | yii\sphinx\Schema |
Public Methods
Method | Description | Defined By |
---|---|---|
convertException() | Converts a DB exception to a more concrete one if possible. | yii\sphinx\Schema |
createQueryBuilder() | Creates a query builder for the Sphinx. | yii\sphinx\Schema |
getIndexNames() | Returns all index names in the Sphinx. | yii\sphinx\Schema |
getIndexSchema() | Obtains the metadata for the named index. | yii\sphinx\Schema |
getIndexSchemas() | Returns the metadata for all indexes in the database. | yii\sphinx\Schema |
getIndexTypes() | Returns all index types in the Sphinx. | yii\sphinx\Schema |
getPdoType() | Determines the PDO type for the given PHP data value. | yii\sphinx\Schema |
getQueryBuilder() | yii\sphinx\Schema | |
getRawIndexName() | Returns the actual name of a given index name. | yii\sphinx\Schema |
isReadQuery() | Returns a value indicating whether a SQL statement is for read purpose. | yii\sphinx\Schema |
quoteColumnName() | Quotes a column name for use in a query. | yii\sphinx\Schema |
quoteIndexName() | Quotes a index name for use in a query. | yii\sphinx\Schema |
quoteSimpleColumnName() | Quotes a column name for use in a query. | yii\sphinx\Schema |
quoteSimpleIndexName() | Quotes a index name for use in a query. | yii\sphinx\Schema |
quoteValue() | Quotes a string value for use in a query. | yii\sphinx\Schema |
refresh() | Refreshes the schema. | yii\sphinx\Schema |
Protected Methods
Method | Description | Defined By |
---|---|---|
applyDefaultColumns() | Sets up the default columns for given index. | yii\sphinx\Schema |
findColumns() | Collects the metadata of index columns. | yii\sphinx\Schema |
findIndexes() | Returns all index names in the Sphinx. | yii\sphinx\Schema |
getCacheKey() | Returns the cache key for the specified index name. | yii\sphinx\Schema |
getCacheTag() | Returns the cache tag name. | yii\sphinx\Schema |
getColumnPhpType() | Extracts the PHP type from abstract DB type. | yii\sphinx\Schema |
initIndexesInfo() | Initializes information about name and type of all index in the Sphinx. | yii\sphinx\Schema |
loadColumnSchema() | Loads the column information into a yii\sphinx\ColumnSchema object. | yii\sphinx\Schema |
loadIndexSchema() | Loads the metadata for the specified index. | yii\sphinx\Schema |
mergeColumnSchema() | Merges two column schemas into a single one. | yii\sphinx\Schema |
resolveIndexNames() | Resolves the index name. | yii\sphinx\Schema |
resolveIndexType() | Resolves the index name. | yii\sphinx\Schema |
Constants
Constant | Value | Description | Defined By |
---|---|---|---|
TYPE_BIGINT | 'bigint' | yii\sphinx\Schema | |
TYPE_BOOLEAN | 'boolean' | yii\sphinx\Schema | |
TYPE_FLOAT | 'float' | yii\sphinx\Schema | |
TYPE_INTEGER | 'integer' | yii\sphinx\Schema | |
TYPE_PK | 'pk' | The following are the supported abstract column data types. | yii\sphinx\Schema |
TYPE_STRING | 'string' | yii\sphinx\Schema | |
TYPE_TIMESTAMP | 'timestamp' | yii\sphinx\Schema |
Property Details
The metadata for all indexes in the Sphinx. Each array element is an instance of yii\sphinx\IndexSchema or its child class.
All index types in the Sphinx in format: index name => index type.
The query builder for this connection.
Mapping from physical column types (keys) to abstract column types (values)
'field' => self::TYPE_STRING,
'string' => self::TYPE_STRING,
'ordinal' => self::TYPE_STRING,
'integer' => self::TYPE_INTEGER,
'int' => self::TYPE_INTEGER,
'uint' => self::TYPE_INTEGER,
'bigint' => self::TYPE_BIGINT,
'timestamp' => self::TYPE_TIMESTAMP,
'bool' => self::TYPE_BOOLEAN,
'float' => self::TYPE_FLOAT,
'mva' => self::TYPE_INTEGER,
'uint_set' => self::TYPE_INTEGER,
]
Method Details
Sets up the default columns for given index.
This method should be used in case there is no way to find actual columns, like in some distributed indexes.
protected void applyDefaultColumns ( $index ) | ||
$index | yii\sphinx\IndexSchema |
The index metadata |
protected function applyDefaultColumns($index)
{
$column = $this->loadColumnSchema([
'Field' => 'id',
'Type' => 'bigint',
]);
$index->columns[$column->name] = $column;
$index->primaryKey = 'id';
}
Converts a DB exception to a more concrete one if possible.
public \yii\db\Exception convertException ( Exception $e, $rawSql ) | ||
$e | Exception | |
$rawSql | string |
SQL that produced exception |
public function convertException(\Exception $e, $rawSql)
{
if ($e instanceof Exception) {
return $e;
}
$message = $e->getMessage() . "\nThe SQL being executed was: $rawSql";
$errorInfo = $e instanceof \PDOException ? $e->errorInfo : null;
return new Exception($message, $errorInfo, (int) $e->getCode(), $e);
}
Creates a query builder for the Sphinx.
public yii\sphinx\QueryBuilder createQueryBuilder ( ) | ||
return | yii\sphinx\QueryBuilder |
Query builder instance |
---|
public function createQueryBuilder()
{
return new QueryBuilder($this->db);
}
Collects the metadata of index columns.
protected boolean findColumns ( $index ) | ||
$index | yii\sphinx\IndexSchema |
The index metadata |
return | boolean |
Whether the index exists in the database |
---|---|---|
throws | Exception |
if DB query fails |
protected function findColumns($index)
{
$sql = 'DESCRIBE ' . $this->quoteSimpleIndexName($index->name);
try {
$columns = $this->db->createCommand($sql)->queryAll();
} catch (\Exception $e) {
$previous = $e->getPrevious();
if ($previous instanceof \PDOException && strpos($previous->getMessage(), 'SQLSTATE[42S02') !== false) {
// index does not exist
// https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html#error_er_bad_table_error
return false;
}
throw $e;
}
if (empty($columns[0]['Agent'])) {
foreach ($columns as $info) {
$column = $this->loadColumnSchema($info);
if (isset($index->columns[$column->name])) {
$column = $this->mergeColumnSchema($index->columns[$column->name], $column);
}
$index->columns[$column->name] = $column;
if ($column->isPrimaryKey) {
$index->primaryKey = $column->name;
}
}
return true;
}
// Distributed index :
foreach ($columns as $column) {
if (!empty($column['Type']) && strcasecmp('local', $column['Type']) !== 0) {
// skip type 'agent'
continue;
}
$agent = $this->getIndexSchema($column['Agent']);
if ($agent !== null) {
$index->columns = $agent->columns;
$index->primaryKey = $agent->primaryKey;
return true;
}
}
$this->applyDefaultColumns($index);
return true;
}
Returns all index names in the Sphinx.
protected array findIndexes ( ) | ||
return | array |
All index names in the Sphinx. |
---|
protected function findIndexes()
{
$sql = 'SHOW TABLES';
return $this->db->createCommand($sql)->queryAll();
}
Returns the cache key for the specified index name.
protected mixed getCacheKey ( $name ) | ||
$name | string |
The index name |
return | mixed |
The cache key |
---|
protected function getCacheKey($name)
{
return [
__CLASS__,
$this->db->dsn,
$this->db->username,
$name,
];
}
Returns the cache tag name.
This allows refresh() to invalidate all cached index schemas.
protected string getCacheTag ( ) | ||
return | string |
The cache tag name |
---|
protected function getCacheTag()
{
return md5(serialize([
__CLASS__,
$this->db->dsn,
$this->db->username,
]));
}
Extracts the PHP type from abstract DB type.
protected string getColumnPhpType ( $column ) | ||
$column | yii\sphinx\ColumnSchema |
The column schema information |
return | string |
PHP type name |
---|
protected function getColumnPhpType($column)
{
static $typeMap = [ // abstract type => php type
'smallint' => 'integer',
'integer' => 'integer',
'bigint' => 'integer',
'timestamp' => 'integer',
'boolean' => 'boolean',
'float' => 'double',
];
if (isset($typeMap[$column->type])) {
if ($column->type === 'bigint') {
return PHP_INT_SIZE == 8 ? 'integer' : 'string';
} elseif ($column->type === 'integer' || $column->type === 'timestamp') {
return PHP_INT_SIZE == 4 ? 'string' : 'integer';
} else {
return $typeMap[$column->type];
}
} else {
return 'string';
}
}
Returns all index names in the Sphinx.
public string[] getIndexNames ( $refresh = false ) | ||
$refresh | boolean |
Whether to fetch the latest available index names. If this is false, index names fetched previously (if available) will be returned. |
return | string[] |
All index names in the Sphinx. |
---|
public function getIndexNames($refresh = false)
{
if (!isset($this->_indexNames) || $refresh) {
$this->initIndexesInfo();
}
return $this->_indexNames;
}
Obtains the metadata for the named index.
public yii\sphinx\IndexSchema|null getIndexSchema ( $name, $refresh = false ) | ||
$name | string |
Index name. The index name may contain schema name if any. Do not quote the index name. |
$refresh | boolean |
Whether to reload the index schema even if it is found in the cache. |
return | yii\sphinx\IndexSchema|null |
Index metadata. |
---|
public function getIndexSchema($name, $refresh = false)
{
if (isset($this->_indexes[$name]) && !$refresh) {
return $this->_indexes[$name];
}
$db = $this->db;
$realName = $this->getRawIndexName($name);
if ($db->enableSchemaCache && !in_array($name, $db->schemaCacheExclude, true)) {
/* @var $cache Cache */
$cache = is_string($db->schemaCache) ? Yii::$app->get($db->schemaCache, false) : $db->schemaCache;
if ($cache instanceof Cache) {
$key = $this->getCacheKey($name);
if ($refresh || ($index = $cache->get($key)) === false) {
$index = $this->loadIndexSchema($realName);
if ($index !== null) {
$cache->set($key, $index, $db->schemaCacheDuration, new TagDependency([
'tags' => $this->getCacheTag(),
]));
}
}
return $this->_indexes[$name] = $index;
}
}
return $this->_indexes[$name] = $this->loadIndexSchema($realName);
}
Returns the metadata for all indexes in the database.
public yii\sphinx\IndexSchema[] getIndexSchemas ( $refresh = false ) | ||
$refresh | boolean |
Whether to fetch the latest available index schemas. If this is false, cached data may be returned if available. |
return | yii\sphinx\IndexSchema[] |
The metadata for all indexes in the Sphinx. Each array element is an instance of yii\sphinx\IndexSchema or its child class. |
---|
public function getIndexSchemas($refresh = false)
{
$indexes = [];
foreach ($this->getIndexNames($refresh) as $name) {
if (($index = $this->getIndexSchema($name, $refresh)) !== null) {
$indexes[] = $index;
}
}
return $indexes;
}
Returns all index types in the Sphinx.
public array getIndexTypes ( $refresh = false ) | ||
$refresh | boolean |
Whether to fetch the latest available index types. If this is false, index types fetched previously (if available) will be returned. |
return | array |
All index types in the Sphinx in format: index name => index type. |
---|
public function getIndexTypes($refresh = false)
{
if (!isset($this->_indexTypes) || $refresh) {
$this->initIndexesInfo();
}
return $this->_indexTypes;
}
Determines the PDO type for the given PHP data value.
public integer getPdoType ( $data ) | ||
$data | mixed |
The data whose PDO type is to be determined |
return | integer |
The PDO type |
---|
public function getPdoType($data)
{
static $typeMap = [
// php type => PDO type
'bool' => \PDO::PARAM_BOOL,
'boolean' => \PDO::PARAM_BOOL,
'int' => \PDO::PARAM_INT,
'integer' => \PDO::PARAM_INT,
'string' => \PDO::PARAM_STR,
'resource' => \PDO::PARAM_LOB,
'NULL' => \PDO::PARAM_NULL,
];
$type = gettype($data);
return isset($typeMap[$type]) ? $typeMap[$type] : \PDO::PARAM_STR;
}
public yii\sphinx\QueryBuilder getQueryBuilder ( ) | ||
return | yii\sphinx\QueryBuilder |
The query builder for this connection. |
---|
public function getQueryBuilder()
{
if ($this->_builder === null) {
$this->_builder = $this->createQueryBuilder();
}
return $this->_builder;
}
Returns the actual name of a given index name.
This method will strip off curly brackets from the given index name and replace the percentage character '%' with Connection::indexPrefix.
public string getRawIndexName ( $name ) | ||
$name | string |
The index name to be converted |
return | string |
The real name of the given index name |
---|
public function getRawIndexName($name)
{
if (strpos($name, '{{') !== false) {
$name = preg_replace('/\\{\\{(.*?)\\}\\}/', '\1', $name);
return str_replace('%', $this->db->tablePrefix, $name);
} else {
return $name;
}
}
Initializes information about name and type of all index in the Sphinx.
protected void initIndexesInfo ( ) |
protected function initIndexesInfo()
{
$this->_indexNames = [];
$this->_indexTypes = [];
$indexes = $this->findIndexes();
foreach ($indexes as $index) {
$indexName = $index['Index'];
$this->_indexNames[] = $indexName;
$this->_indexTypes[$indexName] = $index['Type'];
}
}
Returns a value indicating whether a SQL statement is for read purpose.
public boolean isReadQuery ( $sql ) | ||
$sql | string |
The SQL statement |
return | boolean |
Whether a SQL statement is for read purpose. |
---|
public function isReadQuery($sql)
{
$pattern = '/^\s*(SELECT|SHOW|DESCRIBE)\b/i';
return preg_match($pattern, $sql) > 0;
}
Loads the column information into a yii\sphinx\ColumnSchema object.
protected yii\sphinx\ColumnSchema loadColumnSchema ( $info ) | ||
$info | array |
Column information |
return | yii\sphinx\ColumnSchema |
The column schema object |
---|
protected function loadColumnSchema($info)
{
$column = new ColumnSchema();
$column->name = $info['Field'];
$column->dbType = $info['Type'];
$column->isPrimaryKey = ($column->name === 'id');
$type = $info['Type'];
if (isset($this->typeMap[$type])) {
$column->type = $this->typeMap[$type];
} else {
$column->type = self::TYPE_STRING;
}
$column->isField = ($type === 'field');
$column->isAttribute = !$column->isField;
$column->isMva = $type === 'mva' || $type === 'uint_set';
$column->phpType = $this->getColumnPhpType($column);
return $column;
}
Loads the metadata for the specified index.
protected yii\sphinx\IndexSchema|null loadIndexSchema ( $name ) | ||
$name | string |
Index name |
return | yii\sphinx\IndexSchema|null |
Driver dependent index metadata. |
---|
protected function loadIndexSchema($name)
{
$index = new IndexSchema();
$this->resolveIndexNames($index, $name);
$this->resolveIndexType($index);
if ($this->findColumns($index)) {
return $index;
}
return null;
}
Merges two column schemas into a single one.
protected yii\sphinx\ColumnSchema mergeColumnSchema ( $origin, $override ) | ||
$origin | yii\sphinx\ColumnSchema |
Original column schema. |
$override | yii\sphinx\ColumnSchema |
Column schema to be applied over original one. |
return | yii\sphinx\ColumnSchema |
Merge result. |
---|
protected function mergeColumnSchema($origin, $override)
{
$override->dbType .= ',' . $override->dbType;
if ($override->isField) {
$origin->isField = true;
}
if ($override->isAttribute) {
$origin->isAttribute = true;
$origin->type = $override->type;
$origin->phpType = $override->phpType;
if ($override->isMva) {
$origin->isMva = true;
}
}
return $origin;
}
Quotes a column name for use in a query.
If the column name contains prefix, the prefix will also be properly quoted. If the column name is already quoted or contains '(', '[[' or '{{', then this method will do nothing.
See also quoteSimpleColumnName().
public string quoteColumnName ( $name ) | ||
$name | string |
Column name |
return | string |
The properly quoted column name |
---|
public function quoteColumnName($name)
{
if (strpos($name, '(') !== false || strpos($name, '[[') !== false || strpos($name, '{{') !== false) {
return $name;
}
if (($pos = strrpos($name, '.')) !== false) {
$prefix = $this->quoteIndexName(substr($name, 0, $pos)) . '.';
$name = substr($name, $pos + 1);
} else {
$prefix = '';
}
return $prefix . $this->quoteSimpleColumnName($name);
}
Quotes a index name for use in a query.
If the index name contains schema prefix, the prefix will also be properly quoted. If the index name is already quoted or contains '(' or '{{', then this method will do nothing.
See also \yii\sphinx\quoteSimpleTableName.
public string quoteIndexName ( $name ) | ||
$name | string |
Index name |
return | string |
The properly quoted index name |
---|
public function quoteIndexName($name)
{
if (strpos($name, '(') !== false || strpos($name, '{{') !== false) {
return $name;
}
return $this->quoteSimpleIndexName($name);
}
Quotes a column name for use in a query.
A simple column name has no prefix.
public string quoteSimpleColumnName ( $name ) | ||
$name | string |
Column name |
return | string |
The properly quoted column name |
---|
public function quoteSimpleColumnName($name)
{
return strpos($name, '`') !== false || $name === '*' ? $name : '`' . $name . '`';
}
Quotes a index name for use in a query.
A simple index name has no schema prefix.
public string quoteSimpleIndexName ( $name ) | ||
$name | string |
Index name |
return | string |
The properly quoted index name |
---|
public function quoteSimpleIndexName($name)
{
return strpos($name, "`") !== false ? $name : "`" . $name . "`";
}
Quotes a string value for use in a query.
Note that if the parameter is not a string, it will be returned without change.
See also https://www.php.net/manual/en/function.PDO-quote.php.
public string quoteValue ( $str ) | ||
$str | string |
String to be quoted |
return | string |
The properly quoted string |
---|
public function quoteValue($str)
{
if (is_string($str)) {
return $this->db->getSlavePdo()->quote($str);
}
return $str;
}
Refreshes the schema.
This method cleans up all cached index schemas so that they can be re-created later to reflect the Sphinx schema change.
public void refresh ( ) |
public function refresh()
{
/* @var $cache Cache */
$cache = is_string($this->db->schemaCache) ? Yii::$app->get($this->db->schemaCache, false) : $this->db->schemaCache;
if ($this->db->enableSchemaCache && $cache instanceof Cache) {
TagDependency::invalidate($cache, $this->getCacheTag());
}
$this->_indexNames = [];
$this->_indexes = [];
}
Resolves the index name.
protected void resolveIndexNames ( $index, $name ) | ||
$index | yii\sphinx\IndexSchema |
The index metadata object |
$name | string |
The index name |
protected function resolveIndexNames($index, $name)
{
$index->name = str_replace('`', '', $name);
}
Resolves the index name.
protected void resolveIndexType ( $index ) | ||
$index | yii\sphinx\IndexSchema |
The index metadata object |
protected function resolveIndexType($index)
{
$indexTypes = $this->getIndexTypes();
$index->type = array_key_exists($index->name, $indexTypes) ? $indexTypes[$index->name] : 'unknown';
$index->isRt = ($index->type == 'rt');
}