(bug 26895) in /include/db/LoadBalancer.php function "closeConnecton" should be calle...
[mediawiki.git] / includes / search / SearchPostgres.php
blob639d0a22d64e596a06ef09a5d7ba3793d5357204
1 <?php
2 /**
3 * PostgreSQL search engine
5 * Copyright © 2006-2007 Greg Sabino Mullane <greg@turnstep.com>
6 * http://www.mediawiki.org/
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
23 * @file
24 * @ingroup Search
27 /**
28 * Search engine hook base class for Postgres
29 * @ingroup Search
31 class SearchPostgres extends SearchEngine {
32 /**
33 * Creates an instance of this class
34 * @param $db DatabaseSqlite: database object
36 function __construct( $db ) {
37 parent::__construct( $db );
40 /**
41 * Perform a full text search query via tsearch2 and return a result set.
42 * Currently searches a page's current title (page.page_title) and
43 * latest revision article text (pagecontent.old_text)
45 * @param $term String: raw search term
46 * @return PostgresSearchResultSet
48 function searchTitle( $term ) {
49 $q = $this->searchQuery( $term , 'titlevector', 'page_title' );
50 $olderror = error_reporting(E_ERROR);
51 $resultSet = $this->db->resultObject( $this->db->query( $q, 'SearchPostgres', true ) );
52 error_reporting($olderror);
53 if (!$resultSet) {
54 // Needed for "Query requires full scan, GIN doesn't support it"
55 return new SearchResultTooMany();
57 return new PostgresSearchResultSet( $resultSet, $this->searchTerms );
59 function searchText( $term ) {
60 $q = $this->searchQuery( $term, 'textvector', 'old_text' );
61 $olderror = error_reporting(E_ERROR);
62 $resultSet = $this->db->resultObject( $this->db->query( $q, 'SearchPostgres', true ) );
63 error_reporting($olderror);
64 if (!$resultSet) {
65 return new SearchResultTooMany();
67 return new PostgresSearchResultSet( $resultSet, $this->searchTerms );
72 * Transform the user's search string into a better form for tsearch2
73 * Returns an SQL fragment consisting of quoted text to search for.
75 function parseQuery( $term ) {
77 wfDebug( "parseQuery received: $term \n" );
79 ## No backslashes allowed
80 $term = preg_replace('/\\\/', '', $term);
82 ## Collapse parens into nearby words:
83 $term = preg_replace('/\s*\(\s*/', ' (', $term);
84 $term = preg_replace('/\s*\)\s*/', ') ', $term);
86 ## Treat colons as word separators:
87 $term = preg_replace('/:/', ' ', $term);
89 $searchstring = '';
90 $m = array();
91 if( preg_match_all('/([-!]?)(\S+)\s*/', $term, $m, PREG_SET_ORDER ) ) {
92 foreach( $m as $terms ) {
93 if (strlen($terms[1])) {
94 $searchstring .= ' & !';
96 if (strtolower($terms[2]) === 'and') {
97 $searchstring .= ' & ';
99 else if (strtolower($terms[2]) === 'or' or $terms[2] === '|') {
100 $searchstring .= ' | ';
102 else if (strtolower($terms[2]) === 'not') {
103 $searchstring .= ' & !';
105 else {
106 $searchstring .= " & $terms[2]";
111 ## Strip out leading junk
112 $searchstring = preg_replace('/^[\s\&\|]+/', '', $searchstring);
114 ## Remove any doubled-up operators
115 $searchstring = preg_replace('/([\!\&\|]) +(?:[\&\|] +)+/', "$1 ", $searchstring);
117 ## Remove any non-spaced operators (e.g. "Zounds!")
118 $searchstring = preg_replace('/([^ ])[\!\&\|]/', "$1", $searchstring);
120 ## Remove any trailing whitespace or operators
121 $searchstring = preg_replace('/[\s\!\&\|]+$/', '', $searchstring);
123 ## Remove unnecessary quotes around everything
124 $searchstring = preg_replace('/^[\'"](.*)[\'"]$/', "$1", $searchstring);
126 ## Quote the whole thing
127 $searchstring = $this->db->addQuotes($searchstring);
129 wfDebug( "parseQuery returned: $searchstring \n" );
131 return $searchstring;
136 * Construct the full SQL query to do the search.
137 * @param $term String
138 * @param $fulltext String
139 * @param $colname
141 function searchQuery( $term, $fulltext, $colname ) {
142 $postgresVersion = $this->db->getServerVersion();
144 $prefix = $postgresVersion < 8.3 ? "'default'," : '';
146 # Get the SQL fragment for the given term
147 $searchstring = $this->parseQuery( $term );
149 ## We need a separate query here so gin does not complain about empty searches
150 $SQL = "SELECT to_tsquery($prefix $searchstring)";
151 $res = $this->db->doQuery($SQL);
152 if (!$res) {
153 ## TODO: Better output (example to catch: one 'two)
154 die ("Sorry, that was not a valid search string. Please go back and try again");
156 $top = pg_fetch_result($res,0,0);
158 if ($top === "") { ## e.g. if only stopwords are used XXX return something better
159 $query = "SELECT page_id, page_namespace, page_title, 0 AS score ".
160 "FROM page p, revision r, pagecontent c WHERE p.page_latest = r.rev_id " .
161 "AND r.rev_text_id = c.old_id AND 1=0";
163 else {
164 $m = array();
165 if( preg_match_all("/'([^']+)'/", $top, $m, PREG_SET_ORDER ) ) {
166 foreach( $m as $terms ) {
167 $this->searchTerms[$terms[1]] = $terms[1];
171 $rankscore = $postgresVersion > 8.2 ? 5 : 1;
172 $rank = $postgresVersion < 8.3 ? 'rank' : 'ts_rank';
173 $query = "SELECT page_id, page_namespace, page_title, ".
174 "$rank($fulltext, to_tsquery($prefix $searchstring), $rankscore) AS score ".
175 "FROM page p, revision r, pagecontent c WHERE p.page_latest = r.rev_id " .
176 "AND r.rev_text_id = c.old_id AND $fulltext @@ to_tsquery($prefix $searchstring)";
179 ## Redirects
180 if (! $this->showRedirects)
181 $query .= ' AND page_is_redirect = 0';
183 ## Namespaces - defaults to 0
184 if( !is_null($this->namespaces) ){ // null -> search all
185 if ( count($this->namespaces) < 1)
186 $query .= ' AND page_namespace = 0';
187 else {
188 $namespaces = $this->db->makeList( $this->namespaces );
189 $query .= " AND page_namespace IN ($namespaces)";
193 $query .= " ORDER BY score DESC, page_id DESC";
195 $query .= $this->db->limitResult( '', $this->limit, $this->offset );
197 wfDebug( "searchQuery returned: $query \n" );
199 return $query;
202 ## Most of the work of these two functions are done automatically via triggers
204 function update( $pageid, $title, $text ) {
205 ## We don't want to index older revisions
206 $SQL = "UPDATE pagecontent SET textvector = NULL WHERE old_id IN ".
207 "(SELECT rev_text_id FROM revision WHERE rev_page = " . intval( $pageid ) .
208 " ORDER BY rev_text_id DESC OFFSET 1)";
209 $this->db->query($SQL);
210 return true;
213 function updateTitle( $id, $title ) {
214 return true;
217 } ## end of the SearchPostgres class
220 * @ingroup Search
222 class PostgresSearchResult extends SearchResult {
223 function __construct( $row ) {
224 parent::__construct($row);
225 $this->score = $row->score;
227 function getScore() {
228 return $this->score;
233 * @ingroup Search
235 class PostgresSearchResultSet extends SqlSearchResultSet {
236 function __construct( $resultSet, $terms ) {
237 parent::__construct( $resultSet, $terms );
240 function next() {
241 $row = $this->mResultSet->fetchObject();
242 if( $row === false ) {
243 return false;
244 } else {
245 return new PostgresSearchResult( $row );