Debian Codegraph @

contrib/xml2/xpath.c

raw
1 /*
2 * contrib/xml2/xpath.c
3 *
4 * Parser interface for DOM-based parser (libxml) rather than
5 * stream-based SAX-type parser
6 */
7 #include "postgres.h"
8
9 #include "access/htup_details.h"
10 #include "executor/spi.h"
11 #include "fmgr.h"
12 #include "funcapi.h"
13 #include "lib/stringinfo.h"
14 #include "utils/builtins.h"
15 #include "utils/xml.h"
16
17 /* libxml includes */
18
19 #include <libxml/xpath.h>
20 #include <libxml/tree.h>
21 #include <libxml/xmlmemory.h>
22 #include <libxml/xmlerror.h>
23 #include <libxml/parserInternals.h>
24
25 PG_MODULE_MAGIC_EXT(
26 .name = "xml2",
27 .version = PG_VERSION
28 );
29
30 /* exported for use by xslt_proc.c */
31
32 PgXmlErrorContext *pgxml_parser_init(PgXmlStrictness strictness);
33
34 /* workspace for pgxml_xpath() */
35
36 typedef struct
37 {
38 xmlDocPtr doctree;
39 xmlXPathContextPtr ctxt;
40 xmlXPathObjectPtr res;
41 } xpath_workspace;
42
43 /* local declarations */
44
45 static xmlChar *pgxmlNodeSetToText(xmlNodeSetPtr nodeset,
46 xmlChar *toptagname, xmlChar *septagname,
47 xmlChar *plainsep);
48
49 static text *pgxml_result_to_text(xmlXPathObjectPtr res, xmlChar *toptag,
50 xmlChar *septag, xmlChar *plainsep);
51
52 static xmlChar *pgxml_texttoxmlchar(text *textstring);
53
54 static xmlXPathObjectPtr pgxml_xpath(text *document, xmlChar *xpath,
55 xpath_workspace *workspace);
56
57 static void cleanup_workspace(xpath_workspace *workspace);
58
59
60 /*
61 * Initialize for xml parsing.
62 *
63 * As with the underlying pg_xml_init function, calls to this MUST be followed
64 * by a PG_TRY block that guarantees that pg_xml_done is called.
65 */
66 PgXmlErrorContext *
67 pgxml_parser_init(PgXmlStrictness strictness)
68 {
69 PgXmlErrorContext *xmlerrcxt;
70
71 /* Set up error handling (we share the core's error handler) */
72 xmlerrcxt = pg_xml_init(strictness);
73
74 /* Note: we're assuming an elog cannot be thrown by the following calls */
75
76 /* Initialize libxml */
77 xmlInitParser();
78
79 return xmlerrcxt;
80 }
81
82
83 /* Encodes special characters (<, >, &, " and \r) as XML entities */
84
85 PG_FUNCTION_INFO_V1(xml_encode_special_chars);
86
87 Datum
88 xml_encode_special_chars(PG_FUNCTION_ARGS)
89 {
90 text *tin = PG_GETARG_TEXT_PP(0);
91 text *tout;
92 xmlChar *ts,
93 *tt;
94
95 ts = pgxml_texttoxmlchar(tin);
96
97 tt = xmlEncodeSpecialChars(NULL, ts);
98
99 pfree(ts);
100
101 tout = cstring_to_text((char *) tt);
102
103 xmlFree(tt);
104
105 PG_RETURN_TEXT_P(tout);
106 }
107
108 /*
109 * Function translates a nodeset into a text representation
110 *
111 * iterates over each node in the set and calls xmlNodeDump to write it to
112 * an xmlBuffer -from which an xmlChar * string is returned.
113 *
114 * each representation is surrounded by <tagname> ... </tagname>
115 *
116 * plainsep is an ordinary (not tag) separator - if used, then nodes are
117 * cast to string as output method
118 */
119 static xmlChar *
120 pgxmlNodeSetToText(xmlNodeSetPtr nodeset,
121 xmlChar *toptagname,
122 xmlChar *septagname,
123 xmlChar *plainsep)
124 {
125 xmlBufferPtr buf;
126 xmlChar *result;
127 int i;
128
129 buf = xmlBufferCreate();
130
131 if ((toptagname != NULL) && (xmlStrlen(toptagname) > 0))
132 {
133 xmlBufferWriteChar(buf, "<");
134 xmlBufferWriteCHAR(buf, toptagname);
135 xmlBufferWriteChar(buf, ">");
136 }
137 if (nodeset != NULL)
138 {
139 for (i = 0; i < nodeset->nodeNr; i++)
140 {
141 if (plainsep != NULL)
142 {
143 xmlBufferWriteCHAR(buf,
144 xmlXPathCastNodeToString(nodeset->nodeTab[i]));
145
146 /* If this isn't the last entry, write the plain sep. */
147 if (i < (nodeset->nodeNr) - 1)
148 xmlBufferWriteChar(buf, (char *) plainsep);
149 }
150 else
151 {
152 xmlNodePtr node = nodeset->nodeTab[i];
153
154 if ((septagname != NULL) && (xmlStrlen(septagname) > 0))
155 {
156 xmlBufferWriteChar(buf, "<");
157 xmlBufferWriteCHAR(buf, septagname);
158 xmlBufferWriteChar(buf, ">");
159 }
160
161 /*
162 * XML_NAMESPACE_DECL nodes are xmlNs structs, that cannot
163 * be processed by xmlNodeDump().
164 */
165 if (node->type == XML_NAMESPACE_DECL)
166 xmlBufferWriteCHAR(buf, xmlXPathCastNodeToString(node));
167 else
168 xmlNodeDump(buf, node->doc, node, 1, 0);
169
170 if ((septagname != NULL) && (xmlStrlen(septagname) > 0))
171 {
172 xmlBufferWriteChar(buf, "</");
173 xmlBufferWriteCHAR(buf, septagname);
174 xmlBufferWriteChar(buf, ">");
175 }
176 }
177 }
178 }
179
180 if ((toptagname != NULL) && (xmlStrlen(toptagname) > 0))
181 {
182 xmlBufferWriteChar(buf, "</");
183 xmlBufferWriteCHAR(buf, toptagname);
184 xmlBufferWriteChar(buf, ">");
185 }
186 result = xmlStrdup(xmlBufferContent(buf));
187 xmlBufferFree(buf);
188 return result;
189 }
190
191
192 /* Translate a PostgreSQL "varlena" -i.e. a variable length parameter
193 * into the libxml2 representation
194 */
195 static xmlChar *
196 pgxml_texttoxmlchar(text *textstring)
197 {
198 return (xmlChar *) text_to_cstring(textstring);
199 }
200
201 /* Publicly visible XPath functions */
202
203 /*
204 * This is a "raw" xpath function. Check that it returns child elements
205 * properly
206 */
207 PG_FUNCTION_INFO_V1(xpath_nodeset);
208
209 Datum
210 xpath_nodeset(PG_FUNCTION_ARGS)
211 {
212 text *document = PG_GETARG_TEXT_PP(0);
213 text *xpathsupp = PG_GETARG_TEXT_PP(1); /* XPath expression */
214 xmlChar *toptag = pgxml_texttoxmlchar(PG_GETARG_TEXT_PP(2));
215 xmlChar *septag = pgxml_texttoxmlchar(PG_GETARG_TEXT_PP(3));
216 xmlChar *xpath;
217 text *xpres;
218 xmlXPathObjectPtr res;
219 xpath_workspace workspace;
220
221 xpath = pgxml_texttoxmlchar(xpathsupp);
222
223 res = pgxml_xpath(document, xpath, &workspace);
224
225 xpres = pgxml_result_to_text(res, toptag, septag, NULL);
226
227 cleanup_workspace(&workspace);
228
229 pfree(xpath);
230
231 if (xpres == NULL)
232 PG_RETURN_NULL();
233 PG_RETURN_TEXT_P(xpres);
234 }
235
236 /*
237 * The following function is almost identical, but returns the elements in
238 * a list.
239 */
240 PG_FUNCTION_INFO_V1(xpath_list);
241
242 Datum
243 xpath_list(PG_FUNCTION_ARGS)
244 {
245 text *document = PG_GETARG_TEXT_PP(0);
246 text *xpathsupp = PG_GETARG_TEXT_PP(1); /* XPath expression */
247 xmlChar *plainsep = pgxml_texttoxmlchar(PG_GETARG_TEXT_PP(2));
248 xmlChar *xpath;
249 text *xpres;
250 xmlXPathObjectPtr res;
251 xpath_workspace workspace;
252
253 xpath = pgxml_texttoxmlchar(xpathsupp);
254
255 res = pgxml_xpath(document, xpath, &workspace);
256
257 xpres = pgxml_result_to_text(res, NULL, NULL, plainsep);
258
259 cleanup_workspace(&workspace);
260
261 pfree(xpath);
262
263 if (xpres == NULL)
264 PG_RETURN_NULL();
265 PG_RETURN_TEXT_P(xpres);
266 }
267
268
269 PG_FUNCTION_INFO_V1(xpath_string);
270
271 Datum
272 xpath_string(PG_FUNCTION_ARGS)
273 {
274 text *document = PG_GETARG_TEXT_PP(0);
275 text *xpathsupp = PG_GETARG_TEXT_PP(1); /* XPath expression */
276 xmlChar *xpath;
277 int32 pathsize;
278 text *xpres;
279 xmlXPathObjectPtr res;
280 xpath_workspace workspace;
281
282 pathsize = VARSIZE_ANY_EXHDR(xpathsupp);
283
284 /*
285 * We encapsulate the supplied path with "string()" = 8 chars + 1 for NUL
286 * at end
287 */
288 /* We could try casting to string using the libxml function? */
289
290 xpath = (xmlChar *) palloc(pathsize + 9);
291 memcpy(xpath, "string(", 7);
292 memcpy(xpath + 7, VARDATA_ANY(xpathsupp), pathsize);
293 xpath[pathsize + 7] = ')';
294 xpath[pathsize + 8] = '\0';
295
296 res = pgxml_xpath(document, xpath, &workspace);
297
298 xpres = pgxml_result_to_text(res, NULL, NULL, NULL);
299
300 cleanup_workspace(&workspace);
301
302 pfree(xpath);
303
304 if (xpres == NULL)
305 PG_RETURN_NULL();
306 PG_RETURN_TEXT_P(xpres);
307 }
308
309
310 PG_FUNCTION_INFO_V1(xpath_number);
311
312 Datum
313 xpath_number(PG_FUNCTION_ARGS)
314 {
315 text *document = PG_GETARG_TEXT_PP(0);
316 text *xpathsupp = PG_GETARG_TEXT_PP(1); /* XPath expression */
317 xmlChar *xpath;
318 float4 fRes;
319 xmlXPathObjectPtr res;
320 xpath_workspace workspace;
321
322 xpath = pgxml_texttoxmlchar(xpathsupp);
323
324 res = pgxml_xpath(document, xpath, &workspace);
325
326 pfree(xpath);
327
328 if (res == NULL)
329 PG_RETURN_NULL();
330
331 fRes = xmlXPathCastToNumber(res);
332
333 cleanup_workspace(&workspace);
334
335 if (xmlXPathIsNaN(fRes))
336 PG_RETURN_NULL();
337
338 PG_RETURN_FLOAT4(fRes);
339 }
340
341
342 PG_FUNCTION_INFO_V1(xpath_bool);
343
344 Datum
345 xpath_bool(PG_FUNCTION_ARGS)
346 {
347 text *document = PG_GETARG_TEXT_PP(0);
348 text *xpathsupp = PG_GETARG_TEXT_PP(1); /* XPath expression */
349 xmlChar *xpath;
350 int bRes;
351 xmlXPathObjectPtr res;
352 xpath_workspace workspace;
353
354 xpath = pgxml_texttoxmlchar(xpathsupp);
355
356 res = pgxml_xpath(document, xpath, &workspace);
357
358 pfree(xpath);
359
360 if (res == NULL)
361 PG_RETURN_BOOL(false);
362
363 bRes = xmlXPathCastToBoolean(res);
364
365 cleanup_workspace(&workspace);
366
367 PG_RETURN_BOOL(bRes);
368 }
369
370
371
372 /* Core function to evaluate XPath query */
373
374 static xmlXPathObjectPtr
375 pgxml_xpath(text *document, xmlChar *xpath, xpath_workspace *workspace)
376 {
377 int32 docsize = VARSIZE_ANY_EXHDR(document);
378 PgXmlErrorContext *xmlerrcxt;
379 xmlXPathCompExprPtr comppath;
380
381 workspace->doctree = NULL;
382 workspace->ctxt = NULL;
383 workspace->res = NULL;
384
385 xmlerrcxt = pgxml_parser_init(PG_XML_STRICTNESS_LEGACY);
386
387 PG_TRY();
388 {
389 workspace->doctree = xmlReadMemory((char *) VARDATA_ANY(document),
390 docsize, NULL, NULL,
391 XML_PARSE_NOENT);
392 if (workspace->doctree != NULL)
393 {
394 workspace->ctxt = xmlXPathNewContext(workspace->doctree);
395 workspace->ctxt->node = xmlDocGetRootElement(workspace->doctree);
396
397 /* compile the path */
398 comppath = xmlXPathCtxtCompile(workspace->ctxt, xpath);
399 if (comppath == NULL)
400 xml_ereport(xmlerrcxt, ERROR, ERRCODE_INVALID_ARGUMENT_FOR_XQUERY,
401 "XPath Syntax Error");
402
403 /* Now evaluate the path expression. */
404 workspace->res = xmlXPathCompiledEval(comppath, workspace->ctxt);
405
406 xmlXPathFreeCompExpr(comppath);
407 }
408 }
409 PG_CATCH();
410 {
411 cleanup_workspace(workspace);
412
413 pg_xml_done(xmlerrcxt, true);
414
415 PG_RE_THROW();
416 }
417 PG_END_TRY();
418
419 if (workspace->res == NULL)
420 cleanup_workspace(workspace);
421
422 pg_xml_done(xmlerrcxt, false);
423
424 return workspace->res;
425 }
426
427 /* Clean up after processing the result of pgxml_xpath() */
428 static void
429 cleanup_workspace(xpath_workspace *workspace)
430 {
431 if (workspace->res)
432 xmlXPathFreeObject(workspace->res);
433 workspace->res = NULL;
434 if (workspace->ctxt)
435 xmlXPathFreeContext(workspace->ctxt);
436 workspace->ctxt = NULL;
437 if (workspace->doctree)
438 xmlFreeDoc(workspace->doctree);
439 workspace->doctree = NULL;
440 }
441
442 static text *
443 pgxml_result_to_text(xmlXPathObjectPtr res,
444 xmlChar *toptag,
445 xmlChar *septag,
446 xmlChar *plainsep)
447 {
448 xmlChar *xpresstr;
449 text *xpres;
450
451 if (res == NULL)
452 return NULL;
453
454 switch (res->type)
455 {
456 case XPATH_NODESET:
457 xpresstr = pgxmlNodeSetToText(res->nodesetval,
458 toptag,
459 septag, plainsep);
460 break;
461
462 case XPATH_STRING:
463 xpresstr = xmlStrdup(res->stringval);
464 break;
465
466 default:
467 elog(NOTICE, "unsupported XQuery result: %d", res->type);
468 xpresstr = xmlStrdup((const xmlChar *) "<unsupported/>");
469 }
470
471 /* Now convert this result back to text */
472 xpres = cstring_to_text((char *) xpresstr);
473
474 /* Free various storage */
475 xmlFree(xpresstr);
476
477 return xpres;
478 }
479
480 /*
481 * xpath_table is a table function. It needs some tidying (as do the
482 * other functions here!
483 */
484 PG_FUNCTION_INFO_V1(xpath_table);
485
486 Datum
487 xpath_table(PG_FUNCTION_ARGS)
488 {
489 /* Function parameters */
490 char *pkeyfield = text_to_cstring(PG_GETARG_TEXT_PP(0));
491 char *xmlfield = text_to_cstring(PG_GETARG_TEXT_PP(1));
492 char *relname = text_to_cstring(PG_GETARG_TEXT_PP(2));
493 char *xpathset = text_to_cstring(PG_GETARG_TEXT_PP(3));
494 char *condition = text_to_cstring(PG_GETARG_TEXT_PP(4));
495
496 /* SPI (input tuple) support */
497 SPITupleTable *tuptable;
498 HeapTuple spi_tuple;
499 TupleDesc spi_tupdesc;
500
501
502 ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
503 AttInMetadata *attinmeta;
504
505 char **values;
506 xmlChar **xpaths;
507 char *pos;
508 const char *pathsep = "|";
509
510 int numpaths;
511 int ret;
512 uint64 proc;
513 int j;
514 int rownr; /* For issuing multiple rows from one original
515 * document */
516 bool had_values; /* To determine end of nodeset results */
517 StringInfoData query_buf;
518 PgXmlErrorContext *xmlerrcxt;
519 volatile xmlDocPtr doctree = NULL;
520
521 InitMaterializedSRF(fcinfo, MAT_SRF_USE_EXPECTED_DESC);
522
523 /* must have at least one output column (for the pkey) */
524 if (rsinfo->setDesc->natts < 1)
525 ereport(ERROR,
526 (errcode(ERRCODE_SYNTAX_ERROR),
527 errmsg("xpath_table must have at least one output column")));
528
529 /*
530 * At the moment we assume that the returned attributes make sense for the
531 * XPath specified (i.e. we trust the caller). It's not fatal if they get
532 * it wrong - the input function for the column type will raise an error
533 * if the path result can't be converted into the correct binary
534 * representation.
535 */
536
537 attinmeta = TupleDescGetAttInMetadata(rsinfo->setDesc);
538
539 values = (char **) palloc(rsinfo->setDesc->natts * sizeof(char *));
540 xpaths = (xmlChar **) palloc(rsinfo->setDesc->natts * sizeof(xmlChar *));
541
542 /*
543 * Split XPaths. xpathset is a writable CString.
544 *
545 * Note that we stop splitting once we've done all needed for tupdesc
546 */
547 numpaths = 0;
548 pos = xpathset;
549 while (numpaths < (rsinfo->setDesc->natts - 1))
550 {
551 xpaths[numpaths++] = (xmlChar *) pos;
552 pos = strstr(pos, pathsep);
553 if (pos != NULL)
554 {
555 *pos = '\0';
556 pos++;
557 }
558 else
559 break;
560 }
561
562 /* Now build query */
563 initStringInfo(&query_buf);
564
565 /* Build initial sql statement */
566 appendStringInfo(&query_buf, "SELECT %s, %s FROM %s WHERE %s",
567 pkeyfield,
568 xmlfield,
569 relname,
570 condition);
571
572 SPI_connect();
573
574 if ((ret = SPI_exec(query_buf.data, 0)) != SPI_OK_SELECT)
575 elog(ERROR, "xpath_table: SPI execution failed for query %s",
576 query_buf.data);
577
578 proc = SPI_processed;
579 tuptable = SPI_tuptable;
580 spi_tupdesc = tuptable->tupdesc;
581
582 /*
583 * Check that SPI returned correct result. If you put a comma into one of
584 * the function parameters, this will catch it when the SPI query returns
585 * e.g. 3 columns.
586 */
587 if (spi_tupdesc->natts != 2)
588 {
589 ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
590 errmsg("expression returning multiple columns is not valid in parameter list"),
591 errdetail("Expected two columns in SPI result, got %d.", spi_tupdesc->natts)));
592 }
593
594 /*
595 * Setup the parser. This should happen after we are done evaluating the
596 * query, in case it calls functions that set up libxml differently.
597 */
598 xmlerrcxt = pgxml_parser_init(PG_XML_STRICTNESS_LEGACY);
599
600 PG_TRY();
601 {
602 /* For each row i.e. document returned from SPI */
603 uint64 i;
604
605 for (i = 0; i < proc; i++)
606 {
607 char *pkey;
608 char *xmldoc;
609 xmlXPathContextPtr ctxt;
610 xmlXPathObjectPtr res;
611 xmlChar *resstr;
612 xmlXPathCompExprPtr comppath;
613 HeapTuple ret_tuple;
614
615 /* Extract the row data as C Strings */
616 spi_tuple = tuptable->vals[i];
617 pkey = SPI_getvalue(spi_tuple, spi_tupdesc, 1);
618 xmldoc = SPI_getvalue(spi_tuple, spi_tupdesc, 2);
619
620 /*
621 * Clear the values array, so that not-well-formed documents
622 * return NULL in all columns. Note that this also means that
623 * spare columns will be NULL.
624 */
625 for (j = 0; j < rsinfo->setDesc->natts; j++)
626 values[j] = NULL;
627
628 /* Insert primary key */
629 values[0] = pkey;
630
631 /* Parse the document */
632 if (xmldoc)
633 doctree = xmlReadMemory(xmldoc, strlen(xmldoc),
634 NULL, NULL,
635 XML_PARSE_NOENT);
636 else /* treat NULL as not well-formed */
637 doctree = NULL;
638
639 if (doctree == NULL)
640 {
641 /* not well-formed, so output all-NULL tuple */
642 ret_tuple = BuildTupleFromCStrings(attinmeta, values);
643 tuplestore_puttuple(rsinfo->setResult, ret_tuple);
644 heap_freetuple(ret_tuple);
645 }
646 else
647 {
648 /* New loop here - we have to deal with nodeset results */
649 rownr = 0;
650
651 do
652 {
653 /* Now evaluate the set of xpaths. */
654 had_values = false;
655 for (j = 0; j < numpaths; j++)
656 {
657 ctxt = xmlXPathNewContext(doctree);
658 ctxt->node = xmlDocGetRootElement(doctree);
659
660 /* compile the path */
661 comppath = xmlXPathCtxtCompile(ctxt, xpaths[j]);
662 if (comppath == NULL)
663 xml_ereport(xmlerrcxt, ERROR,
664 ERRCODE_INVALID_ARGUMENT_FOR_XQUERY,
665 "XPath Syntax Error");
666
667 /* Now evaluate the path expression. */
668 res = xmlXPathCompiledEval(comppath, ctxt);
669 xmlXPathFreeCompExpr(comppath);
670
671 if (res != NULL)
672 {
673 switch (res->type)
674 {
675 case XPATH_NODESET:
676 /* We see if this nodeset has enough nodes */
677 if (res->nodesetval != NULL &&
678 rownr < res->nodesetval->nodeNr)
679 {
680 resstr = xmlXPathCastNodeToString(res->nodesetval->nodeTab[rownr]);
681 had_values = true;
682 }
683 else
684 resstr = NULL;
685
686 break;
687
688 case XPATH_STRING:
689 resstr = xmlStrdup(res->stringval);
690 break;
691
692 default:
693 elog(NOTICE, "unsupported XQuery result: %d", res->type);
694 resstr = xmlStrdup((const xmlChar *) "<unsupported/>");
695 }
696
697 /*
698 * Insert this into the appropriate column in the
699 * result tuple.
700 */
701 values[j + 1] = (char *) resstr;
702 }
703 xmlXPathFreeContext(ctxt);
704 }
705
706 /* Now add the tuple to the output, if there is one. */
707 if (had_values)
708 {
709 ret_tuple = BuildTupleFromCStrings(attinmeta, values);
710 tuplestore_puttuple(rsinfo->setResult, ret_tuple);
711 heap_freetuple(ret_tuple);
712 }
713
714 rownr++;
715 } while (had_values);
716 }
717
718 if (doctree != NULL)
719 xmlFreeDoc(doctree);
720 doctree = NULL;
721
722 if (pkey)
723 pfree(pkey);
724 if (xmldoc)
725 pfree(xmldoc);
726 }
727 }
728 PG_CATCH();
729 {
730 if (doctree != NULL)
731 xmlFreeDoc(doctree);
732
733 pg_xml_done(xmlerrcxt, true);
734
735 PG_RE_THROW();
736 }
737 PG_END_TRY();
738
739 if (doctree != NULL)
740 xmlFreeDoc(doctree);
741
742 pg_xml_done(xmlerrcxt, false);
743
744 SPI_finish();
745
746 /*
747 * SFRM_Materialize mode expects us to return a NULL Datum. The actual
748 * tuples are in our tuplestore and passed back through rsinfo->setResult.
749 * rsinfo->setDesc is set to the tuple description that we actually used
750 * to build our tuples with, so the caller can verify we did what it was
751 * expecting.
752 */
753 return (Datum) 0;
754 }