Browse Source

Sphinx documentation updated.

tags/2.0.0-beta
Paul Klimov 11 years ago
parent
commit
d1c87c7e31
  1. 53
      extensions/sphinx/ActiveRecord.php
  2. 38
      extensions/sphinx/Command.php
  3. 52
      extensions/sphinx/Connection.php
  4. 92
      extensions/sphinx/Query.php
  5. 45
      extensions/sphinx/QueryBuilder.php
  6. 11
      extensions/sphinx/README.md
  7. 7
      extensions/sphinx/Schema.php
  8. 4
      extensions/sphinx/composer.json

53
extensions/sphinx/ActiveRecord.php

@ -14,14 +14,22 @@ use yii\base\ModelEvent;
use yii\base\NotSupportedException; use yii\base\NotSupportedException;
use yii\base\UnknownMethodException; use yii\base\UnknownMethodException;
use yii\db\ActiveRelationInterface; use yii\db\ActiveRelationInterface;
use yii\db\Expression;
use yii\db\StaleObjectException; use yii\db\StaleObjectException;
use yii\helpers\Inflector; use yii\helpers\Inflector;
use yii\helpers\StringHelper; use yii\helpers\StringHelper;
use Yii; use Yii;
/** /**
* Class ActiveRecord * ActiveRecord is the base class for classes representing relational data in terms of objects.
*
* @property array $dirtyAttributes The changed attribute values (name-value pairs). This property is
* read-only.
* @property boolean $isNewRecord Whether the record is new and should be inserted when calling [[save()]].
* @property array $oldAttributes The old attribute values (name-value pairs).
* @property integer $oldPrimaryKey The old primary key value. This property is read-only.
* @property array $populatedRelations An array of relation data indexed by relation names. This property is
* read-only.
* @property integer $primaryKey The primary key value. This property is read-only.
* *
* @author Paul Klimov <klimov.paul@gmail.com> * @author Paul Klimov <klimov.paul@gmail.com>
* @since 2.0 * @since 2.0
@ -148,7 +156,7 @@ class ActiveRecord extends Model
* Below is an example: * Below is an example:
* *
* ~~~ * ~~~
* $customers = Customer::findBySql('SELECT * FROM tbl_customer')->all(); * $customers = Article::findBySql("SELECT * FROM `idx_article` WHERE MATCH('development')")->all();
* ~~~ * ~~~
* *
* @param string $sql the SQL statement to be executed * @param string $sql the SQL statement to be executed
@ -164,10 +172,10 @@ class ActiveRecord extends Model
/** /**
* Updates the whole table using the provided attribute values and conditions. * Updates the whole table using the provided attribute values and conditions.
* For example, to change the status to be 1 for all customers whose status is 2: * For example, to change the status to be 1 for all articles which status is 2:
* *
* ~~~ * ~~~
* Customer::updateAll(['status' => 1], 'status = 2'); * Article::updateAll(['status' => 1], 'status = 2');
* ~~~ * ~~~
* *
* @param array $attributes attribute values (name-value pairs) to be saved into the table * @param array $attributes attribute values (name-value pairs) to be saved into the table
@ -184,13 +192,12 @@ class ActiveRecord extends Model
} }
/** /**
* Deletes rows in the table using the provided conditions. * Deletes rows in the index using the provided conditions.
* WARNING: If you do not specify any condition, this method will delete ALL rows in the table.
* *
* For example, to delete all customers whose status is 3: * For example, to delete all articles whose status is 3:
* *
* ~~~ * ~~~
* Customer::deleteAll('status = 3'); * Article::deleteAll('status = 3');
* ~~~ * ~~~
* *
* @param string|array $condition the conditions that will be put in the WHERE part of the DELETE SQL. * @param string|array $condition the conditions that will be put in the WHERE part of the DELETE SQL.
@ -208,8 +215,8 @@ class ActiveRecord extends Model
/** /**
* Creates an [[ActiveQuery]] instance. * Creates an [[ActiveQuery]] instance.
* This method is called by [[find()]], [[findBySql()]] and [[count()]] to start a SELECT query. * This method is called by [[find()]], [[findBySql()]] and [[count()]] to start a SELECT query.
* You may override this method to return a customized query (e.g. `CustomerQuery` specified * You may override this method to return a customized query (e.g. `ArticleQuery` specified
* written for querying `Customer` purpose.) * written for querying `Article` purpose.)
* @return ActiveQuery the newly created [[ActiveQuery]] instance. * @return ActiveQuery the newly created [[ActiveQuery]] instance.
*/ */
public static function createQuery() public static function createQuery()
@ -218,11 +225,11 @@ class ActiveRecord extends Model
} }
/** /**
* Declares the name of the database table associated with this AR class. * Declares the name of the Sphinx index associated with this AR class.
* By default this method returns the class name as the table name by calling [[Inflector::camel2id()]] * By default this method returns the class name as the index name by calling [[Inflector::camel2id()]].
* with prefix 'tbl_'. For example, 'Customer' becomes 'tbl_customer', and 'OrderItem' becomes * For example, 'Article' becomes 'article', and 'StockItem' becomes
* 'tbl_order_item'. You may override this method if the table is not named after this convention. * 'stock_item'. You may override this method if the index is not named after this convention.
* @return string the table name * @return string the index name
*/ */
public static function indexName() public static function indexName()
{ {
@ -230,9 +237,9 @@ class ActiveRecord extends Model
} }
/** /**
* Returns the schema information of the DB table associated with this AR class. * Returns the schema information of the Sphinx index associated with this AR class.
* @return IndexSchema the schema information of the DB table associated with this AR class. * @return IndexSchema the schema information of the Sphinx index associated with this AR class.
* @throws InvalidConfigException if the table for the AR class does not exist. * @throws InvalidConfigException if the index for the AR class does not exist.
*/ */
public static function getIndexSchema() public static function getIndexSchema()
{ {
@ -246,7 +253,7 @@ class ActiveRecord extends Model
/** /**
* Returns the primary key name for this AR class. * Returns the primary key name for this AR class.
* @return string the primary keys of the associated database table. * @return string the primary key of the associated Sphinx index.
*/ */
public static function primaryKey() public static function primaryKey()
{ {
@ -257,15 +264,15 @@ class ActiveRecord extends Model
* Builds a snippet from provided data and query, using specified index settings. * Builds a snippet from provided data and query, using specified index settings.
* @param string|array $source is the source data to extract a snippet from. * @param string|array $source is the source data to extract a snippet from.
* It could be either a single string or array of strings. * It could be either a single string or array of strings.
* @param string $query the full-text query to build snippets for. * @param string $match the full-text query to build snippets for.
* @param array $options list of options in format: optionName => optionValue * @param array $options list of options in format: optionName => optionValue
* @return string|array built snippet in case "source" is a string, list of built snippets * @return string|array built snippet in case "source" is a string, list of built snippets
* in case "source" is an array. * in case "source" is an array.
*/ */
public static function callSnippets($source, $query, $options = []) public static function callSnippets($source, $match, $options = [])
{ {
$command = static::getDb()->createCommand(); $command = static::getDb()->createCommand();
$command->callSnippets(static::indexName(), $source, $query, $options); $command->callSnippets(static::indexName(), $source, $match, $options);
if (is_array($source)) { if (is_array($source)) {
return $command->queryColumn(); return $command->queryColumn();
} else { } else {

38
extensions/sphinx/Command.php

@ -13,7 +13,37 @@ use yii\caching\Cache;
use yii\db\Exception; use yii\db\Exception;
/** /**
* Class Command * Command represents a SQL statement to be executed against a Sphinx.
*
* A command object is usually created by calling [[Connection::createCommand()]].
* The SQL statement it represents can be set via the [[sql]] property.
*
* To execute a non-query SQL (such as INSERT, REPLACE, DELETE, UPDATE), call [[execute()]].
* To execute a SQL statement that returns result data set (such as SELECT, CALL SNIPPETS, CALL KEYWORDS),
* use [[queryAll()]], [[queryOne()]], [[queryColumn()]], [[queryScalar()]], or [[query()]].
* For example,
*
* ~~~
* $articles = $connection->createCommand("SELECT * FROM `idx_article` WHERE MATCH('programming')")->queryAll();
* ~~~
*
* Command supports SQL statement preparation and parameter binding just as [[\yii\db\Command]] does.
*
* Command also supports building SQL statements by providing methods such as [[insert()]],
* [[update()]], etc. For example,
*
* ~~~
* $connection->createCommand()->update('idx_article', [
* 'genre_id' => 15,
* 'author_id' => 157,
* ])->execute();
* ~~~
*
* To build SELECT SQL statements, please use [[Query]] and [[QueryBuilder]] instead.
*
* @property string $rawSql The raw SQL with parameter values inserted into the corresponding placeholders in
* [[sql]]. This property is read-only.
* @property string $sql The SQL statement to be executed.
* *
* @author Paul Klimov <klimov.paul@gmail.com> * @author Paul Klimov <klimov.paul@gmail.com>
* @since 2.0 * @since 2.0
@ -554,14 +584,14 @@ class Command extends Component
* @param string $index name of the index, from which to take the text processing settings. * @param string $index name of the index, from which to take the text processing settings.
* @param string|array $source is the source data to extract a snippet from. * @param string|array $source is the source data to extract a snippet from.
* It could be either a single string or array of strings. * It could be either a single string or array of strings.
* @param string $query the full-text query to build snippets for. * @param string $match the full-text query to build snippets for.
* @param array $options list of options in format: optionName => optionValue * @param array $options list of options in format: optionName => optionValue
* @return static the command object itself * @return static the command object itself
*/ */
public function callSnippets($index, $source, $query, $options = []) public function callSnippets($index, $source, $match, $options = [])
{ {
$params = []; $params = [];
$sql = $this->db->getQueryBuilder()->callSnippets($index, $source, $query, $options, $params); $sql = $this->db->getQueryBuilder()->callSnippets($index, $source, $match, $options, $params);
return $this->setSql($sql)->bindValues($params); return $this->setSql($sql)->bindValues($params);
} }

52
extensions/sphinx/Connection.php

@ -6,14 +6,51 @@
*/ */
namespace yii\sphinx; namespace yii\sphinx;
use yii\base\NotSupportedException;
/** /**
* Class Connection * Connection represents the Sphinx connection via MySQL protocol.
* This class uses [PDO](http://www.php.net/manual/en/ref.pdo.php) to maintain such connection.
* Note: although PDO supports numerous database drivers, this class supports only MySQL.
*
* In order to setup Sphinx "searchd" to support MySQL protocol following configuration should be added:
* ```
* searchd
* {
* listen = localhost:9306:mysql41
* ...
* }
* ```
*
* The following example shows how to create a Connection instance and establish
* the Sphinx connection:
* ~~~
* $connection = new \yii\db\Connection([
* 'dsn' => 'mysql:host=127.0.0.1;port=9306;',
* 'username' => $username,
* 'password' => $password,
* ]);
* $connection->open();
* ~~~
*
* After the Sphinx connection is established, one can execute SQL statements like the following:
* ~~~
* $command = $connection->createCommand("SELECT * FROM idx_article WHERE MATCH('programming')");
* $articles = $command->queryAll();
* $command = $connection->createCommand('UPDATE idx_article SET status=2 WHERE id=1');
* $command->execute();
* ~~~
*
* For more information about how to perform various DB queries, please refer to [[Command]].
*
* This class supports transactions exactly as "yii\db\Connection".
*
* Note: while this class extends "yii\db\Connection" some of its methods are not supported.
* *
* @property Schema $schema The schema information for this Sphinx connection. This property is read-only. * @property Schema $schema The schema information for this Sphinx connection. This property is read-only.
* @property \yii\sphinx\QueryBuilder $queryBuilder The query builder for this Sphinx connection. This property is * @property \yii\sphinx\QueryBuilder $queryBuilder The query builder for this Sphinx connection. This property is
* read-only. * read-only.
* @method Schema getSchema() The schema information for this Sphinx connection * @method \yii\sphinx\Schema getSchema() The schema information for this Sphinx connection
* @method \yii\sphinx\QueryBuilder getQueryBuilder() the query builder for this Sphinx connection * @method \yii\sphinx\QueryBuilder getQueryBuilder() the query builder for this Sphinx connection
* *
* @author Paul Klimov <klimov.paul@gmail.com> * @author Paul Klimov <klimov.paul@gmail.com>
@ -78,4 +115,15 @@ class Connection extends \yii\db\Connection
]); ]);
return $command->bindValues($params); return $command->bindValues($params);
} }
/**
* This method is not supported by Sphinx.
* @param string $sequenceName name of the sequence object
* @return string the row ID of the last row inserted, or the last value retrieved from the sequence object
* @throws \yii\base\NotSupportedException always.
*/
public function getLastInsertID($sequenceName = '')
{
throw new NotSupportedException('"' . $this->className() . '::getLastInsertID" is not supported.');
}
} }

92
extensions/sphinx/Query.php

@ -15,10 +15,31 @@ use yii\db\QueryInterface;
use yii\db\QueryTrait; use yii\db\QueryTrait;
/** /**
* Class Query * Query represents a SELECT SQL statement.
* *
* Query provides a set of methods to facilitate the specification of different clauses
* in a SELECT statement. These methods can be chained together.
* *
* Note: implicit LIMIT 0,20 is present by default. * By calling [[createCommand()]], we can get a [[Command]] instance which can be further
* used to perform/execute the Sphinx query.
*
* For example,
*
* ~~~
* $query = new Query;
* $query->select('id, groupd_id')
* ->from('idx_item')
* ->limit(10);
* // build and execute the query
* $command = $query->createCommand();
* // $command->sql returns the actual SQL
* $rows = $command->queryAll();
* ~~~
*
* Since Sphinx does not store the original indexed text, the snippets for the rows in query result
* should be build separately via another query. You can simplify this workflow using [[snippetCallback]].
*
* Warning: even if you do not set any query limit, implicit LIMIT 0,20 is present by default!
* *
* @author Paul Klimov <klimov.paul@gmail.com> * @author Paul Klimov <klimov.paul@gmail.com>
* @since 2.0 * @since 2.0
@ -43,7 +64,7 @@ class Query extends Component implements QueryInterface
*/ */
public $distinct; public $distinct;
/** /**
* @var array the index(es) to be selected from. For example, `['idx_user', 'idx_post']`. * @var array the index(es) to be selected from. For example, `['idx_user', 'idx_user_delta']`.
* This is used to construct the FROM clause in a SQL statement. * This is used to construct the FROM clause in a SQL statement.
* @see from() * @see from()
*/ */
@ -149,8 +170,8 @@ class Query extends Component implements QueryInterface
/** /**
* Executes the query and returns all results as an array. * Executes the query and returns all results as an array.
* @param Connection $db the database connection used to generate the SQL statement. * @param Connection $db the Sphinx connection used to generate the SQL statement.
* If this parameter is not given, the `db` application component will be used. * If this parameter is not given, the `sphinx` application component will be used.
* @return array the query results. If the query results in nothing, an empty array will be returned. * @return array the query results. If the query results in nothing, an empty array will be returned.
*/ */
public function all($db = null) public function all($db = null)
@ -174,8 +195,8 @@ class Query extends Component implements QueryInterface
/** /**
* Executes the query and returns a single row of result. * Executes the query and returns a single row of result.
* @param Connection $db the database connection used to generate the SQL statement. * @param Connection $db the Sphinx connection used to generate the SQL statement.
* If this parameter is not given, the `db` application component will be used. * If this parameter is not given, the `sphinx` application component will be used.
* @return array|boolean the first row (in terms of an array) of the query result. False is returned if the query * @return array|boolean the first row (in terms of an array) of the query result. False is returned if the query
* results in nothing. * results in nothing.
*/ */
@ -191,8 +212,8 @@ class Query extends Component implements QueryInterface
/** /**
* Returns the query result as a scalar value. * Returns the query result as a scalar value.
* The value returned will be the first column in the first row of the query results. * The value returned will be the first column in the first row of the query results.
* @param Connection $db the database connection used to generate the SQL statement. * @param Connection $db the Sphinx connection used to generate the SQL statement.
* If this parameter is not given, the `db` application component will be used. * If this parameter is not given, the `sphinx` application component will be used.
* @return string|boolean the value of the first column in the first row of the query result. * @return string|boolean the value of the first column in the first row of the query result.
* False is returned if the query result is empty. * False is returned if the query result is empty.
*/ */
@ -203,8 +224,8 @@ class Query extends Component implements QueryInterface
/** /**
* Executes the query and returns the first column of the result. * Executes the query and returns the first column of the result.
* @param Connection $db the database connection used to generate the SQL statement. * @param Connection $db the Sphinx connection used to generate the SQL statement.
* If this parameter is not given, the `db` application component will be used. * If this parameter is not given, the `sphinx` application component will be used.
* @return array the first column of the query result. An empty array is returned if the query results in nothing. * @return array the first column of the query result. An empty array is returned if the query results in nothing.
*/ */
public function column($db = null) public function column($db = null)
@ -216,8 +237,8 @@ class Query extends Component implements QueryInterface
* Returns the number of records. * Returns the number of records.
* @param string $q the COUNT expression. Defaults to '*'. * @param string $q the COUNT expression. Defaults to '*'.
* Make sure you properly quote column names in the expression. * Make sure you properly quote column names in the expression.
* @param Connection $db the database connection used to generate the SQL statement. * @param Connection $db the Sphinx connection used to generate the SQL statement.
* If this parameter is not given, the `db` application component will be used. * If this parameter is not given, the `sphinx` application component will be used.
* @return integer number of records * @return integer number of records
*/ */
public function count($q = '*', $db = null) public function count($q = '*', $db = null)
@ -230,8 +251,8 @@ class Query extends Component implements QueryInterface
* Returns the sum of the specified column values. * Returns the sum of the specified column values.
* @param string $q the column name or expression. * @param string $q the column name or expression.
* Make sure you properly quote column names in the expression. * Make sure you properly quote column names in the expression.
* @param Connection $db the database connection used to generate the SQL statement. * @param Connection $db the Sphinx connection used to generate the SQL statement.
* If this parameter is not given, the `db` application component will be used. * If this parameter is not given, the `sphinx` application component will be used.
* @return integer the sum of the specified column values * @return integer the sum of the specified column values
*/ */
public function sum($q, $db = null) public function sum($q, $db = null)
@ -244,8 +265,8 @@ class Query extends Component implements QueryInterface
* Returns the average of the specified column values. * Returns the average of the specified column values.
* @param string $q the column name or expression. * @param string $q the column name or expression.
* Make sure you properly quote column names in the expression. * Make sure you properly quote column names in the expression.
* @param Connection $db the database connection used to generate the SQL statement. * @param Connection $db the Sphinx connection used to generate the SQL statement.
* If this parameter is not given, the `db` application component will be used. * If this parameter is not given, the `sphinx` application component will be used.
* @return integer the average of the specified column values. * @return integer the average of the specified column values.
*/ */
public function average($q, $db = null) public function average($q, $db = null)
@ -258,8 +279,8 @@ class Query extends Component implements QueryInterface
* Returns the minimum of the specified column values. * Returns the minimum of the specified column values.
* @param string $q the column name or expression. * @param string $q the column name or expression.
* Make sure you properly quote column names in the expression. * Make sure you properly quote column names in the expression.
* @param Connection $db the database connection used to generate the SQL statement. * @param Connection $db the Sphinx connection used to generate the SQL statement.
* If this parameter is not given, the `db` application component will be used. * If this parameter is not given, the `sphinx` application component will be used.
* @return integer the minimum of the specified column values. * @return integer the minimum of the specified column values.
*/ */
public function min($q, $db = null) public function min($q, $db = null)
@ -272,8 +293,8 @@ class Query extends Component implements QueryInterface
* Returns the maximum of the specified column values. * Returns the maximum of the specified column values.
* @param string $q the column name or expression. * @param string $q the column name or expression.
* Make sure you properly quote column names in the expression. * Make sure you properly quote column names in the expression.
* @param Connection $db the database connection used to generate the SQL statement. * @param Connection $db the Sphinx connection used to generate the SQL statement.
* If this parameter is not given, the `db` application component will be used. * If this parameter is not given, the `sphinx` application component will be used.
* @return integer the maximum of the specified column values. * @return integer the maximum of the specified column values.
*/ */
public function max($q, $db = null) public function max($q, $db = null)
@ -284,8 +305,8 @@ class Query extends Component implements QueryInterface
/** /**
* Returns a value indicating whether the query result contains any row of data. * Returns a value indicating whether the query result contains any row of data.
* @param Connection $db the database connection used to generate the SQL statement. * @param Connection $db the Sphinx connection used to generate the SQL statement.
* If this parameter is not given, the `db` application component will be used. * If this parameter is not given, the `sphinx` application component will be used.
* @return boolean whether the query result contains any row of data. * @return boolean whether the query result contains any row of data.
*/ */
public function exists($db = null) public function exists($db = null)
@ -298,11 +319,9 @@ class Query extends Component implements QueryInterface
* Sets the SELECT part of the query. * Sets the SELECT part of the query.
* @param string|array $columns the columns to be selected. * @param string|array $columns the columns to be selected.
* Columns can be specified in either a string (e.g. "id, name") or an array (e.g. ['id', 'name']). * Columns can be specified in either a string (e.g. "id, name") or an array (e.g. ['id', 'name']).
* Columns can contain table prefixes (e.g. "tbl_user.id") and/or column aliases (e.g. "tbl_user.id AS user_id").
* The method will automatically quote the column names unless a column contains some parenthesis * The method will automatically quote the column names unless a column contains some parenthesis
* (which means the column contains a DB expression). * (which means the column contains a Sphinx expression).
* @param string $option additional option that should be appended to the 'SELECT' keyword. For example, * @param string $option additional option that should be appended to the 'SELECT' keyword.
* in MySQL, the option 'SQL_CALC_FOUND_ROWS' can be used.
* @return static the query object itself * @return static the query object itself
*/ */
public function select($columns, $option = null) public function select($columns, $option = null)
@ -328,11 +347,10 @@ class Query extends Component implements QueryInterface
/** /**
* Sets the FROM part of the query. * Sets the FROM part of the query.
* @param string|array $tables the table(s) to be selected from. This can be either a string (e.g. `'tbl_user'`) * @param string|array $tables the table(s) to be selected from. This can be either a string (e.g. `'idx_user'`)
* or an array (e.g. `['tbl_user', 'tbl_profile']`) specifying one or several table names. * or an array (e.g. `['idx_user', 'idx_user_delta']`) specifying one or several index names.
* Table names can contain schema prefixes (e.g. `'public.tbl_user'`) and/or table aliases (e.g. `'tbl_user u'`).
* The method will automatically quote the table names unless it contains some parenthesis * The method will automatically quote the table names unless it contains some parenthesis
* (which means the table is given as a sub-query or DB expression). * (which means the table is given as a sub-query or Sphinx expression).
* @return static the query object itself * @return static the query object itself
*/ */
public function from($tables) public function from($tables)
@ -618,8 +636,11 @@ class Query extends Component implements QueryInterface
} }
/** /**
* @param callback $callback * Sets the PHP callback, which should be used to retrieve the source data
* for the snippets building.
* @param callback $callback PHP callback, which should be used to fetch source data for the snippets.
* @return static the query object itself * @return static the query object itself
* @see snippetCallback
*/ */
public function snippetCallback($callback) public function snippetCallback($callback)
{ {
@ -628,8 +649,10 @@ class Query extends Component implements QueryInterface
} }
/** /**
* @param array $options * Sets the call snippets query options.
* @param array $options call snippet options in format: option_name => option_value
* @return static the query object itself * @return static the query object itself
* @see snippetCallback
*/ */
public function snippetOptions($options) public function snippetOptions($options)
{ {
@ -661,7 +684,8 @@ class Query extends Component implements QueryInterface
/** /**
* Builds a snippets from provided source data. * Builds a snippets from provided source data.
* @param array $source the source data to extract a snippet from. * @param array $source the source data to extract a snippet from.
* @return array snippets list * @throws InvalidCallException in case [[match]] is not specified.
* @return array snippets list.
*/ */
protected function callSnippets(array $source) protected function callSnippets(array $source)
{ {

45
extensions/sphinx/QueryBuilder.php

@ -12,7 +12,10 @@ use yii\db\Exception;
use yii\db\Expression; use yii\db\Expression;
/** /**
* Class QueryBuilder * QueryBuilder builds a SELECT SQL statement based on the specification given as a [[Query]] object.
*
* QueryBuilder can also be used to build SQL statements such as INSERT, REPLACE, UPDATE, DELETE,
* from a [[Query]] object.
* *
* @author Paul Klimov <klimov.paul@gmail.com> * @author Paul Klimov <klimov.paul@gmail.com>
* @since 2.0 * @since 2.0
@ -22,7 +25,7 @@ class QueryBuilder extends Object
/** /**
* The prefix for automatically generated query binding parameters. * The prefix for automatically generated query binding parameters.
*/ */
const PARAM_PREFIX = ':sp'; const PARAM_PREFIX = ':qp';
/** /**
* @var Connection the Sphinx connection. * @var Connection the Sphinx connection.
@ -80,6 +83,7 @@ class QueryBuilder extends Object
* $sql = $queryBuilder->insert('idx_user', [ * $sql = $queryBuilder->insert('idx_user', [
* 'name' => 'Sam', * 'name' => 'Sam',
* 'age' => 30, * 'age' => 30,
* 'id' => 10,
* ], $params); * ], $params);
* ~~~ * ~~~
* *
@ -104,6 +108,7 @@ class QueryBuilder extends Object
* $sql = $queryBuilder->replace('idx_user', [ * $sql = $queryBuilder->replace('idx_user', [
* 'name' => 'Sam', * 'name' => 'Sam',
* 'age' => 30, * 'age' => 30,
* 'id' => 10,
* ], $params); * ], $params);
* ~~~ * ~~~
* *
@ -151,10 +156,10 @@ class QueryBuilder extends Object
* For example, * For example,
* *
* ~~~ * ~~~
* $connection->createCommand()->batchInsert('idx_user', ['name', 'age'], [ * $connection->createCommand()->batchInsert('idx_user', ['id', 'name', 'age'], [
* ['Tom', 30], * [1, 'Tom', 30],
* ['Jane', 20], * [2, 'Jane', 20],
* ['Linda', 25], * [3, 'Linda', 25],
* ])->execute(); * ])->execute();
* ~~~ * ~~~
* *
@ -164,7 +169,7 @@ class QueryBuilder extends Object
* @param array $columns the column names * @param array $columns the column names
* @param array $rows the rows to be batch inserted into the index * @param array $rows the rows to be batch inserted into the index
* @param array $params the binding parameters that will be generated by this method. * @param array $params the binding parameters that will be generated by this method.
* They should be bound to the DB command later. * They should be bound to the Sphinx command later.
* @return string the batch INSERT SQL statement * @return string the batch INSERT SQL statement
*/ */
public function batchInsert($index, $columns, $rows, &$params) public function batchInsert($index, $columns, $rows, &$params)
@ -177,10 +182,10 @@ class QueryBuilder extends Object
* For example, * For example,
* *
* ~~~ * ~~~
* $connection->createCommand()->batchReplace('idx_user', ['name', 'age'], [ * $connection->createCommand()->batchReplace('idx_user', ['id', 'name', 'age'], [
* ['Tom', 30], * [1, 'Tom', 30],
* ['Jane', 20], * [2, 'Jane', 20],
* ['Linda', 25], * [3, 'Linda', 25],
* ])->execute(); * ])->execute();
* ~~~ * ~~~
* *
@ -190,7 +195,7 @@ class QueryBuilder extends Object
* @param array $columns the column names * @param array $columns the column names
* @param array $rows the rows to be batch replaced in the index * @param array $rows the rows to be batch replaced in the index
* @param array $params the binding parameters that will be generated by this method. * @param array $params the binding parameters that will be generated by this method.
* They should be bound to the DB command later. * They should be bound to the Sphinx command later.
* @return string the batch INSERT SQL statement * @return string the batch INSERT SQL statement
*/ */
public function batchReplace($index, $columns, $rows, &$params) public function batchReplace($index, $columns, $rows, &$params)
@ -248,7 +253,7 @@ class QueryBuilder extends Object
* @param array|string $condition the condition that will be put in the WHERE part. Please * @param array|string $condition the condition that will be put in the WHERE part. Please
* refer to [[Query::where()]] on how to specify condition. * refer to [[Query::where()]] on how to specify condition.
* @param array $params the binding parameters that will be modified by this method * @param array $params the binding parameters that will be modified by this method
* so that they can be bound to the DB command later. * so that they can be bound to the Sphinx command later.
* @param array $options list of options in format: optionName => optionValue * @param array $options list of options in format: optionName => optionValue
* @return string the UPDATE SQL * @return string the UPDATE SQL
*/ */
@ -282,7 +287,7 @@ class QueryBuilder extends Object
* For example, * For example,
* *
* ~~~ * ~~~
* $sql = $queryBuilder->delete('tbl_user', 'status = 0'); * $sql = $queryBuilder->delete('idx_user', 'status = 0');
* ~~~ * ~~~
* *
* The method will properly escape the index and column names. * The method will properly escape the index and column names.
@ -291,7 +296,7 @@ class QueryBuilder extends Object
* @param array|string $condition the condition that will be put in the WHERE part. Please * @param array|string $condition the condition that will be put in the WHERE part. Please
* refer to [[Query::where()]] on how to specify condition. * refer to [[Query::where()]] on how to specify condition.
* @param array $params the binding parameters that will be modified by this method * @param array $params the binding parameters that will be modified by this method
* so that they can be bound to the DB command later. * so that they can be bound to the Sphinx command later.
* @return string the DELETE SQL * @return string the DELETE SQL
*/ */
public function delete($index, $condition, &$params) public function delete($index, $condition, &$params)
@ -316,13 +321,13 @@ class QueryBuilder extends Object
* @param string $index name of the index, from which to take the text processing settings. * @param string $index name of the index, from which to take the text processing settings.
* @param string|array $source is the source data to extract a snippet from. * @param string|array $source is the source data to extract a snippet from.
* It could be either a single string or array of strings. * It could be either a single string or array of strings.
* @param string $query the full-text query to build snippets for. * @param string $match the full-text query to build snippets for.
* @param array $options list of options in format: optionName => optionValue * @param array $options list of options in format: optionName => optionValue
* @param array $params the binding parameters that will be modified by this method * @param array $params the binding parameters that will be modified by this method
* so that they can be bound to the Sphinx command later. * so that they can be bound to the Sphinx command later.
* @return string the SQL statement for call snippets. * @return string the SQL statement for call snippets.
*/ */
public function callSnippets($index, $source, $query, $options, &$params) public function callSnippets($index, $source, $match, $options, &$params)
{ {
if (is_array($source)) { if (is_array($source)) {
$dataSqlParts = []; $dataSqlParts = [];
@ -339,8 +344,8 @@ class QueryBuilder extends Object
} }
$indexParamName = self::PARAM_PREFIX . count($params); $indexParamName = self::PARAM_PREFIX . count($params);
$params[$indexParamName] = $index; $params[$indexParamName] = $index;
$queryParamName = self::PARAM_PREFIX . count($params); $matchParamName = self::PARAM_PREFIX . count($params);
$params[$queryParamName] = $query; $params[$matchParamName] = $match;
if (!empty($options)) { if (!empty($options)) {
$optionParts = []; $optionParts = [];
foreach ($options as $name => $value) { foreach ($options as $name => $value) {
@ -356,7 +361,7 @@ class QueryBuilder extends Object
} else { } else {
$optionSql = ''; $optionSql = '';
} }
return 'CALL SNIPPETS(' . $dataSql. ', ' . $indexParamName . ', ' . $queryParamName . $optionSql. ')'; return 'CALL SNIPPETS(' . $dataSql. ', ' . $indexParamName . ', ' . $matchParamName . $optionSql. ')';
} }
/** /**

11
extensions/sphinx/README.md

@ -39,4 +39,15 @@ Usage & Documentation
This extension adds [Sphinx](http://sphinxsearch.com/docs) full text search engine extension for the Yii framework. This extension adds [Sphinx](http://sphinxsearch.com/docs) full text search engine extension for the Yii framework.
This extension interact with Sphinx search daemon using MySQL protocol and [SphinxQL](http://sphinxsearch.com/docs/current.html#sphinxql) query language. This extension interact with Sphinx search daemon using MySQL protocol and [SphinxQL](http://sphinxsearch.com/docs/current.html#sphinxql) query language.
In order to setup Sphinx "searchd" to support MySQL protocol following configuration should be added:
```
searchd
{
listen = localhost:9306:mysql41
...
}
```
This extension supports all Sphinx features including [Runtime Indexes](http://sphinxsearch.com/docs/current.html#rt-indexes).
Since this extension uses MySQL protocol to access Sphinx, it shares base approach and much code from the
regular "yii\db" package.

7
extensions/sphinx/Schema.php

@ -15,6 +15,13 @@ use yii\caching\GroupDependency;
/** /**
* Schema represents the Sphinx schema information. * Schema represents the Sphinx schema information.
* *
* @property QueryBuilder $queryBuilder The query builder for this connection. This property is read-only.
* @property string[] $indexNames All index names in the Sphinx. This property is read-only.
* @property string[] $indexTypes ALL index types in the Sphinx (index name => index type).
* This property is read-only.
* @property IndexSchema[] $tableSchemas The metadata for all indexes in the Sphinx. Each array element is an
* instance of [[IndexSchema]] or its child class. This property is read-only.
*
* @author Paul Klimov <klimov.paul@gmail.com> * @author Paul Klimov <klimov.paul@gmail.com>
* @since 2.0 * @since 2.0
*/ */

4
extensions/sphinx/composer.json

@ -19,7 +19,9 @@
], ],
"minimum-stability": "dev", "minimum-stability": "dev",
"require": { "require": {
"yiisoft/yii2": "*" "yiisoft/yii2": "*",
"ext-pdo": "*",
"ext-pdo_mysql": "*"
}, },
"autoload": { "autoload": {
"psr-0": { "yii\\sphinx\\": "" } "psr-0": { "yii\\sphinx\\": "" }

Loading…
Cancel
Save