ea2aa8feeb1f8d0ea86358ca3b66c8a77432aa03
3 * SQLite search backend, based upon SearchMysql
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
25 * Search engine hook for SQLite
28 class SearchSqlite
extends SearchEngine
{
30 * Creates an instance of this class
31 * @param $db DatabaseSqlite: database object
33 function __construct( $db ) {
38 * Whether fulltext search is supported by current schema
41 function fulltextSearchSupported() {
42 return $this->db
->checkForEnabledSearch();
46 * Parse the user's query and transform it into an SQL fragment which will
47 * become part of a WHERE clause
49 function parseQuery( $filteredText, $fulltext ) {
51 $lc = SearchEngine
::legalSearchChars(); // Minus format chars
53 $this->searchTerms
= array();
56 if( preg_match_all( '/([-+<>~]?)(([' . $lc . ']+)(\*?)|"[^"]*")/',
57 $filteredText, $m, PREG_SET_ORDER
) ) {
58 foreach( $m as $bits ) {
59 @list
( /* all */, $modifier, $term, $nonQuoted, $wildcard ) = $bits;
61 if( $nonQuoted != '' ) {
65 $term = str_replace( '"', '', $term );
69 if( $searchon !== '' ) $searchon .= ' ';
71 // Some languages such as Serbian store the input form in the search index,
72 // so we may need to search for matches in multiple writing system variants.
73 $convertedVariants = $wgContLang->autoConvertToAllVariants( $term );
74 if( is_array( $convertedVariants ) ) {
75 $variants = array_unique( array_values( $convertedVariants ) );
77 $variants = array( $term );
80 // The low-level search index does some processing on input to work
81 // around problems with minimum lengths and encoding in MySQL's
83 // For Chinese this also inserts spaces between adjacent Han characters.
84 $strippedVariants = array_map(
85 array( $wgContLang, 'normalizeForSearch' ),
88 // Some languages such as Chinese force all variants to a canonical
89 // form when stripping to the low-level search index, so to be sure
90 // let's check our variants list for unique items after stripping.
91 $strippedVariants = array_unique( $strippedVariants );
93 $searchon .= $modifier;
94 if( count( $strippedVariants) > 1 )
96 foreach( $strippedVariants as $stripped ) {
97 if( $nonQuoted && strpos( $stripped, ' ' ) !== false ) {
98 // Hack for Chinese: we need to toss in quotes for
99 // multiple-character phrases since normalizeForSearch()
100 // added spaces between them to make word breaks.
101 $stripped = '"' . trim( $stripped ) . '"';
103 $searchon .= "$quote$stripped$quote$wildcard ";
105 if( count( $strippedVariants) > 1 )
108 // Match individual terms or quoted phrase in result highlighting...
109 // Note that variants will be introduced in a later stage for highlighting!
110 $regexp = $this->regexTerm( $term, $wildcard );
111 $this->searchTerms
[] = $regexp;
115 wfDebug( __METHOD__
. ": Can't understand search query '{$filteredText}'\n" );
118 $searchon = $this->db
->strencode( $searchon );
119 $field = $this->getIndexField( $fulltext );
120 return " $field MATCH '$searchon' ";
123 function regexTerm( $string, $wildcard ) {
126 $regex = preg_quote( $string, '/' );
127 if( $wgContLang->hasWordBreaks() ) {
129 // Don't cut off the final bit!
132 $regex = "\b$regex\b";
135 // For Chinese, words may legitimately abut other words in the text literal.
136 // Don't add \b boundary checks... note this could cause false positives
142 public static function legalSearchChars() {
143 return "\"*" . parent
::legalSearchChars();
147 * Perform a full text search query and return a result set.
149 * @param $term String: raw search term
150 * @return SqliteSearchResultSet
152 function searchText( $term ) {
153 return $this->searchInternal( $term, true );
157 * Perform a title-only search query and return a result set.
159 * @param $term String: raw search term
160 * @return SqliteSearchResultSet
162 function searchTitle( $term ) {
163 return $this->searchInternal( $term, false );
166 protected function searchInternal( $term, $fulltext ) {
167 global $wgCountTotalSearchHits, $wgContLang;
169 if ( !$this->fulltextSearchSupported() ) {
173 $filteredTerm = $this->filter( $wgContLang->lc( $term ) );
174 $resultSet = $this->db
->query( $this->getQuery( $filteredTerm, $fulltext ) );
177 if( $wgCountTotalSearchHits ) {
178 $totalResult = $this->db
->query( $this->getCountQuery( $filteredTerm, $fulltext ) );
179 $row = $totalResult->fetchObject();
181 $total = intval( $row->c
);
183 $totalResult->free();
186 return new SqliteSearchResultSet( $resultSet, $this->searchTerms
, $total );
191 * Return a partial WHERE clause to exclude redirects, if so set
194 function queryRedirect() {
195 if( $this->showRedirects
) {
198 return 'AND page_is_redirect=0';
203 * Return a partial WHERE clause to limit the search to the given namespaces
206 function queryNamespaces() {
207 if( is_null($this->namespaces
) )
208 return ''; # search all
209 if ( !count( $this->namespaces
) ) {
212 $namespaces = $this->db
->makeList( $this->namespaces
);
214 return 'AND page_namespace IN (' . $namespaces . ')';
218 * Returns a query with limit for number of results set.
219 * @param $sql String:
222 function limitResult( $sql ) {
223 return $this->db
->limitResult( $sql, $this->limit
, $this->offset
);
227 * Construct the full SQL query to do the search.
228 * The guts shoulds be constructed in queryMain()
229 * @param $filteredTerm String
230 * @param $fulltext Boolean
232 function getQuery( $filteredTerm, $fulltext ) {
233 return $this->limitResult(
234 $this->queryMain( $filteredTerm, $fulltext ) . ' ' .
235 $this->queryRedirect() . ' ' .
236 $this->queryNamespaces()
241 * Picks which field to index on, depending on what type of query.
242 * @param $fulltext Boolean
245 function getIndexField( $fulltext ) {
246 return $fulltext ?
'si_text' : 'si_title';
250 * Get the base part of the search query.
252 * @param $filteredTerm String
253 * @param $fulltext Boolean
256 function queryMain( $filteredTerm, $fulltext ) {
257 $match = $this->parseQuery( $filteredTerm, $fulltext );
258 $page = $this->db
->tableName( 'page' );
259 $searchindex = $this->db
->tableName( 'searchindex' );
260 return "SELECT $searchindex.rowid, page_namespace, page_title " .
261 "FROM $page,$searchindex " .
262 "WHERE page_id=$searchindex.rowid AND $match";
265 function getCountQuery( $filteredTerm, $fulltext ) {
266 $match = $this->parseQuery( $filteredTerm, $fulltext );
267 $page = $this->db
->tableName( 'page' );
268 $searchindex = $this->db
->tableName( 'searchindex' );
269 return "SELECT COUNT(*) AS c " .
270 "FROM $page,$searchindex " .
271 "WHERE page_id=$searchindex.rowid AND $match" .
272 $this->queryRedirect() . ' ' .
273 $this->queryNamespaces();
277 * Create or update the search index record for the given page.
278 * Title and text should be pre-processed.
281 * @param $title String
282 * @param $text String
284 function update( $id, $title, $text ) {
285 if ( !$this->fulltextSearchSupported() ) {
288 // @todo: find a method to do it in a single request,
289 // couldn't do it so far due to typelessness of FTS3 tables.
290 $dbw = wfGetDB( DB_MASTER
);
292 $dbw->delete( 'searchindex', array( 'rowid' => $id ), __METHOD__
);
294 $dbw->insert( 'searchindex',
297 'si_title' => $title,
303 * Update a search index record's title only.
304 * Title should be pre-processed.
307 * @param $title String
309 function updateTitle( $id, $title ) {
310 if ( !$this->fulltextSearchSupported() ) {
313 $dbw = wfGetDB( DB_MASTER
);
315 $dbw->update( 'searchindex',
316 array( 'si_title' => $title ),
317 array( 'rowid' => $id ),
325 class SqliteSearchResultSet
extends SqlSearchResultSet
{
326 function SqliteSearchResultSet( $resultSet, $terms, $totalHits=null ) {
327 parent
::__construct( $resultSet, $terms );
328 $this->mTotalHits
= $totalHits;
331 function getTotalHits() {
332 return $this->mTotalHits
;