2 # Copyright (C) 2006-2007 Greg Sabino Mullane <greg@turnstep.com>
3 # http://www.mediawiki.org/
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
26 * Search engine hook base class for Postgres
29 class SearchPostgres
extends SearchEngine
{
31 function __construct( $db ) {
36 * Perform a full text search query via tsearch2 and return a result set.
37 * Currently searches a page's current title (page.page_title) and
38 * latest revision article text (pagecontent.old_text)
40 * @param $term String: raw search term
41 * @return PostgresSearchResultSet
43 function searchTitle( $term ) {
44 $q = $this->searchQuery( $term , 'titlevector', 'page_title' );
45 $olderror = error_reporting(E_ERROR
);
46 $resultSet = $this->db
->resultObject( $this->db
->query( $q, 'SearchPostgres', true ) );
47 error_reporting($olderror);
49 // Needed for "Query requires full scan, GIN doesn't support it"
50 return new SearchResultTooMany();
52 return new PostgresSearchResultSet( $resultSet, $this->searchTerms
);
54 function searchText( $term ) {
55 $q = $this->searchQuery( $term, 'textvector', 'old_text' );
56 $olderror = error_reporting(E_ERROR
);
57 $resultSet = $this->db
->resultObject( $this->db
->query( $q, 'SearchPostgres', true ) );
58 error_reporting($olderror);
60 return new SearchResultTooMany();
62 return new PostgresSearchResultSet( $resultSet, $this->searchTerms
);
67 * Transform the user's search string into a better form for tsearch2
68 * Returns an SQL fragment consisting of quoted text to search for.
70 function parseQuery( $term ) {
72 wfDebug( "parseQuery received: $term \n" );
74 ## No backslashes allowed
75 $term = preg_replace('/\\\/', '', $term);
77 ## Collapse parens into nearby words:
78 $term = preg_replace('/\s*\(\s*/', ' (', $term);
79 $term = preg_replace('/\s*\)\s*/', ') ', $term);
81 ## Treat colons as word separators:
82 $term = preg_replace('/:/', ' ', $term);
86 if( preg_match_all('/([-!]?)(\S+)\s*/', $term, $m, PREG_SET_ORDER
) ) {
87 foreach( $m as $terms ) {
88 if (strlen($terms[1])) {
89 $searchstring .= ' & !';
91 if (strtolower($terms[2]) === 'and') {
92 $searchstring .= ' & ';
94 else if (strtolower($terms[2]) === 'or' or $terms[2] === '|') {
95 $searchstring .= ' | ';
97 else if (strtolower($terms[2]) === 'not') {
98 $searchstring .= ' & !';
101 $searchstring .= " & $terms[2]";
106 ## Strip out leading junk
107 $searchstring = preg_replace('/^[\s\&\|]+/', '', $searchstring);
109 ## Remove any doubled-up operators
110 $searchstring = preg_replace('/([\!\&\|]) +(?:[\&\|] +)+/', "$1 ", $searchstring);
112 ## Remove any non-spaced operators (e.g. "Zounds!")
113 $searchstring = preg_replace('/([^ ])[\!\&\|]/', "$1", $searchstring);
115 ## Remove any trailing whitespace or operators
116 $searchstring = preg_replace('/[\s\!\&\|]+$/', '', $searchstring);
118 ## Remove unnecessary quotes around everything
119 $searchstring = preg_replace('/^[\'"](.*)[\'"]$/', "$1", $searchstring);
121 ## Quote the whole thing
122 $searchstring = $this->db
->addQuotes($searchstring);
124 wfDebug( "parseQuery returned: $searchstring \n" );
126 return $searchstring;
131 * Construct the full SQL query to do the search.
132 * @param $term String
133 * @param $fulltext String
136 function searchQuery( $term, $fulltext, $colname ) {
139 if ( !isset( $wgDBversion ) ) {
140 $this->db
->getServerVersion();
141 $wgDBversion = $this->db
->numeric_version
;
143 $prefix = $wgDBversion < 8.3 ?
"'default'," : '';
145 # Get the SQL fragment for the given term
146 $searchstring = $this->parseQuery( $term );
148 ## We need a separate query here so gin does not complain about empty searches
149 $SQL = "SELECT to_tsquery($prefix $searchstring)";
150 $res = $this->db
->doQuery($SQL);
152 ## TODO: Better output (example to catch: one 'two)
153 die ("Sorry, that was not a valid search string. Please go back and try again");
155 $top = pg_fetch_result($res,0,0);
157 if ($top === "") { ## e.g. if only stopwords are used XXX return something better
158 $query = "SELECT page_id, page_namespace, page_title, 0 AS score ".
159 "FROM page p, revision r, pagecontent c WHERE p.page_latest = r.rev_id " .
160 "AND r.rev_text_id = c.old_id AND 1=0";
164 if( preg_match_all("/'([^']+)'/", $top, $m, PREG_SET_ORDER
) ) {
165 foreach( $m as $terms ) {
166 $this->searchTerms
[$terms[1]] = $terms[1];
170 $rankscore = $wgDBversion > 8.2 ?
5 : 1;
171 $rank = $wgDBversion < 8.3 ?
'rank' : 'ts_rank';
172 $query = "SELECT page_id, page_namespace, page_title, ".
173 "$rank($fulltext, to_tsquery($prefix $searchstring), $rankscore) AS score ".
174 "FROM page p, revision r, pagecontent c WHERE p.page_latest = r.rev_id " .
175 "AND r.rev_text_id = c.old_id AND $fulltext @@ to_tsquery($prefix $searchstring)";
179 if (! $this->showRedirects
)
180 $query .= ' AND page_is_redirect = 0';
182 ## Namespaces - defaults to 0
183 if( !is_null($this->namespaces
) ){ // null -> search all
184 if ( count($this->namespaces
) < 1)
185 $query .= ' AND page_namespace = 0';
187 $namespaces = $this->db
->makeList( $this->namespaces
);
188 $query .= " AND page_namespace IN ($namespaces)";
192 $query .= " ORDER BY score DESC, page_id DESC";
194 $query .= $this->db
->limitResult( '', $this->limit
, $this->offset
);
196 wfDebug( "searchQuery returned: $query \n" );
201 ## Most of the work of these two functions are done automatically via triggers
203 function update( $pageid, $title, $text ) {
204 ## We don't want to index older revisions
205 $SQL = "UPDATE pagecontent SET textvector = NULL WHERE old_id IN ".
206 "(SELECT rev_text_id FROM revision WHERE rev_page = " . intval( $pageid ) .
207 " ORDER BY rev_text_id DESC OFFSET 1)";
208 $this->db
->doQuery($SQL);
212 function updateTitle( $id, $title ) {
216 } ## end of the SearchPostgres class
221 class PostgresSearchResult
extends SearchResult
{
222 function __construct( $row ) {
223 parent
::__construct($row);
224 $this->score
= $row->score
;
226 function getScore() {
234 class PostgresSearchResultSet
extends SqlSearchResultSet
{
235 function __construct( $resultSet, $terms ) {
236 parent
::__construct( $resultSet, $terms );
240 $row = $this->mResultSet
->fetchObject();
241 if( $row === false ) {
244 return new PostgresSearchResult( $row );