2 * Copyright (c) 2006 Teodor Sigaev <teodor@sigaev.ru>
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 3. Neither the name of the author nor the names of any co-contributors
14 * may be used to endorse or promote products derived from this software
15 * without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY CONTRIBUTORS ``AS IS'' AND ANY EXPRESS
18 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL CONTRIBUTORS BE LIABLE FOR ANY
21 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
23 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
25 * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
26 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
27 * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36 #include <sys/types.h>
37 #include <netinet/in.h>
45 #ifdef HAVE_SYS_POLL_H
48 #error Not defined HAVE_POLL_H or HAVE_SYS_POLL_H
49 #endif /* HAVE_SYS_POLL_H */
50 #endif /* HAVE_POLL */
56 typedef enum SocketState {
64 typedef enum ResStatus {
69 typedef struct ftsPG {
73 PQnoticeReceiver origreceiver;
84 NoticeReceiver(void *arg, const PGresult *res) {
85 ftsPG *db = (ftsPG*) arg;
89 if ( strcmp(PQresultErrorField(res,PG_DIAG_SQLSTATE), "00000") == 0 ) {
90 char *msg = PQresultErrorMessage(res);
92 if ( strstr(msg, "does not exist, skipping")!=NULL ) {
93 /* skip 'NOTICE: table "wow" does not exist, skipping' */
96 if ( strstr(msg, "query contains only stopword(s) or doesn't contain lexeme(s), ignored")!=NULL ) {
102 db->origreceiver(db, res);
109 flushres=PQflush(db->conn);
110 if ( flushres > 0 ) {
111 /* need more write */
112 db->state = SS_WRITE;
113 } else if ( flushres == 0 ) {
114 /* success write, waits for read */
117 fatal( "PQflush failed: %s\n", PQerrorMessage(db->conn));
122 checkStatus(ftsPG* db) {
123 switch( db->state ) {
128 return RS_INPROGRESS;
130 PQconsumeInput(db->conn);
131 if ( PQisBusy(db->conn) != 0 ) {
133 return RS_INPROGRESS;
138 fatal( "Should not be here!\n");
146 waitResult(ftsPG *db) {
152 pfd.events = pfd.revents = 0;
153 if ( db->state == SS_READ ) {
155 } else if ( db->state == SS_WRITE ) {
156 pfd.events = POLLOUT;
160 int ret = poll( &pfd, 1, INFTIM);
162 fatal("poll failed: %s\n", strerror(errno));
164 if ( pfd.revents & (POLLHUP | POLLNVAL | POLLERR) ) {
165 fatal("Poll report about socket error\n");
166 } else if ( pfd.revents & POLLIN ) {
167 db->state = SS_READYREAD;
168 } else if ( pfd.revents & POLLOUT ) {
169 db->state = SS_READYWRITE;
172 } while( checkStatus(db) != RS_OK );
174 while ( (res = PQgetResult(db->conn))!= NULL ) {
175 if (PQresultStatus(res) != PGRES_COMMAND_OK)
176 fatal( "Execution of prepared statement failed: %s\n", PQerrorMessage(db->conn));
182 checkEmptyQuery(ftsPG *db, PGresult *res) {
184 db->emptyquery > 0 &&
185 PQresultStatus(res) == PGRES_FATAL_ERROR &&
186 strcmp(PQresultErrorField(res,PG_DIAG_SQLSTATE), "0A000") == 0 && /* FEATURE_NOT_SUPPORTED */
187 strstr(PQresultErrorField(res, PG_DIAG_SOURCE_FILE), "ginscan.c") != NULL
195 execQuery(ftsDB* adb, char ** words, int flags) {
196 ftsPG *db = (ftsPG*)adb;
197 const char *paramValues[1];
201 if ( db->prepared == 0 ) {
207 sprintf(buf, "SELECT count(*) FROM ftsbench WHERE %s @@ to_tsquery( $1 ::text );",
208 ( flags & FLG_FUNC ) ? "to_tsvector(body)" : "fts" );
210 res = PQprepare( db->conn, "search_ftsbench", buf, 1, NULL );
212 if (PQresultStatus(res) != PGRES_COMMAND_OK)
213 fatal( "PREPARE SELECT command failed: %s\n", PQerrorMessage(db->conn));
225 sb_add(&db->b, (db->flags & FLG_OR) ? " | '" : " & '", 4);
227 sb_add(&db->b, "'", 1);
231 sb_add(&db->b, "'", 1);
232 sb_add(&db->b, ptr, 1);
235 sb_add(&db->b, "'", 1);
241 paramValues[0] = db->b.str;
243 res = PQexecPrepared( db->conn, "search_ftsbench",
247 if (PQresultStatus(res) != PGRES_TUPLES_OK) {
248 /* skip error ' all words are a stop word' for GIN index -
249 result is empty, in any case */
250 if ( checkEmptyQuery(db, res) == 0 )
251 fatal( "Execution of prepared statement failed: %s\n", PQerrorMessage(db->conn));
252 } else if ( PQntuples(res) == 1 ) {
253 db->db.nres += atoi( PQgetvalue(res,0,0) );
255 fatal("Bad PQntuples %d\n", PQntuples(res));
261 pthread_mutex_lock(&(db->db.nqueryMutex));
263 pthread_mutex_unlock(&(db->db.nqueryMutex));
267 startCreateScheme(ftsDB* adb, int flags) {
268 ftsPG *db = (ftsPG*)adb;
274 res = PQexec(db->conn, "DROP TABLE IF EXISTS ftsbench CASCADE;");
275 if (PQresultStatus(res) != PGRES_COMMAND_OK)
276 fatal( "DROP TABLE command failed: %s\n", PQerrorMessage(db->conn));
279 if ( flags & FLG_FUNC )
280 sprintf(buf,"CREATE TABLE ftsbench( id int not null, body text );");
282 sprintf(buf,"CREATE TABLE ftsbench( id int not null, body text, fts tsvector ); "
283 "CREATE TRIGGER tsvectorupdate BEFORE UPDATE OR INSERT ON ftsbench "
284 "FOR EACH ROW EXECUTE PROCEDURE tsearch2(fts, body);" );
286 res = PQexec(db->conn, buf);
287 if (PQresultStatus(res) != PGRES_COMMAND_OK)
288 fatal( "CREATE TABLE command failed: %s\n", PQerrorMessage(db->conn));
291 res = PQexec(db->conn, "BEGIN;");
292 if (PQresultStatus(res) != PGRES_COMMAND_OK)
293 fatal( "CREATE TABLE command failed: %s\n", PQerrorMessage(db->conn));
300 finishCreateScheme(ftsDB* adb) {
301 ftsPG *db = (ftsPG*)adb;
304 if ( db->db.nquery > 0 ) {
307 if ( PQsetnonblocking(db->conn, 0) != 0 )
308 fatal( "PQsetnonblocking command failed: %s\n", PQerrorMessage(db->conn));
311 res = PQexec(db->conn, "COMMIT;");
312 if (PQresultStatus(res) != PGRES_COMMAND_OK)
313 fatal( "CREATE TABLE command failed: %s\n", PQerrorMessage(db->conn));
316 if ( (db->flags & (FLG_GIST | FLG_GIN)) != 0 ) {
319 if ( db->flags & FLG_FUNC )
320 sprintf(buf,"CREATE INDEX ftsindex ON ftsbench USING %s ( to_tsvector(body) );",
321 (db->flags & FLG_GIST) ? "GiST" : "GIN" );
323 sprintf(buf,"CREATE INDEX ftsindex ON ftsbench USING %s ( fts );",
324 (db->flags & FLG_GIST) ? "GiST" : "GIN" );
326 report("(create index, ");
328 res = PQexec(db->conn, buf);
329 if (PQresultStatus(res) != PGRES_COMMAND_OK)
330 fatal( "CREATE INDEX command failed: %s\n", PQerrorMessage(db->conn));
337 res = PQexec(db->conn, "VACUUM ANALYZE ftsbench;");
338 if (PQresultStatus(res) != PGRES_COMMAND_OK)
339 fatal( "VACUUM ANALYZE command failed: %s\n", PQerrorMessage(db->conn));
349 InsertRow(ftsDB* adb, int id, char *txt) {
350 ftsPG *db = (ftsPG*)adb;
352 const char *paramValues[2];
353 uint32_t binaryIntVal;
354 int paramLengths[] = {sizeof(binaryIntVal), 0};
355 int paramFormats[] = {1, 0};
357 if ( db->db.nquery == 0 ) {
360 res = PQprepare( db->conn, "insert_ftsbench",
361 "INSERT INTO ftsbench (id, body) VALUES ( $1 ::int4, $2 ::text);",
364 if (PQresultStatus(res) != PGRES_COMMAND_OK)
365 fatal( "PREPARE INSERT command failed: %s\n", PQerrorMessage(db->conn));
368 if ( PQsetnonblocking(db->conn, 1) != 0 )
369 fatal( "PQsetnonblocking command failed: %s\n", PQerrorMessage(db->conn));
374 binaryIntVal = htonl((uint32_t) id);
375 paramValues[0] = (char*)&binaryIntVal;
376 paramValues[1] = txt;
378 if ( PQsendQueryPrepared( db->conn, "insert_ftsbench",
380 paramLengths, paramFormats, 0) == 0 )
381 fatal( "PQsendQueryPrepared failed: %s\n", PQerrorMessage(db->conn));
390 ftsPG *db = (ftsPG*)adb;
396 PGInit(char * connstr) {
397 ftsPG *db = (ftsPG*)malloc(sizeof(ftsPG));
400 memset(db,0,sizeof(ftsPG));
402 sprintf(conninfo, "dbname=%s", connstr);
403 db->conn = PQconnectdb(conninfo);
405 if (PQstatus(db->conn) != CONNECTION_OK)
406 fatal( "Connection to database failed: %s\n", PQerrorMessage(db->conn));
408 db->origreceiver = PQsetNoticeReceiver(db->conn, NoticeReceiver, (void *)db);
410 db->db.execQuery = execQuery;
411 db->db.startCreateScheme = startCreateScheme;
412 db->db.finishCreateScheme = finishCreateScheme;
413 db->db.InsertRow = InsertRow;
414 db->db.Close = Close;
415 db->socket = PQsocket(db->conn);
416 if ( db->socket < 0 )
417 fatal("Socket error\n");