2 # SQLite search backend, based upon SearchMysql
4 # This program is free software; you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation; either version 2 of the License, or
7 # (at your option) any later version.
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
14 # You should have received a copy of the GNU General Public License along
15 # with this program; if not, write to the Free Software Foundation, Inc.,
16 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 # http://www.gnu.org/copyleft/gpl.html
25 * Search engine hook for SQLite
28 class SearchSqlite
extends SearchEngine
{
29 // Cached because SearchUpdate keeps recreating our class
30 private static $fulltextSupported = null;
33 * Creates an instance of this class
34 * @param $db DatabaseSqlite: database object
36 function __construct( $db ) {
41 * Whether fulltext search is supported by current schema
44 function fulltextSearchSupported() {
45 if ( self
::$fulltextSupported === null ) {
46 self
::$fulltextSupported = $this->db
->selectField(
49 array( 'ul_key' => 'fts3' ),
50 __METHOD__
) !== false;
52 return self
::$fulltextSupported;
56 * Parse the user's query and transform it into an SQL fragment which will
57 * become part of a WHERE clause
59 function parseQuery( $filteredText, $fulltext ) {
61 $lc = SearchEngine
::legalSearchChars(); // Minus format chars
63 $this->searchTerms
= array();
66 if( preg_match_all( '/([-+<>~]?)(([' . $lc . ']+)(\*?)|"[^"]*")/',
67 $filteredText, $m, PREG_SET_ORDER
) ) {
68 foreach( $m as $bits ) {
69 @list
( /* all */, $modifier, $term, $nonQuoted, $wildcard ) = $bits;
71 if( $nonQuoted != '' ) {
75 $term = str_replace( '"', '', $term );
79 if( $searchon !== '' ) $searchon .= ' ';
81 // Some languages such as Serbian store the input form in the search index,
82 // so we may need to search for matches in multiple writing system variants.
83 $convertedVariants = $wgContLang->autoConvertToAllVariants( $term );
84 if( is_array( $convertedVariants ) ) {
85 $variants = array_unique( array_values( $convertedVariants ) );
87 $variants = array( $term );
90 // The low-level search index does some processing on input to work
91 // around problems with minimum lengths and encoding in MySQL's
93 // For Chinese this also inserts spaces between adjacent Han characters.
94 $strippedVariants = array_map(
95 array( $wgContLang, 'normalizeForSearch' ),
98 // Some languages such as Chinese force all variants to a canonical
99 // form when stripping to the low-level search index, so to be sure
100 // let's check our variants list for unique items after stripping.
101 $strippedVariants = array_unique( $strippedVariants );
103 $searchon .= $modifier;
104 if( count( $strippedVariants) > 1 )
106 foreach( $strippedVariants as $stripped ) {
107 if( $nonQuoted && strpos( $stripped, ' ' ) !== false ) {
108 // Hack for Chinese: we need to toss in quotes for
109 // multiple-character phrases since normalizeForSearch()
110 // added spaces between them to make word breaks.
111 $stripped = '"' . trim( $stripped ) . '"';
113 $searchon .= "$quote$stripped$quote$wildcard ";
115 if( count( $strippedVariants) > 1 )
118 // Match individual terms or quoted phrase in result highlighting...
119 // Note that variants will be introduced in a later stage for highlighting!
120 $regexp = $this->regexTerm( $term, $wildcard );
121 $this->searchTerms
[] = $regexp;
125 wfDebug( __METHOD__
. ": Can't understand search query '{$filteredText}'\n" );
128 $searchon = $this->db
->strencode( $searchon );
129 $field = $this->getIndexField( $fulltext );
130 return " $field MATCH '$searchon' ";
133 function regexTerm( $string, $wildcard ) {
136 $regex = preg_quote( $string, '/' );
137 if( $wgContLang->hasWordBreaks() ) {
139 // Don't cut off the final bit!
142 $regex = "\b$regex\b";
145 // For Chinese, words may legitimately abut other words in the text literal.
146 // Don't add \b boundary checks... note this could cause false positives
152 public static function legalSearchChars() {
153 return "\"*" . parent
::legalSearchChars();
157 * Perform a full text search query and return a result set.
159 * @param $term String: raw search term
160 * @return SqliteSearchResultSet
162 function searchText( $term ) {
163 return $this->searchInternal( $term, true );
167 * Perform a title-only search query and return a result set.
169 * @param $term String: raw search term
170 * @return SqliteSearchResultSet
172 function searchTitle( $term ) {
173 return $this->searchInternal( $term, false );
176 protected function searchInternal( $term, $fulltext ) {
177 global $wgCountTotalSearchHits, $wgContLang;
179 if ( !$this->fulltextSearchSupported() ) {
183 $filteredTerm = $this->filter( $wgContLang->lc( $term ) );
184 $resultSet = $this->db
->query( $this->getQuery( $filteredTerm, $fulltext ) );
187 if( $wgCountTotalSearchHits ) {
188 $totalResult = $this->db
->query( $this->getCountQuery( $filteredTerm, $fulltext ) );
189 $row = $totalResult->fetchObject();
191 $total = intval( $row->c
);
193 $totalResult->free();
196 return new SqliteSearchResultSet( $resultSet, $this->searchTerms
, $total );
201 * Return a partial WHERE clause to exclude redirects, if so set
204 function queryRedirect() {
205 if( $this->showRedirects
) {
208 return 'AND page_is_redirect=0';
213 * Return a partial WHERE clause to limit the search to the given namespaces
216 function queryNamespaces() {
217 if( is_null($this->namespaces
) )
218 return ''; # search all
219 if ( !count( $this->namespaces
) ) {
222 $namespaces = $this->db
->makeList( $this->namespaces
);
224 return 'AND page_namespace IN (' . $namespaces . ')';
228 * Returns a query with limit for number of results set.
229 * @param $sql String:
232 function limitResult( $sql ) {
233 return $this->db
->limitResult( $sql, $this->limit
, $this->offset
);
237 * Construct the full SQL query to do the search.
238 * The guts shoulds be constructed in queryMain()
239 * @param $filteredTerm String
240 * @param $fulltext Boolean
242 function getQuery( $filteredTerm, $fulltext ) {
243 return $this->limitResult(
244 $this->queryMain( $filteredTerm, $fulltext ) . ' ' .
245 $this->queryRedirect() . ' ' .
246 $this->queryNamespaces()
251 * Picks which field to index on, depending on what type of query.
252 * @param $fulltext Boolean
255 function getIndexField( $fulltext ) {
256 return $fulltext ?
'si_text' : 'si_title';
260 * Get the base part of the search query.
262 * @param $filteredTerm String
263 * @param $fulltext Boolean
266 function queryMain( $filteredTerm, $fulltext ) {
267 $match = $this->parseQuery( $filteredTerm, $fulltext );
268 $page = $this->db
->tableName( 'page' );
269 $searchindex = $this->db
->tableName( 'searchindex' );
270 return "SELECT $searchindex.rowid, page_namespace, page_title " .
271 "FROM $page,$searchindex " .
272 "WHERE page_id=$searchindex.rowid AND $match";
275 function getCountQuery( $filteredTerm, $fulltext ) {
276 $match = $this->parseQuery( $filteredTerm, $fulltext );
277 $page = $this->db
->tableName( 'page' );
278 $searchindex = $this->db
->tableName( 'searchindex' );
279 return "SELECT COUNT(*) AS c " .
280 "FROM $page,$searchindex " .
281 "WHERE page_id=$searchindex.rowid AND $match" .
282 $this->queryRedirect() . ' ' .
283 $this->queryNamespaces();
287 * Create or update the search index record for the given page.
288 * Title and text should be pre-processed.
291 * @param $title String
292 * @param $text String
294 function update( $id, $title, $text ) {
295 if ( !$this->fulltextSearchSupported() ) {
298 // @todo: find a method to do it in a single request,
299 // couldn't do it so far due to typelessness of FTS3 tables.
300 $dbw = wfGetDB( DB_MASTER
);
302 $dbw->delete( 'searchindex', array( 'rowid' => $id ), __METHOD__
);
304 $dbw->insert( 'searchindex',
307 'si_title' => $title,
313 * Update a search index record's title only.
314 * Title should be pre-processed.
317 * @param $title String
319 function updateTitle( $id, $title ) {
320 if ( !$this->fulltextSearchSupported() ) {
323 $dbw = wfGetDB( DB_MASTER
);
325 $dbw->update( 'searchindex',
326 array( 'rowid' => $id ),
327 array( 'si_title' => $title ),
335 class SqliteSearchResultSet
extends SqlSearchResultSet
{
336 function SqliteSearchResultSet( $resultSet, $terms, $totalHits=null ) {
337 parent
::__construct( $resultSet, $terms );
338 $this->mTotalHits
= $totalHits;
341 function getTotalHits() {
342 return $this->mTotalHits
;