OSDN Git Service

pgindent run for 8.2.
[pg-rex/syncrep.git] / contrib / xml2 / xpath.c
1 /* Parser interface for DOM-based parser (libxml) rather than
2    stream-based SAX-type parser */
3
4 #include "postgres.h"
5 #include "fmgr.h"
6 #include "executor/spi.h"
7 #include "funcapi.h"
8 #include "miscadmin.h"
9 #include "lib/stringinfo.h"
10
11 /* libxml includes */
12
13 #include <libxml/xpath.h>
14 #include <libxml/tree.h>
15 #include <libxml/xmlmemory.h>
16 #include <libxml/xmlerror.h>
17 #include <libxml/parserInternals.h>
18
19
20 PG_MODULE_MAGIC;
21
22 /* declarations */
23
24 static void *pgxml_palloc(size_t size);
25 static void *pgxml_repalloc(void *ptr, size_t size);
26 static void pgxml_pfree(void *ptr);
27 static char *pgxml_pstrdup(const char *string);
28 static void pgxml_errorHandler(void *ctxt, const char *msg,...);
29
30 void            elog_error(int level, char *explain, int force);
31 void            pgxml_parser_init(void);
32
33 static xmlChar *pgxmlNodeSetToText(xmlNodeSetPtr nodeset,
34                                    xmlChar * toptagname, xmlChar * septagname,
35                                    xmlChar * plainsep);
36
37 text *pgxml_result_to_text(xmlXPathObjectPtr res, xmlChar * toptag,
38                                          xmlChar * septag, xmlChar * plainsep);
39
40 xmlChar    *pgxml_texttoxmlchar(text *textstring);
41
42 static xmlXPathObjectPtr pgxml_xpath(text *document, xmlChar * xpath);
43
44
45 Datum           xml_is_well_formed(PG_FUNCTION_ARGS);
46 Datum           xml_encode_special_chars(PG_FUNCTION_ARGS);
47 Datum           xpath_nodeset(PG_FUNCTION_ARGS);
48 Datum           xpath_string(PG_FUNCTION_ARGS);
49 Datum           xpath_number(PG_FUNCTION_ARGS);
50 Datum           xpath_bool(PG_FUNCTION_ARGS);
51 Datum           xpath_list(PG_FUNCTION_ARGS);
52 Datum           xpath_table(PG_FUNCTION_ARGS);
53
54 /* Global variables */
55 char       *errbuf;                             /* per line error buffer */
56 char       *pgxml_errorMsg = NULL;              /* overall error message */
57
58 /* Convenience macros */
59
60 #define GET_TEXT(cstrp) DatumGetTextP(DirectFunctionCall1(textin, CStringGetDatum(cstrp)))
61 #define GET_STR(textp) DatumGetCString(DirectFunctionCall1(textout, PointerGetDatum(textp)))
62
63 #define ERRBUF_SIZE 200
64
65 /* memory handling passthrough functions (e.g. palloc, pstrdup are
66    currently macros, and the others might become so...) */
67
68 static void *
69 pgxml_palloc(size_t size)
70 {
71 /*      elog(DEBUG1,"Alloc %d in CMC %p",size,CurrentMemoryContext); */
72         return palloc(size);
73 }
74
75 static void *
76 pgxml_repalloc(void *ptr, size_t size)
77 {
78 /*      elog(DEBUG1,"ReAlloc in CMC %p",CurrentMemoryContext);*/
79         return repalloc(ptr, size);
80 }
81
82 static void
83 pgxml_pfree(void *ptr)
84 {
85 /*      elog(DEBUG1,"Free in CMC %p",CurrentMemoryContext); */
86         pfree(ptr);
87 }
88
89 static char *
90 pgxml_pstrdup(const char *string)
91 {
92         return pstrdup(string);
93 }
94
95 /* The error handling function. This formats an error message and sets
96  * a flag - an ereport will be issued prior to return
97  */
98
99 static void
100 pgxml_errorHandler(void *ctxt, const char *msg,...)
101 {
102         va_list         args;
103
104         va_start(args, msg);
105         vsnprintf(errbuf, ERRBUF_SIZE, msg, args);
106         va_end(args);
107         /* Now copy the argument across */
108         if (pgxml_errorMsg == NULL)
109                 pgxml_errorMsg = pstrdup(errbuf);
110         else
111         {
112                 int32           xsize = strlen(pgxml_errorMsg);
113
114                 pgxml_errorMsg = repalloc(pgxml_errorMsg,
115                                                                   (size_t) (xsize + strlen(errbuf) + 1));
116                 strncpy(&pgxml_errorMsg[xsize - 1], errbuf, strlen(errbuf));
117                 pgxml_errorMsg[xsize + strlen(errbuf) - 1] = '\0';
118
119         }
120         memset(errbuf, 0, ERRBUF_SIZE);
121 }
122
123 /* This function reports the current message at the level specified */
124 void
125 elog_error(int level, char *explain, int force)
126 {
127         if (force || (pgxml_errorMsg != NULL))
128         {
129                 if (pgxml_errorMsg == NULL)
130                 {
131                         ereport(level, (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
132                                                         errmsg(explain)));
133                 }
134                 else
135                 {
136                         ereport(level, (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
137                                                         errmsg("%s:%s", explain, pgxml_errorMsg)));
138                         pfree(pgxml_errorMsg);
139                 }
140         }
141 }
142
143 void
144 pgxml_parser_init()
145 {
146         /*
147          * This code could also set parser settings from  user-supplied info.
148          * Quite how these settings are made is another matter :)
149          */
150
151         xmlMemSetup(pgxml_pfree, pgxml_palloc, pgxml_repalloc, pgxml_pstrdup);
152         xmlInitParser();
153
154         xmlSetGenericErrorFunc(NULL, pgxml_errorHandler);
155
156         xmlSubstituteEntitiesDefault(1);
157         xmlLoadExtDtdDefaultValue = 1;
158
159         pgxml_errorMsg = NULL;
160
161         errbuf = palloc(200);
162         memset(errbuf, 0, 200);
163
164 }
165
166
167 /* Returns true if document is well-formed */
168
169 PG_FUNCTION_INFO_V1(xml_is_well_formed);
170
171 Datum
172 xml_is_well_formed(PG_FUNCTION_ARGS)
173 {
174         /* called as xml_is_well_formed(document) */
175         xmlDocPtr       doctree;
176         text       *t = PG_GETARG_TEXT_P(0);            /* document buffer */
177         int32           docsize = VARSIZE(t) - VARHDRSZ;
178
179         pgxml_parser_init();
180
181         doctree = xmlParseMemory((char *) VARDATA(t), docsize);
182         if (doctree == NULL)
183         {
184                 xmlCleanupParser();
185                 PG_RETURN_BOOL(false);  /* i.e. not well-formed */
186         }
187         xmlCleanupParser();
188         xmlFreeDoc(doctree);
189         PG_RETURN_BOOL(true);
190 }
191
192
193 /* Encodes special characters (<, >, &, " and \r) as XML entities */
194
195 PG_FUNCTION_INFO_V1(xml_encode_special_chars);
196
197 Datum
198 xml_encode_special_chars(PG_FUNCTION_ARGS)
199 {
200         text       *tin = PG_GETARG_TEXT_P(0);
201         text       *tout;
202         int32           ressize;
203         xmlChar    *ts,
204                            *tt;
205
206         ts = pgxml_texttoxmlchar(tin);
207
208         tt = xmlEncodeSpecialChars(NULL, ts);
209
210         pfree(ts);
211
212         ressize = strlen(tt);
213         tout = (text *) palloc(ressize + VARHDRSZ);
214         memcpy(VARDATA(tout), tt, ressize);
215         VARATT_SIZEP(tout) = ressize + VARHDRSZ;
216
217         xmlFree(tt);
218
219         PG_RETURN_TEXT_P(tout);
220 }
221
222 static xmlChar
223 *
224 pgxmlNodeSetToText(xmlNodeSetPtr nodeset,
225                                    xmlChar * toptagname,
226                                    xmlChar * septagname,
227                                    xmlChar * plainsep)
228 {
229         /* Function translates a nodeset into a text representation */
230
231         /*
232          * iterates over each node in the set and calls xmlNodeDump to write it to
233          * an xmlBuffer -from which an xmlChar * string is returned.
234          */
235
236         /* each representation is surrounded by <tagname> ... </tagname> */
237
238         /*
239          * plainsep is an ordinary (not tag) seperator - if used, then nodes are
240          * cast to string as output method
241          */
242
243
244         xmlBufferPtr buf;
245         xmlChar    *result;
246         int                     i;
247
248         buf = xmlBufferCreate();
249
250         if ((toptagname != NULL) && (xmlStrlen(toptagname) > 0))
251         {
252                 xmlBufferWriteChar(buf, "<");
253                 xmlBufferWriteCHAR(buf, toptagname);
254                 xmlBufferWriteChar(buf, ">");
255         }
256         if (nodeset != NULL)
257         {
258                 for (i = 0; i < nodeset->nodeNr; i++)
259                 {
260
261                         if (plainsep != NULL)
262                         {
263                                 xmlBufferWriteCHAR(buf,
264                                                           xmlXPathCastNodeToString(nodeset->nodeTab[i]));
265
266                                 /* If this isn't the last entry, write the plain sep. */
267                                 if (i < (nodeset->nodeNr) - 1)
268                                         xmlBufferWriteChar(buf, plainsep);
269                         }
270                         else
271                         {
272
273
274                                 if ((septagname != NULL) && (xmlStrlen(septagname) > 0))
275                                 {
276                                         xmlBufferWriteChar(buf, "<");
277                                         xmlBufferWriteCHAR(buf, septagname);
278                                         xmlBufferWriteChar(buf, ">");
279                                 }
280                                 xmlNodeDump(buf,
281                                                         nodeset->nodeTab[i]->doc,
282                                                         nodeset->nodeTab[i],
283                                                         1, 0);
284
285                                 if ((septagname != NULL) && (xmlStrlen(septagname) > 0))
286                                 {
287                                         xmlBufferWriteChar(buf, "</");
288                                         xmlBufferWriteCHAR(buf, septagname);
289                                         xmlBufferWriteChar(buf, ">");
290                                 }
291                         }
292                 }
293         }
294
295         if ((toptagname != NULL) && (xmlStrlen(toptagname) > 0))
296         {
297                 xmlBufferWriteChar(buf, "</");
298                 xmlBufferWriteCHAR(buf, toptagname);
299                 xmlBufferWriteChar(buf, ">");
300         }
301         result = xmlStrdup(buf->content);
302         xmlBufferFree(buf);
303         return result;
304 }
305
306
307 /* Translate a PostgreSQL "varlena" -i.e. a variable length parameter
308  * into the libxml2 representation
309  */
310
311 xmlChar *
312 pgxml_texttoxmlchar(text *textstring)
313 {
314         xmlChar    *res;
315         int32           txsize;
316
317         txsize = VARSIZE(textstring) - VARHDRSZ;
318         res = (xmlChar *) palloc(txsize + 1);
319         memcpy((char *) res, VARDATA(textstring), txsize);
320         res[txsize] = '\0';
321         return res;
322 }
323
324 /* Public visible XPath functions */
325
326 /* This is a "raw" xpath function. Check that it returns child elements
327  * properly
328  */
329
330 PG_FUNCTION_INFO_V1(xpath_nodeset);
331
332 Datum
333 xpath_nodeset(PG_FUNCTION_ARGS)
334 {
335         xmlChar    *xpath,
336                            *toptag,
337                            *septag;
338         int32           pathsize;
339         text
340                            *xpathsupp,
341                            *xpres;
342
343         /* PG_GETARG_TEXT_P(0) is document buffer */
344         xpathsupp = PG_GETARG_TEXT_P(1);        /* XPath expression */
345
346         toptag = pgxml_texttoxmlchar(PG_GETARG_TEXT_P(2));
347         septag = pgxml_texttoxmlchar(PG_GETARG_TEXT_P(3));
348
349         pathsize = VARSIZE(xpathsupp) - VARHDRSZ;
350
351         xpath = pgxml_texttoxmlchar(xpathsupp);
352
353         xpres = pgxml_result_to_text(
354                                                                  pgxml_xpath(PG_GETARG_TEXT_P(0), xpath),
355                                                                  toptag, septag, NULL);
356
357         /* xmlCleanupParser(); done by result_to_text routine */
358         pfree(xpath);
359
360         if (xpres == NULL)
361                 PG_RETURN_NULL();
362         PG_RETURN_TEXT_P(xpres);
363 }
364
365 /*      The following function is almost identical, but returns the elements in */
366 /*      a list. */
367
368 PG_FUNCTION_INFO_V1(xpath_list);
369
370 Datum
371 xpath_list(PG_FUNCTION_ARGS)
372 {
373         xmlChar    *xpath,
374                            *plainsep;
375         int32           pathsize;
376         text
377                            *xpathsupp,
378                            *xpres;
379
380         /* PG_GETARG_TEXT_P(0) is document buffer */
381         xpathsupp = PG_GETARG_TEXT_P(1);        /* XPath expression */
382
383         plainsep = pgxml_texttoxmlchar(PG_GETARG_TEXT_P(2));
384
385         pathsize = VARSIZE(xpathsupp) - VARHDRSZ;
386
387         xpath = pgxml_texttoxmlchar(xpathsupp);
388
389         xpres = pgxml_result_to_text(
390                                                                  pgxml_xpath(PG_GETARG_TEXT_P(0), xpath),
391                                                                  NULL, NULL, plainsep);
392
393         /* xmlCleanupParser(); done by result_to_text routine */
394         pfree(xpath);
395
396         if (xpres == NULL)
397                 PG_RETURN_NULL();
398         PG_RETURN_TEXT_P(xpres);
399 }
400
401
402 PG_FUNCTION_INFO_V1(xpath_string);
403
404 Datum
405 xpath_string(PG_FUNCTION_ARGS)
406 {
407         xmlChar    *xpath;
408         int32           pathsize;
409         text
410                            *xpathsupp,
411                            *xpres;
412
413         /* PG_GETARG_TEXT_P(0) is document buffer */
414         xpathsupp = PG_GETARG_TEXT_P(1);        /* XPath expression */
415
416         pathsize = VARSIZE(xpathsupp) - VARHDRSZ;
417
418         /*
419          * We encapsulate the supplied path with "string()" = 8 chars + 1 for NUL
420          * at end
421          */
422         /* We could try casting to string using the libxml function? */
423
424         xpath = (xmlChar *) palloc(pathsize + 9);
425         memcpy((char *) (xpath + 7), VARDATA(xpathsupp), pathsize);
426         strncpy((char *) xpath, "string(", 7);
427         xpath[pathsize + 7] = ')';
428         xpath[pathsize + 8] = '\0';
429
430         xpres = pgxml_result_to_text(
431                                                                  pgxml_xpath(PG_GETARG_TEXT_P(0), xpath),
432                                                                  NULL, NULL, NULL);
433
434         xmlCleanupParser();
435         pfree(xpath);
436
437         if (xpres == NULL)
438                 PG_RETURN_NULL();
439         PG_RETURN_TEXT_P(xpres);
440 }
441
442
443 PG_FUNCTION_INFO_V1(xpath_number);
444
445 Datum
446 xpath_number(PG_FUNCTION_ARGS)
447 {
448         xmlChar    *xpath;
449         int32           pathsize;
450         text
451                            *xpathsupp;
452
453         float4          fRes;
454
455         xmlXPathObjectPtr res;
456
457         /* PG_GETARG_TEXT_P(0) is document buffer */
458         xpathsupp = PG_GETARG_TEXT_P(1);        /* XPath expression */
459
460         pathsize = VARSIZE(xpathsupp) - VARHDRSZ;
461
462         xpath = pgxml_texttoxmlchar(xpathsupp);
463
464         res = pgxml_xpath(PG_GETARG_TEXT_P(0), xpath);
465         pfree(xpath);
466
467         if (res == NULL)
468         {
469                 xmlCleanupParser();
470                 PG_RETURN_NULL();
471         }
472
473         fRes = xmlXPathCastToNumber(res);
474         xmlCleanupParser();
475         if (xmlXPathIsNaN(fRes))
476                 PG_RETURN_NULL();
477
478         PG_RETURN_FLOAT4(fRes);
479
480 }
481
482
483 PG_FUNCTION_INFO_V1(xpath_bool);
484
485 Datum
486 xpath_bool(PG_FUNCTION_ARGS)
487 {
488         xmlChar    *xpath;
489         int32           pathsize;
490         text
491                            *xpathsupp;
492
493         int                     bRes;
494
495         xmlXPathObjectPtr res;
496
497         /* PG_GETARG_TEXT_P(0) is document buffer */
498         xpathsupp = PG_GETARG_TEXT_P(1);        /* XPath expression */
499
500         pathsize = VARSIZE(xpathsupp) - VARHDRSZ;
501
502         xpath = pgxml_texttoxmlchar(xpathsupp);
503
504         res = pgxml_xpath(PG_GETARG_TEXT_P(0), xpath);
505         pfree(xpath);
506
507         if (res == NULL)
508         {
509                 xmlCleanupParser();
510                 PG_RETURN_BOOL(false);
511         }
512
513         bRes = xmlXPathCastToBoolean(res);
514         xmlCleanupParser();
515         PG_RETURN_BOOL(bRes);
516
517 }
518
519
520
521 /* Core function to evaluate XPath query */
522
523 xmlXPathObjectPtr
524 pgxml_xpath(text *document, xmlChar * xpath)
525 {
526
527         xmlDocPtr       doctree;
528         xmlXPathContextPtr ctxt;
529         xmlXPathObjectPtr res;
530
531         xmlXPathCompExprPtr comppath;
532
533         int32           docsize;
534
535
536         docsize = VARSIZE(document) - VARHDRSZ;
537
538         pgxml_parser_init();
539
540         doctree = xmlParseMemory((char *) VARDATA(document), docsize);
541         if (doctree == NULL)
542         {                                                       /* not well-formed */
543                 return NULL;
544         }
545
546         ctxt = xmlXPathNewContext(doctree);
547         ctxt->node = xmlDocGetRootElement(doctree);
548
549
550         /* compile the path */
551         comppath = xmlXPathCompile(xpath);
552         if (comppath == NULL)
553         {
554                 xmlCleanupParser();
555                 xmlFreeDoc(doctree);
556                 elog_error(ERROR, "XPath Syntax Error", 1);
557
558                 return NULL;
559         }
560
561         /* Now evaluate the path expression. */
562         res = xmlXPathCompiledEval(comppath, ctxt);
563         xmlXPathFreeCompExpr(comppath);
564
565         if (res == NULL)
566         {
567                 xmlXPathFreeContext(ctxt);
568                 /* xmlCleanupParser(); */
569                 xmlFreeDoc(doctree);
570
571                 return NULL;
572         }
573         /* xmlFreeDoc(doctree); */
574         return res;
575 }
576
577 text
578                    *
579 pgxml_result_to_text(xmlXPathObjectPtr res,
580                                          xmlChar * toptag,
581                                          xmlChar * septag,
582                                          xmlChar * plainsep)
583 {
584         xmlChar    *xpresstr;
585         int32           ressize;
586         text       *xpres;
587
588         if (res == NULL)
589         {
590                 xmlCleanupParser();
591                 return NULL;
592         }
593         switch (res->type)
594         {
595                 case XPATH_NODESET:
596                         xpresstr = pgxmlNodeSetToText(res->nodesetval,
597                                                                                   toptag,
598                                                                                   septag, plainsep);
599                         break;
600
601                 case XPATH_STRING:
602                         xpresstr = xmlStrdup(res->stringval);
603                         break;
604
605                 default:
606                         elog(NOTICE, "unsupported XQuery result: %d", res->type);
607                         xpresstr = xmlStrdup("<unsupported/>");
608         }
609
610
611         /* Now convert this result back to text */
612         ressize = strlen(xpresstr);
613         xpres = (text *) palloc(ressize + VARHDRSZ);
614         memcpy(VARDATA(xpres), xpresstr, ressize);
615         VARATT_SIZEP(xpres) = ressize + VARHDRSZ;
616
617         /* Free various storage */
618         xmlCleanupParser();
619         /* xmlFreeDoc(doctree);  -- will die at end of tuple anyway */
620
621         xmlFree(xpresstr);
622
623         elog_error(ERROR, "XPath error", 0);
624
625
626         return xpres;
627 }
628
629 /* xpath_table is a table function. It needs some tidying (as do the
630  * other functions here!
631  */
632
633 PG_FUNCTION_INFO_V1(xpath_table);
634
635 Datum
636 xpath_table(PG_FUNCTION_ARGS)
637 {
638 /* SPI (input tuple) support */
639         SPITupleTable *tuptable;
640         HeapTuple       spi_tuple;
641         TupleDesc       spi_tupdesc;
642
643 /* Output tuple (tuplestore) support */
644         Tuplestorestate *tupstore = NULL;
645         TupleDesc       ret_tupdesc;
646         HeapTuple       ret_tuple;
647
648         ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
649         AttInMetadata *attinmeta;
650         MemoryContext per_query_ctx;
651         MemoryContext oldcontext;
652
653 /* Function parameters */
654         char       *pkeyfield = GET_STR(PG_GETARG_TEXT_P(0));
655         char       *xmlfield = GET_STR(PG_GETARG_TEXT_P(1));
656         char       *relname = GET_STR(PG_GETARG_TEXT_P(2));
657         char       *xpathset = GET_STR(PG_GETARG_TEXT_P(3));
658         char       *condition = GET_STR(PG_GETARG_TEXT_P(4));
659
660         char      **values;
661         xmlChar   **xpaths;
662         xmlChar    *pos;
663         xmlChar    *pathsep = "|";
664
665         int                     numpaths;
666         int                     ret;
667         int                     proc;
668         int                     i;
669         int                     j;
670         int                     rownr;                  /* For issuing multiple rows from one original
671                                                                  * document */
672         int                     had_values;             /* To determine end of nodeset results */
673
674         StringInfoData query_buf;
675
676         /* We only have a valid tuple description in table function mode */
677         if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
678                 ereport(ERROR,
679                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
680                                  errmsg("set-valued function called in context that cannot accept a set")));
681         if (rsinfo->expectedDesc == NULL)
682                 ereport(ERROR,
683                                 (errcode(ERRCODE_SYNTAX_ERROR),
684                                  errmsg("xpath_table must be called as a table function")));
685
686         /*
687          * We want to materialise because it means that we don't have to carry
688          * libxml2 parser state between invocations of this function
689          */
690         if (!(rsinfo->allowedModes & SFRM_Materialize))
691                 ereport(ERROR,
692                                 (errcode(ERRCODE_SYNTAX_ERROR),
693                            errmsg("xpath_table requires Materialize mode, but it is not "
694                                           "allowed in this context")));
695
696         /*
697          * The tuplestore must exist in a higher context than this function call
698          * (per_query_ctx is used)
699          */
700
701         per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
702         oldcontext = MemoryContextSwitchTo(per_query_ctx);
703
704         /*
705          * Create the tuplestore - work_mem is the max in-memory size before a
706          * file is created on disk to hold it.
707          */
708         tupstore = tuplestore_begin_heap(true, false, work_mem);
709
710         MemoryContextSwitchTo(oldcontext);
711
712         /* get the requested return tuple description */
713         ret_tupdesc = CreateTupleDescCopy(rsinfo->expectedDesc);
714
715         /*
716          * At the moment we assume that the returned attributes make sense for the
717          * XPath specififed (i.e. we trust the caller). It's not fatal if they get
718          * it wrong - the input function for the column type will raise an error
719          * if the path result can't be converted into the correct binary
720          * representation.
721          */
722
723         attinmeta = TupleDescGetAttInMetadata(ret_tupdesc);
724
725         /* Set return mode and allocate value space. */
726         rsinfo->returnMode = SFRM_Materialize;
727         rsinfo->setDesc = ret_tupdesc;
728
729         values = (char **) palloc(ret_tupdesc->natts * sizeof(char *));
730
731         xpaths = (xmlChar **) palloc(ret_tupdesc->natts * sizeof(xmlChar *));
732
733         /* Split XPaths. xpathset is a writable CString. */
734
735         /* Note that we stop splitting once we've done all needed for tupdesc */
736
737         numpaths = 0;
738         pos = xpathset;
739         do
740         {
741                 xpaths[numpaths] = pos;
742                 pos = strstr(pos, pathsep);
743                 if (pos != NULL)
744                 {
745                         *pos = '\0';
746                         pos++;
747                 }
748                 numpaths++;
749         } while ((pos != NULL) && (numpaths < (ret_tupdesc->natts - 1)));
750
751         /* Now build query */
752         initStringInfo(&query_buf);
753
754         /* Build initial sql statement */
755         appendStringInfo(&query_buf, "SELECT %s, %s FROM %s WHERE %s",
756                                          pkeyfield,
757                                          xmlfield,
758                                          relname,
759                                          condition
760                 );
761
762
763         if ((ret = SPI_connect()) < 0)
764                 elog(ERROR, "xpath_table: SPI_connect returned %d", ret);
765
766         if ((ret = SPI_exec(query_buf.data, 0)) != SPI_OK_SELECT)
767                 elog(ERROR, "xpath_table: SPI execution failed for query %s", query_buf.data);
768
769         proc = SPI_processed;
770         /* elog(DEBUG1,"xpath_table: SPI returned %d rows",proc); */
771         tuptable = SPI_tuptable;
772         spi_tupdesc = tuptable->tupdesc;
773
774 /* Switch out of SPI context */
775         MemoryContextSwitchTo(oldcontext);
776
777
778 /* Check that SPI returned correct result. If you put a comma into one of
779  * the function parameters, this will catch it when the SPI query returns
780  * e.g. 3 columns.
781  */
782
783         if (spi_tupdesc->natts != 2)
784         {
785                 ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
786                                                 errmsg("expression returning multiple columns is not valid in parameter list"),
787                                                 errdetail("Expected two columns in SPI result, got %d.", spi_tupdesc->natts)));
788         }
789
790 /* Setup the parser. Beware that this must happen in the same context as the
791  * cleanup - which means that any error from here on must do cleanup to
792  * ensure that the entity table doesn't get freed by being out of context.
793  */
794         pgxml_parser_init();
795
796         /* For each row i.e. document returned from SPI */
797         for (i = 0; i < proc; i++)
798         {
799                 char       *pkey;
800                 char       *xmldoc;
801
802                 xmlDocPtr       doctree;
803                 xmlXPathContextPtr ctxt;
804                 xmlXPathObjectPtr res;
805                 xmlChar    *resstr;
806
807
808                 xmlXPathCompExprPtr comppath;
809
810                 /* Extract the row data as C Strings */
811
812                 spi_tuple = tuptable->vals[i];
813                 pkey = SPI_getvalue(spi_tuple, spi_tupdesc, 1);
814                 xmldoc = SPI_getvalue(spi_tuple, spi_tupdesc, 2);
815
816
817                 /*
818                  * Clear the values array, so that not-well-formed documents return
819                  * NULL in all columns.
820                  */
821
822                 /* Note that this also means that spare columns will be NULL. */
823                 for (j = 0; j < ret_tupdesc->natts; j++)
824                         values[j] = NULL;
825
826                 /* Insert primary key */
827                 values[0] = pkey;
828
829                 /* Parse the document */
830                 doctree = xmlParseMemory(xmldoc, strlen(xmldoc));
831
832                 if (doctree == NULL)
833                 {                                               /* not well-formed, so output all-NULL tuple */
834
835                         ret_tuple = BuildTupleFromCStrings(attinmeta, values);
836                         oldcontext = MemoryContextSwitchTo(per_query_ctx);
837                         tuplestore_puttuple(tupstore, ret_tuple);
838                         MemoryContextSwitchTo(oldcontext);
839                         heap_freetuple(ret_tuple);
840                 }
841                 else
842                 {
843                         /* New loop here - we have to deal with nodeset results */
844                         rownr = 0;
845
846                         do
847                         {
848                                 /* Now evaluate the set of xpaths. */
849                                 had_values = 0;
850                                 for (j = 0; j < numpaths; j++)
851                                 {
852
853                                         ctxt = xmlXPathNewContext(doctree);
854                                         ctxt->node = xmlDocGetRootElement(doctree);
855                                         xmlSetGenericErrorFunc(ctxt, pgxml_errorHandler);
856
857                                         /* compile the path */
858                                         comppath = xmlXPathCompile(xpaths[j]);
859                                         if (comppath == NULL)
860                                         {
861                                                 xmlCleanupParser();
862                                                 xmlFreeDoc(doctree);
863
864                                                 elog_error(ERROR, "XPath Syntax Error", 1);
865
866                                                 PG_RETURN_NULL();               /* Keep compiler happy */
867                                         }
868
869                                         /* Now evaluate the path expression. */
870                                         res = xmlXPathCompiledEval(comppath, ctxt);
871                                         xmlXPathFreeCompExpr(comppath);
872
873                                         if (res != NULL)
874                                         {
875                                                 switch (res->type)
876                                                 {
877                                                         case XPATH_NODESET:
878                                                                 /* We see if this nodeset has enough nodes */
879                                                                 if ((res->nodesetval != NULL) && (rownr < res->nodesetval->nodeNr))
880                                                                 {
881                                                                         resstr =
882                                                                                 xmlXPathCastNodeToString(res->nodesetval->nodeTab[rownr]);
883                                                                         had_values = 1;
884                                                                 }
885                                                                 else
886                                                                         resstr = NULL;
887
888                                                                 break;
889
890                                                         case XPATH_STRING:
891                                                                 resstr = xmlStrdup(res->stringval);
892                                                                 break;
893
894                                                         default:
895                                                                 elog(NOTICE, "unsupported XQuery result: %d", res->type);
896                                                                 resstr = xmlStrdup("<unsupported/>");
897                                                 }
898
899
900                                                 /*
901                                                  * Insert this into the appropriate column in the
902                                                  * result tuple.
903                                                  */
904                                                 values[j + 1] = resstr;
905                                         }
906                                         xmlXPathFreeContext(ctxt);
907                                 }
908                                 /* Now add the tuple to the output, if there is one. */
909                                 if (had_values)
910                                 {
911                                         ret_tuple = BuildTupleFromCStrings(attinmeta, values);
912                                         oldcontext = MemoryContextSwitchTo(per_query_ctx);
913                                         tuplestore_puttuple(tupstore, ret_tuple);
914                                         MemoryContextSwitchTo(oldcontext);
915                                         heap_freetuple(ret_tuple);
916                                 }
917
918                                 rownr++;
919
920                         } while (had_values);
921
922                 }
923
924                 xmlFreeDoc(doctree);
925
926                 pfree(pkey);
927                 pfree(xmldoc);
928         }
929
930         xmlCleanupParser();
931 /* Needed to flag completeness in 7.3.1. 7.4 defines it as a no-op. */
932         tuplestore_donestoring(tupstore);
933
934         SPI_finish();
935
936         rsinfo->setResult = tupstore;
937
938         /*
939          * SFRM_Materialize mode expects us to return a NULL Datum. The actual
940          * tuples are in our tuplestore and passed back through rsinfo->setResult.
941          * rsinfo->setDesc is set to the tuple description that we actually used
942          * to build our tuples with, so the caller can verify we did what it was
943          * expecting.
944          */
945         return (Datum) 0;
946
947 }