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 $res = $this->db
->selectField( 'updatelog', 'ul_key', array( 'ul_key' => 'fts3' ), __METHOD__
);
49 self
::$fulltextSupported = $res && $this->db
->numRows( $res ) > 0;
51 return self
::$fulltextSupported;
55 * Parse the user's query and transform it into an SQL fragment which will
56 * become part of a WHERE clause
58 function parseQuery( $filteredText, $fulltext ) {
60 $lc = SearchEngine
::legalSearchChars(); // Minus format chars
62 $this->searchTerms
= array();
64 # FIXME: This doesn't handle parenthetical expressions.
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 .= ' ';
80 if( $this->strictMatching
&& ($modifier == '') ) {
81 // If we leave this out, boolean op defaults to OR which is rarely helpful.
85 // Some languages such as Serbian store the input form in the search index,
86 // so we may need to search for matches in multiple writing system variants.
87 $convertedVariants = $wgContLang->autoConvertToAllVariants( $term );
88 if( is_array( $convertedVariants ) ) {
89 $variants = array_unique( array_values( $convertedVariants ) );
91 $variants = array( $term );
94 // The low-level search index does some processing on input to work
95 // around problems with minimum lengths and encoding in MySQL's
97 // For Chinese this also inserts spaces between adjacent Han characters.
98 $strippedVariants = array_map(
99 array( $wgContLang, 'stripForSearch' ),
102 // Some languages such as Chinese force all variants to a canonical
103 // form when stripping to the low-level search index, so to be sure
104 // let's check our variants list for unique items after stripping.
105 $strippedVariants = array_unique( $strippedVariants );
107 $searchon .= $modifier;
108 if( count( $strippedVariants) > 1 )
110 foreach( $strippedVariants as $stripped ) {
111 if( $nonQuoted && strpos( $stripped, ' ' ) !== false ) {
112 // Hack for Chinese: we need to toss in quotes for
113 // multiple-character phrases since stripForSearch()
114 // added spaces between them to make word breaks.
115 $stripped = '"' . trim( $stripped ) . '"';
117 $searchon .= "$quote$stripped$quote$wildcard ";
119 if( count( $strippedVariants) > 1 )
122 // Match individual terms or quoted phrase in result highlighting...
123 // Note that variants will be introduced in a later stage for highlighting!
124 $regexp = $this->regexTerm( $term, $wildcard );
125 $this->searchTerms
[] = $regexp;
127 wfDebug( __METHOD__
. ": Would search with '$searchon'\n" );
128 wfDebug( __METHOD__
. ': Match with /' . implode( '|', $this->searchTerms
) . "/\n" );
130 wfDebug( __METHOD__
. ": Can't understand search query '{$filteredText}'\n" );
133 $searchon = $this->db
->strencode( $searchon );
134 $field = $this->getIndexField( $fulltext );
135 return " $field MATCH '$searchon' ";
138 function regexTerm( $string, $wildcard ) {
141 $regex = preg_quote( $string, '/' );
142 if( $wgContLang->hasWordBreaks() ) {
144 // Don't cut off the final bit!
147 $regex = "\b$regex\b";
150 // For Chinese, words may legitimately abut other words in the text literal.
151 // Don't add \b boundary checks... note this could cause false positives
157 public static function legalSearchChars() {
158 return "\"*" . parent
::legalSearchChars();
162 * Perform a full text search query and return a result set.
164 * @param $term String: raw search term
165 * @return SqliteSearchResultSet
167 function searchText( $term ) {
168 return $this->searchInternal( $term, true );
172 * Perform a title-only search query and return a result set.
174 * @param $term String: raw search term
175 * @return SqliteSearchResultSet
177 function searchTitle( $term ) {
178 return $this->searchInternal( $term, false );
181 protected function searchInternal( $term, $fulltext ) {
182 global $wgSearchMySQLTotalHits, $wgContLang;
184 if ( !$this->fulltextSearchSupported() ) {
188 $filteredTerm = $this->filter( $wgContLang->lc( $term ) );
189 $resultSet = $this->db
->query( $this->getQuery( $filteredTerm, $fulltext ) );
192 if( $wgSearchMySQLTotalHits ) {
193 $totalResult = $this->db
->query( $this->getCountQuery( $filteredTerm, $fulltext ) );
194 $row = $totalResult->fetchObject();
196 $total = intval( $row->c
);
198 $totalResult->free();
201 return new SqliteSearchResultSet( $resultSet, $this->searchTerms
, $total );
206 * Return a partial WHERE clause to exclude redirects, if so set
209 function queryRedirect() {
210 if( $this->showRedirects
) {
213 return 'AND page_is_redirect=0';
218 * Return a partial WHERE clause to limit the search to the given namespaces
221 function queryNamespaces() {
222 if( is_null($this->namespaces
) )
223 return ''; # search all
224 if ( !count( $this->namespaces
) ) {
227 $namespaces = $this->db
->makeList( $this->namespaces
);
229 return 'AND page_namespace IN (' . $namespaces . ')';
233 * Returns a query with limit for number of results set.
234 * @param $sql String:
237 function limitResult( $sql ) {
238 return $this->db
->limitResult( $sql, $this->limit
, $this->offset
);
242 * Does not do anything for generic search engine
243 * subclasses may define this though
246 function queryRanking( $filteredTerm, $fulltext ) {
251 * Construct the full SQL query to do the search.
252 * The guts shoulds be constructed in queryMain()
253 * @param $filteredTerm String
254 * @param $fulltext Boolean
256 function getQuery( $filteredTerm, $fulltext ) {
257 return $this->limitResult(
258 $this->queryMain( $filteredTerm, $fulltext ) . ' ' .
259 $this->queryRedirect() . ' ' .
260 $this->queryNamespaces() . ' ' .
261 $this->queryRanking( $filteredTerm, $fulltext )
266 * Picks which field to index on, depending on what type of query.
267 * @param $fulltext Boolean
270 function getIndexField( $fulltext ) {
271 return $fulltext ?
'si_text' : 'si_title';
275 * Get the base part of the search query.
277 * @param $filteredTerm String
278 * @param $fulltext Boolean
281 function queryMain( $filteredTerm, $fulltext ) {
282 $match = $this->parseQuery( $filteredTerm, $fulltext );
283 $page = $this->db
->tableName( 'page' );
284 $searchindex = $this->db
->tableName( 'searchindex' );
285 return "SELECT $searchindex.rowid, page_namespace, page_title " .
286 "FROM $page,$searchindex " .
287 "WHERE page_id=$searchindex.rowid AND $match";
290 function getCountQuery( $filteredTerm, $fulltext ) {
291 $match = $this->parseQuery( $filteredTerm, $fulltext );
292 $page = $this->db
->tableName( 'page' );
293 $searchindex = $this->db
->tableName( 'searchindex' );
294 return "SELECT COUNT(*) AS c " .
295 "FROM $page,$searchindex " .
296 "WHERE page_id=$searchindex.rowid AND $match" .
297 $this->queryRedirect() . ' ' .
298 $this->queryNamespaces();
302 * Create or update the search index record for the given page.
303 * Title and text should be pre-processed.
306 * @param $title String
307 * @param $text String
309 function update( $id, $title, $text ) {
310 if ( !$this->fulltextSearchSupported() ) {
313 // @todo: find a method to do it in a single request,
314 // couldn't do it so far due to typelessness of FTS3 tables.
315 $dbw = wfGetDB( DB_MASTER
);
317 $dbw->delete( 'searchindex', array( 'rowid' => $id ), __METHOD__
);
319 $dbw->insert( 'searchindex',
322 'si_title' => $title,
328 * Update a search index record's title only.
329 * Title should be pre-processed.
332 * @param $title String
334 function updateTitle( $id, $title ) {
335 if ( !$this->fulltextSearchSupported() ) {
338 $dbw = wfGetDB( DB_MASTER
);
340 $dbw->update( 'searchindex',
341 array( 'rowid' => $id ),
342 array( 'si_title' => $title ),
350 class SqliteSearchResultSet
extends SearchResultSet
{
351 function SqliteSearchResultSet( $resultSet, $terms, $totalHits=null ) {
352 $this->mResultSet
= $resultSet;
353 $this->mTerms
= $terms;
354 $this->mTotalHits
= $totalHits;
357 function termMatches() {
358 return $this->mTerms
;
362 return $this->mResultSet
->numRows();
366 $row = $this->mResultSet
->fetchObject();
367 if( $row === false ) {
370 return new SearchResult( $row );
375 $this->mResultSet
->free();
379 function getTotalHits() {
380 return $this->mTotalHits
;