a3e83d9e7ba2bf41872ff88eb093d60392732a31
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 var $strictMatching = true;
31 // Cached because SearchUpdate keeps recreating our class
32 private static $fulltextSupported = null;
35 * Creates an instance of this class
36 * @param $db DatabaseSqlite: database object
38 function __construct( $db ) {
43 * Whether fulltext search is supported by current schema
46 function fulltextSearchSupported() {
47 if ( self
::$fulltextSupported === null ) {
48 self
::$fulltextSupported = $this->db
->selectField(
51 array( 'ul_key' => 'fts3' ),
52 __METHOD__
) !== false;
54 return self
::$fulltextSupported;
58 * Parse the user's query and transform it into an SQL fragment which will
59 * become part of a WHERE clause
61 function parseQuery( $filteredText, $fulltext ) {
63 $lc = SearchEngine
::legalSearchChars(); // Minus format chars
65 $this->searchTerms
= array();
67 # FIXME: This doesn't handle parenthetical expressions.
69 if( preg_match_all( '/([-+<>~]?)(([' . $lc . ']+)(\*?)|"[^"]*")/',
70 $filteredText, $m, PREG_SET_ORDER
) ) {
71 foreach( $m as $bits ) {
72 @list
( /* all */, $modifier, $term, $nonQuoted, $wildcard ) = $bits;
74 if( $nonQuoted != '' ) {
78 $term = str_replace( '"', '', $term );
82 if( $searchon !== '' ) $searchon .= ' ';
83 if( $this->strictMatching
&& ($modifier == '') ) {
84 // If we leave this out, boolean op defaults to OR which is rarely helpful.
88 // Some languages such as Serbian store the input form in the search index,
89 // so we may need to search for matches in multiple writing system variants.
90 $convertedVariants = $wgContLang->autoConvertToAllVariants( $term );
91 if( is_array( $convertedVariants ) ) {
92 $variants = array_unique( array_values( $convertedVariants ) );
94 $variants = array( $term );
97 // The low-level search index does some processing on input to work
98 // around problems with minimum lengths and encoding in MySQL's
100 // For Chinese this also inserts spaces between adjacent Han characters.
101 $strippedVariants = array_map(
102 array( $wgContLang, 'stripForSearch' ),
105 // Some languages such as Chinese force all variants to a canonical
106 // form when stripping to the low-level search index, so to be sure
107 // let's check our variants list for unique items after stripping.
108 $strippedVariants = array_unique( $strippedVariants );
110 $searchon .= $modifier;
111 if( count( $strippedVariants) > 1 )
113 foreach( $strippedVariants as $stripped ) {
114 if( $nonQuoted && strpos( $stripped, ' ' ) !== false ) {
115 // Hack for Chinese: we need to toss in quotes for
116 // multiple-character phrases since stripForSearch()
117 // added spaces between them to make word breaks.
118 $stripped = '"' . trim( $stripped ) . '"';
120 $searchon .= "$quote$stripped$quote$wildcard ";
122 if( count( $strippedVariants) > 1 )
125 // Match individual terms or quoted phrase in result highlighting...
126 // Note that variants will be introduced in a later stage for highlighting!
127 $regexp = $this->regexTerm( $term, $wildcard );
128 $this->searchTerms
[] = $regexp;
130 wfDebug( __METHOD__
. ": Would search with '$searchon'\n" );
131 wfDebug( __METHOD__
. ': Match with /' . implode( '|', $this->searchTerms
) . "/\n" );
133 wfDebug( __METHOD__
. ": Can't understand search query '{$filteredText}'\n" );
136 $searchon = $this->db
->strencode( $searchon );
137 $field = $this->getIndexField( $fulltext );
138 return " $field MATCH '$searchon' ";
141 function regexTerm( $string, $wildcard ) {
144 $regex = preg_quote( $string, '/' );
145 if( $wgContLang->hasWordBreaks() ) {
147 // Don't cut off the final bit!
150 $regex = "\b$regex\b";
153 // For Chinese, words may legitimately abut other words in the text literal.
154 // Don't add \b boundary checks... note this could cause false positives
160 public static function legalSearchChars() {
161 return "\"*" . parent
::legalSearchChars();
165 * Perform a full text search query and return a result set.
167 * @param $term String: raw search term
168 * @return SqliteSearchResultSet
170 function searchText( $term ) {
171 return $this->searchInternal( $term, true );
175 * Perform a title-only search query and return a result set.
177 * @param $term String: raw search term
178 * @return SqliteSearchResultSet
180 function searchTitle( $term ) {
181 return $this->searchInternal( $term, false );
184 protected function searchInternal( $term, $fulltext ) {
185 global $wgSearchMySQLTotalHits, $wgContLang;
187 if ( !$this->fulltextSearchSupported() ) {
191 $filteredTerm = $this->filter( $wgContLang->lc( $term ) );
192 $resultSet = $this->db
->query( $this->getQuery( $filteredTerm, $fulltext ) );
195 if( $wgSearchMySQLTotalHits ) {
196 $totalResult = $this->db
->query( $this->getCountQuery( $filteredTerm, $fulltext ) );
197 $row = $totalResult->fetchObject();
199 $total = intval( $row->c
);
201 $totalResult->free();
204 return new SqliteSearchResultSet( $resultSet, $this->searchTerms
, $total );
209 * Return a partial WHERE clause to exclude redirects, if so set
212 function queryRedirect() {
213 if( $this->showRedirects
) {
216 return 'AND page_is_redirect=0';
221 * Return a partial WHERE clause to limit the search to the given namespaces
224 function queryNamespaces() {
225 if( is_null($this->namespaces
) )
226 return ''; # search all
227 if ( !count( $this->namespaces
) ) {
230 $namespaces = $this->db
->makeList( $this->namespaces
);
232 return 'AND page_namespace IN (' . $namespaces . ')';
236 * Returns a query with limit for number of results set.
237 * @param $sql String:
240 function limitResult( $sql ) {
241 return $this->db
->limitResult( $sql, $this->limit
, $this->offset
);
245 * Does not do anything for generic search engine
246 * subclasses may define this though
249 function queryRanking( $filteredTerm, $fulltext ) {
254 * Construct the full SQL query to do the search.
255 * The guts shoulds be constructed in queryMain()
256 * @param $filteredTerm String
257 * @param $fulltext Boolean
259 function getQuery( $filteredTerm, $fulltext ) {
260 return $this->limitResult(
261 $this->queryMain( $filteredTerm, $fulltext ) . ' ' .
262 $this->queryRedirect() . ' ' .
263 $this->queryNamespaces() . ' ' .
264 $this->queryRanking( $filteredTerm, $fulltext )
269 * Picks which field to index on, depending on what type of query.
270 * @param $fulltext Boolean
273 function getIndexField( $fulltext ) {
274 return $fulltext ?
'si_text' : 'si_title';
278 * Get the base part of the search query.
280 * @param $filteredTerm String
281 * @param $fulltext Boolean
284 function queryMain( $filteredTerm, $fulltext ) {
285 $match = $this->parseQuery( $filteredTerm, $fulltext );
286 $page = $this->db
->tableName( 'page' );
287 $searchindex = $this->db
->tableName( 'searchindex' );
288 return "SELECT $searchindex.rowid, page_namespace, page_title " .
289 "FROM $page,$searchindex " .
290 "WHERE page_id=$searchindex.rowid AND $match";
293 function getCountQuery( $filteredTerm, $fulltext ) {
294 $match = $this->parseQuery( $filteredTerm, $fulltext );
295 $page = $this->db
->tableName( 'page' );
296 $searchindex = $this->db
->tableName( 'searchindex' );
297 return "SELECT COUNT(*) AS c " .
298 "FROM $page,$searchindex " .
299 "WHERE page_id=$searchindex.rowid AND $match" .
300 $this->queryRedirect() . ' ' .
301 $this->queryNamespaces();
305 * Create or update the search index record for the given page.
306 * Title and text should be pre-processed.
309 * @param $title String
310 * @param $text String
312 function update( $id, $title, $text ) {
313 if ( !$this->fulltextSearchSupported() ) {
316 // @todo: find a method to do it in a single request,
317 // couldn't do it so far due to typelessness of FTS3 tables.
318 $dbw = wfGetDB( DB_MASTER
);
320 $dbw->delete( 'searchindex', array( 'rowid' => $id ), __METHOD__
);
322 $dbw->insert( 'searchindex',
325 'si_title' => $title,
331 * Update a search index record's title only.
332 * Title should be pre-processed.
335 * @param $title String
337 function updateTitle( $id, $title ) {
338 if ( !$this->fulltextSearchSupported() ) {
341 $dbw = wfGetDB( DB_MASTER
);
343 $dbw->update( 'searchindex',
344 array( 'rowid' => $id ),
345 array( 'si_title' => $title ),
353 class SqliteSearchResultSet
extends SearchResultSet
{
354 function SqliteSearchResultSet( $resultSet, $terms, $totalHits=null ) {
355 $this->mResultSet
= $resultSet;
356 $this->mTerms
= $terms;
357 $this->mTotalHits
= $totalHits;
360 function termMatches() {
361 return $this->mTerms
;
365 return $this->mResultSet
->numRows();
369 $row = $this->mResultSet
->fetchObject();
370 if( $row === false ) {
373 return new SearchResult( $row );
378 $this->mResultSet
->free();
382 function getTotalHits() {
383 return $this->mTotalHits
;