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
24 use MediaWiki\MediaWikiServices
;
27 * Search engine hook for SQLite
30 class SearchSqlite
extends SearchDatabase
{
32 * Whether fulltext search is supported by current schema
35 function fulltextSearchSupported() {
36 return $this->db
->checkForEnabledSearch();
40 * Parse the user's query and transform it into an SQL fragment which will
41 * become part of a WHERE clause
43 * @param string $filteredText
44 * @param bool $fulltext
47 private function parseQuery( $filteredText, $fulltext ) {
48 $lc = $this->legalSearchChars( self
::CHARS_NO_SYNTAX
); // Minus syntax chars (" and *)
50 $this->searchTerms
= [];
53 if ( preg_match_all( '/([-+<>~]?)(([' . $lc . ']+)(\*?)|"[^"]*")/',
54 $filteredText, $m, PREG_SET_ORDER
) ) {
55 foreach ( $m as $bits ) {
56 Wikimedia\
suppressWarnings();
57 list( /* all */, $modifier, $term, $nonQuoted, $wildcard ) = $bits;
58 Wikimedia\restoreWarnings
();
60 if ( $nonQuoted != '' ) {
64 $term = str_replace( '"', '', $term );
68 if ( $searchon !== '' ) {
72 // Some languages such as Serbian store the input form in the search index,
73 // so we may need to search for matches in multiple writing system variants.
74 $convertedVariants = MediaWikiServices
::getInstance()->getContentLanguage()->
75 autoConvertToAllVariants( $term );
76 if ( is_array( $convertedVariants ) ) {
77 $variants = array_unique( array_values( $convertedVariants ) );
79 $variants = [ $term ];
82 // The low-level search index does some processing on input to work
83 // around problems with minimum lengths and encoding in MySQL's
85 // For Chinese this also inserts spaces between adjacent Han characters.
86 $strippedVariants = array_map(
87 [ MediaWikiServices
::getInstance()->getContentLanguage(),
88 'normalizeForSearch' ],
91 // Some languages such as Chinese force all variants to a canonical
92 // form when stripping to the low-level search index, so to be sure
93 // let's check our variants list for unique items after stripping.
94 $strippedVariants = array_unique( $strippedVariants );
96 $searchon .= $modifier;
97 if ( count( $strippedVariants ) > 1 ) {
100 foreach ( $strippedVariants as $stripped ) {
101 if ( $nonQuoted && strpos( $stripped, ' ' ) !== false ) {
102 // Hack for Chinese: we need to toss in quotes for
103 // multiple-character phrases since normalizeForSearch()
104 // added spaces between them to make word breaks.
105 $stripped = '"' . trim( $stripped ) . '"';
107 $searchon .= "$quote$stripped$quote$wildcard ";
109 if ( count( $strippedVariants ) > 1 ) {
113 // Match individual terms or quoted phrase in result highlighting...
114 // Note that variants will be introduced in a later stage for highlighting!
115 $regexp = $this->regexTerm( $term, $wildcard );
116 $this->searchTerms
[] = $regexp;
120 wfDebug( __METHOD__
. ": Can't understand search query '{$filteredText}'\n" );
123 $searchon = $this->db
->addQuotes( $searchon );
124 $field = $this->getIndexField( $fulltext );
125 return " $field MATCH $searchon ";
128 private function regexTerm( $string, $wildcard ) {
129 $regex = preg_quote( $string, '/' );
130 if ( MediaWikiServices
::getInstance()->getContentLanguage()->hasWordBreaks() ) {
132 // Don't cut off the final bit!
135 $regex = "\b$regex\b";
138 // For Chinese, words may legitimately abut other words in the text literal.
139 // Don't add \b boundary checks... note this could cause false positives
145 public function legalSearchChars( $type = self
::CHARS_ALL
) {
146 $searchChars = parent
::legalSearchChars( $type );
147 if ( $type === self
::CHARS_ALL
) {
148 // " for phrase, * for wildcard
149 $searchChars = "\"*" . $searchChars;
155 * Perform a full text search query and return a result set.
157 * @param string $term Raw search term
158 * @return SqlSearchResultSet
160 protected function doSearchTextInDB( $term ) {
161 return $this->searchInternal( $term, true );
165 * Perform a title-only search query and return a result set.
167 * @param string $term Raw search term
168 * @return SqlSearchResultSet
170 protected function doSearchTitleInDB( $term ) {
171 return $this->searchInternal( $term, false );
174 protected function searchInternal( $term, $fulltext ) {
175 if ( !$this->fulltextSearchSupported() ) {
180 $this->filter( MediaWikiServices
::getInstance()->getContentLanguage()->lc( $term ) );
181 $resultSet = $this->db
->query( $this->getQuery( $filteredTerm, $fulltext ) );
184 $totalResult = $this->db
->query( $this->getCountQuery( $filteredTerm, $fulltext ) );
185 $row = $totalResult->fetchObject();
187 $total = intval( $row->c
);
189 $totalResult->free();
191 return new SqlSearchResultSet( $resultSet, $this->searchTerms
, $total );
195 * Return a partial WHERE clause to limit the search to the given namespaces
198 private function queryNamespaces() {
199 if ( is_null( $this->namespaces
) ) {
200 return ''; # search all
202 if ( $this->namespaces
=== [] ) {
205 $namespaces = $this->db
->makeList( $this->namespaces
);
207 return 'AND page_namespace IN (' . $namespaces . ')';
211 * Returns a query with limit for number of results set.
215 private function limitResult( $sql ) {
216 return $this->db
->limitResult( $sql, $this->limit
, $this->offset
);
220 * Construct the full SQL query to do the search.
221 * The guts shoulds be constructed in queryMain()
222 * @param string $filteredTerm
223 * @param bool $fulltext
226 private function getQuery( $filteredTerm, $fulltext ) {
227 return $this->limitResult(
228 $this->queryMain( $filteredTerm, $fulltext ) . ' ' .
229 $this->queryNamespaces()
234 * Picks which field to index on, depending on what type of query.
235 * @param bool $fulltext
238 private function getIndexField( $fulltext ) {
239 return $fulltext ?
'si_text' : 'si_title';
243 * Get the base part of the search query.
245 * @param string $filteredTerm
246 * @param bool $fulltext
249 private function queryMain( $filteredTerm, $fulltext ) {
250 $match = $this->parseQuery( $filteredTerm, $fulltext );
251 $page = $this->db
->tableName( 'page' );
252 $searchindex = $this->db
->tableName( 'searchindex' );
253 return "SELECT $searchindex.rowid, page_namespace, page_title " .
254 "FROM $page,$searchindex " .
255 "WHERE page_id=$searchindex.rowid AND $match";
258 private function getCountQuery( $filteredTerm, $fulltext ) {
259 $match = $this->parseQuery( $filteredTerm, $fulltext );
260 $page = $this->db
->tableName( 'page' );
261 $searchindex = $this->db
->tableName( 'searchindex' );
262 return "SELECT COUNT(*) AS c " .
263 "FROM $page,$searchindex " .
264 "WHERE page_id=$searchindex.rowid AND $match " .
265 $this->queryNamespaces();
269 * Create or update the search index record for the given page.
270 * Title and text should be pre-processed.
273 * @param string $title
274 * @param string $text
276 function update( $id, $title, $text ) {
277 if ( !$this->fulltextSearchSupported() ) {
280 // @todo find a method to do it in a single request,
281 // couldn't do it so far due to typelessness of FTS3 tables.
282 $dbw = wfGetDB( DB_MASTER
);
284 $dbw->delete( 'searchindex', [ 'rowid' => $id ], __METHOD__
);
286 $dbw->insert( 'searchindex',
289 'si_title' => $title,
295 * Update a search index record's title only.
296 * Title should be pre-processed.
299 * @param string $title
301 function updateTitle( $id, $title ) {
302 if ( !$this->fulltextSearchSupported() ) {
305 $dbw = wfGetDB( DB_MASTER
);
307 $dbw->update( 'searchindex',
308 [ 'si_title' => $title ],