/[pgswish]/trunk/pgswish.c
This is repository of my old source code which isn't updated any more. Go to git.rot13.org for current projects!
ViewVC logotype

Diff of /trunk/pgswish.c

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 18 by dpavlin, Sun Feb 20 22:58:25 2005 UTC revision 22 by dpavlin, Sun May 29 22:41:20 2005 UTC
# Line 6  Line 6 
6   * TODO:   * TODO:
7   * - check null input using PG_ARGISNULL before using PG_GETARG_xxxx   * - check null input using PG_ARGISNULL before using PG_GETARG_xxxx
8   * - support composite type arguments   * - support composite type arguments
9     * - split error_or_abort
10     * - use getResultPropValue not SwishResultPropertyStr
11     * - fix everything about pgswish_arr which is broken
12   *   *
13   * NOTES:   * NOTES:
14   * - clear structures with memset to support hash indexes (who whould like   * - clear structures with memset to support hash indexes (who whould like
# Line 34  Line 37 
37  #define GET_STR(textp) DatumGetCString(DirectFunctionCall1(textout, PointerGetDatum(textp)))  #define GET_STR(textp) DatumGetCString(DirectFunctionCall1(textout, PointerGetDatum(textp)))
38  #define GET_TEXT(cstrp) DatumGetTextP(DirectFunctionCall1(textin, CStringGetDatum(cstrp)))  #define GET_TEXT(cstrp) DatumGetTextP(DirectFunctionCall1(textin, CStringGetDatum(cstrp)))
39    
40    /* Globals */
41  SW_HANDLE   swish_handle = NULL;/* Database handle */  static SW_HANDLE   swish_handle = NULL; /* Database handle */
42  SW_SEARCH   search = NULL;      /* search handle -- holds search parameters */  static SW_SEARCH   search = NULL;       /* search handle -- search parameters */
43  SW_RESULTS  swish_results = NULL;       /* results handle -- holds list of results */  static SW_RESULTS  swish_results = NULL; /* results handle -- list of results */
44  SW_RESULT   *sw_res = NULL;     /* one row from swish-e results */  static SW_RESULT   *sw_res = NULL;      /* one row from swish-e results */
45    
46  /* define PostgreSQL v1 function */  /* define PostgreSQL v1 function */
47  PG_FUNCTION_INFO_V1(pgswish);  PG_FUNCTION_INFO_V1(pgswish);
# Line 52  Datum pgswish(PG_FUNCTION_ARGS) { Line 55  Datum pgswish(PG_FUNCTION_ARGS) {
55          AttInMetadata   *attinmeta;          AttInMetadata   *attinmeta;
56          char            *index_path;          char            *index_path;
57          char            *query;          char            *query;
58            FILE            *logfh;
59    
60          /* stuff done only on the first call of the function */          /* stuff done only on the first call of the function */
61          if (SRF_IS_FIRSTCALL()) {          if (SRF_IS_FIRSTCALL()) {
# Line 69  Datum pgswish(PG_FUNCTION_ARGS) { Line 73  Datum pgswish(PG_FUNCTION_ARGS) {
73                  oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);                  oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
74    
75                                    
76                  /* Send any errors or warnings to stderr (default is stdout) */                  /* Send any errors or warnings to log, as well as
77                  SwishErrorsToStderr();                   * STDOUT and STDERR (just to be sure) */
78                    if ( logfh = fopen("/tmp/pgswish.log", "a") ) {
79                            set_error_handle( logfh );
80                            elog(INFO, "loggin swish-e errors to /tmp/pgswish.log");
81                            /* redirect STDOUT and STDERR to log */
82                            dup2(1, logfh);
83                            dup2(2, logfh);
84                    } else {
85                            elog(INFO, "can't open /tmp/pgswish.log -- errors from swish-e won't be cought and may result in back-end crashes!");
86                    }
87    
88                  elog(INFO, "pgswish: SwishInit(%s)", index_path);                  elog(INFO, "pgswish: SwishInit(%s)", index_path);
89                    
90                  swish_handle = SwishInit( index_path );                  swish_handle = SwishInit( index_path );
91    
92                    if ( SwishError( swish_handle ) )
93                            elog(INFO, "pgswish: SwishInit(%s) failed: %s", index_path, SwishErrorString( swish_handle ));
94                    
95                    elog(INFO, "handle: %08x", swish_handle);
96    
97                  if (! swish_handle) {                  if (! swish_handle) {
98                          elog(ERROR, "pgswish: can't open %s", index_path);                          elog(ERROR, "pgswish: can't open %s", index_path);
99                          SRF_RETURN_DONE(funcctx);                          SRF_RETURN_DONE(funcctx);
100                  }                  }
101                                    
102                  error_or_abort( swish_handle );                  if (error_or_abort( swish_handle )) SRF_RETURN_DONE(funcctx);
103                  /* set ranking scheme. default is 0 */                  /* set ranking scheme. default is 0 */
104                  SwishRankScheme( swish_handle, 0 );                  SwishRankScheme( swish_handle, 0 );
105                  error_or_abort( swish_handle );                  if (error_or_abort( swish_handle )) SRF_RETURN_DONE(funcctx);
106    
107                  elog(INFO, "pgswish: SwishQuery(%s)", query);                  elog(INFO, "pgswish: SwishQuery(%s)", query);
108                  /* Here's a short-cut to searching that creates a search object and searches at the same time */                  /* Here's a short-cut to searching that creates a search object and searches at the same time */
109                  swish_results = SwishQuery( swish_handle, query);                  swish_results = SwishQuery( swish_handle, query);
110                  error_or_abort( swish_handle );                  if (error_or_abort( swish_handle )) SRF_RETURN_DONE(funcctx);
111    
112                  /* total number of tuples to be returned */                  /* total number of tuples to be returned */
113                  funcctx->max_calls = SwishHits( swish_results );                  funcctx->max_calls = SwishHits( swish_results );
# Line 142  Datum pgswish(PG_FUNCTION_ARGS) { Line 160  Datum pgswish(PG_FUNCTION_ARGS) {
160                  }                  }
161                                    
162                  elog(DEBUG1, "pgswish: check for swish-e error");                  elog(DEBUG1, "pgswish: check for swish-e error");
163                  error_or_abort( swish_handle );                  if (error_or_abort( swish_handle )) SRF_RETURN_DONE(funcctx);
164    
165                  /*                  /*
166                   * Prepare a values array for storage in our slot.                   * Prepare a values array for storage in our slot.
# Line 153  Datum pgswish(PG_FUNCTION_ARGS) { Line 171  Datum pgswish(PG_FUNCTION_ARGS) {
171                  sw_res = SwishNextResult( swish_results );                  sw_res = SwishNextResult( swish_results );
172                  if (! sw_res) {                  if (! sw_res) {
173                          elog(ERROR, "pgswish: swish-e sort result list: %d rows expected %d", call_cntr, max_calls - 1);                          elog(ERROR, "pgswish: swish-e sort result list: %d rows expected %d", call_cntr, max_calls - 1);
174                            Free_Results_Object( swish_results );
175                            Free_Search_Object( search );
176                          SRF_RETURN_DONE(funcctx);                          SRF_RETURN_DONE(funcctx);
177                  }                  }
178                                    
# Line 213  Datum pgswish(PG_FUNCTION_ARGS) { Line 233  Datum pgswish(PG_FUNCTION_ARGS) {
233          }          }
234  }  }
235    
236  /* work in progress */  
237  PG_FUNCTION_INFO_V1(pgswish2);  /*
238  Datum pgswish2(PG_FUNCTION_ARGS)   * new function with support for property selection
239     */
240    
241    PG_FUNCTION_INFO_V1(pgswish_arr);
242    Datum pgswish_arr(PG_FUNCTION_ARGS)
243  {  {
244          int             nrows = 3;          ArrayType       *prop_arr = PG_GETARG_ARRAYTYPE_P(5);
245          int16           typlen;          Oid             prop_element_type = ARR_ELEMTYPE(prop_arr);
246          bool            typbyval;          int             prop_ndims = ARR_NDIM(prop_arr);
247          char            typalign;          int             *prop_dim_counts = ARR_DIMS(prop_arr);
248            int             *prop_dim_lower_bounds = ARR_LBOUND(prop_arr);
249            int             ncols = 0;
250            int             nrows = 0;
251            int             indx[MAXDIM];
252            int16           prop_len;
253            bool            prop_byval;
254            char            prop_align;
255          ReturnSetInfo   *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;          ReturnSetInfo   *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
256          AttInMetadata   *attinmeta;          AttInMetadata   *attinmeta;
257          TupleDesc       tupdesc;          TupleDesc       tupdesc;
258          Tuplestorestate *tupstore = NULL;          Tuplestorestate *tupstore = NULL;
259          HeapTuple       tuple;          HeapTuple       tuple;
260          MemoryContext   per_query_ctx;          MemoryContext   per_query_ctx;
261          MemoryContext   oldcontext;          MemoryContext   oldcontext;
262          Datum           dvalue;          Datum           dvalue;
263          char            **values;          char            **values;
264          int             ncols;          int             rsinfo_ncols;
265          int             i, j;          int             i, j;
266            /* swish-e */
267            FILE            *logfh;
268            int             resnum;
269            int             limit = 0;
270            int             offset = 0;
271    
272            char            *index_path;
273            char            *query;
274            char            *attr;
275    
276    
277            /* only allow 1D input array */
278            if (prop_ndims == 1)
279            {
280                    ncols = prop_dim_counts[0];
281            }
282            else
283                    ereport(ERROR,
284                                    (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
285                                     errmsg("invalid input array"),
286                                     errdetail("Input array must have 1 dimension")));
287                    
288          /* check to see if caller supports us returning a tuplestore */          /* check to see if caller supports us returning a tuplestore */
289          if (!rsinfo || !(rsinfo->allowedModes & SFRM_Materialize))          if (!rsinfo || !(rsinfo->allowedModes & SFRM_Materialize))
290                  ereport(ERROR,                  ereport(ERROR,
# Line 240  Datum pgswish2(PG_FUNCTION_ARGS) Line 292  Datum pgswish2(PG_FUNCTION_ARGS)
292                                   errmsg("materialize mode required, but it is not " \                                   errmsg("materialize mode required, but it is not " \
293                                                  "allowed in this context")));                                                  "allowed in this context")));
294    
295            /* get info about element type needed to construct the array */
296            get_typlenbyvalalign(prop_element_type, &prop_len, &prop_byval, &prop_align);
297    
298          /* get the requested return tuple description */          /* get the requested return tuple description */
299          tupdesc = rsinfo->expectedDesc;          tupdesc = rsinfo->expectedDesc;
300          ncols = tupdesc->natts;          rsinfo_ncols = tupdesc->natts;
301    
302          /*          /*
303           * The requested tuple description better match up with the array           * The requested tuple description better match up with the array
304           * we were given.           * we were given.
305           */           */
306            if (rsinfo_ncols != ncols)
307                    ereport(ERROR,
308                                    (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
309                                     errmsg("invalid input array"),
310                                     errdetail("Number of elements in array must match number of query specified columns.")));
311    
312          /* OK, use it */          /* OK, use it */
313          attinmeta = TupleDescGetAttInMetadata(tupdesc);          attinmeta = TupleDescGetAttInMetadata(tupdesc);
314    
# Line 260  Datum pgswish2(PG_FUNCTION_ARGS) Line 321  Datum pgswish2(PG_FUNCTION_ARGS)
321          /* initialize our tuplestore */          /* initialize our tuplestore */
322          tupstore = tuplestore_begin_heap(true, false, SortMem);          tupstore = tuplestore_begin_heap(true, false, SortMem);
323    
324    
325            /* take rest of arguments from function */
326    
327            /* index path */
328            if (PG_ARGISNULL(0)) {
329                    ereport(ERROR,
330                                    (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
331                                     errmsg("index path can't be null"),
332                                     errdetail("Index path must be valid full path to swish-e index")));
333            }
334            index_path = _textout(PG_GETARG_TEXT_P(0));
335    
336            /* query string */
337            if (PG_ARGISNULL(0)) {
338                    query = "";
339            } else {
340                    query = _textout(PG_GETARG_TEXT_P(1));
341            }
342    
343            /* atribute filter */
344            if (PG_ARGISNULL(2)) {
345                    attr = "";
346            } else {
347                    attr = _textout(PG_GETARG_TEXT_P(2));
348            }
349    
350            /* limit */
351            if (PG_ARGISNULL(3)) {
352                    limit = 0;
353            } else {
354                    limit = PG_GETARG_INT32(3);
355            }
356    
357            /* offset */
358            if (PG_ARGISNULL(4)) {
359                    offset = 0;
360            } else {
361                    offset = PG_GETARG_INT32(4);
362            }
363    
364    
365            /* Send any errors or warnings to log, as well as
366             * STDOUT and STDERR (just to be sure) */
367            if ( logfh = fopen("/tmp/pgswish.log", "a") ) {
368                    set_error_handle( logfh );
369                    elog(INFO, "loggin swish-e errors to /tmp/pgswish.log");
370                    /* redirect STDOUT and STDERR to log */
371                    dup2(1, logfh);
372                    dup2(2, logfh);
373            } else {
374                    elog(INFO, "can't open /tmp/pgswish.log -- errors from swish-e won't be cought and may result in back-end crashes!");
375            }
376    
377            elog(INFO, "pgswish: SwishInit(%s)", index_path);
378    
379            swish_handle = SwishInit( index_path );
380    
381            if ( SwishError( swish_handle ) || ! swish_handle )
382                    ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
383                            errmsg("pgswish: SwishInit(%s) failed", index_path ),
384                            errdetail( SwishErrorString( swish_handle ) )
385                    ));
386    
387            elog(DEBUG1, "pgswish: query[%s] attr[%s] limit %d offset %d", query, (PG_ARGISNULL(2) ? "NULL" : attr), limit, offset);
388    
389    
390            /* set ranking scheme. default is 0 */
391            SwishRankScheme( swish_handle, 0 );
392            error_or_abort( swish_handle );
393    
394            elog(INFO, "pgswish: SwishQuery(%s)", query);
395            /* Here's a short-cut to searching that creates a search object
396             * and searches at the same time */
397            
398            /* set the search phrase to the search condition object */
399            if (! PG_ARGISNULL(1) && strlen(query) > 0)
400                    swish_results = SwishQuery( swish_handle, query);
401            error_or_abort( swish_handle );
402    
403            /* total number of tuples to be returned */
404            resnum = SwishHits( swish_results );
405    
406            /* FIXME */
407            if (! PG_ARGISNULL(2) && strlen(attr) >= 10) {
408                    elog(DEBUG1,"ignored: %s", attr);
409            }
410    
411            /* check if results exists */
412            if ( 0 == resnum ) {
413                    elog(INFO, "pgswish: no results for: %s", query );
414            }
415    
416            /* total number of tuples to be returned */
417            if (limit && limit < resnum) {
418                    nrows = limit - offset;
419            } else {
420                    nrows = resnum - offset;
421            }
422    
423    
424            elog(DEBUG1, "pgswish: found %d hits for %s", resnum, query);
425    
426    
427          values = (char **) palloc(ncols * sizeof(char *));          values = (char **) palloc(ncols * sizeof(char *));
428    
429          for (i = 0; i < nrows; i++)          for (i = 0; i < nrows; i++)
430          {          {
431                    SwishSeekResult( swish_results, i + offset );
432                    sw_res = SwishNextResult( swish_results );
433    
434                    /* get result from swish-e */
435                    if (! ( SwishErrorString( swish_handle ) ) ) {
436                            elog(INFO, "can't find result %d", i + offset);
437                    } else {
438                            elog(INFO, "Path: %s\n  Rank: %lu\n  Size: %lu\n  Title: %s\n  Index: %s\n  Modified: %s\n  Record #: %lu\n  File   #: %lu\n\n",
439                                    SwishResultPropertyStr   ( sw_res, "swishdocpath" ),
440                                    SwishResultPropertyULong ( sw_res, "swishrank" ),
441                                    SwishResultPropertyULong ( sw_res, "swishdocsize" ),
442                                    SwishResultPropertyStr   ( sw_res, "swishtitle"),
443                                    SwishResultPropertyStr   ( sw_res, "swishdbfile" ),
444                                    SwishResultPropertyStr   ( sw_res, "swishlastmodified" ),
445                                    SwishResultPropertyULong ( sw_res, "swishreccount" ),  /* can figure this out in loop, of course */
446                                    SwishResultPropertyULong ( sw_res, "swishfilenum" )
447                            );
448                    }
449    
450                    /* iterate over results */
451                  for (j = 0; j < ncols; j++)                  for (j = 0; j < ncols; j++)
452                  {                  {
453                          values[j] = DatumGetCString( "foo" );                          bool    isnull;
454    
455                            /* array value of this position */
456                            indx[0] = j + prop_dim_lower_bounds[0];
457    
458                            dvalue = array_ref(prop_arr, prop_ndims, indx, -1, prop_len, prop_byval, prop_align, &isnull);
459    
460                            if (!isnull && sw_res)
461                                    values[j] = DatumGetCString(
462                                            prop2text( sw_res,
463                                                    (char *)DirectFunctionCall1(textout, dvalue)
464                                            ));
465                            else
466                                    values[j] = NULL;
467                  }                  }
468                  /* construct the tuple */                  /* construct the tuple */
469                  tuple = BuildTupleFromCStrings(attinmeta, values);                  tuple = BuildTupleFromCStrings(attinmeta, values);
470    
471                  /* now store it */                  /* now store it */
472                  tuplestore_puttuple(tupstore, tuple);                  tuplestore_puttuple(tupstore, tuple);
473    
474          }          }
475    
476          tuplestore_donestoring(tupstore);          tuplestore_donestoring(tupstore);
# Line 288  Datum pgswish2(PG_FUNCTION_ARGS) Line 486  Datum pgswish2(PG_FUNCTION_ARGS)
486          rsinfo->setDesc = tupdesc;          rsinfo->setDesc = tupdesc;
487          MemoryContextSwitchTo(oldcontext);          MemoryContextSwitchTo(oldcontext);
488    
489            /* free swish object and close */
490            Free_Search_Object( search );
491            SwishClose( swish_handle );
492    
493          return (Datum) 0;          return (Datum) 0;
494  }  }
495    
496    
497  /* make text var prom property */  
498    
499    /* make text var from property */
500  char *prop2text(SW_RESULT sw_res, char *propname) {  char *prop2text(SW_RESULT sw_res, char *propname) {
501          char *val;          char *val;
502          char *prop;          char *prop;
# Line 301  char *prop2text(SW_RESULT sw_res, char * Line 505  char *prop2text(SW_RESULT sw_res, char *
505          elog(DEBUG2, "prop2text(%s)", propname);          elog(DEBUG2, "prop2text(%s)", propname);
506    
507          prop = SwishResultPropertyStr( sw_res, propname );          prop = SwishResultPropertyStr( sw_res, propname );
508          error_or_abort( swish_handle );          if (error_or_abort( swish_handle )) return NULL;
509    
510          len = strlen(prop);          len = strlen(prop);
511          elog(DEBUG1, "prop2text(%s) = '%s' %d bytes", propname, prop, len);          elog(DEBUG1, "prop2text(%s) = '%s' %d bytes", propname, prop, len);
# Line 330  char *prop2int(SW_RESULT sw_res, char *p Line 534  char *prop2int(SW_RESULT sw_res, char *p
534          elog(DEBUG2, "prop2int(%s)", propname);          elog(DEBUG2, "prop2int(%s)", propname);
535    
536          prop = SwishResultPropertyULong( sw_res, propname );          prop = SwishResultPropertyULong( sw_res, propname );
537          error_or_abort( swish_handle );          if (error_or_abort( swish_handle )) return NULL;
538    
539          elog(DEBUG1, "prop2int(%s) = %lu", propname, prop);          elog(DEBUG1, "prop2int(%s) = %lu", propname, prop);
540    
# Line 351  char *prop2int(SW_RESULT sw_res, char *p Line 555  char *prop2int(SW_RESULT sw_res, char *p
555  /*  /*
556   * check if swish has returned error, and elog it.   * check if swish has returned error, and elog it.
557   */   */
558  static void error_or_abort( SW_HANDLE swish_handle ) {  static int error_or_abort( SW_HANDLE swish_handle ) {
559          if ( !SwishError( swish_handle ) )          if ( !SwishError( swish_handle ) )
560                  return;                  return 0;
561    
562          /* print a message */          /* print a message */
563          elog(ERROR,          elog(ERROR,
# Line 362  static void error_or_abort( SW_HANDLE sw Line 566  static void error_or_abort( SW_HANDLE sw
566                          SwishErrorString( swish_handle ),                          SwishErrorString( swish_handle ),
567                          SwishLastErrorMsg( swish_handle )                          SwishLastErrorMsg( swish_handle )
568          );          );
569            if ( swish_results ) Free_Results_Object( swish_results );
570          if ( search ) Free_Search_Object( search );          if ( search ) Free_Search_Object( search );
571          SwishClose( swish_handle );          SwishClose( swish_handle );
572    
573            return 1;
574  }  }
575    

Legend:
Removed from v.18  
changed lines
  Added in v.22

  ViewVC Help
Powered by ViewVC 1.1.26