/[pgestraier]/trunk/pgest.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/pgest.c

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

revision 19 by dpavlin, Thu May 26 17:56:53 2005 UTC revision 51 by dpavlin, Tue May 9 22:55:42 2006 UTC
# Line 14  Line 14 
14   *   *
15   * Based on:   * Based on:
16   * - C example from PostgreSQL documentation (BSD licence)   * - C example from PostgreSQL documentation (BSD licence)
17   * - example002.c from Hyper Estraier (GPL)   * - coreexample002.c and nodeexample002.c from Hyper Estraier (GPL)
18   * - _textin/_textout from pgcurl.c (LGPL)   * - _textin/_textout from pgcurl.c (LGPL)
19   *   *
20   * This code is licenced under GPL   * This code is licenced under GPL
# Line 28  Line 28 
28  #include "miscadmin.h"  #include "miscadmin.h"
29  #include <estraier.h>  #include <estraier.h>
30  #include <cabin.h>  #include <cabin.h>
31    #include <estnode.h>
32    
33  #define _textin(str) DirectFunctionCall1(textin, CStringGetDatum(str))  #define _textin(str) DirectFunctionCall1(textin, CStringGetDatum(str))
34  #define _textout(str) DatumGetPointer(DirectFunctionCall1(textout, PointerGetDatum(str)))  #define _textout(str) DatumGetPointer(DirectFunctionCall1(textout, PointerGetDatum(str)))
35  #define GET_STR(textp) DatumGetCString(DirectFunctionCall1(textout, PointerGetDatum(textp)))  #define GET_STR(textp) DatumGetCString(DirectFunctionCall1(textout, PointerGetDatum(textp)))
36  #define GET_TEXT(cstrp) DatumGetTextP(DirectFunctionCall1(textin, CStringGetDatum(cstrp)))  #define GET_TEXT(cstrp) DatumGetTextP(DirectFunctionCall1(textin, CStringGetDatum(cstrp)))
37    
38    /* SortMem got renamed in PostgreSQL 8.0 */
39    #ifndef SortMem
40     #define SortMem 16 * 1024
41    #endif
42    
43    #define ATTR_DELIMITER "{{!}}"
44    
45  /* prototype */  /* prototype */
46  char *attr2text(ESTDOC *doc, char *attr);  char *attr2text(ESTDOC *doc, char *attr);
47    char *node_attr2text(ESTRESDOC *rdoc, char *attr);
48    
49  ESTDB *db;  
50  ESTCOND *cond;  /* work in progress */
51  ESTDOC *doc;  PG_FUNCTION_INFO_V1(pgest_attr);
52  const CBLIST *texts;  Datum pgest_attr(PG_FUNCTION_ARGS)
53  int ecode, *est_result, resnum, i, j;  {
54  int limit = 0;          ArrayType       *attr_arr = PG_GETARG_ARRAYTYPE_P(6);
55  int offset = 0;          Oid             attr_element_type = ARR_ELEMTYPE(attr_arr);
56            int             attr_ndims = ARR_NDIM(attr_arr);
57  /* define PostgreSQL v1 function */          int             *attr_dim_counts = ARR_DIMS(attr_arr);
58  PG_FUNCTION_INFO_V1(pgest);          int             *attr_dim_lower_bounds = ARR_LBOUND(attr_arr);
59  Datum pgest(PG_FUNCTION_ARGS) {          int             ncols = 0;
60            int             nrows = 0;
61          FuncCallContext *funcctx;          int             indx[MAXDIM];
62          int             call_cntr;          int16           attr_len;
63          int             max_calls;          bool            attr_byval;
64          TupleDesc       tupdesc;          char            attr_align;
65          TupleTableSlot  *slot;          ReturnSetInfo   *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
66          AttInMetadata   *attinmeta;          AttInMetadata   *attinmeta;
67            TupleDesc       tupdesc;
68            Tuplestorestate *tupstore = NULL;
69            HeapTuple       tuple;
70            MemoryContext   per_query_ctx;
71            MemoryContext   oldcontext;
72            Datum           dvalue;
73            char            **values;
74            int             rsinfo_ncols;
75            int             i, j;
76            /* estvars */
77            ESTDB *db;
78            ESTCOND *cond;
79            ESTDOC *doc;
80            const CBLIST *texts;
81            int ecode, *est_result, resnum;
82            int limit = 0;
83            int offset = 0;
84    
85          char            *index_path;          char            *index_path;
86          char            *query;          char            *query;
87          char            *attr;          char            *attr;
88            char            *order;
89    
         /* stuff done only on the first call of the function */  
         if (SRF_IS_FIRSTCALL()) {  
                 MemoryContext   oldcontext;  
   
                 /* create a function context for cross-call persistence */  
                 funcctx = SRF_FIRSTCALL_INIT();  
   
                 /* switch to memory context appropriate for multiple function calls */  
                 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);  
                 /* take arguments from function */  
   
                 /* index path */  
                 if (PG_ARGISNULL(0)) {  
                         elog(ERROR, "index path can't be null");  
                         SRF_RETURN_DONE(funcctx);  
                 }  
                 index_path = _textout(PG_GETARG_TEXT_P(0));  
90    
91                  /* query string */          /* only allow 1D input array */
92                  if (PG_ARGISNULL(0)) {          if (attr_ndims == 1)
93                          query = "";          {
94                  } else {                  ncols = attr_dim_counts[0];
95                          query = _textout(PG_GETARG_TEXT_P(1));          }
96                  }          else
97                    ereport(ERROR,
98                                    (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
99                                     errmsg("invalid input array"),
100                                     errdetail("Input array must have 1 dimension")));
101                    
102            /* check to see if caller supports us returning a tuplestore */
103            if (!rsinfo || !(rsinfo->allowedModes & SFRM_Materialize))
104                    ereport(ERROR,
105                                    (errcode(ERRCODE_SYNTAX_ERROR),
106                                     errmsg("materialize mode required, but it is not " \
107                                                    "allowed in this context")));
108    
109                  /* atribute filter */          /* get info about element type needed to construct the array */
110                  if (PG_ARGISNULL(2)) {          get_typlenbyvalalign(attr_element_type, &attr_len, &attr_byval, &attr_align);
                         attr = "";  
                 } else {  
                         attr = _textout(PG_GETARG_TEXT_P(2));  
                 }  
111    
112                  /* limit */          /* get the requested return tuple description */
113                  if (PG_ARGISNULL(3)) {          tupdesc = rsinfo->expectedDesc;
114                          limit = 0;          rsinfo_ncols = tupdesc->natts;
                 } else {  
                         limit = PG_GETARG_INT32(3);  
                 }  
115    
116                  /* offset */          /*
117                  if (PG_ARGISNULL(4)) {           * The requested tuple description better match up with the array
118                          offset = 0;           * we were given.
119                  } else {           */
120                          offset = PG_GETARG_INT32(4);          if (rsinfo_ncols != ncols)
121                  }                  ereport(ERROR,
122                                    (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
123                                     errmsg("invalid input array"),
124                                     errdetail("Number of elements in array must match number of query specified columns.")));
125    
126            /* OK, use it */
127            attinmeta = TupleDescGetAttInMetadata(tupdesc);
128    
129                  /* open the database */          /* Now go to work */
130                  elog(DEBUG1, "pgest: est_db_open(%s)", index_path);          rsinfo->returnMode = SFRM_Materialize;
                   
                 if(!(db = est_db_open(index_path, ESTDBREADER, &ecode))){  
                         elog(ERROR, "est_db_open: can't open %s [%d]: %s", index_path, ecode, est_err_msg(ecode));  
                         SRF_RETURN_DONE(funcctx);  
                 }  
                   
                 elog(INFO, "pgest: query[%s] attr[%s] limit %d offset %d", query, (PG_ARGISNULL(2) ? "NULL" : attr), limit, offset);  
                   
                 /* create a search condition object */  
                 if (!(cond = est_cond_new())) {  
                         elog(INFO, "pgest: est_cond_new failed");  
                         SRF_RETURN_DONE(funcctx);  
                 }  
                   
                 /* set the search phrase to the search condition object */  
                 if (! PG_ARGISNULL(1) && strlen(query) > 0)  
                         est_cond_set_phrase(cond, query);  
   
                 /* minimum valid attribute length is 10: @a STREQ a */  
                 if (! PG_ARGISNULL(2) && strlen(attr) >= 10) {  
                         elog(INFO,"est_cond_add_attr(%s)", attr);  
                         est_cond_add_attr(cond, attr);  
                 }  
131    
132                  /* get the result of search */          per_query_ctx = fcinfo->flinfo->fn_mcxt;
133                  est_result = est_db_search(db, cond, &resnum, NULL);          oldcontext = MemoryContextSwitchTo(per_query_ctx);
                   
                 /* total number of tuples to be returned */  
                 if (limit && limit < resnum) {  
                         funcctx->max_calls = limit - offset;  
                 } else {  
                         funcctx->max_calls = resnum - offset;  
                 }  
134    
135                  /* check if results exists */          /* initialize our tuplestore */
136                  if ( 0 == funcctx->max_calls )          tupstore = tuplestore_begin_heap(true, false, SortMem);
                         elog(INFO, "pgest: no results for: %s", query );  
137    
                 elog(DEBUG1, "pgest: found %d hits for %s", resnum, query);  
138    
139                  /* Build a tuple description for a __pgest tuple */          /* take rest of arguments from function */
                 tupdesc = RelationNameGetTupleDesc("__pgest");  
140    
141                  /* allocate a slot for a tuple with this tupdesc */          /* index path */
142                  slot = TupleDescGetSlot(tupdesc);          if (PG_ARGISNULL(0)) {
143                    ereport(ERROR,
144                                    (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
145                                     errmsg("index path can't be null"),
146                                     errdetail("Index path must be valid full path to HyperEstraier index")));
147            }
148            index_path = _textout(PG_GETARG_TEXT_P(0));
149    
150            /* query string */
151            if (PG_ARGISNULL(1)) {
152                    query = "";
153            } else {
154                    query = _textout(PG_GETARG_TEXT_P(1));
155            }
156    
157            /* atribute filter */
158            if (PG_ARGISNULL(2)) {
159                    attr = "";
160            } else {
161                    attr = _textout(PG_GETARG_TEXT_P(2));
162            }
163            
164            /* sort order */
165            if (PG_ARGISNULL(3)) {
166                    order = "";
167            } else {
168                    order = _textout(PG_GETARG_TEXT_P(3));
169            }
170    
171    
172            /* limit */
173            if (PG_ARGISNULL(4)) {
174                    limit = 0;
175            } else {
176                    limit = PG_GETARG_INT32(4);
177            }
178    
179                  /* assign slot to function context */          /* offset */
180                  funcctx->slot = slot;          if (PG_ARGISNULL(5)) {
181                    offset = 0;
182            } else {
183                    offset = PG_GETARG_INT32(5);
184            }
185    
186    
187            /* open the database */
188            elog(DEBUG1, "pgest_attr: est_db_open(%s)", index_path);
189                    
190            if(!(db = est_db_open(index_path, ESTDBREADER, &ecode))){
191                    ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
192                            errmsg("est_db_open: can't open %s: %d", index_path, ecode),
193                            errdetail(est_err_msg(ecode))));
194            }
195                    
196            elog(DEBUG1, "pgest_attr: query[%s] attr[%s] limit %d offset %d", query, (PG_ARGISNULL(2) ? "NULL" : attr), limit, offset);
197            
198            /* create a search condition object */
199            if (!(cond = est_cond_new())) {
200                    ereport(ERROR, (errcode(ERRCODE_QUERY_CANCELED),
201                            errmsg("pgest_attr: est_cond_new failed")));
202            }
203            
204            /* set the search phrase to the search condition object */
205            if (! PG_ARGISNULL(1) && strlen(query) > 0)
206                    est_cond_set_phrase(cond, query);
207    
208                  /*          /* minimum valid attribute length is 10: @a STREQ a */
209                   * generate attribute metadata needed later to produce tuples from raw          if (! PG_ARGISNULL(2) && strlen(attr) >= 10) {
210                   * C strings                  elog(DEBUG1,"attributes: %s", attr);
211                   */                  char *curr_attr;
212                  attinmeta = TupleDescGetAttInMetadata(tupdesc);                  curr_attr = strtok(attr, ATTR_DELIMITER);
213                  funcctx->attinmeta = attinmeta;                  while (curr_attr) {
214                            elog(DEBUG1,"est_cond_add_attr(%s)", curr_attr);
215                            est_cond_add_attr(cond, curr_attr);
216                            curr_attr = strtok(NULL, ATTR_DELIMITER);
217                    }
218            }
219    
220                  MemoryContextSwitchTo(oldcontext);          /* set the search phrase to the search condition object */
221            if (! PG_ARGISNULL(3) && strlen(order) > 0) {
222                    elog(DEBUG1,"est_cond_set_order(%s)", order);
223                    est_cond_set_order(cond, order);
224            }
225    
226                  elog(DEBUG1, "SRF_IS_FIRSTCALL done");          if (limit) {
227                    elog(DEBUG1,"est_cond_set_max(%d)", limit + offset);
228                    est_cond_set_max(cond, limit + offset);
229          }          }
230    
231          /* stuff done on every call of the function */          /* get the result of search */
232          funcctx = SRF_PERCALL_SETUP();          est_result = est_db_search(db, cond, &resnum, NULL);
233    
234          call_cntr = funcctx->call_cntr;          /* check if results exists */
235          max_calls = funcctx->max_calls;          if ( 0 == resnum ) {
236          slot = funcctx->slot;                  elog(INFO, "pgest_attr: no results for: %s", query );
237          attinmeta = funcctx->attinmeta;          }
238    
239          if (limit && call_cntr > limit - 1) {          /* total number of tuples to be returned */
240                  elog(INFO, "call_cntr: %d limit: %d", call_cntr, limit);          if (limit && limit < resnum) {
241                  SRF_RETURN_DONE(funcctx);                  nrows = limit;
242            } else {
243                    nrows = resnum - offset;
244          }          }
245    
         if (call_cntr < max_calls) {  
                 char            **values;  
                 HeapTuple       tuple;  
                 Datum           result;  
246    
247                  elog(DEBUG1, "pgest: loop count %d", call_cntr);          elog(DEBUG1, "pgest_attr: found %d hits for %s", resnum, query);
248    
249                  if (! est_result) {          values = (char **) palloc(ncols * sizeof(char *));
                         elog(ERROR, "pgest: no estraier results");  
                         SRF_RETURN_DONE(funcctx);  
                 }  
                   
                 /*  
                  * Prepare a values array for storage in our slot.  
                  * This should be an array of C strings which will  
                  * be processed later by the type input functions.  
                  */  
250    
251                  if (doc = est_db_get_doc(db, est_result[call_cntr + offset], 0)) {          for (i = 0; i < nrows; i++)
252                            {
253    
254                    /* get result from estraier */
255                    if (! ( doc = est_db_get_doc(db, est_result[i + offset], 0)) ) {
256                            elog(INFO, "pgest_attr: can't find result %d", i + offset);
257                    } else {
258                          elog(DEBUG1, "URI: %s\n Title: %s\n",                          elog(DEBUG1, "URI: %s\n Title: %s\n",
259                                  est_doc_attr(doc, "@uri"),                                  est_doc_attr(doc, "@uri"),
260                                  est_doc_attr(doc, "@title")                                  est_doc_attr(doc, "@title")
261                          );                          );
262                    }
263    
264                    /* iterate over results */
265                    for (j = 0; j < ncols; j++)
266                    {
267                            bool    isnull;
268    
269                          values = (char **) palloc(4 * sizeof(char *));                          /* array value of this position */
270                            indx[0] = j + attr_dim_lower_bounds[0];
271    
272  //                      values[0] = (char *) palloc(strlen(_estval) * sizeof(char));                          dvalue = array_ref(attr_arr, attr_ndims, indx, -1, attr_len, attr_byval, attr_align, &isnull);
273    
274                          values[0] = (char *) attr2text(doc,"@id");                          if (!isnull && doc)
275                          values[1] = (char *) attr2text(doc,"@uri");                                  values[j] = DatumGetCString(
276                          values[2] = (char *) attr2text(doc,"@title");                                          attr2text(doc,
277                          values[3] = (char *) attr2text(doc,"@size");                                                  (char *)DirectFunctionCall1(textout, dvalue)
278                                            ));
279                          /* destloy the document object */                          else
280                          elog(DEBUG2, "est_doc_delete");                                  values[j] = NULL;
                         est_doc_delete(doc);  
                 } else {  
                         elog(INFO, "no result from estraier");  
                         values[0] = DatumGetCString( "" );  
                         values[1] = DatumGetCString( "" );  
                         values[2] = DatumGetCString( "" );  
                         values[3] = DatumGetCString( "" );  
281                  }                  }
282                    /* construct the tuple */
283                    tuple = BuildTupleFromCStrings(attinmeta, values);
284    
285                    /* now store it */
286                    tuplestore_puttuple(tupstore, tuple);
287    
288                    /* delete estraier document object */
289                    if (doc) est_doc_delete(doc);
290            }
291    
292                  elog(DEBUG2, "build tuple");          tuplestore_donestoring(tupstore);
293                  /* build a tuple */          rsinfo->setResult = tupstore;
                 tuple = BuildTupleFromCStrings(attinmeta, values);  
294    
295                  elog(DEBUG2, "make tuple into datum");          /*
296                  /* make the tuple into a datum */           * SFRM_Materialize mode expects us to return a NULL Datum. The actual
297                  result = TupleGetDatum(slot, tuple);           * tuples are in our tuplestore and passed back through
298             * rsinfo->setResult. rsinfo->setDesc is set to the tuple description
299             * that we actually used to build our tuples with, so the caller can
300             * verify we did what it was expecting.
301             */
302            rsinfo->setDesc = tupdesc;
303            MemoryContextSwitchTo(oldcontext);
304    
305                  elog(DEBUG2, "cleanup");          est_cond_delete(cond);
                 /* clean up ? */  
 /*  
                 pfree(values[0]);  
                 pfree(values[1]);  
                 pfree(values[2]);  
                 pfree(values[3]);  
                 pfree(values);  
 */  
                   
                 elog(DEBUG2, "cleanup over");  
           
                 SRF_RETURN_NEXT(funcctx, result);  
         } else {  
                 elog(DEBUG1, "loop over");  
306    
307                  if(!est_db_close(db, &ecode)){          if(!est_db_close(db, &ecode)){
308                          elog(INFO, "est_db_close error: %s", est_err_msg(ecode));                  ereport(ERROR, (errcode(ERRCODE_IO_ERROR),
309                  }                          errmsg("est_db_close: %d", ecode),
310                            errdetail(est_err_msg(ecode))));
311            }
312    
313            return (Datum) 0;
314    }
315    
316    
317    /* make text var from attr */
318    char *attr2text(ESTDOC *doc, char *attr) {
319            char *val;
320            const char *attrval;
321            int len;
322            int attrlen;
323    
324            if (! doc) return (Datum) NULL;
325    
326                  /* do when there is no more left */          elog(DEBUG1, "doc: %08x, attr: %s", doc, attr);
327                  SRF_RETURN_DONE(funcctx);  
328            if ( (attrval = est_doc_attr(doc, attr)) && (attrlen = strlen(attrval)) ) {
329                    val = (char *) palloc(attrlen * sizeof(char));
330            } else {
331                    return (Datum) NULL;
332          }          }
333    
334            len = strlen(attrval);
335            elog(DEBUG1, "attr2text(%s) = '%s' %d bytes", attr, attrval, len);
336    
337            len++;
338            len *= sizeof(char);
339    
340            elog(DEBUG2, "palloc(%d)", len);
341    
342            val = palloc(len);
343    
344            memset(val, 0, len);
345            strncpy(val, attrval, len);
346    
347            elog(DEBUG2, "val=%s", val);
348    
349            return val;
350  }  }
351    
352  /* work in progress */  /*
353  PG_FUNCTION_INFO_V1(pgest_attr);   * variation on theme: use node API which doesn't open index on
354  Datum pgest_attr(PG_FUNCTION_ARGS)   * every query which is much faster for large indexes
355     *
356     */
357    
358    /* select * from pgest( */
359    #define _arg_node_uri 0
360    #define _arg_login 1
361    #define _arg_passwd 2
362    #define _arg_depth 3
363    #define _arg_query 4
364    #define _arg_attr 5
365    #define _arg_order 6
366    #define _arg_limit 7
367    #define _arg_offset 8
368    #define _arg_attr_array 9
369    /* as (foo text, ... ); */
370    
371    
372    PG_FUNCTION_INFO_V1(pgest_node);
373    Datum pgest_node(PG_FUNCTION_ARGS)
374  {  {
375          ArrayType       *attr_arr = PG_GETARG_ARRAYTYPE_P(5);          ArrayType       *attr_arr = PG_GETARG_ARRAYTYPE_P(_arg_attr_array);
376          Oid             element_type = ARR_ELEMTYPE(attr_arr);          Oid             attr_element_type = ARR_ELEMTYPE(attr_arr);
377          int             ndims = ARR_NDIM(attr_arr);          int             attr_ndims = ARR_NDIM(attr_arr);
378          int             *dim_counts = ARR_DIMS(attr_arr);          int             *attr_dim_counts = ARR_DIMS(attr_arr);
379          int             *dim_lower_bounds = ARR_LBOUND(attr_arr);          int             *attr_dim_lower_bounds = ARR_LBOUND(attr_arr);
380          int             ncols = 0;          int             ncols = 0;
381          int             nrows = 0;          int             nrows = 0;
382          int             indx[MAXDIM];          int             indx[MAXDIM];
383          int16           typlen;          int16           attr_len;
384          bool            typbyval;          bool            attr_byval;
385          char            typalign;          char            attr_align;
386          ReturnSetInfo   *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;          ReturnSetInfo   *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
387          AttInMetadata   *attinmeta;          AttInMetadata   *attinmeta;
388          TupleDesc       tupdesc;          TupleDesc       tupdesc;
# Line 288  Datum pgest_attr(PG_FUNCTION_ARGS) Line 395  Datum pgest_attr(PG_FUNCTION_ARGS)
395          int             rsinfo_ncols;          int             rsinfo_ncols;
396          int             i, j;          int             i, j;
397          /* estvars */          /* estvars */
398          char            *index_path;          ESTNODE *node;
399            ESTCOND *cond;
400            ESTNODERES *nres;
401            ESTRESDOC *rdoc;
402            const CBLIST *texts;
403            int resnum = 0;
404            int limit = 0;
405            int offset = 0;
406            int depth = 0;
407    
408            char            *node_url;
409            char            *user, *passwd;
410          char            *query;          char            *query;
411          char            *attr;          char            *attr;
412            char            *order;
413    
414    
415          /* only allow 1D input array */          /* only allow 1D input array */
416          if (ndims == 1)          if (attr_ndims == 1)
417          {          {
418                  ncols = dim_counts[0];                  ncols = attr_dim_counts[0];
419          }          }
420          else          else
421                  ereport(ERROR,                  ereport(ERROR,
# Line 312  Datum pgest_attr(PG_FUNCTION_ARGS) Line 431  Datum pgest_attr(PG_FUNCTION_ARGS)
431                                                  "allowed in this context")));                                                  "allowed in this context")));
432    
433          /* get info about element type needed to construct the array */          /* get info about element type needed to construct the array */
434          get_typlenbyvalalign(element_type, &typlen, &typbyval, &typalign);          get_typlenbyvalalign(attr_element_type, &attr_len, &attr_byval, &attr_align);
435    
436          /* get the requested return tuple description */          /* get the requested return tuple description */
437          tupdesc = rsinfo->expectedDesc;          tupdesc = rsinfo->expectedDesc;
# Line 343  Datum pgest_attr(PG_FUNCTION_ARGS) Line 462  Datum pgest_attr(PG_FUNCTION_ARGS)
462    
463          /* take rest of arguments from function */          /* take rest of arguments from function */
464    
465          /* index path */          /* node URL */
466          if (PG_ARGISNULL(0)) {          if (PG_ARGISNULL(_arg_node_uri)) {
467                  ereport(ERROR,                  ereport(ERROR,
468                                  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),                                  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
469                                   errmsg("index path can't be null"),                                   errmsg("node URL can't be null"),
470                                   errdetail("Index path must be valid full path to HyperEstraier index")));                                   errdetail("Node URL must be valid URL to HyperEstraier node")));
471            }
472            node_url = _textout(PG_GETARG_TEXT_P(_arg_node_uri));
473    
474            /* login and password */
475            if (PG_ARGISNULL(_arg_login) || PG_ARGISNULL(_arg_passwd)) {
476                    ereport(ERROR,
477                                    (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
478                                     errmsg("username and password can't be NULL"),
479                                     errdetail("You must specify valid username and password to HyperEstraier node")));
480            }
481            user = _textout(PG_GETARG_TEXT_P(_arg_login));
482            passwd = _textout(PG_GETARG_TEXT_P(_arg_passwd));
483    
484            /* depth of search */
485            if (PG_ARGISNULL(_arg_depth)) {
486                    depth = 0;
487            } else {
488                    depth = PG_GETARG_INT32(_arg_depth);
489          }          }
         index_path = _textout(PG_GETARG_TEXT_P(0));  
490    
491          /* query string */          /* query string */
492          if (PG_ARGISNULL(0)) {          if (PG_ARGISNULL(_arg_query)) {
493                  query = "";                  query = "";
494          } else {          } else {
495                  query = _textout(PG_GETARG_TEXT_P(1));                  query = _textout(PG_GETARG_TEXT_P(_arg_query));
496          }          }
497    
498          /* atribute filter */          /* atribute filter */
499          if (PG_ARGISNULL(2)) {          if (PG_ARGISNULL(_arg_attr)) {
500                  attr = "";                  attr = "";
501          } else {          } else {
502                  attr = _textout(PG_GETARG_TEXT_P(2));                  attr = _textout(PG_GETARG_TEXT_P(_arg_attr));
503          }          }
504            
505            /* sort order */
506            if (PG_ARGISNULL(_arg_order)) {
507                    order = "";
508            } else {
509                    order = _textout(PG_GETARG_TEXT_P(_arg_order));
510            }
511    
512    
513          /* limit */          /* limit */
514          if (PG_ARGISNULL(3)) {          if (PG_ARGISNULL(_arg_limit)) {
515                  limit = 0;                  limit = 0;
516          } else {          } else {
517                  limit = PG_GETARG_INT32(3);                  limit = PG_GETARG_INT32(_arg_limit);
518          }          }
519    
520          /* offset */          /* offset */
521          if (PG_ARGISNULL(4)) {          if (PG_ARGISNULL(_arg_offset)) {
522                  offset = 0;                  offset = 0;
523          } else {          } else {
524                  offset = PG_GETARG_INT32(4);                  offset = PG_GETARG_INT32(_arg_offset);
525          }          }
526    
527            /* initialize the network environment */
528          /* open the database */          if(!est_init_net_env()){
529          elog(DEBUG1, "pgest_attr: est_db_open(%s)", index_path);                  ereport(ERROR, (errcode(ERRCODE_QUERY_CANCELED),
530                                            errmsg("pgest_node: can't create network enviroment")));
         if(!(db = est_db_open(index_path, ESTDBREADER, &ecode))){  
                 ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),  
                         errmsg("est_db_open: can't open %s: %d", index_path, ecode),  
                         errdetail(est_err_msg(ecode))));  
531          }          }
532                    
533          elog(INFO, "pgest_attr: query[%s] attr[%s] limit %d offset %d", query, (PG_ARGISNULL(2) ? "NULL" : attr), limit, offset);          /* create the node connection object */
534            elog(DEBUG1, "pgest_node: est_node_new(%s) as %s", node_url, user);
535            node = est_node_new(node_url);
536            est_node_set_auth(node, user, passwd);
537    
538            elog(DEBUG1, "pgest_node: node: %s (d:%d) query[%s] attr[%s] limit %d offset %d", node_url, depth, query, (PG_ARGISNULL(_arg_attr) ? "NULL" : attr), limit, offset);
539                    
540          /* create a search condition object */          /* create a search condition object */
541          if (!(cond = est_cond_new())) {          if (!(cond = est_cond_new())) {
542                  ereport(ERROR, (errcode(ERRCODE_QUERY_CANCELED),                  ereport(ERROR, (errcode(ERRCODE_QUERY_CANCELED),
543                          errmsg("pgest_attr: est_cond_new failed")));                          errmsg("pgest_node: est_cond_new failed")));
544          }          }
545                    
546          /* set the search phrase to the search condition object */          /* set the search phrase to the search condition object */
547          if (! PG_ARGISNULL(1) && strlen(query) > 0)          if (! PG_ARGISNULL(_arg_query) && strlen(query) > 0)
548                  est_cond_set_phrase(cond, query);                  est_cond_set_phrase(cond, query);
549    
550          /* minimum valid attribute length is 10: @a STREQ a */          /* minimum valid attribute length is 10: @a STREQ a */
551          if (! PG_ARGISNULL(2) && strlen(attr) >= 10) {          if (! PG_ARGISNULL(_arg_attr) && strlen(attr) >= 10) {
552                  elog(INFO,"est_cond_add_attr(%s)", attr);                  elog(DEBUG1,"attributes: %s", attr);
553                  est_cond_add_attr(cond, attr);                  char *curr_attr;
554                    curr_attr = strtok(attr, ATTR_DELIMITER);
555                    while (curr_attr) {
556                            elog(DEBUG1,"est_cond_add_attr(%s)", curr_attr);
557                            est_cond_add_attr(cond, curr_attr);
558                            curr_attr = strtok(NULL, ATTR_DELIMITER);
559                    }
560            }
561    
562            /* set the search phrase to the search condition object */
563            if (! PG_ARGISNULL(_arg_order) && strlen(order) > 0) {
564                    elog(DEBUG1,"est_cond_set_order(%s)", order);
565                    est_cond_set_order(cond, order);
566            }
567    
568            if (limit) {
569                    elog(DEBUG1,"est_cond_set_max(%d)", limit + offset);
570                    est_cond_set_max(cond, limit + offset);
571            }
572    
573            if (offset) {
574                    elog(DEBUG1,"est_cond_set_skip(%d)", offset);
575                    est_cond_set_skip(cond, offset);
576          }          }
577    
578          /* get the result of search */          /* get the result of search */
579          est_result = est_db_search(db, cond, &resnum, NULL);          nres = est_node_search(node, cond, depth);
580    
581            if (! nres) {
582                    int status = est_node_status(node);
583                    est_cond_delete(cond);
584                    est_node_delete(node);
585                    est_free_net_env();
586                    ereport(ERROR, (errcode(ERRCODE_QUERY_CANCELED),
587                            errmsg("pgest_node: search failed, node status %d", status)));
588            }
589    
590            /* get number of results */
591            resnum = est_noderes_doc_num(nres);
592    
593          /* check if results exists */          /* check if results exists */
594          if ( 0 == resnum ) {          if ( 0 == resnum ) {
595                  elog(INFO, "pgest_attr: no results for: %s", query );                  elog(INFO, "pgest_node: no results for: %s", query );
596          }          }
597    
598          /* total number of tuples to be returned */          /* total number of tuples to be returned */
599          if (limit && limit < resnum) {          if (limit && limit < resnum) {
600                  nrows = limit - offset;                  nrows = limit;
601          } else {          } else {
602                  nrows = resnum - offset;                  nrows = resnum - offset;
603          }          }
604    
605            elog(DEBUG1, "pgest_node: found %d hits for %s", resnum, query);
         elog(DEBUG1, "pgest_attr: found %d hits for %s", resnum, query);  
606    
607    
608          values = (char **) palloc(ncols * sizeof(char *));          values = (char **) palloc(ncols * sizeof(char *));
# Line 433  Datum pgest_attr(PG_FUNCTION_ARGS) Line 611  Datum pgest_attr(PG_FUNCTION_ARGS)
611          {          {
612    
613                  /* get result from estraier */                  /* get result from estraier */
614                  if (! ( doc = est_db_get_doc(db, est_result[i + offset], 0)) ) {                  if (! ( rdoc = est_noderes_get_doc(nres, i) )) {
615                          elog(INFO, "can't find result %d", i + offset);                          elog(INFO, "pgest_node: can't find result %d", i + offset);
616                  } else {                  } else {
617                          elog(DEBUG1, "URI: %s\n Title: %s\n",                          elog(DEBUG1, "URI: %s\n Title: %s\n",
618                                  est_doc_attr(doc, "@uri"),                                  est_resdoc_attr(rdoc, "@uri"),
619                                  est_doc_attr(doc, "@title")                                  est_resdoc_attr(rdoc, "@title")
620                          );                          );
621                  }                  }
622    
# Line 448  Datum pgest_attr(PG_FUNCTION_ARGS) Line 626  Datum pgest_attr(PG_FUNCTION_ARGS)
626                          bool    isnull;                          bool    isnull;
627    
628                          /* array value of this position */                          /* array value of this position */
629                          indx[0] = j + dim_lower_bounds[0];                          indx[0] = j + attr_dim_lower_bounds[0];
630    
631                          dvalue = array_ref(attr_arr, ndims, indx, -1, typlen, typbyval, typalign, &isnull);                          dvalue = array_ref(attr_arr, attr_ndims, indx, -1, attr_len, attr_byval, attr_align, &isnull);
632    
633                          if (!isnull && doc)                          if (!isnull && rdoc)
634                                  values[j] = DatumGetCString(                                  values[j] = DatumGetCString(
635                                          attr2text(doc,                                          node_attr2text(rdoc,
636                                                  DirectFunctionCall1(textout, dvalue)                                                  (char *)DirectFunctionCall1(textout, dvalue)
637                                          ));                                          ));
638                          else                          else
639                                  values[j] = NULL;                                  values[j] = NULL;
# Line 466  Datum pgest_attr(PG_FUNCTION_ARGS) Line 644  Datum pgest_attr(PG_FUNCTION_ARGS)
644                  /* now store it */                  /* now store it */
645                  tuplestore_puttuple(tupstore, tuple);                  tuplestore_puttuple(tupstore, tuple);
646    
   
                 /* delete estraier document object */  
                 est_doc_delete(doc);  
647          }          }
648    
649          tuplestore_donestoring(tupstore);          tuplestore_donestoring(tupstore);
# Line 484  Datum pgest_attr(PG_FUNCTION_ARGS) Line 659  Datum pgest_attr(PG_FUNCTION_ARGS)
659          rsinfo->setDesc = tupdesc;          rsinfo->setDesc = tupdesc;
660          MemoryContextSwitchTo(oldcontext);          MemoryContextSwitchTo(oldcontext);
661    
662          if(!est_db_close(db, &ecode)){          /* delete the node result object */
663                  ereport(ERROR, (errcode(ERRCODE_IO_ERROR),          est_noderes_delete(nres);
664                          errmsg("est_db_close: %d", ecode),  
665                          errdetail(est_err_msg(ecode))));          /* destroy the search condition object */                          
666          }          est_cond_delete(cond);
667    
668            /* destroy the node object */
669            est_node_delete(node);
670    
671            /* free the networking environment */
672            est_free_net_env();
673    
674          return (Datum) 0;          return (Datum) 0;
675  }  }
676    
677    /* make text var from node attr */
678  /* make text var from attr */  char *node_attr2text(ESTRESDOC *rdoc, char *attr) {
 char *attr2text(ESTDOC *doc, char *attr) {  
679          char *val;          char *val;
680          const char *attrval;          const char *attrval;
681          int len;          int len;
682          int attrlen;          int attrlen;
683    
684          elog(DEBUG1, "doc: %08x, attr: %s", doc, attr);          if (! rdoc) return (Datum) NULL;
685    
686          if ( (attrval = est_doc_attr(doc, attr)) && (attrlen = strlen(attrval)) ) {          elog(DEBUG1, "doc: %08x, attr: %s", rdoc, attr);
687    
688            if ( (attrval = est_resdoc_attr(rdoc, attr)) && (attrlen = strlen(attrval)) ) {
689                  val = (char *) palloc(attrlen * sizeof(char));                  val = (char *) palloc(attrlen * sizeof(char));
690          } else {          } else {
691                  return (Datum) NULL;                  return (Datum) NULL;
692          }          }
693    
694          len = strlen(attrval);          len = strlen(attrval);
695          elog(DEBUG1, "attr2text(%s) = '%s' %d bytes", attr, attrval, len);          elog(DEBUG1, "node_attr2text(%s) = '%s' %d bytes", attr, attrval, len);
696    
697          len++;          len++;
698          len *= sizeof(char);          len *= sizeof(char);

Legend:
Removed from v.19  
changed lines
  Added in v.51

  ViewVC Help
Powered by ViewVC 1.1.26