Debian Codegraph @

src/backend/utils/adt/xml.c

raw
1 /*-------------------------------------------------------------------------
2 *
3 * xml.c
4 * XML data type support.
5 *
6 *
7 * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
8 * Portions Copyright (c) 1994, Regents of the University of California
9 *
10 * src/backend/utils/adt/xml.c
11 *
12 *-------------------------------------------------------------------------
13 */
14
15 /*
16 * Generally, XML type support is only available when libxml use was
17 * configured during the build. But even if that is not done, the
18 * type and all the functions are available, but most of them will
19 * fail. For one thing, this avoids having to manage variant catalog
20 * installations. But it also has nice effects such as that you can
21 * dump a database containing XML type data even if the server is not
22 * linked with libxml. Thus, make sure xml_out() works even if nothing
23 * else does.
24 */
25
26 /*
27 * Notes on memory management:
28 *
29 * Sometimes libxml allocates global structures in the hope that it can reuse
30 * them later on. This makes it impractical to change the xmlMemSetup
31 * functions on-the-fly; that is likely to lead to trying to pfree() chunks
32 * allocated with malloc() or vice versa. Since libxml might be used by
33 * loadable modules, eg libperl, our only safe choices are to change the
34 * functions at postmaster/backend launch or not at all. Since we'd rather
35 * not activate libxml in sessions that might never use it, the latter choice
36 * is the preferred one. However, for debugging purposes it can be awfully
37 * handy to constrain libxml's allocations to be done in a specific palloc
38 * context, where they're easy to track. Therefore there is code here that
39 * can be enabled in debug builds to redirect libxml's allocations into a
40 * special context LibxmlContext. It's not recommended to turn this on in
41 * a production build because of the possibility of bad interactions with
42 * external modules.
43 */
44 /* #define USE_LIBXMLCONTEXT */
45
46 #include "postgres.h"
47
48 #ifdef USE_LIBXML
49 #include <libxml/chvalid.h>
50 #include <libxml/entities.h>
51 #include <libxml/parser.h>
52 #include <libxml/parserInternals.h>
53 #include <libxml/tree.h>
54 #include <libxml/uri.h>
55 #include <libxml/xmlerror.h>
56 #include <libxml/xmlsave.h>
57 #include <libxml/xmlversion.h>
58 #include <libxml/xmlwriter.h>
59 #include <libxml/xpath.h>
60 #include <libxml/xpathInternals.h>
61
62 /*
63 * We used to check for xmlStructuredErrorContext via a configure test; but
64 * that doesn't work on Windows, so instead use this grottier method of
65 * testing the library version number.
66 */
67 #if LIBXML_VERSION >= 20704
68 #define HAVE_XMLSTRUCTUREDERRORCONTEXT 1
69 #endif
70
71 /*
72 * libxml2 2.12 decided to insert "const" into the error handler API.
73 */
74 #if LIBXML_VERSION >= 21200
75 #define PgXmlErrorPtr const xmlError *
76 #else
77 #define PgXmlErrorPtr xmlErrorPtr
78 #endif
79
80 #endif /* USE_LIBXML */
81
82 #include "access/htup_details.h"
83 #include "access/table.h"
84 #include "catalog/namespace.h"
85 #include "catalog/pg_class.h"
86 #include "catalog/pg_type.h"
87 #include "commands/dbcommands.h"
88 #include "executor/spi.h"
89 #include "executor/tablefunc.h"
90 #include "fmgr.h"
91 #include "lib/stringinfo.h"
92 #include "libpq/pqformat.h"
93 #include "mb/pg_wchar.h"
94 #include "miscadmin.h"
95 #include "nodes/execnodes.h"
96 #include "nodes/miscnodes.h"
97 #include "nodes/nodeFuncs.h"
98 #include "utils/array.h"
99 #include "utils/builtins.h"
100 #include "utils/date.h"
101 #include "utils/datetime.h"
102 #include "utils/lsyscache.h"
103 #include "utils/rel.h"
104 #include "utils/syscache.h"
105 #include "utils/xml.h"
106
107
108 /* GUC variables */
109 int xmlbinary = XMLBINARY_BASE64;
110 int xmloption = XMLOPTION_CONTENT;
111
112 #ifdef USE_LIBXML
113
114 /* random number to identify PgXmlErrorContext */
115 #define ERRCXT_MAGIC 68275028
116
117 struct PgXmlErrorContext
118 {
119 int magic;
120 /* strictness argument passed to pg_xml_init */
121 PgXmlStrictness strictness;
122 /* current error status and accumulated message, if any */
123 bool err_occurred;
124 StringInfoData err_buf;
125 /* previous libxml error handling state (saved by pg_xml_init) */
126 xmlStructuredErrorFunc saved_errfunc;
127 void *saved_errcxt;
128 /* previous libxml entity handler (saved by pg_xml_init) */
129 xmlExternalEntityLoader saved_entityfunc;
130 };
131
132 static xmlParserInputPtr xmlPgEntityLoader(const char *URL, const char *ID,
133 xmlParserCtxtPtr ctxt);
134 static void xml_errsave(Node *escontext, PgXmlErrorContext *errcxt,
135 int sqlcode, const char *msg);
136 static void xml_errorHandler(void *data, PgXmlErrorPtr error);
137 static int errdetail_for_xml_code(int code);
138 static void chopStringInfoNewlines(StringInfo str);
139 static void appendStringInfoLineSeparator(StringInfo str);
140
141 #ifdef USE_LIBXMLCONTEXT
142
143 static MemoryContext LibxmlContext = NULL;
144
145 static void xml_memory_init(void);
146 static void *xml_palloc(size_t size);
147 static void *xml_repalloc(void *ptr, size_t size);
148 static void xml_pfree(void *ptr);
149 static char *xml_pstrdup(const char *string);
150 #endif /* USE_LIBXMLCONTEXT */
151
152 static xmlChar *xml_text2xmlChar(text *in);
153 static int parse_xml_decl(const xmlChar *str, size_t *lenp,
154 xmlChar **version, xmlChar **encoding, int *standalone);
155 static bool print_xml_decl(StringInfo buf, const xmlChar *version,
156 pg_enc encoding, int standalone);
157 static bool xml_doctype_in_content(const xmlChar *str);
158 static xmlDocPtr xml_parse(text *data, XmlOptionType xmloption_arg,
159 bool preserve_whitespace, int encoding,
160 XmlOptionType *parsed_xmloptiontype,
161 xmlNodePtr *parsed_nodes,
162 Node *escontext);
163 static text *xml_xmlnodetoxmltype(xmlNodePtr cur, PgXmlErrorContext *xmlerrcxt);
164 static int xml_xpathobjtoxmlarray(xmlXPathObjectPtr xpathobj,
165 ArrayBuildState *astate,
166 PgXmlErrorContext *xmlerrcxt);
167 static xmlChar *pg_xmlCharStrndup(const char *str, size_t len);
168 #endif /* USE_LIBXML */
169
170 static void xmldata_root_element_start(StringInfo result, const char *eltname,
171 const char *xmlschema, const char *targetns,
172 bool top_level);
173 static void xmldata_root_element_end(StringInfo result, const char *eltname);
174 static StringInfo query_to_xml_internal(const char *query, char *tablename,
175 const char *xmlschema, bool nulls, bool tableforest,
176 const char *targetns, bool top_level);
177 static const char *map_sql_table_to_xmlschema(TupleDesc tupdesc, Oid relid,
178 bool nulls, bool tableforest, const char *targetns);
179 static const char *map_sql_schema_to_xmlschema_types(Oid nspid,
180 List *relid_list, bool nulls,
181 bool tableforest, const char *targetns);
182 static const char *map_sql_catalog_to_xmlschema_types(List *nspid_list,
183 bool nulls, bool tableforest,
184 const char *targetns);
185 static const char *map_sql_type_to_xml_name(Oid typeoid, int typmod);
186 static const char *map_sql_typecoll_to_xmlschema_types(List *tupdesc_list);
187 static const char *map_sql_type_to_xmlschema_type(Oid typeoid, int typmod);
188 static void SPI_sql_row_to_xmlelement(uint64 rownum, StringInfo result,
189 char *tablename, bool nulls, bool tableforest,
190 const char *targetns, bool top_level);
191
192 /* XMLTABLE support */
193 #ifdef USE_LIBXML
194 /* random number to identify XmlTableContext */
195 #define XMLTABLE_CONTEXT_MAGIC 46922182
196 typedef struct XmlTableBuilderData
197 {
198 int magic;
199 int natts;
200 long int row_count;
201 PgXmlErrorContext *xmlerrcxt;
202 xmlParserCtxtPtr ctxt;
203 xmlDocPtr doc;
204 xmlXPathContextPtr xpathcxt;
205 xmlXPathCompExprPtr xpathcomp;
206 xmlXPathObjectPtr xpathobj;
207 xmlXPathCompExprPtr *xpathscomp;
208 } XmlTableBuilderData;
209 #endif
210
211 static void XmlTableInitOpaque(struct TableFuncScanState *state, int natts);
212 static void XmlTableSetDocument(struct TableFuncScanState *state, Datum value);
213 static void XmlTableSetNamespace(struct TableFuncScanState *state, const char *name,
214 const char *uri);
215 static void XmlTableSetRowFilter(struct TableFuncScanState *state, const char *path);
216 static void XmlTableSetColumnFilter(struct TableFuncScanState *state,
217 const char *path, int colnum);
218 static bool XmlTableFetchRow(struct TableFuncScanState *state);
219 static Datum XmlTableGetValue(struct TableFuncScanState *state, int colnum,
220 Oid typid, int32 typmod, bool *isnull);
221 static void XmlTableDestroyOpaque(struct TableFuncScanState *state);
222
223 const TableFuncRoutine XmlTableRoutine =
224 {
225 .InitOpaque = XmlTableInitOpaque,
226 .SetDocument = XmlTableSetDocument,
227 .SetNamespace = XmlTableSetNamespace,
228 .SetRowFilter = XmlTableSetRowFilter,
229 .SetColumnFilter = XmlTableSetColumnFilter,
230 .FetchRow = XmlTableFetchRow,
231 .GetValue = XmlTableGetValue,
232 .DestroyOpaque = XmlTableDestroyOpaque
233 };
234
235 #define NO_XML_SUPPORT() \
236 ereport(ERROR, \
237 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), \
238 errmsg("unsupported XML feature"), \
239 errdetail("This functionality requires the server to be built with libxml support.")))
240
241
242 /* from SQL/XML:2008 section 4.9 */
243 #define NAMESPACE_XSD "http://www.w3.org/2001/XMLSchema"
244 #define NAMESPACE_XSI "http://www.w3.org/2001/XMLSchema-instance"
245 #define NAMESPACE_SQLXML "http://standards.iso.org/iso/9075/2003/sqlxml"
246
247
248 #ifdef USE_LIBXML
249
250 static int
251 xmlChar_to_encoding(const xmlChar *encoding_name)
252 {
253 int encoding = pg_char_to_encoding((const char *) encoding_name);
254
255 if (encoding < 0)
256 ereport(ERROR,
257 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
258 errmsg("invalid encoding name \"%s\"",
259 (const char *) encoding_name)));
260 return encoding;
261 }
262 #endif
263
264
265 /*
266 * xml_in uses a plain C string to VARDATA conversion, so for the time being
267 * we use the conversion function for the text datatype.
268 *
269 * This is only acceptable so long as xmltype and text use the same
270 * representation.
271 */
272 Datum
273 xml_in(PG_FUNCTION_ARGS)
274 {
275 #ifdef USE_LIBXML
276 char *s = PG_GETARG_CSTRING(0);
277 xmltype *vardata;
278 xmlDocPtr doc;
279
280 /* Build the result object. */
281 vardata = (xmltype *) cstring_to_text(s);
282
283 /*
284 * Parse the data to check if it is well-formed XML data.
285 *
286 * Note: we don't need to worry about whether a soft error is detected.
287 */
288 doc = xml_parse(vardata, xmloption, true, GetDatabaseEncoding(),
289 NULL, NULL, fcinfo->context);
290 if (doc != NULL)
291 xmlFreeDoc(doc);
292
293 PG_RETURN_XML_P(vardata);
294 #else
295 NO_XML_SUPPORT();
296 return 0;
297 #endif
298 }
299
300
301 #define PG_XML_DEFAULT_VERSION "1.0"
302
303
304 /*
305 * xml_out_internal uses a plain VARDATA to C string conversion, so for the
306 * time being we use the conversion function for the text datatype.
307 *
308 * This is only acceptable so long as xmltype and text use the same
309 * representation.
310 */
311 static char *
312 xml_out_internal(xmltype *x, pg_enc target_encoding)
313 {
314 char *str = text_to_cstring((text *) x);
315
316 #ifdef USE_LIBXML
317 size_t len = strlen(str);
318 xmlChar *version;
319 int standalone;
320 int res_code;
321
322 if ((res_code = parse_xml_decl((xmlChar *) str,
323 &len, &version, NULL, &standalone)) == 0)
324 {
325 StringInfoData buf;
326
327 initStringInfo(&buf);
328
329 if (!print_xml_decl(&buf, version, target_encoding, standalone))
330 {
331 /*
332 * If we are not going to produce an XML declaration, eat a single
333 * newline in the original string to prevent empty first lines in
334 * the output.
335 */
336 if (*(str + len) == '\n')
337 len += 1;
338 }
339 appendStringInfoString(&buf, str + len);
340
341 pfree(str);
342
343 return buf.data;
344 }
345
346 ereport(WARNING,
347 errcode(ERRCODE_DATA_CORRUPTED),
348 errmsg_internal("could not parse XML declaration in stored value"),
349 errdetail_for_xml_code(res_code));
350 #endif
351 return str;
352 }
353
354
355 Datum
356 xml_out(PG_FUNCTION_ARGS)
357 {
358 xmltype *x = PG_GETARG_XML_P(0);
359
360 /*
361 * xml_out removes the encoding property in all cases. This is because we
362 * cannot control from here whether the datum will be converted to a
363 * different client encoding, so we'd do more harm than good by including
364 * it.
365 */
366 PG_RETURN_CSTRING(xml_out_internal(x, 0));
367 }
368
369
370 Datum
371 xml_recv(PG_FUNCTION_ARGS)
372 {
373 #ifdef USE_LIBXML
374 StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
375 xmltype *result;
376 char *str;
377 char *newstr;
378 int nbytes;
379 xmlDocPtr doc;
380 xmlChar *encodingStr = NULL;
381 int encoding;
382
383 /*
384 * Read the data in raw format. We don't know yet what the encoding is, as
385 * that information is embedded in the xml declaration; so we have to
386 * parse that before converting to server encoding.
387 */
388 nbytes = buf->len - buf->cursor;
389 str = (char *) pq_getmsgbytes(buf, nbytes);
390
391 /*
392 * We need a null-terminated string to pass to parse_xml_decl(). Rather
393 * than make a separate copy, make the temporary result one byte bigger
394 * than it needs to be.
395 */
396 result = palloc(nbytes + 1 + VARHDRSZ);
397 SET_VARSIZE(result, nbytes + VARHDRSZ);
398 memcpy(VARDATA(result), str, nbytes);
399 str = VARDATA(result);
400 str[nbytes] = '\0';
401
402 parse_xml_decl((const xmlChar *) str, NULL, NULL, &encodingStr, NULL);
403
404 /*
405 * If encoding wasn't explicitly specified in the XML header, treat it as
406 * UTF-8, as that's the default in XML. This is different from xml_in(),
407 * where the input has to go through the normal client to server encoding
408 * conversion.
409 */
410 encoding = encodingStr ? xmlChar_to_encoding(encodingStr) : PG_UTF8;
411
412 /*
413 * Parse the data to check if it is well-formed XML data. Assume that
414 * xml_parse will throw ERROR if not.
415 */
416 doc = xml_parse(result, xmloption, true, encoding, NULL, NULL, NULL);
417 xmlFreeDoc(doc);
418
419 /* Now that we know what we're dealing with, convert to server encoding */
420 newstr = pg_any_to_server(str, nbytes, encoding);
421
422 if (newstr != str)
423 {
424 pfree(result);
425 result = (xmltype *) cstring_to_text(newstr);
426 pfree(newstr);
427 }
428
429 PG_RETURN_XML_P(result);
430 #else
431 NO_XML_SUPPORT();
432 return 0;
433 #endif
434 }
435
436
437 Datum
438 xml_send(PG_FUNCTION_ARGS)
439 {
440 xmltype *x = PG_GETARG_XML_P(0);
441 char *outval;
442 StringInfoData buf;
443
444 /*
445 * xml_out_internal doesn't convert the encoding, it just prints the right
446 * declaration. pq_sendtext will do the conversion.
447 */
448 outval = xml_out_internal(x, pg_get_client_encoding());
449
450 pq_begintypsend(&buf);
451 pq_sendtext(&buf, outval, strlen(outval));
452 pfree(outval);
453 PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
454 }
455
456
457 #ifdef USE_LIBXML
458 static void
459 appendStringInfoText(StringInfo str, const text *t)
460 {
461 appendBinaryStringInfo(str, VARDATA_ANY(t), VARSIZE_ANY_EXHDR(t));
462 }
463 #endif
464
465
466 static xmltype *
467 stringinfo_to_xmltype(StringInfo buf)
468 {
469 return (xmltype *) cstring_to_text_with_len(buf->data, buf->len);
470 }
471
472
473 static xmltype *
474 cstring_to_xmltype(const char *string)
475 {
476 return (xmltype *) cstring_to_text(string);
477 }
478
479
480 #ifdef USE_LIBXML
481 static xmltype *
482 xmlBuffer_to_xmltype(xmlBufferPtr buf)
483 {
484 return (xmltype *) cstring_to_text_with_len((const char *) xmlBufferContent(buf),
485 xmlBufferLength(buf));
486 }
487 #endif
488
489
490 Datum
491 xmlcomment(PG_FUNCTION_ARGS)
492 {
493 #ifdef USE_LIBXML
494 text *arg = PG_GETARG_TEXT_PP(0);
495 char *argdata = VARDATA_ANY(arg);
496 int len = VARSIZE_ANY_EXHDR(arg);
497 StringInfoData buf;
498 int i;
499
500 /* check for "--" in string or "-" at the end */
501 for (i = 1; i < len; i++)
502 {
503 if (argdata[i] == '-' && argdata[i - 1] == '-')
504 ereport(ERROR,
505 (errcode(ERRCODE_INVALID_XML_COMMENT),
506 errmsg("invalid XML comment")));
507 }
508 if (len > 0 && argdata[len - 1] == '-')
509 ereport(ERROR,
510 (errcode(ERRCODE_INVALID_XML_COMMENT),
511 errmsg("invalid XML comment")));
512
513 initStringInfo(&buf);
514 appendStringInfoString(&buf, "<!--");
515 appendStringInfoText(&buf, arg);
516 appendStringInfoString(&buf, "-->");
517
518 PG_RETURN_XML_P(stringinfo_to_xmltype(&buf));
519 #else
520 NO_XML_SUPPORT();
521 return 0;
522 #endif
523 }
524
525
526 Datum
527 xmltext(PG_FUNCTION_ARGS)
528 {
529 #ifdef USE_LIBXML
530 text *arg = PG_GETARG_TEXT_PP(0);
531 text *result;
532 xmlChar *xmlbuf = NULL;
533
534 xmlbuf = xmlEncodeSpecialChars(NULL, xml_text2xmlChar(arg));
535
536 Assert(xmlbuf);
537
538 result = cstring_to_text_with_len((const char *) xmlbuf, xmlStrlen(xmlbuf));
539 xmlFree(xmlbuf);
540 PG_RETURN_XML_P(result);
541 #else
542 NO_XML_SUPPORT();
543 return 0;
544 #endif /* not USE_LIBXML */
545 }
546
547
548 /*
549 * TODO: xmlconcat needs to merge the notations and unparsed entities
550 * of the argument values. Not very important in practice, though.
551 */
552 xmltype *
553 xmlconcat(List *args)
554 {
555 #ifdef USE_LIBXML
556 int global_standalone = 1;
557 xmlChar *global_version = NULL;
558 bool global_version_no_value = false;
559 StringInfoData buf;
560 ListCell *v;
561
562 initStringInfo(&buf);
563 foreach(v, args)
564 {
565 xmltype *x = DatumGetXmlP(PointerGetDatum(lfirst(v)));
566 size_t len;
567 xmlChar *version;
568 int standalone;
569 char *str;
570
571 len = VARSIZE(x) - VARHDRSZ;
572 str = text_to_cstring((text *) x);
573
574 parse_xml_decl((xmlChar *) str, &len, &version, NULL, &standalone);
575
576 if (standalone == 0 && global_standalone == 1)
577 global_standalone = 0;
578 if (standalone < 0)
579 global_standalone = -1;
580
581 if (!version)
582 global_version_no_value = true;
583 else if (!global_version)
584 global_version = version;
585 else if (xmlStrcmp(version, global_version) != 0)
586 global_version_no_value = true;
587
588 appendStringInfoString(&buf, str + len);
589 pfree(str);
590 }
591
592 if (!global_version_no_value || global_standalone >= 0)
593 {
594 StringInfoData buf2;
595
596 initStringInfo(&buf2);
597
598 print_xml_decl(&buf2,
599 (!global_version_no_value) ? global_version : NULL,
600 0,
601 global_standalone);
602
603 appendBinaryStringInfo(&buf2, buf.data, buf.len);
604 buf = buf2;
605 }
606
607 return stringinfo_to_xmltype(&buf);
608 #else
609 NO_XML_SUPPORT();
610 return NULL;
611 #endif
612 }
613
614
615 /*
616 * XMLAGG support
617 */
618 Datum
619 xmlconcat2(PG_FUNCTION_ARGS)
620 {
621 if (PG_ARGISNULL(0))
622 {
623 if (PG_ARGISNULL(1))
624 PG_RETURN_NULL();
625 else
626 PG_RETURN_XML_P(PG_GETARG_XML_P(1));
627 }
628 else if (PG_ARGISNULL(1))
629 PG_RETURN_XML_P(PG_GETARG_XML_P(0));
630 else
631 PG_RETURN_XML_P(xmlconcat(list_make2(PG_GETARG_XML_P(0),
632 PG_GETARG_XML_P(1))));
633 }
634
635
636 Datum
637 texttoxml(PG_FUNCTION_ARGS)
638 {
639 text *data = PG_GETARG_TEXT_PP(0);
640
641 PG_RETURN_XML_P(xmlparse(data, xmloption, true));
642 }
643
644
645 Datum
646 xmltotext(PG_FUNCTION_ARGS)
647 {
648 xmltype *data = PG_GETARG_XML_P(0);
649
650 /* It's actually binary compatible. */
651 PG_RETURN_TEXT_P((text *) data);
652 }
653
654
655 text *
656 xmltotext_with_options(xmltype *data, XmlOptionType xmloption_arg, bool indent)
657 {
658 #ifdef USE_LIBXML
659 text *volatile result;
660 xmlDocPtr doc;
661 XmlOptionType parsed_xmloptiontype;
662 xmlNodePtr content_nodes;
663 volatile xmlBufferPtr buf = NULL;
664 volatile xmlSaveCtxtPtr ctxt = NULL;
665 ErrorSaveContext escontext = {T_ErrorSaveContext};
666 PgXmlErrorContext *volatile xmlerrcxt = NULL;
667 #endif
668
669 if (xmloption_arg != XMLOPTION_DOCUMENT && !indent)
670 {
671 /*
672 * We don't actually need to do anything, so just return the
673 * binary-compatible input. For backwards-compatibility reasons,
674 * allow such cases to succeed even without USE_LIBXML.
675 */
676 return (text *) data;
677 }
678
679 #ifdef USE_LIBXML
680
681 /*
682 * Parse the input according to the xmloption.
683 *
684 * preserve_whitespace is set to false in case we are indenting, otherwise
685 * libxml2 will fail to indent elements that have whitespace between them.
686 */
687 doc = xml_parse(data, xmloption_arg, !indent, GetDatabaseEncoding(),
688 &parsed_xmloptiontype, &content_nodes,
689 (Node *) &escontext);
690 if (doc == NULL || escontext.error_occurred)
691 {
692 if (doc)
693 xmlFreeDoc(doc);
694 /* A soft error must be failure to conform to XMLOPTION_DOCUMENT */
695 ereport(ERROR,
696 (errcode(ERRCODE_NOT_AN_XML_DOCUMENT),
697 errmsg("not an XML document")));
698 }
699
700 /* If we weren't asked to indent, we're done. */
701 if (!indent)
702 {
703 xmlFreeDoc(doc);
704 return (text *) data;
705 }
706
707 /*
708 * Otherwise, we gotta spin up some error handling. Unlike most other
709 * routines in this module, we already have a libxml "doc" structure to
710 * free, so we need to call pg_xml_init() inside the PG_TRY and be
711 * prepared for it to fail (typically due to palloc OOM).
712 */
713 PG_TRY();
714 {
715 size_t decl_len = 0;
716
717 xmlerrcxt = pg_xml_init(PG_XML_STRICTNESS_ALL);
718
719 /* The serialized data will go into this buffer. */
720 buf = xmlBufferCreate();
721
722 if (buf == NULL || xmlerrcxt->err_occurred)
723 xml_ereport(xmlerrcxt, ERROR, ERRCODE_OUT_OF_MEMORY,
724 "could not allocate xmlBuffer");
725
726 /* Detect whether there's an XML declaration */
727 parse_xml_decl(xml_text2xmlChar(data), &decl_len, NULL, NULL, NULL);
728
729 /*
730 * Emit declaration only if the input had one. Note: some versions of
731 * xmlSaveToBuffer leak memory if a non-null encoding argument is
732 * passed, so don't do that. We don't want any encoding conversion
733 * anyway.
734 */
735 if (decl_len == 0)
736 ctxt = xmlSaveToBuffer(buf, NULL,
737 XML_SAVE_NO_DECL | XML_SAVE_FORMAT);
738 else
739 ctxt = xmlSaveToBuffer(buf, NULL,
740 XML_SAVE_FORMAT);
741
742 if (ctxt == NULL || xmlerrcxt->err_occurred)
743 xml_ereport(xmlerrcxt, ERROR, ERRCODE_OUT_OF_MEMORY,
744 "could not allocate xmlSaveCtxt");
745
746 if (parsed_xmloptiontype == XMLOPTION_DOCUMENT)
747 {
748 /* If it's a document, saving is easy. */
749 if (xmlSaveDoc(ctxt, doc) == -1 || xmlerrcxt->err_occurred)
750 xml_ereport(xmlerrcxt, ERROR, ERRCODE_OUT_OF_MEMORY,
751 "could not save document to xmlBuffer");
752 }
753 else if (content_nodes != NULL)
754 {
755 /*
756 * Deal with the case where we have non-singly-rooted XML.
757 * libxml's dump functions don't work well for that without help.
758 * We build a fake root node that serves as a container for the
759 * content nodes, and then iterate over the nodes.
760 */
761 xmlNodePtr root;
762 xmlNodePtr oldroot;
763 xmlNodePtr newline;
764
765 root = xmlNewNode(NULL, (const xmlChar *) "content-root");
766 if (root == NULL || xmlerrcxt->err_occurred)
767 xml_ereport(xmlerrcxt, ERROR, ERRCODE_OUT_OF_MEMORY,
768 "could not allocate xml node");
769
770 /*
771 * This attaches root to doc, so we need not free it separately...
772 * but instead, we have to free the old root if there was one.
773 */
774 oldroot = xmlDocSetRootElement(doc, root);
775 if (oldroot != NULL)
776 xmlFreeNode(oldroot);
777
778 xmlAddChildList(root, content_nodes);
779
780 /*
781 * We use this node to insert newlines in the dump. Note: in at
782 * least some libxml versions, xmlNewDocText would not attach the
783 * node to the document even if we passed it. Therefore, manage
784 * freeing of this node manually, and pass NULL here to make sure
785 * there's not a dangling link.
786 */
787 newline = xmlNewDocText(NULL, (const xmlChar *) "\n");
788 if (newline == NULL || xmlerrcxt->err_occurred)
789 xml_ereport(xmlerrcxt, ERROR, ERRCODE_OUT_OF_MEMORY,
790 "could not allocate xml node");
791
792 for (xmlNodePtr node = root->children; node; node = node->next)
793 {
794 /* insert newlines between nodes */
795 if (node->type != XML_TEXT_NODE && node->prev != NULL)
796 {
797 if (xmlSaveTree(ctxt, newline) == -1 || xmlerrcxt->err_occurred)
798 {
799 xmlFreeNode(newline);
800 xml_ereport(xmlerrcxt, ERROR, ERRCODE_OUT_OF_MEMORY,
801 "could not save newline to xmlBuffer");
802 }
803 }
804
805 if (xmlSaveTree(ctxt, node) == -1 || xmlerrcxt->err_occurred)
806 {
807 xmlFreeNode(newline);
808 xml_ereport(xmlerrcxt, ERROR, ERRCODE_OUT_OF_MEMORY,
809 "could not save content to xmlBuffer");
810 }
811 }
812
813 xmlFreeNode(newline);
814 }
815
816 if (xmlSaveClose(ctxt) == -1 || xmlerrcxt->err_occurred)
817 {
818 ctxt = NULL; /* don't try to close it again */
819 xml_ereport(xmlerrcxt, ERROR, ERRCODE_INTERNAL_ERROR,
820 "could not close xmlSaveCtxtPtr");
821 }
822
823 /*
824 * xmlDocContentDumpOutput may add a trailing newline, so remove that.
825 */
826 if (xmloption_arg == XMLOPTION_DOCUMENT)
827 {
828 const char *str = (const char *) xmlBufferContent(buf);
829 int len = xmlBufferLength(buf);
830
831 while (len > 0 && (str[len - 1] == '\n' ||
832 str[len - 1] == '\r'))
833 len--;
834
835 result = cstring_to_text_with_len(str, len);
836 }
837 else
838 result = (text *) xmlBuffer_to_xmltype(buf);
839 }
840 PG_CATCH();
841 {
842 if (ctxt)
843 xmlSaveClose(ctxt);
844 if (buf)
845 xmlBufferFree(buf);
846 xmlFreeDoc(doc);
847
848 if (xmlerrcxt)
849 pg_xml_done(xmlerrcxt, true);
850
851 PG_RE_THROW();
852 }
853 PG_END_TRY();
854
855 xmlBufferFree(buf);
856 xmlFreeDoc(doc);
857
858 pg_xml_done(xmlerrcxt, false);
859
860 return result;
861 #else
862 NO_XML_SUPPORT();
863 return NULL;
864 #endif
865 }
866
867
868 xmltype *
869 xmlelement(XmlExpr *xexpr,
870 Datum *named_argvalue, bool *named_argnull,
871 Datum *argvalue, bool *argnull)
872 {
873 #ifdef USE_LIBXML
874 xmltype *result;
875 List *named_arg_strings;
876 List *arg_strings;
877 int i;
878 ListCell *arg;
879 ListCell *narg;
880 PgXmlErrorContext *xmlerrcxt;
881 volatile xmlBufferPtr buf = NULL;
882 volatile xmlTextWriterPtr writer = NULL;
883
884 /*
885 * All arguments are already evaluated, and their values are passed in the
886 * named_argvalue/named_argnull or argvalue/argnull arrays. This avoids
887 * issues if one of the arguments involves a call to some other function
888 * or subsystem that wants to use libxml on its own terms. We examine the
889 * original XmlExpr to identify the numbers and types of the arguments.
890 */
891 named_arg_strings = NIL;
892 i = 0;
893 foreach(arg, xexpr->named_args)
894 {
895 Expr *e = (Expr *) lfirst(arg);
896 char *str;
897
898 if (named_argnull[i])
899 str = NULL;
900 else
901 str = map_sql_value_to_xml_value(named_argvalue[i],
902 exprType((Node *) e),
903 false);
904 named_arg_strings = lappend(named_arg_strings, str);
905 i++;
906 }
907
908 arg_strings = NIL;
909 i = 0;
910 foreach(arg, xexpr->args)
911 {
912 Expr *e = (Expr *) lfirst(arg);
913 char *str;
914
915 /* here we can just forget NULL elements immediately */
916 if (!argnull[i])
917 {
918 str = map_sql_value_to_xml_value(argvalue[i],
919 exprType((Node *) e),
920 true);
921 arg_strings = lappend(arg_strings, str);
922 }
923 i++;
924 }
925
926 xmlerrcxt = pg_xml_init(PG_XML_STRICTNESS_ALL);
927
928 PG_TRY();
929 {
930 buf = xmlBufferCreate();
931 if (buf == NULL || xmlerrcxt->err_occurred)
932 xml_ereport(xmlerrcxt, ERROR, ERRCODE_OUT_OF_MEMORY,
933 "could not allocate xmlBuffer");
934 writer = xmlNewTextWriterMemory(buf, 0);
935 if (writer == NULL || xmlerrcxt->err_occurred)
936 xml_ereport(xmlerrcxt, ERROR, ERRCODE_OUT_OF_MEMORY,
937 "could not allocate xmlTextWriter");
938
939 xmlTextWriterStartElement(writer, (xmlChar *) xexpr->name);
940
941 forboth(arg, named_arg_strings, narg, xexpr->arg_names)
942 {
943 char *str = (char *) lfirst(arg);
944 char *argname = strVal(lfirst(narg));
945
946 if (str)
947 xmlTextWriterWriteAttribute(writer,
948 (xmlChar *) argname,
949 (xmlChar *) str);
950 }
951
952 foreach(arg, arg_strings)
953 {
954 char *str = (char *) lfirst(arg);
955
956 xmlTextWriterWriteRaw(writer, (xmlChar *) str);
957 }
958
959 xmlTextWriterEndElement(writer);
960
961 /* we MUST do this now to flush data out to the buffer ... */
962 xmlFreeTextWriter(writer);
963 writer = NULL;
964
965 result = xmlBuffer_to_xmltype(buf);
966 }
967 PG_CATCH();
968 {
969 if (writer)
970 xmlFreeTextWriter(writer);
971 if (buf)
972 xmlBufferFree(buf);
973
974 pg_xml_done(xmlerrcxt, true);
975
976 PG_RE_THROW();
977 }
978 PG_END_TRY();
979
980 xmlBufferFree(buf);
981
982 pg_xml_done(xmlerrcxt, false);
983
984 return result;
985 #else
986 NO_XML_SUPPORT();
987 return NULL;
988 #endif
989 }
990
991
992 xmltype *
993 xmlparse(text *data, XmlOptionType xmloption_arg, bool preserve_whitespace)
994 {
995 #ifdef USE_LIBXML
996 xmlDocPtr doc;
997
998 doc = xml_parse(data, xmloption_arg, preserve_whitespace,
999 GetDatabaseEncoding(), NULL, NULL, NULL);
1000 xmlFreeDoc(doc);
1001
1002 return (xmltype *) data;
1003 #else
1004 NO_XML_SUPPORT();
1005 return NULL;
1006 #endif
1007 }
1008
1009
1010 xmltype *
1011 xmlpi(const char *target, text *arg, bool arg_is_null, bool *result_is_null)
1012 {
1013 #ifdef USE_LIBXML
1014 xmltype *result;
1015 StringInfoData buf;
1016
1017 if (pg_strcasecmp(target, "xml") == 0)
1018 ereport(ERROR,
1019 (errcode(ERRCODE_INVALID_XML_PROCESSING_INSTRUCTION),
1020 errmsg("invalid XML processing instruction"),
1021 errdetail("XML processing instruction target name cannot be \"%s\".", target)));
1022
1023 /*
1024 * Following the SQL standard, the null check comes after the syntax check
1025 * above.
1026 */
1027 *result_is_null = arg_is_null;
1028 if (*result_is_null)
1029 return NULL;
1030
1031 initStringInfo(&buf);
1032
1033 appendStringInfo(&buf, "<?%s", target);
1034
1035 if (arg != NULL)
1036 {
1037 char *string;
1038
1039 string = text_to_cstring(arg);
1040 if (strstr(string, "?>") != NULL)
1041 ereport(ERROR,
1042 (errcode(ERRCODE_INVALID_XML_PROCESSING_INSTRUCTION),
1043 errmsg("invalid XML processing instruction"),
1044 errdetail("XML processing instruction cannot contain \"?>\".")));
1045
1046 appendStringInfoChar(&buf, ' ');
1047 appendStringInfoString(&buf, string + strspn(string, " "));
1048 pfree(string);
1049 }
1050 appendStringInfoString(&buf, "?>");
1051
1052 result = stringinfo_to_xmltype(&buf);
1053 pfree(buf.data);
1054 return result;
1055 #else
1056 NO_XML_SUPPORT();
1057 return NULL;
1058 #endif
1059 }
1060
1061
1062 xmltype *
1063 xmlroot(xmltype *data, text *version, int standalone)
1064 {
1065 #ifdef USE_LIBXML
1066 char *str;
1067 size_t len;
1068 xmlChar *orig_version;
1069 int orig_standalone;
1070 StringInfoData buf;
1071
1072 len = VARSIZE(data) - VARHDRSZ;
1073 str = text_to_cstring((text *) data);
1074
1075 parse_xml_decl((xmlChar *) str, &len, &orig_version, NULL, &orig_standalone);
1076
1077 if (version)
1078 orig_version = xml_text2xmlChar(version);
1079 else
1080 orig_version = NULL;
1081
1082 switch (standalone)
1083 {
1084 case XML_STANDALONE_YES:
1085 orig_standalone = 1;
1086 break;
1087 case XML_STANDALONE_NO:
1088 orig_standalone = 0;
1089 break;
1090 case XML_STANDALONE_NO_VALUE:
1091 orig_standalone = -1;
1092 break;
1093 case XML_STANDALONE_OMITTED:
1094 /* leave original value */
1095 break;
1096 }
1097
1098 initStringInfo(&buf);
1099 print_xml_decl(&buf, orig_version, 0, orig_standalone);
1100 appendStringInfoString(&buf, str + len);
1101
1102 return stringinfo_to_xmltype(&buf);
1103 #else
1104 NO_XML_SUPPORT();
1105 return NULL;
1106 #endif
1107 }
1108
1109
1110 /*
1111 * Validate document (given as string) against DTD (given as external link)
1112 *
1113 * This has been removed because it is a security hole: unprivileged users
1114 * should not be able to use Postgres to fetch arbitrary external files,
1115 * which unfortunately is exactly what libxml is willing to do with the DTD
1116 * parameter.
1117 */
1118 Datum
1119 xmlvalidate(PG_FUNCTION_ARGS)
1120 {
1121 ereport(ERROR,
1122 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1123 errmsg("xmlvalidate is not implemented")));
1124 return 0;
1125 }
1126
1127
1128 bool
1129 xml_is_document(xmltype *arg)
1130 {
1131 #ifdef USE_LIBXML
1132 xmlDocPtr doc;
1133 ErrorSaveContext escontext = {T_ErrorSaveContext};
1134
1135 /*
1136 * We'll report "true" if no soft error is reported by xml_parse().
1137 */
1138 doc = xml_parse((text *) arg, XMLOPTION_DOCUMENT, true,
1139 GetDatabaseEncoding(), NULL, NULL, (Node *) &escontext);
1140 if (doc)
1141 xmlFreeDoc(doc);
1142
1143 return !escontext.error_occurred;
1144 #else /* not USE_LIBXML */
1145 NO_XML_SUPPORT();
1146 return false;
1147 #endif /* not USE_LIBXML */
1148 }
1149
1150
1151 #ifdef USE_LIBXML
1152
1153 /*
1154 * pg_xml_init_library --- set up for use of libxml
1155 *
1156 * This should be called by each function that is about to use libxml
1157 * facilities but doesn't require error handling. It initializes libxml
1158 * and verifies compatibility with the loaded libxml version. These are
1159 * once-per-session activities.
1160 *
1161 * TODO: xmlChar is utf8-char, make proper tuning (initdb with enc!=utf8 and
1162 * check)
1163 */
1164 void
1165 pg_xml_init_library(void)
1166 {
1167 static bool first_time = true;
1168
1169 if (first_time)
1170 {
1171 /* Stuff we need do only once per session */
1172
1173 /*
1174 * Currently, we have no pure UTF-8 support for internals -- check if
1175 * we can work.
1176 */
1177 if (sizeof(char) != sizeof(xmlChar))
1178 ereport(ERROR,
1179 (errmsg("could not initialize XML library"),
1180 errdetail("libxml2 has incompatible char type: sizeof(char)=%zu, sizeof(xmlChar)=%zu.",
1181 sizeof(char), sizeof(xmlChar))));
1182
1183 #ifdef USE_LIBXMLCONTEXT
1184 /* Set up libxml's memory allocation our way */
1185 xml_memory_init();
1186 #endif
1187
1188 /* Check library compatibility */
1189 LIBXML_TEST_VERSION;
1190
1191 first_time = false;
1192 }
1193 }
1194
1195 /*
1196 * pg_xml_init --- set up for use of libxml and register an error handler
1197 *
1198 * This should be called by each function that is about to use libxml
1199 * facilities and requires error handling. It initializes libxml with
1200 * pg_xml_init_library() and establishes our libxml error handler.
1201 *
1202 * strictness determines which errors are reported and which are ignored.
1203 *
1204 * Calls to this function MUST be followed by a PG_TRY block that guarantees
1205 * that pg_xml_done() is called during either normal or error exit.
1206 *
1207 * This is exported for use by contrib/xml2, as well as other code that might
1208 * wish to share use of this module's libxml error handler.
1209 */
1210 PgXmlErrorContext *
1211 pg_xml_init(PgXmlStrictness strictness)
1212 {
1213 PgXmlErrorContext *errcxt;
1214 void *new_errcxt;
1215
1216 /* Do one-time setup if needed */
1217 pg_xml_init_library();
1218
1219 /* Create error handling context structure */
1220 errcxt = (PgXmlErrorContext *) palloc(sizeof(PgXmlErrorContext));
1221 errcxt->magic = ERRCXT_MAGIC;
1222 errcxt->strictness = strictness;
1223 errcxt->err_occurred = false;
1224 initStringInfo(&errcxt->err_buf);
1225
1226 /*
1227 * Save original error handler and install ours. libxml originally didn't
1228 * distinguish between the contexts for generic and for structured error
1229 * handlers. If we're using an old libxml version, we must thus save the
1230 * generic error context, even though we're using a structured error
1231 * handler.
1232 */
1233 errcxt->saved_errfunc = xmlStructuredError;
1234
1235 #ifdef HAVE_XMLSTRUCTUREDERRORCONTEXT
1236 errcxt->saved_errcxt = xmlStructuredErrorContext;
1237 #else
1238 errcxt->saved_errcxt = xmlGenericErrorContext;
1239 #endif
1240
1241 xmlSetStructuredErrorFunc(errcxt, xml_errorHandler);
1242
1243 /*
1244 * Verify that xmlSetStructuredErrorFunc set the context variable we
1245 * expected it to. If not, the error context pointer we just saved is not
1246 * the correct thing to restore, and since that leaves us without a way to
1247 * restore the context in pg_xml_done, we must fail.
1248 *
1249 * The only known situation in which this test fails is if we compile with
1250 * headers from a libxml2 that doesn't track the structured error context
1251 * separately (< 2.7.4), but at runtime use a version that does, or vice
1252 * versa. The libxml2 authors did not treat that change as constituting
1253 * an ABI break, so the LIBXML_TEST_VERSION test in pg_xml_init_library
1254 * fails to protect us from this.
1255 */
1256
1257 #ifdef HAVE_XMLSTRUCTUREDERRORCONTEXT
1258 new_errcxt = xmlStructuredErrorContext;
1259 #else
1260 new_errcxt = xmlGenericErrorContext;
1261 #endif
1262
1263 if (new_errcxt != errcxt)
1264 ereport(ERROR,
1265 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1266 errmsg("could not set up XML error handler"),
1267 errhint("This probably indicates that the version of libxml2"
1268 " being used is not compatible with the libxml2"
1269 " header files that PostgreSQL was built with.")));
1270
1271 /*
1272 * Also, install an entity loader to prevent unwanted fetches of external
1273 * files and URLs.
1274 */
1275 errcxt->saved_entityfunc = xmlGetExternalEntityLoader();
1276 xmlSetExternalEntityLoader(xmlPgEntityLoader);
1277
1278 return errcxt;
1279 }
1280
1281
1282 /*
1283 * pg_xml_done --- restore previous libxml error handling
1284 *
1285 * Resets libxml's global error-handling state to what it was before
1286 * pg_xml_init() was called.
1287 *
1288 * This routine verifies that all pending errors have been dealt with
1289 * (in assert-enabled builds, anyway).
1290 */
1291 void
1292 pg_xml_done(PgXmlErrorContext *errcxt, bool isError)
1293 {
1294 void *cur_errcxt;
1295
1296 /* An assert seems like enough protection here */
1297 Assert(errcxt->magic == ERRCXT_MAGIC);
1298
1299 /*
1300 * In a normal exit, there should be no un-handled libxml errors. But we
1301 * shouldn't try to enforce this during error recovery, since the longjmp
1302 * could have been thrown before xml_ereport had a chance to run.
1303 */
1304 Assert(!errcxt->err_occurred || isError);
1305
1306 /*
1307 * Check that libxml's global state is correct, warn if not. This is a
1308 * real test and not an Assert because it has a higher probability of
1309 * happening.
1310 */
1311 #ifdef HAVE_XMLSTRUCTUREDERRORCONTEXT
1312 cur_errcxt = xmlStructuredErrorContext;
1313 #else
1314 cur_errcxt = xmlGenericErrorContext;
1315 #endif
1316
1317 if (cur_errcxt != errcxt)
1318 elog(WARNING, "libxml error handling state is out of sync with xml.c");
1319
1320 /* Restore the saved handlers */
1321 xmlSetStructuredErrorFunc(errcxt->saved_errcxt, errcxt->saved_errfunc);
1322 xmlSetExternalEntityLoader(errcxt->saved_entityfunc);
1323
1324 /*
1325 * Mark the struct as invalid, just in case somebody somehow manages to
1326 * call xml_errorHandler or xml_ereport with it.
1327 */
1328 errcxt->magic = 0;
1329
1330 /* Release memory */
1331 pfree(errcxt->err_buf.data);
1332 pfree(errcxt);
1333 }
1334
1335
1336 /*
1337 * pg_xml_error_occurred() --- test the error flag
1338 */
1339 bool
1340 pg_xml_error_occurred(PgXmlErrorContext *errcxt)
1341 {
1342 return errcxt->err_occurred;
1343 }
1344
1345
1346 /*
1347 * SQL/XML allows storing "XML documents" or "XML content". "XML
1348 * documents" are specified by the XML specification and are parsed
1349 * easily by libxml. "XML content" is specified by SQL/XML as the
1350 * production "XMLDecl? content". But libxml can only parse the
1351 * "content" part, so we have to parse the XML declaration ourselves
1352 * to complete this.
1353 */
1354
1355 #define CHECK_XML_SPACE(p) \
1356 do { \
1357 if (!xmlIsBlank_ch(*(p))) \
1358 return XML_ERR_SPACE_REQUIRED; \
1359 } while (0)
1360
1361 #define SKIP_XML_SPACE(p) \
1362 while (xmlIsBlank_ch(*(p))) (p)++
1363
1364 /* Letter | Digit | '.' | '-' | '_' | ':' | CombiningChar | Extender */
1365 /* Beware of multiple evaluations of argument! */
1366 #define PG_XMLISNAMECHAR(c) \
1367 (xmlIsBaseChar_ch(c) || xmlIsIdeographicQ(c) \
1368 || xmlIsDigit_ch(c) \
1369 || c == '.' || c == '-' || c == '_' || c == ':' \
1370 || xmlIsCombiningQ(c) \
1371 || xmlIsExtender_ch(c))
1372
1373 /* pnstrdup, but deal with xmlChar not char; len is measured in xmlChars */
1374 static xmlChar *
1375 xml_pnstrdup(const xmlChar *str, size_t len)
1376 {
1377 xmlChar *result;
1378
1379 result = (xmlChar *) palloc((len + 1) * sizeof(xmlChar));
1380 memcpy(result, str, len * sizeof(xmlChar));
1381 result[len] = 0;
1382 return result;
1383 }
1384
1385 /* Ditto, except input is char* */
1386 static xmlChar *
1387 pg_xmlCharStrndup(const char *str, size_t len)
1388 {
1389 xmlChar *result;
1390
1391 result = (xmlChar *) palloc((len + 1) * sizeof(xmlChar));
1392 memcpy(result, str, len);
1393 result[len] = '\0';
1394
1395 return result;
1396 }
1397
1398 /*
1399 * Copy xmlChar string to PostgreSQL-owned memory, freeing the input.
1400 *
1401 * The input xmlChar is freed regardless of success of the copy.
1402 */
1403 static char *
1404 xml_pstrdup_and_free(xmlChar *str)
1405 {
1406 char *result;
1407
1408 if (str)
1409 {
1410 PG_TRY();
1411 {
1412 result = pstrdup((char *) str);
1413 }
1414 PG_FINALLY();
1415 {
1416 xmlFree(str);
1417 }
1418 PG_END_TRY();
1419 }
1420 else
1421 result = NULL;
1422
1423 return result;
1424 }
1425
1426 /*
1427 * str is the null-terminated input string. Remaining arguments are
1428 * output arguments; each can be NULL if value is not wanted.
1429 * version and encoding are returned as locally-palloc'd strings.
1430 * Result is 0 if OK, an error code if not.
1431 */
1432 static int
1433 parse_xml_decl(const xmlChar *str, size_t *lenp,
1434 xmlChar **version, xmlChar **encoding, int *standalone)
1435 {
1436 const xmlChar *p;
1437 const xmlChar *save_p;
1438 size_t len;
1439 int utf8char;
1440 int utf8len;
1441
1442 /*
1443 * Only initialize libxml. We don't need error handling here, but we do
1444 * need to make sure libxml is initialized before calling any of its
1445 * functions. Note that this is safe (and a no-op) if caller has already
1446 * done pg_xml_init().
1447 */
1448 pg_xml_init_library();
1449
1450 /* Initialize output arguments to "not present" */
1451 if (version)
1452 *version = NULL;
1453 if (encoding)
1454 *encoding = NULL;
1455 if (standalone)
1456 *standalone = -1;
1457
1458 p = str;
1459
1460 if (xmlStrncmp(p, (xmlChar *) "<?xml", 5) != 0)
1461 goto finished;
1462
1463 /*
1464 * If next char is a name char, it's a PI like <?xml-stylesheet ...?>
1465 * rather than an XMLDecl, so we have done what we came to do and found no
1466 * XMLDecl.
1467 *
1468 * We need an input length value for xmlGetUTF8Char, but there's no need
1469 * to count the whole document size, so use strnlen not strlen.
1470 */
1471 utf8len = strnlen((const char *) (p + 5), MAX_MULTIBYTE_CHAR_LEN);
1472 utf8char = xmlGetUTF8Char(p + 5, &utf8len);
1473 if (PG_XMLISNAMECHAR(utf8char))
1474 goto finished;
1475
1476 p += 5;
1477
1478 /* version */
1479 CHECK_XML_SPACE(p);
1480 SKIP_XML_SPACE(p);
1481 if (xmlStrncmp(p, (xmlChar *) "version", 7) != 0)
1482 return XML_ERR_VERSION_MISSING;
1483 p += 7;
1484 SKIP_XML_SPACE(p);
1485 if (*p != '=')
1486 return XML_ERR_VERSION_MISSING;
1487 p += 1;
1488 SKIP_XML_SPACE(p);
1489
1490 if (*p == '\'' || *p == '"')
1491 {
1492 const xmlChar *q;
1493
1494 q = xmlStrchr(p + 1, *p);
1495 if (!q)
1496 return XML_ERR_VERSION_MISSING;
1497
1498 if (version)
1499 *version = xml_pnstrdup(p + 1, q - p - 1);
1500 p = q + 1;
1501 }
1502 else
1503 return XML_ERR_VERSION_MISSING;
1504
1505 /* encoding */
1506 save_p = p;
1507 SKIP_XML_SPACE(p);
1508 if (xmlStrncmp(p, (xmlChar *) "encoding", 8) == 0)
1509 {
1510 CHECK_XML_SPACE(save_p);
1511 p += 8;
1512 SKIP_XML_SPACE(p);
1513 if (*p != '=')
1514 return XML_ERR_MISSING_ENCODING;
1515 p += 1;
1516 SKIP_XML_SPACE(p);
1517
1518 if (*p == '\'' || *p == '"')
1519 {
1520 const xmlChar *q;
1521
1522 q = xmlStrchr(p + 1, *p);
1523 if (!q)
1524 return XML_ERR_MISSING_ENCODING;
1525
1526 if (encoding)
1527 *encoding = xml_pnstrdup(p + 1, q - p - 1);
1528 p = q + 1;
1529 }
1530 else
1531 return XML_ERR_MISSING_ENCODING;
1532 }
1533 else
1534 {
1535 p = save_p;
1536 }
1537
1538 /* standalone */
1539 save_p = p;
1540 SKIP_XML_SPACE(p);
1541 if (xmlStrncmp(p, (xmlChar *) "standalone", 10) == 0)
1542 {
1543 CHECK_XML_SPACE(save_p);
1544 p += 10;
1545 SKIP_XML_SPACE(p);
1546 if (*p != '=')
1547 return XML_ERR_STANDALONE_VALUE;
1548 p += 1;
1549 SKIP_XML_SPACE(p);
1550 if (xmlStrncmp(p, (xmlChar *) "'yes'", 5) == 0 ||
1551 xmlStrncmp(p, (xmlChar *) "\"yes\"", 5) == 0)
1552 {
1553 if (standalone)
1554 *standalone = 1;
1555 p += 5;
1556 }
1557 else if (xmlStrncmp(p, (xmlChar *) "'no'", 4) == 0 ||
1558 xmlStrncmp(p, (xmlChar *) "\"no\"", 4) == 0)
1559 {
1560 if (standalone)
1561 *standalone = 0;
1562 p += 4;
1563 }
1564 else
1565 return XML_ERR_STANDALONE_VALUE;
1566 }
1567 else
1568 {
1569 p = save_p;
1570 }
1571
1572 SKIP_XML_SPACE(p);
1573 if (xmlStrncmp(p, (xmlChar *) "?>", 2) != 0)
1574 return XML_ERR_XMLDECL_NOT_FINISHED;
1575 p += 2;
1576
1577 finished:
1578 len = p - str;
1579
1580 for (p = str; p < str + len; p++)
1581 if (*p > 127)
1582 return XML_ERR_INVALID_CHAR;
1583
1584 if (lenp)
1585 *lenp = len;
1586
1587 return XML_ERR_OK;
1588 }
1589
1590
1591 /*
1592 * Write an XML declaration. On output, we adjust the XML declaration
1593 * as follows. (These rules are the moral equivalent of the clause
1594 * "Serialization of an XML value" in the SQL standard.)
1595 *
1596 * We try to avoid generating an XML declaration if possible. This is
1597 * so that you don't get trivial things like xml '<foo/>' resulting in
1598 * '<?xml version="1.0"?><foo/>', which would surely be annoying. We
1599 * must provide a declaration if the standalone property is specified
1600 * or if we include an encoding declaration. If we have a
1601 * declaration, we must specify a version (XML requires this).
1602 * Otherwise we only make a declaration if the version is not "1.0",
1603 * which is the default version specified in SQL:2003.
1604 */
1605 static bool
1606 print_xml_decl(StringInfo buf, const xmlChar *version,
1607 pg_enc encoding, int standalone)
1608 {
1609 if ((version && strcmp((const char *) version, PG_XML_DEFAULT_VERSION) != 0)
1610 || (encoding && encoding != PG_UTF8)
1611 || standalone != -1)
1612 {
1613 appendStringInfoString(buf, "<?xml");
1614
1615 if (version)
1616 appendStringInfo(buf, " version=\"%s\"", version);
1617 else
1618 appendStringInfo(buf, " version=\"%s\"", PG_XML_DEFAULT_VERSION);
1619
1620 if (encoding && encoding != PG_UTF8)
1621 {
1622 /*
1623 * XXX might be useful to convert this to IANA names (ISO-8859-1
1624 * instead of LATIN1 etc.); needs field experience
1625 */
1626 appendStringInfo(buf, " encoding=\"%s\"",
1627 pg_encoding_to_char(encoding));
1628 }
1629
1630 if (standalone == 1)
1631 appendStringInfoString(buf, " standalone=\"yes\"");
1632 else if (standalone == 0)
1633 appendStringInfoString(buf, " standalone=\"no\"");
1634 appendStringInfoString(buf, "?>");
1635
1636 return true;
1637 }
1638 else
1639 return false;
1640 }
1641
1642 /*
1643 * Test whether an input that is to be parsed as CONTENT contains a DTD.
1644 *
1645 * The SQL/XML:2003 definition of CONTENT ("XMLDecl? content") is not
1646 * satisfied by a document with a DTD, which is a bit of a wart, as it means
1647 * the CONTENT type is not a proper superset of DOCUMENT. SQL/XML:2006 and
1648 * later fix that, by redefining content with reference to the "more
1649 * permissive" Document Node of the XQuery/XPath Data Model, such that any
1650 * DOCUMENT value is indeed also a CONTENT value. That definition is more
1651 * useful, as CONTENT becomes usable for parsing input of unknown form (think
1652 * pg_restore).
1653 *
1654 * As used below in parse_xml when parsing for CONTENT, libxml does not give
1655 * us the 2006+ behavior, but only the 2003; it will choke if the input has
1656 * a DTD. But we can provide the 2006+ definition of CONTENT easily enough,
1657 * by detecting this case first and simply doing the parse as DOCUMENT.
1658 *
1659 * A DTD can be found arbitrarily far in, but that would be a contrived case;
1660 * it will ordinarily start within a few dozen characters. The only things
1661 * that can precede it are an XMLDecl (here, the caller will have called
1662 * parse_xml_decl already), whitespace, comments, and processing instructions.
1663 * This function need only return true if it sees a valid sequence of such
1664 * things leading to <!DOCTYPE. It can simply return false in any other
1665 * cases, including malformed input; that will mean the input gets parsed as
1666 * CONTENT as originally planned, with libxml reporting any errors.
1667 *
1668 * This is only to be called from xml_parse, when pg_xml_init has already
1669 * been called. The input is already in UTF8 encoding.
1670 */
1671 static bool
1672 xml_doctype_in_content(const xmlChar *str)
1673 {
1674 const xmlChar *p = str;
1675
1676 for (;;)
1677 {
1678 const xmlChar *e;
1679
1680 SKIP_XML_SPACE(p);
1681 if (*p != '<')
1682 return false;
1683 p++;
1684
1685 if (*p == '!')
1686 {
1687 p++;
1688
1689 /* if we see <!DOCTYPE, we can return true */
1690 if (xmlStrncmp(p, (xmlChar *) "DOCTYPE", 7) == 0)
1691 return true;
1692
1693 /* otherwise, if it's not a comment, fail */
1694 if (xmlStrncmp(p, (xmlChar *) "--", 2) != 0)
1695 return false;
1696 /* find end of comment: find -- and a > must follow */
1697 p = xmlStrstr(p + 2, (xmlChar *) "--");
1698 if (!p || p[2] != '>')
1699 return false;
1700 /* advance over comment, and keep scanning */
1701 p += 3;
1702 continue;
1703 }
1704
1705 /* otherwise, if it's not a PI <?target something?>, fail */
1706 if (*p != '?')
1707 return false;
1708 p++;
1709
1710 /* find end of PI (the string ?> is forbidden within a PI) */
1711 e = xmlStrstr(p, (xmlChar *) "?>");
1712 if (!e)
1713 return false;
1714
1715 /* advance over PI, keep scanning */
1716 p = e + 2;
1717 }
1718 }
1719
1720
1721 /*
1722 * Convert a text object to XML internal representation
1723 *
1724 * data is the source data (must not be toasted!), encoding is its encoding,
1725 * and xmloption_arg and preserve_whitespace are options for the
1726 * transformation.
1727 *
1728 * If parsed_xmloptiontype isn't NULL, *parsed_xmloptiontype is set to the
1729 * XmlOptionType actually used to parse the input (typically the same as
1730 * xmloption_arg, but a DOCTYPE node in the input can force DOCUMENT mode).
1731 *
1732 * If parsed_nodes isn't NULL and we parse in CONTENT mode, the list
1733 * of parsed nodes from the xmlParseBalancedChunkMemory call will be returned
1734 * to *parsed_nodes. (It is caller's responsibility to free that.)
1735 *
1736 * Errors normally result in ereport(ERROR), but if escontext is an
1737 * ErrorSaveContext, then "safe" errors are reported there instead, and the
1738 * caller must check SOFT_ERROR_OCCURRED() to see whether that happened.
1739 *
1740 * Note: it is caller's responsibility to xmlFreeDoc() the result,
1741 * else a permanent memory leak will ensue! But note the result could
1742 * be NULL after a soft error.
1743 *
1744 * TODO maybe libxml2's xmlreader is better? (do not construct DOM,
1745 * yet do not use SAX - see xmlreader.c)
1746 */
1747 static xmlDocPtr
1748 xml_parse(text *data, XmlOptionType xmloption_arg,
1749 bool preserve_whitespace, int encoding,
1750 XmlOptionType *parsed_xmloptiontype, xmlNodePtr *parsed_nodes,
1751 Node *escontext)
1752 {
1753 int32 len;
1754 xmlChar *string;
1755 xmlChar *utf8string;
1756 PgXmlErrorContext *xmlerrcxt;
1757 volatile xmlParserCtxtPtr ctxt = NULL;
1758 volatile xmlDocPtr doc = NULL;
1759 volatile int save_keep_blanks = -1;
1760
1761 /*
1762 * This step looks annoyingly redundant, but we must do it to have a
1763 * null-terminated string in case encoding conversion isn't required.
1764 */
1765 len = VARSIZE_ANY_EXHDR(data); /* will be useful later */
1766 string = xml_text2xmlChar(data);
1767
1768 /*
1769 * If the data isn't UTF8, we must translate before giving it to libxml.
1770 *
1771 * XXX ideally, we'd catch any encoding conversion failure and return a
1772 * soft error. However, failure to convert to UTF8 should be pretty darn
1773 * rare, so for now this is left undone.
1774 */
1775 utf8string = pg_do_encoding_conversion(string,
1776 len,
1777 encoding,
1778 PG_UTF8);
1779
1780 /* Start up libxml and its parser */
1781 xmlerrcxt = pg_xml_init(PG_XML_STRICTNESS_WELLFORMED);
1782
1783 /* Use a TRY block to ensure we clean up correctly */
1784 PG_TRY();
1785 {
1786 bool parse_as_document = false;
1787 int res_code;
1788 size_t count = 0;
1789 xmlChar *version = NULL;
1790 int standalone = 0;
1791
1792 /* Any errors here are reported as hard ereport's */
1793 xmlInitParser();
1794
1795 /* Decide whether to parse as document or content */
1796 if (xmloption_arg == XMLOPTION_DOCUMENT)
1797 parse_as_document = true;
1798 else
1799 {
1800 /* Parse and skip over the XML declaration, if any */
1801 res_code = parse_xml_decl(utf8string,
1802 &count, &version, NULL, &standalone);
1803 if (res_code != 0)
1804 {
1805 errsave(escontext,
1806 errcode(ERRCODE_INVALID_XML_CONTENT),
1807 errmsg_internal("invalid XML content: invalid XML declaration"),
1808 errdetail_for_xml_code(res_code));
1809 goto fail;
1810 }
1811
1812 /* Is there a DOCTYPE element? */
1813 if (xml_doctype_in_content(utf8string + count))
1814 parse_as_document = true;
1815 }
1816
1817 /* initialize output parameters */
1818 if (parsed_xmloptiontype != NULL)
1819 *parsed_xmloptiontype = parse_as_document ? XMLOPTION_DOCUMENT :
1820 XMLOPTION_CONTENT;
1821 if (parsed_nodes != NULL)
1822 *parsed_nodes = NULL;
1823
1824 if (parse_as_document)
1825 {
1826 int options;
1827
1828 /* set up parser context used by xmlCtxtReadDoc */
1829 ctxt = xmlNewParserCtxt();
1830 if (ctxt == NULL || xmlerrcxt->err_occurred)
1831 xml_ereport(xmlerrcxt, ERROR, ERRCODE_OUT_OF_MEMORY,
1832 "could not allocate parser context");
1833
1834 /*
1835 * Select parse options.
1836 *
1837 * Note that here we try to apply DTD defaults (XML_PARSE_DTDATTR)
1838 * according to SQL/XML:2008 GR 10.16.7.d: 'Default values defined
1839 * by internal DTD are applied'. As for external DTDs, we try to
1840 * support them too (see SQL/XML:2008 GR 10.16.7.e), but that
1841 * doesn't really happen because xmlPgEntityLoader prevents it.
1842 */
1843 options = XML_PARSE_NOENT | XML_PARSE_DTDATTR
1844 | (preserve_whitespace ? 0 : XML_PARSE_NOBLANKS);
1845
1846 doc = xmlCtxtReadDoc(ctxt, utf8string,
1847 NULL, /* no URL */
1848 "UTF-8",
1849 options);
1850
1851 if (doc == NULL || xmlerrcxt->err_occurred)
1852 {
1853 /* Use original option to decide which error code to report */
1854 if (xmloption_arg == XMLOPTION_DOCUMENT)
1855 xml_errsave(escontext, xmlerrcxt,
1856 ERRCODE_INVALID_XML_DOCUMENT,
1857 "invalid XML document");
1858 else
1859 xml_errsave(escontext, xmlerrcxt,
1860 ERRCODE_INVALID_XML_CONTENT,
1861 "invalid XML content");
1862 goto fail;
1863 }
1864 }
1865 else
1866 {
1867 /* set up document that xmlParseBalancedChunkMemory will add to */
1868 doc = xmlNewDoc(version);
1869 if (doc == NULL || xmlerrcxt->err_occurred)
1870 xml_ereport(xmlerrcxt, ERROR, ERRCODE_OUT_OF_MEMORY,
1871 "could not allocate XML document");
1872
1873 Assert(doc->encoding == NULL);
1874 doc->encoding = xmlStrdup((const xmlChar *) "UTF-8");
1875 if (doc->encoding == NULL || xmlerrcxt->err_occurred)
1876 xml_ereport(xmlerrcxt, ERROR, ERRCODE_OUT_OF_MEMORY,
1877 "could not allocate XML document");
1878 doc->standalone = standalone;
1879
1880 /* set parse options --- have to do this the ugly way */
1881 save_keep_blanks = xmlKeepBlanksDefault(preserve_whitespace ? 1 : 0);
1882
1883 /* allow empty content */
1884 if (*(utf8string + count))
1885 {
1886 res_code = xmlParseBalancedChunkMemory(doc, NULL, NULL, 0,
1887 utf8string + count,
1888 parsed_nodes);
1889 if (res_code != 0 || xmlerrcxt->err_occurred)
1890 {
1891 xml_errsave(escontext, xmlerrcxt,
1892 ERRCODE_INVALID_XML_CONTENT,
1893 "invalid XML content");
1894 goto fail;
1895 }
1896 }
1897 }
1898
1899 fail:
1900 ;
1901 }
1902 PG_CATCH();
1903 {
1904 if (save_keep_blanks != -1)
1905 xmlKeepBlanksDefault(save_keep_blanks);
1906 if (doc != NULL)
1907 xmlFreeDoc(doc);
1908 if (ctxt != NULL)
1909 xmlFreeParserCtxt(ctxt);
1910
1911 pg_xml_done(xmlerrcxt, true);
1912
1913 PG_RE_THROW();
1914 }
1915 PG_END_TRY();
1916
1917 if (save_keep_blanks != -1)
1918 xmlKeepBlanksDefault(save_keep_blanks);
1919
1920 if (ctxt != NULL)
1921 xmlFreeParserCtxt(ctxt);
1922
1923 pg_xml_done(xmlerrcxt, false);
1924
1925 return doc;
1926 }
1927
1928
1929 /*
1930 * xmlChar<->text conversions
1931 */
1932 static xmlChar *
1933 xml_text2xmlChar(text *in)
1934 {
1935 return (xmlChar *) text_to_cstring(in);
1936 }
1937
1938
1939 #ifdef USE_LIBXMLCONTEXT
1940
1941 /*
1942 * Manage the special context used for all libxml allocations (but only
1943 * in special debug builds; see notes at top of file)
1944 */
1945 static void
1946 xml_memory_init(void)
1947 {
1948 /* Create memory context if not there already */
1949 if (LibxmlContext == NULL)
1950 LibxmlContext = AllocSetContextCreate(TopMemoryContext,
1951 "Libxml context",
1952 ALLOCSET_DEFAULT_SIZES);
1953
1954 /* Re-establish the callbacks even if already set */
1955 xmlMemSetup(xml_pfree, xml_palloc, xml_repalloc, xml_pstrdup);
1956 }
1957
1958 /*
1959 * Wrappers for memory management functions
1960 */
1961 static void *
1962 xml_palloc(size_t size)
1963 {
1964 return MemoryContextAlloc(LibxmlContext, size);
1965 }
1966
1967
1968 static void *
1969 xml_repalloc(void *ptr, size_t size)
1970 {
1971 return repalloc(ptr, size);
1972 }
1973
1974
1975 static void
1976 xml_pfree(void *ptr)
1977 {
1978 /* At least some parts of libxml assume xmlFree(NULL) is allowed */
1979 if (ptr)
1980 pfree(ptr);
1981 }
1982
1983
1984 static char *
1985 xml_pstrdup(const char *string)
1986 {
1987 return MemoryContextStrdup(LibxmlContext, string);
1988 }
1989 #endif /* USE_LIBXMLCONTEXT */
1990
1991
1992 /*
1993 * xmlPgEntityLoader --- entity loader callback function
1994 *
1995 * Silently prevent any external entity URL from being loaded. We don't want
1996 * to throw an error, so instead make the entity appear to expand to an empty
1997 * string.
1998 *
1999 * We would prefer to allow loading entities that exist in the system's
2000 * global XML catalog; but the available libxml2 APIs make that a complex
2001 * and fragile task. For now, just shut down all external access.
2002 */
2003 static xmlParserInputPtr
2004 xmlPgEntityLoader(const char *URL, const char *ID,
2005 xmlParserCtxtPtr ctxt)
2006 {
2007 return xmlNewStringInputStream(ctxt, (const xmlChar *) "");
2008 }
2009
2010
2011 /*
2012 * xml_ereport --- report an XML-related error
2013 *
2014 * The "msg" is the SQL-level message; some can be adopted from the SQL/XML
2015 * standard. This function adds libxml's native error message, if any, as
2016 * detail.
2017 *
2018 * This is exported for modules that want to share the core libxml error
2019 * handler. Note that pg_xml_init() *must* have been called previously.
2020 */
2021 void
2022 xml_ereport(PgXmlErrorContext *errcxt, int level, int sqlcode, const char *msg)
2023 {
2024 char *detail;
2025
2026 /* Defend against someone passing us a bogus context struct */
2027 if (errcxt->magic != ERRCXT_MAGIC)
2028 elog(ERROR, "xml_ereport called with invalid PgXmlErrorContext");
2029
2030 /* Flag that the current libxml error has been reported */
2031 errcxt->err_occurred = false;
2032
2033 /* Include detail only if we have some text from libxml */
2034 if (errcxt->err_buf.len > 0)
2035 detail = errcxt->err_buf.data;
2036 else
2037 detail = NULL;
2038
2039 ereport(level,
2040 (errcode(sqlcode),
2041 errmsg_internal("%s", msg),
2042 detail ? errdetail_internal("%s", detail) : 0));
2043 }
2044
2045
2046 /*
2047 * xml_errsave --- save an XML-related error
2048 *
2049 * If escontext is an ErrorSaveContext, error details are saved into it,
2050 * and control returns normally.
2051 *
2052 * Otherwise, the error is thrown, so that this is equivalent to
2053 * xml_ereport() with level == ERROR.
2054 *
2055 * This should be used only for errors that we're sure we do not need
2056 * a transaction abort to clean up after.
2057 */
2058 static void
2059 xml_errsave(Node *escontext, PgXmlErrorContext *errcxt,
2060 int sqlcode, const char *msg)
2061 {
2062 char *detail;
2063
2064 /* Defend against someone passing us a bogus context struct */
2065 if (errcxt->magic != ERRCXT_MAGIC)
2066 elog(ERROR, "xml_errsave called with invalid PgXmlErrorContext");
2067
2068 /* Flag that the current libxml error has been reported */
2069 errcxt->err_occurred = false;
2070
2071 /* Include detail only if we have some text from libxml */
2072 if (errcxt->err_buf.len > 0)
2073 detail = errcxt->err_buf.data;
2074 else
2075 detail = NULL;
2076
2077 errsave(escontext,
2078 (errcode(sqlcode),
2079 errmsg_internal("%s", msg),
2080 detail ? errdetail_internal("%s", detail) : 0));
2081 }
2082
2083
2084 /*
2085 * Error handler for libxml errors and warnings
2086 */
2087 static void
2088 xml_errorHandler(void *data, PgXmlErrorPtr error)
2089 {
2090 PgXmlErrorContext *xmlerrcxt = (PgXmlErrorContext *) data;
2091 xmlParserCtxtPtr ctxt = (xmlParserCtxtPtr) error->ctxt;
2092 xmlParserInputPtr input = (ctxt != NULL) ? ctxt->input : NULL;
2093 xmlNodePtr node = error->node;
2094 const xmlChar *name = (node != NULL &&
2095 node->type == XML_ELEMENT_NODE) ? node->name : NULL;
2096 int domain = error->domain;
2097 int level = error->level;
2098 StringInfo errorBuf;
2099
2100 /*
2101 * Defend against someone passing us a bogus context struct.
2102 *
2103 * We force a backend exit if this check fails because longjmp'ing out of
2104 * libxml would likely render it unsafe to use further.
2105 */
2106 if (xmlerrcxt->magic != ERRCXT_MAGIC)
2107 elog(FATAL, "xml_errorHandler called with invalid PgXmlErrorContext");
2108
2109 /*----------
2110 * Older libxml versions report some errors differently.
2111 * First, some errors were previously reported as coming from the parser
2112 * domain but are now reported as coming from the namespace domain.
2113 * Second, some warnings were upgraded to errors.
2114 * We attempt to compensate for that here.
2115 *----------
2116 */
2117 switch (error->code)
2118 {
2119 case XML_WAR_NS_URI:
2120 level = XML_ERR_ERROR;
2121 domain = XML_FROM_NAMESPACE;
2122 break;
2123
2124 case XML_ERR_NS_DECL_ERROR:
2125 case XML_WAR_NS_URI_RELATIVE:
2126 case XML_WAR_NS_COLUMN:
2127 case XML_NS_ERR_XML_NAMESPACE:
2128 case XML_NS_ERR_UNDEFINED_NAMESPACE:
2129 case XML_NS_ERR_QNAME:
2130 case XML_NS_ERR_ATTRIBUTE_REDEFINED:
2131 case XML_NS_ERR_EMPTY:
2132 domain = XML_FROM_NAMESPACE;
2133 break;
2134 }
2135
2136 /* Decide whether to act on the error or not */
2137 switch (domain)
2138 {
2139 case XML_FROM_PARSER:
2140
2141 /*
2142 * XML_ERR_NOT_WELL_BALANCED is typically reported after some
2143 * other, more on-point error. Furthermore, libxml2 2.13 reports
2144 * it under a completely different set of rules than prior
2145 * versions. To avoid cross-version behavioral differences,
2146 * suppress it so long as we already logged some error.
2147 */
2148 if (error->code == XML_ERR_NOT_WELL_BALANCED &&
2149 xmlerrcxt->err_occurred)
2150 return;
2151 /* fall through */
2152
2153 case XML_FROM_NONE:
2154 case XML_FROM_MEMORY:
2155 case XML_FROM_IO:
2156
2157 /*
2158 * Suppress warnings about undeclared entities. We need to do
2159 * this to avoid problems due to not loading DTD definitions.
2160 */
2161 if (error->code == XML_WAR_UNDECLARED_ENTITY)
2162 return;
2163
2164 /* Otherwise, accept error regardless of the parsing purpose */
2165 break;
2166
2167 default:
2168 /* Ignore error if only doing well-formedness check */
2169 if (xmlerrcxt->strictness == PG_XML_STRICTNESS_WELLFORMED)
2170 return;
2171 break;
2172 }
2173
2174 /* Prepare error message in errorBuf */
2175 errorBuf = makeStringInfo();
2176
2177 if (error->line > 0)
2178 appendStringInfo(errorBuf, "line %d: ", error->line);
2179 if (name != NULL)
2180 appendStringInfo(errorBuf, "element %s: ", name);
2181 if (error->message != NULL)
2182 appendStringInfoString(errorBuf, error->message);
2183 else
2184 appendStringInfoString(errorBuf, "(no message provided)");
2185
2186 /*
2187 * Append context information to errorBuf.
2188 *
2189 * xmlParserPrintFileContext() uses libxml's "generic" error handler to
2190 * write the context. Since we don't want to duplicate libxml
2191 * functionality here, we set up a generic error handler temporarily.
2192 *
2193 * We use appendStringInfo() directly as libxml's generic error handler.
2194 * This should work because it has essentially the same signature as
2195 * libxml expects, namely (void *ptr, const char *msg, ...).
2196 */
2197 if (input != NULL)
2198 {
2199 xmlGenericErrorFunc errFuncSaved = xmlGenericError;
2200 void *errCtxSaved = xmlGenericErrorContext;
2201
2202 xmlSetGenericErrorFunc(errorBuf,
2203 (xmlGenericErrorFunc) appendStringInfo);
2204
2205 /* Add context information to errorBuf */
2206 appendStringInfoLineSeparator(errorBuf);
2207
2208 xmlParserPrintFileContext(input);
2209
2210 /* Restore generic error func */
2211 xmlSetGenericErrorFunc(errCtxSaved, errFuncSaved);
2212 }
2213
2214 /* Get rid of any trailing newlines in errorBuf */
2215 chopStringInfoNewlines(errorBuf);
2216
2217 /*
2218 * Legacy error handling mode. err_occurred is never set, we just add the
2219 * message to err_buf. This mode exists because the xml2 contrib module
2220 * uses our error-handling infrastructure, but we don't want to change its
2221 * behaviour since it's deprecated anyway. This is also why we don't
2222 * distinguish between notices, warnings and errors here --- the old-style
2223 * generic error handler wouldn't have done that either.
2224 */
2225 if (xmlerrcxt->strictness == PG_XML_STRICTNESS_LEGACY)
2226 {
2227 appendStringInfoLineSeparator(&xmlerrcxt->err_buf);
2228 appendBinaryStringInfo(&xmlerrcxt->err_buf, errorBuf->data,
2229 errorBuf->len);
2230
2231 destroyStringInfo(errorBuf);
2232 return;
2233 }
2234
2235 /*
2236 * We don't want to ereport() here because that'd probably leave libxml in
2237 * an inconsistent state. Instead, we remember the error and ereport()
2238 * from xml_ereport().
2239 *
2240 * Warnings and notices can be reported immediately since they won't cause
2241 * a longjmp() out of libxml.
2242 */
2243 if (level >= XML_ERR_ERROR)
2244 {
2245 appendStringInfoLineSeparator(&xmlerrcxt->err_buf);
2246 appendBinaryStringInfo(&xmlerrcxt->err_buf, errorBuf->data,
2247 errorBuf->len);
2248
2249 xmlerrcxt->err_occurred = true;
2250 }
2251 else if (level >= XML_ERR_WARNING)
2252 {
2253 ereport(WARNING,
2254 (errmsg_internal("%s", errorBuf->data)));
2255 }
2256 else
2257 {
2258 ereport(NOTICE,
2259 (errmsg_internal("%s", errorBuf->data)));
2260 }
2261
2262 destroyStringInfo(errorBuf);
2263 }
2264
2265
2266 /*
2267 * Convert libxml error codes into textual errdetail messages.
2268 *
2269 * This should be called within an ereport or errsave invocation,
2270 * just as errdetail would be.
2271 *
2272 * At the moment, we only need to cover those codes that we
2273 * may raise in this file.
2274 */
2275 static int
2276 errdetail_for_xml_code(int code)
2277 {
2278 const char *det;
2279
2280 switch (code)
2281 {
2282 case XML_ERR_INVALID_CHAR:
2283 det = gettext_noop("Invalid character value.");
2284 break;
2285 case XML_ERR_SPACE_REQUIRED:
2286 det = gettext_noop("Space required.");
2287 break;
2288 case XML_ERR_STANDALONE_VALUE:
2289 det = gettext_noop("standalone accepts only 'yes' or 'no'.");
2290 break;
2291 case XML_ERR_VERSION_MISSING:
2292 det = gettext_noop("Malformed declaration: missing version.");
2293 break;
2294 case XML_ERR_MISSING_ENCODING:
2295 det = gettext_noop("Missing encoding in text declaration.");
2296 break;
2297 case XML_ERR_XMLDECL_NOT_FINISHED:
2298 det = gettext_noop("Parsing XML declaration: '?>' expected.");
2299 break;
2300 default:
2301 det = gettext_noop("Unrecognized libxml error code: %d.");
2302 break;
2303 }
2304
2305 return errdetail(det, code);
2306 }
2307
2308
2309 /*
2310 * Remove all trailing newlines from a StringInfo string
2311 */
2312 static void
2313 chopStringInfoNewlines(StringInfo str)
2314 {
2315 while (str->len > 0 && str->data[str->len - 1] == '\n')
2316 str->data[--str->len] = '\0';
2317 }
2318
2319
2320 /*
2321 * Append a newline after removing any existing trailing newlines
2322 */
2323 static void
2324 appendStringInfoLineSeparator(StringInfo str)
2325 {
2326 chopStringInfoNewlines(str);
2327 if (str->len > 0)
2328 appendStringInfoChar(str, '\n');
2329 }
2330
2331
2332 /*
2333 * Convert one char in the current server encoding to a Unicode codepoint.
2334 */
2335 static pg_wchar
2336 sqlchar_to_unicode(const char *s)
2337 {
2338 char *utf8string;
2339 pg_wchar ret[2]; /* need space for trailing zero */
2340
2341 utf8string = pg_server_to_any(s, pg_mblen_cstr(s), PG_UTF8);
2342
2343 pg_encoding_mb2wchar_with_len(PG_UTF8, utf8string, ret,
2344 pg_encoding_mblen(PG_UTF8, utf8string));
2345
2346 if (utf8string != s)
2347 pfree(utf8string);
2348
2349 return ret[0];
2350 }
2351
2352
2353 static bool
2354 is_valid_xml_namefirst(pg_wchar c)
2355 {
2356 /* (Letter | '_' | ':') */
2357 return (xmlIsBaseCharQ(c) || xmlIsIdeographicQ(c)
2358 || c == '_' || c == ':');
2359 }
2360
2361
2362 static bool
2363 is_valid_xml_namechar(pg_wchar c)
2364 {
2365 /* Letter | Digit | '.' | '-' | '_' | ':' | CombiningChar | Extender */
2366 return (xmlIsBaseCharQ(c) || xmlIsIdeographicQ(c)
2367 || xmlIsDigitQ(c)
2368 || c == '.' || c == '-' || c == '_' || c == ':'
2369 || xmlIsCombiningQ(c)
2370 || xmlIsExtenderQ(c));
2371 }
2372 #endif /* USE_LIBXML */
2373
2374
2375 /*
2376 * Map SQL identifier to XML name; see SQL/XML:2008 section 9.1.
2377 */
2378 char *
2379 map_sql_identifier_to_xml_name(const char *ident, bool fully_escaped,
2380 bool escape_period)
2381 {
2382 #ifdef USE_LIBXML
2383 StringInfoData buf;
2384 const char *p;
2385
2386 /*
2387 * SQL/XML doesn't make use of this case anywhere, so it's probably a
2388 * mistake.
2389 */
2390 Assert(fully_escaped || !escape_period);
2391
2392 initStringInfo(&buf);
2393
2394 for (p = ident; *p; p += pg_mblen_cstr(p))
2395 {
2396 if (*p == ':' && (p == ident || fully_escaped))
2397 appendStringInfoString(&buf, "_x003A_");
2398 else if (*p == '_' && *(p + 1) == 'x')
2399 appendStringInfoString(&buf, "_x005F_");
2400 else if (fully_escaped && p == ident &&
2401 pg_strncasecmp(p, "xml", 3) == 0)
2402 {
2403 if (*p == 'x')
2404 appendStringInfoString(&buf, "_x0078_");
2405 else
2406 appendStringInfoString(&buf, "_x0058_");
2407 }
2408 else if (escape_period && *p == '.')
2409 appendStringInfoString(&buf, "_x002E_");
2410 else
2411 {
2412 pg_wchar u = sqlchar_to_unicode(p);
2413
2414 if ((p == ident)
2415 ? !is_valid_xml_namefirst(u)
2416 : !is_valid_xml_namechar(u))
2417 appendStringInfo(&buf, "_x%04X_", (unsigned int) u);
2418 else
2419 appendBinaryStringInfo(&buf, p, pg_mblen_cstr(p));
2420 }
2421 }
2422
2423 return buf.data;
2424 #else /* not USE_LIBXML */
2425 NO_XML_SUPPORT();
2426 return NULL;
2427 #endif /* not USE_LIBXML */
2428 }
2429
2430
2431 /*
2432 * Map XML name to SQL identifier; see SQL/XML:2008 section 9.3.
2433 */
2434 char *
2435 map_xml_name_to_sql_identifier(const char *name)
2436 {
2437 StringInfoData buf;
2438 const char *p;
2439
2440 initStringInfo(&buf);
2441
2442 for (p = name; *p; p += pg_mblen_cstr(p))
2443 {
2444 if (*p == '_' && *(p + 1) == 'x'
2445 && isxdigit((unsigned char) *(p + 2))
2446 && isxdigit((unsigned char) *(p + 3))
2447 && isxdigit((unsigned char) *(p + 4))
2448 && isxdigit((unsigned char) *(p + 5))
2449 && *(p + 6) == '_')
2450 {
2451 char cbuf[MAX_UNICODE_EQUIVALENT_STRING + 1];
2452 unsigned int u;
2453
2454 sscanf(p + 2, "%X", &u);
2455 pg_unicode_to_server(u, (unsigned char *) cbuf);
2456 appendStringInfoString(&buf, cbuf);
2457 p += 6;
2458 }
2459 else
2460 appendBinaryStringInfo(&buf, p, pg_mblen_cstr(p));
2461 }
2462
2463 return buf.data;
2464 }
2465
2466 /*
2467 * Map SQL value to XML value; see SQL/XML:2008 section 9.8.
2468 *
2469 * When xml_escape_strings is true, then certain characters in string
2470 * values are replaced by entity references (&lt; etc.), as specified
2471 * in SQL/XML:2008 section 9.8 GR 9) a) iii). This is normally what is
2472 * wanted. The false case is mainly useful when the resulting value
2473 * is used with xmlTextWriterWriteAttribute() to write out an
2474 * attribute, because that function does the escaping itself.
2475 */
2476 char *
2477 map_sql_value_to_xml_value(Datum value, Oid type, bool xml_escape_strings)
2478 {
2479 if (type_is_array_domain(type))
2480 {
2481 ArrayType *array;
2482 Oid elmtype;
2483 int16 elmlen;
2484 bool elmbyval;
2485 char elmalign;
2486 int num_elems;
2487 Datum *elem_values;
2488 bool *elem_nulls;
2489 StringInfoData buf;
2490 int i;
2491
2492 array = DatumGetArrayTypeP(value);
2493 elmtype = ARR_ELEMTYPE(array);
2494 get_typlenbyvalalign(elmtype, &elmlen, &elmbyval, &elmalign);
2495
2496 deconstruct_array(array, elmtype,
2497 elmlen, elmbyval, elmalign,
2498 &elem_values, &elem_nulls,
2499 &num_elems);
2500
2501 initStringInfo(&buf);
2502
2503 for (i = 0; i < num_elems; i++)
2504 {
2505 if (elem_nulls[i])
2506 continue;
2507 appendStringInfoString(&buf, "<element>");
2508 appendStringInfoString(&buf,
2509 map_sql_value_to_xml_value(elem_values[i],
2510 elmtype, true));
2511 appendStringInfoString(&buf, "</element>");
2512 }
2513
2514 pfree(elem_values);
2515 pfree(elem_nulls);
2516
2517 return buf.data;
2518 }
2519 else
2520 {
2521 Oid typeOut;
2522 bool isvarlena;
2523 char *str;
2524
2525 /*
2526 * Flatten domains; the special-case treatments below should apply to,
2527 * eg, domains over boolean not just boolean.
2528 */
2529 type = getBaseType(type);
2530
2531 /*
2532 * Special XSD formatting for some data types
2533 */
2534 switch (type)
2535 {
2536 case BOOLOID:
2537 if (DatumGetBool(value))
2538 return "true";
2539 else
2540 return "false";
2541
2542 case DATEOID:
2543 {
2544 DateADT date;
2545 struct pg_tm tm;
2546 char buf[MAXDATELEN + 1];
2547
2548 date = DatumGetDateADT(value);
2549 /* XSD doesn't support infinite values */
2550 if (DATE_NOT_FINITE(date))
2551 ereport(ERROR,
2552 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2553 errmsg("date out of range"),
2554 errdetail("XML does not support infinite date values.")));
2555 j2date(date + POSTGRES_EPOCH_JDATE,
2556 &(tm.tm_year), &(tm.tm_mon), &(tm.tm_mday));
2557 EncodeDateOnly(&tm, USE_XSD_DATES, buf);
2558
2559 return pstrdup(buf);
2560 }
2561
2562 case TIMESTAMPOID:
2563 {
2564 Timestamp timestamp;
2565 struct pg_tm tm;
2566 fsec_t fsec;
2567 char buf[MAXDATELEN + 1];
2568
2569 timestamp = DatumGetTimestamp(value);
2570
2571 /* XSD doesn't support infinite values */
2572 if (TIMESTAMP_NOT_FINITE(timestamp))
2573 ereport(ERROR,
2574 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2575 errmsg("timestamp out of range"),
2576 errdetail("XML does not support infinite timestamp values.")));
2577 else if (timestamp2tm(timestamp, NULL, &tm, &fsec, NULL, NULL) == 0)
2578 EncodeDateTime(&tm, fsec, false, 0, NULL, USE_XSD_DATES, buf);
2579 else
2580 ereport(ERROR,
2581 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2582 errmsg("timestamp out of range")));
2583
2584 return pstrdup(buf);
2585 }
2586
2587 case TIMESTAMPTZOID:
2588 {
2589 TimestampTz timestamp;
2590 struct pg_tm tm;
2591 int tz;
2592 fsec_t fsec;
2593 const char *tzn = NULL;
2594 char buf[MAXDATELEN + 1];
2595
2596 timestamp = DatumGetTimestamp(value);
2597
2598 /* XSD doesn't support infinite values */
2599 if (TIMESTAMP_NOT_FINITE(timestamp))
2600 ereport(ERROR,
2601 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2602 errmsg("timestamp out of range"),
2603 errdetail("XML does not support infinite timestamp values.")));
2604 else if (timestamp2tm(timestamp, &tz, &tm, &fsec, &tzn, NULL) == 0)
2605 EncodeDateTime(&tm, fsec, true, tz, tzn, USE_XSD_DATES, buf);
2606 else
2607 ereport(ERROR,
2608 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2609 errmsg("timestamp out of range")));
2610
2611 return pstrdup(buf);
2612 }
2613
2614 #ifdef USE_LIBXML
2615 case BYTEAOID:
2616 {
2617 bytea *bstr = DatumGetByteaPP(value);
2618 PgXmlErrorContext *xmlerrcxt;
2619 volatile xmlBufferPtr buf = NULL;
2620 volatile xmlTextWriterPtr writer = NULL;
2621 char *result;
2622
2623 xmlerrcxt = pg_xml_init(PG_XML_STRICTNESS_ALL);
2624
2625 PG_TRY();
2626 {
2627 buf = xmlBufferCreate();
2628 if (buf == NULL || xmlerrcxt->err_occurred)
2629 xml_ereport(xmlerrcxt, ERROR, ERRCODE_OUT_OF_MEMORY,
2630 "could not allocate xmlBuffer");
2631 writer = xmlNewTextWriterMemory(buf, 0);
2632 if (writer == NULL || xmlerrcxt->err_occurred)
2633 xml_ereport(xmlerrcxt, ERROR, ERRCODE_OUT_OF_MEMORY,
2634 "could not allocate xmlTextWriter");
2635
2636 if (xmlbinary == XMLBINARY_BASE64)
2637 xmlTextWriterWriteBase64(writer, VARDATA_ANY(bstr),
2638 0, VARSIZE_ANY_EXHDR(bstr));
2639 else
2640 xmlTextWriterWriteBinHex(writer, VARDATA_ANY(bstr),
2641 0, VARSIZE_ANY_EXHDR(bstr));
2642
2643 /* we MUST do this now to flush data out to the buffer */
2644 xmlFreeTextWriter(writer);
2645 writer = NULL;
2646
2647 result = pstrdup((const char *) xmlBufferContent(buf));
2648 }
2649 PG_CATCH();
2650 {
2651 if (writer)
2652 xmlFreeTextWriter(writer);
2653 if (buf)
2654 xmlBufferFree(buf);
2655
2656 pg_xml_done(xmlerrcxt, true);
2657
2658 PG_RE_THROW();
2659 }
2660 PG_END_TRY();
2661
2662 xmlBufferFree(buf);
2663
2664 pg_xml_done(xmlerrcxt, false);
2665
2666 return result;
2667 }
2668 #endif /* USE_LIBXML */
2669
2670 }
2671
2672 /*
2673 * otherwise, just use the type's native text representation
2674 */
2675 getTypeOutputInfo(type, &typeOut, &isvarlena);
2676 str = OidOutputFunctionCall(typeOut, value);
2677
2678 /* ... exactly as-is for XML, and when escaping is not wanted */
2679 if (type == XMLOID || !xml_escape_strings)
2680 return str;
2681
2682 /* otherwise, translate special characters as needed */
2683 return escape_xml(str);
2684 }
2685 }
2686
2687
2688 /*
2689 * Escape characters in text that have special meanings in XML.
2690 *
2691 * Returns a palloc'd string.
2692 *
2693 * NB: this is intentionally not dependent on libxml.
2694 */
2695 char *
2696 escape_xml(const char *str)
2697 {
2698 StringInfoData buf;
2699 const char *p;
2700
2701 initStringInfo(&buf);
2702 for (p = str; *p; p++)
2703 {
2704 switch (*p)
2705 {
2706 case '&':
2707 appendStringInfoString(&buf, "&amp;");
2708 break;
2709 case '<':
2710 appendStringInfoString(&buf, "&lt;");
2711 break;
2712 case '>':
2713 appendStringInfoString(&buf, "&gt;");
2714 break;
2715 case '\r':
2716 appendStringInfoString(&buf, "&#x0d;");
2717 break;
2718 default:
2719 appendStringInfoCharMacro(&buf, *p);
2720 break;
2721 }
2722 }
2723 return buf.data;
2724 }
2725
2726
2727 static char *
2728 _SPI_strdup(const char *s)
2729 {
2730 size_t len = strlen(s) + 1;
2731 char *ret = SPI_palloc(len);
2732
2733 memcpy(ret, s, len);
2734 return ret;
2735 }
2736
2737
2738 /*
2739 * SQL to XML mapping functions
2740 *
2741 * What follows below was at one point intentionally organized so that
2742 * you can read along in the SQL/XML standard. The functions are
2743 * mostly split up the way the clauses lay out in the standards
2744 * document, and the identifiers are also aligned with the standard
2745 * text. Unfortunately, SQL/XML:2006 reordered the clauses
2746 * differently than SQL/XML:2003, so the order below doesn't make much
2747 * sense anymore.
2748 *
2749 * There are many things going on there:
2750 *
2751 * There are two kinds of mappings: Mapping SQL data (table contents)
2752 * to XML documents, and mapping SQL structure (the "schema") to XML
2753 * Schema. And there are functions that do both at the same time.
2754 *
2755 * Then you can map a database, a schema, or a table, each in both
2756 * ways. This breaks down recursively: Mapping a database invokes
2757 * mapping schemas, which invokes mapping tables, which invokes
2758 * mapping rows, which invokes mapping columns, although you can't
2759 * call the last two from the outside. Because of this, there are a
2760 * number of xyz_internal() functions which are to be called both from
2761 * the function manager wrapper and from some upper layer in a
2762 * recursive call.
2763 *
2764 * See the documentation about what the common function arguments
2765 * nulls, tableforest, and targetns mean.
2766 *
2767 * Some style guidelines for XML output: Use double quotes for quoting
2768 * XML attributes. Indent XML elements by two spaces, but remember
2769 * that a lot of code is called recursively at different levels, so
2770 * it's better not to indent rather than create output that indents
2771 * and outdents weirdly. Add newlines to make the output look nice.
2772 */
2773
2774
2775 /*
2776 * Visibility of objects for XML mappings; see SQL/XML:2008 section
2777 * 4.10.8.
2778 */
2779
2780 /*
2781 * Given a query, which must return type oid as first column, produce
2782 * a list of Oids with the query results.
2783 */
2784 static List *
2785 query_to_oid_list(const char *query)
2786 {
2787 uint64 i;
2788 List *list = NIL;
2789 int spi_result;
2790
2791 spi_result = SPI_execute(query, true, 0);
2792 if (spi_result != SPI_OK_SELECT)
2793 elog(ERROR, "SPI_execute returned %s for %s",
2794 SPI_result_code_string(spi_result), query);
2795
2796 for (i = 0; i < SPI_processed; i++)
2797 {
2798 Datum oid;
2799 bool isnull;
2800
2801 oid = SPI_getbinval(SPI_tuptable->vals[i],
2802 SPI_tuptable->tupdesc,
2803 1,
2804 &isnull);
2805 if (!isnull)
2806 list = lappend_oid(list, DatumGetObjectId(oid));
2807 }
2808
2809 return list;
2810 }
2811
2812
2813 static List *
2814 schema_get_xml_visible_tables(Oid nspid)
2815 {
2816 StringInfoData query;
2817
2818 initStringInfo(&query);
2819 appendStringInfo(&query, "SELECT oid FROM pg_catalog.pg_class"
2820 " WHERE relnamespace = %u AND relkind IN ("
2821 CppAsString2(RELKIND_RELATION) ","
2822 CppAsString2(RELKIND_MATVIEW) ","
2823 CppAsString2(RELKIND_VIEW) ")"
2824 " AND pg_catalog.has_table_privilege (oid, 'SELECT')"
2825 " ORDER BY relname;", nspid);
2826
2827 return query_to_oid_list(query.data);
2828 }
2829
2830
2831 /*
2832 * Including the system schemas is probably not useful for a database
2833 * mapping.
2834 */
2835 #define XML_VISIBLE_SCHEMAS_EXCLUDE "(nspname ~ '^pg_' OR nspname = 'information_schema')"
2836
2837 #define XML_VISIBLE_SCHEMAS "SELECT oid FROM pg_catalog.pg_namespace WHERE pg_catalog.has_schema_privilege (oid, 'USAGE') AND NOT " XML_VISIBLE_SCHEMAS_EXCLUDE
2838
2839
2840 static List *
2841 database_get_xml_visible_schemas(void)
2842 {
2843 return query_to_oid_list(XML_VISIBLE_SCHEMAS " ORDER BY nspname;");
2844 }
2845
2846
2847 static List *
2848 database_get_xml_visible_tables(void)
2849 {
2850 /* At the moment there is no order required here. */
2851 return query_to_oid_list("SELECT oid FROM pg_catalog.pg_class"
2852 " WHERE relkind IN ("
2853 CppAsString2(RELKIND_RELATION) ","
2854 CppAsString2(RELKIND_MATVIEW) ","
2855 CppAsString2(RELKIND_VIEW) ")"
2856 " AND pg_catalog.has_table_privilege(pg_class.oid, 'SELECT')"
2857 " AND relnamespace IN (" XML_VISIBLE_SCHEMAS ");");
2858 }
2859
2860
2861 /*
2862 * Map SQL table to XML and/or XML Schema document; see SQL/XML:2008
2863 * section 9.11.
2864 */
2865
2866 static StringInfo
2867 table_to_xml_internal(Oid relid,
2868 const char *xmlschema, bool nulls, bool tableforest,
2869 const char *targetns, bool top_level)
2870 {
2871 StringInfoData query;
2872
2873 initStringInfo(&query);
2874 appendStringInfo(&query, "SELECT * FROM %s",
2875 DatumGetCString(DirectFunctionCall1(regclassout,
2876 ObjectIdGetDatum(relid))));
2877 return query_to_xml_internal(query.data, get_rel_name(relid),
2878 xmlschema, nulls, tableforest,
2879 targetns, top_level);
2880 }
2881
2882
2883 Datum
2884 table_to_xml(PG_FUNCTION_ARGS)
2885 {
2886 Oid relid = PG_GETARG_OID(0);
2887 bool nulls = PG_GETARG_BOOL(1);
2888 bool tableforest = PG_GETARG_BOOL(2);
2889 const char *targetns = text_to_cstring(PG_GETARG_TEXT_PP(3));
2890
2891 PG_RETURN_XML_P(stringinfo_to_xmltype(table_to_xml_internal(relid, NULL,
2892 nulls, tableforest,
2893 targetns, true)));
2894 }
2895
2896
2897 Datum
2898 query_to_xml(PG_FUNCTION_ARGS)
2899 {
2900 char *query = text_to_cstring(PG_GETARG_TEXT_PP(0));
2901 bool nulls = PG_GETARG_BOOL(1);
2902 bool tableforest = PG_GETARG_BOOL(2);
2903 const char *targetns = text_to_cstring(PG_GETARG_TEXT_PP(3));
2904
2905 PG_RETURN_XML_P(stringinfo_to_xmltype(query_to_xml_internal(query, NULL,
2906 NULL, nulls, tableforest,
2907 targetns, true)));
2908 }
2909
2910
2911 Datum
2912 cursor_to_xml(PG_FUNCTION_ARGS)
2913 {
2914 char *name = text_to_cstring(PG_GETARG_TEXT_PP(0));
2915 int32 count = PG_GETARG_INT32(1);
2916 bool nulls = PG_GETARG_BOOL(2);
2917 bool tableforest = PG_GETARG_BOOL(3);
2918 const char *targetns = text_to_cstring(PG_GETARG_TEXT_PP(4));
2919
2920 StringInfoData result;
2921 Portal portal;
2922 uint64 i;
2923
2924 initStringInfo(&result);
2925
2926 if (!tableforest)
2927 {
2928 xmldata_root_element_start(&result, "table", NULL, targetns, true);
2929 appendStringInfoChar(&result, '\n');
2930 }
2931
2932 SPI_connect();
2933 portal = SPI_cursor_find(name);
2934 if (portal == NULL)
2935 ereport(ERROR,
2936 (errcode(ERRCODE_UNDEFINED_CURSOR),
2937 errmsg("cursor \"%s\" does not exist", name)));
2938
2939 SPI_cursor_fetch(portal, true, count);
2940 for (i = 0; i < SPI_processed; i++)
2941 SPI_sql_row_to_xmlelement(i, &result, NULL, nulls,
2942 tableforest, targetns, true);
2943
2944 SPI_finish();
2945
2946 if (!tableforest)
2947 xmldata_root_element_end(&result, "table");
2948
2949 PG_RETURN_XML_P(stringinfo_to_xmltype(&result));
2950 }
2951
2952
2953 /*
2954 * Write the start tag of the root element of a data mapping.
2955 *
2956 * top_level means that this is the very top level of the eventual
2957 * output. For example, when the user calls table_to_xml, then a call
2958 * with a table name to this function is the top level. When the user
2959 * calls database_to_xml, then a call with a schema name to this
2960 * function is not the top level. If top_level is false, then the XML
2961 * namespace declarations are omitted, because they supposedly already
2962 * appeared earlier in the output. Repeating them is not wrong, but
2963 * it looks ugly.
2964 */
2965 static void
2966 xmldata_root_element_start(StringInfo result, const char *eltname,
2967 const char *xmlschema, const char *targetns,
2968 bool top_level)
2969 {
2970 /* This isn't really wrong but currently makes no sense. */
2971 Assert(top_level || !xmlschema);
2972
2973 appendStringInfo(result, "<%s", eltname);
2974 if (top_level)
2975 {
2976 appendStringInfoString(result, " xmlns:xsi=\"" NAMESPACE_XSI "\"");
2977 if (strlen(targetns) > 0)
2978 appendStringInfo(result, " xmlns=\"%s\"", targetns);
2979 }
2980 if (xmlschema)
2981 {
2982 /* FIXME: better targets */
2983 if (strlen(targetns) > 0)
2984 appendStringInfo(result, " xsi:schemaLocation=\"%s #\"", targetns);
2985 else
2986 appendStringInfoString(result, " xsi:noNamespaceSchemaLocation=\"#\"");
2987 }
2988 appendStringInfoString(result, ">\n");
2989 }
2990
2991
2992 static void
2993 xmldata_root_element_end(StringInfo result, const char *eltname)
2994 {
2995 appendStringInfo(result, "</%s>\n", eltname);
2996 }
2997
2998
2999 static StringInfo
3000 query_to_xml_internal(const char *query, char *tablename,
3001 const char *xmlschema, bool nulls, bool tableforest,
3002 const char *targetns, bool top_level)
3003 {
3004 StringInfo result;
3005 char *xmltn;
3006 uint64 i;
3007
3008 if (tablename)
3009 xmltn = map_sql_identifier_to_xml_name(tablename, true, false);
3010 else
3011 xmltn = "table";
3012
3013 result = makeStringInfo();
3014
3015 SPI_connect();
3016 if (SPI_execute(query, true, 0) != SPI_OK_SELECT)
3017 ereport(ERROR,
3018 (errcode(ERRCODE_DATA_EXCEPTION),
3019 errmsg("invalid query")));
3020
3021 if (!tableforest)
3022 {
3023 xmldata_root_element_start(result, xmltn, xmlschema,
3024 targetns, top_level);
3025 appendStringInfoChar(result, '\n');
3026 }
3027
3028 if (xmlschema)
3029 appendStringInfo(result, "%s\n\n", xmlschema);
3030
3031 for (i = 0; i < SPI_processed; i++)
3032 SPI_sql_row_to_xmlelement(i, result, tablename, nulls,
3033 tableforest, targetns, top_level);
3034
3035 if (!tableforest)
3036 xmldata_root_element_end(result, xmltn);
3037
3038 SPI_finish();
3039
3040 return result;
3041 }
3042
3043
3044 Datum
3045 table_to_xmlschema(PG_FUNCTION_ARGS)
3046 {
3047 Oid relid = PG_GETARG_OID(0);
3048 bool nulls = PG_GETARG_BOOL(1);
3049 bool tableforest = PG_GETARG_BOOL(2);
3050 const char *targetns = text_to_cstring(PG_GETARG_TEXT_PP(3));
3051 const char *result;
3052 Relation rel;
3053
3054 rel = table_open(relid, AccessShareLock);
3055 result = map_sql_table_to_xmlschema(rel->rd_att, relid, nulls,
3056 tableforest, targetns);
3057 table_close(rel, NoLock);
3058
3059 PG_RETURN_XML_P(cstring_to_xmltype(result));
3060 }
3061
3062
3063 Datum
3064 query_to_xmlschema(PG_FUNCTION_ARGS)
3065 {
3066 char *query = text_to_cstring(PG_GETARG_TEXT_PP(0));
3067 bool nulls = PG_GETARG_BOOL(1);
3068 bool tableforest = PG_GETARG_BOOL(2);
3069 const char *targetns = text_to_cstring(PG_GETARG_TEXT_PP(3));
3070 const char *result;
3071 SPIPlanPtr plan;
3072 Portal portal;
3073
3074 SPI_connect();
3075
3076 if ((plan = SPI_prepare(query, 0, NULL)) == NULL)
3077 elog(ERROR, "SPI_prepare(\"%s\") failed", query);
3078
3079 if ((portal = SPI_cursor_open(NULL, plan, NULL, NULL, true)) == NULL)
3080 elog(ERROR, "SPI_cursor_open(\"%s\") failed", query);
3081
3082 result = _SPI_strdup(map_sql_table_to_xmlschema(portal->tupDesc,
3083 InvalidOid, nulls,
3084 tableforest, targetns));
3085 SPI_cursor_close(portal);
3086 SPI_finish();
3087
3088 PG_RETURN_XML_P(cstring_to_xmltype(result));
3089 }
3090
3091
3092 Datum
3093 cursor_to_xmlschema(PG_FUNCTION_ARGS)
3094 {
3095 char *name = text_to_cstring(PG_GETARG_TEXT_PP(0));
3096 bool nulls = PG_GETARG_BOOL(1);
3097 bool tableforest = PG_GETARG_BOOL(2);
3098 const char *targetns = text_to_cstring(PG_GETARG_TEXT_PP(3));
3099 const char *xmlschema;
3100 Portal portal;
3101
3102 SPI_connect();
3103 portal = SPI_cursor_find(name);
3104 if (portal == NULL)
3105 ereport(ERROR,
3106 (errcode(ERRCODE_UNDEFINED_CURSOR),
3107 errmsg("cursor \"%s\" does not exist", name)));
3108 if (portal->tupDesc == NULL)
3109 ereport(ERROR,
3110 (errcode(ERRCODE_INVALID_CURSOR_STATE),
3111 errmsg("portal \"%s\" does not return tuples", name)));
3112
3113 xmlschema = _SPI_strdup(map_sql_table_to_xmlschema(portal->tupDesc,
3114 InvalidOid, nulls,
3115 tableforest, targetns));
3116 SPI_finish();
3117
3118 PG_RETURN_XML_P(cstring_to_xmltype(xmlschema));
3119 }
3120
3121
3122 Datum
3123 table_to_xml_and_xmlschema(PG_FUNCTION_ARGS)
3124 {
3125 Oid relid = PG_GETARG_OID(0);
3126 bool nulls = PG_GETARG_BOOL(1);
3127 bool tableforest = PG_GETARG_BOOL(2);
3128 const char *targetns = text_to_cstring(PG_GETARG_TEXT_PP(3));
3129 Relation rel;
3130 const char *xmlschema;
3131
3132 rel = table_open(relid, AccessShareLock);
3133 xmlschema = map_sql_table_to_xmlschema(rel->rd_att, relid, nulls,
3134 tableforest, targetns);
3135 table_close(rel, NoLock);
3136
3137 PG_RETURN_XML_P(stringinfo_to_xmltype(table_to_xml_internal(relid,
3138 xmlschema, nulls, tableforest,
3139 targetns, true)));
3140 }
3141
3142
3143 Datum
3144 query_to_xml_and_xmlschema(PG_FUNCTION_ARGS)
3145 {
3146 char *query = text_to_cstring(PG_GETARG_TEXT_PP(0));
3147 bool nulls = PG_GETARG_BOOL(1);
3148 bool tableforest = PG_GETARG_BOOL(2);
3149 const char *targetns = text_to_cstring(PG_GETARG_TEXT_PP(3));
3150
3151 const char *xmlschema;
3152 SPIPlanPtr plan;
3153 Portal portal;
3154
3155 SPI_connect();
3156
3157 if ((plan = SPI_prepare(query, 0, NULL)) == NULL)
3158 elog(ERROR, "SPI_prepare(\"%s\") failed", query);
3159
3160 if ((portal = SPI_cursor_open(NULL, plan, NULL, NULL, true)) == NULL)
3161 elog(ERROR, "SPI_cursor_open(\"%s\") failed", query);
3162
3163 xmlschema = _SPI_strdup(map_sql_table_to_xmlschema(portal->tupDesc,
3164 InvalidOid, nulls, tableforest, targetns));
3165 SPI_cursor_close(portal);
3166 SPI_finish();
3167
3168 PG_RETURN_XML_P(stringinfo_to_xmltype(query_to_xml_internal(query, NULL,
3169 xmlschema, nulls, tableforest,
3170 targetns, true)));
3171 }
3172
3173
3174 /*
3175 * Map SQL schema to XML and/or XML Schema document; see SQL/XML:2008
3176 * sections 9.13, 9.14.
3177 */
3178
3179 static StringInfo
3180 schema_to_xml_internal(Oid nspid, const char *xmlschema, bool nulls,
3181 bool tableforest, const char *targetns, bool top_level)
3182 {
3183 StringInfo result;
3184 char *xmlsn;
3185 List *relid_list;
3186 ListCell *cell;
3187
3188 xmlsn = map_sql_identifier_to_xml_name(get_namespace_name(nspid),
3189 true, false);
3190 result = makeStringInfo();
3191
3192 xmldata_root_element_start(result, xmlsn, xmlschema, targetns, top_level);
3193 appendStringInfoChar(result, '\n');
3194
3195 if (xmlschema)
3196 appendStringInfo(result, "%s\n\n", xmlschema);
3197
3198 SPI_connect();
3199
3200 relid_list = schema_get_xml_visible_tables(nspid);
3201
3202 foreach(cell, relid_list)
3203 {
3204 Oid relid = lfirst_oid(cell);
3205 StringInfo subres;
3206
3207 subres = table_to_xml_internal(relid, NULL, nulls, tableforest,
3208 targetns, false);
3209
3210 appendBinaryStringInfo(result, subres->data, subres->len);
3211 appendStringInfoChar(result, '\n');
3212 }
3213
3214 SPI_finish();
3215
3216 xmldata_root_element_end(result, xmlsn);
3217
3218 return result;
3219 }
3220
3221
3222 Datum
3223 schema_to_xml(PG_FUNCTION_ARGS)
3224 {
3225 Name name = PG_GETARG_NAME(0);
3226 bool nulls = PG_GETARG_BOOL(1);
3227 bool tableforest = PG_GETARG_BOOL(2);
3228 const char *targetns = text_to_cstring(PG_GETARG_TEXT_PP(3));
3229
3230 char *schemaname;
3231 Oid nspid;
3232
3233 schemaname = NameStr(*name);
3234 nspid = LookupExplicitNamespace(schemaname, false);
3235
3236 PG_RETURN_XML_P(stringinfo_to_xmltype(schema_to_xml_internal(nspid, NULL,
3237 nulls, tableforest, targetns, true)));
3238 }
3239
3240
3241 /*
3242 * Write the start element of the root element of an XML Schema mapping.
3243 */
3244 static void
3245 xsd_schema_element_start(StringInfo result, const char *targetns)
3246 {
3247 appendStringInfoString(result,
3248 "<xsd:schema\n"
3249 " xmlns:xsd=\"" NAMESPACE_XSD "\"");
3250 if (strlen(targetns) > 0)
3251 appendStringInfo(result,
3252 "\n"
3253 " targetNamespace=\"%s\"\n"
3254 " elementFormDefault=\"qualified\"",
3255 targetns);
3256 appendStringInfoString(result,
3257 ">\n\n");
3258 }
3259
3260
3261 static void
3262 xsd_schema_element_end(StringInfo result)
3263 {
3264 appendStringInfoString(result, "</xsd:schema>");
3265 }
3266
3267
3268 static StringInfo
3269 schema_to_xmlschema_internal(const char *schemaname, bool nulls,
3270 bool tableforest, const char *targetns)
3271 {
3272 Oid nspid;
3273 List *relid_list;
3274 List *tupdesc_list;
3275 ListCell *cell;
3276 StringInfo result;
3277
3278 result = makeStringInfo();
3279
3280 nspid = LookupExplicitNamespace(schemaname, false);
3281
3282 xsd_schema_element_start(result, targetns);
3283
3284 SPI_connect();
3285
3286 relid_list = schema_get_xml_visible_tables(nspid);
3287
3288 tupdesc_list = NIL;
3289 foreach(cell, relid_list)
3290 {
3291 Relation rel;
3292
3293 rel = table_open(lfirst_oid(cell), AccessShareLock);
3294 tupdesc_list = lappend(tupdesc_list, CreateTupleDescCopy(rel->rd_att));
3295 table_close(rel, NoLock);
3296 }
3297
3298 appendStringInfoString(result,
3299 map_sql_typecoll_to_xmlschema_types(tupdesc_list));
3300
3301 appendStringInfoString(result,
3302 map_sql_schema_to_xmlschema_types(nspid, relid_list,
3303 nulls, tableforest, targetns));
3304
3305 xsd_schema_element_end(result);
3306
3307 SPI_finish();
3308
3309 return result;
3310 }
3311
3312
3313 Datum
3314 schema_to_xmlschema(PG_FUNCTION_ARGS)
3315 {
3316 Name name = PG_GETARG_NAME(0);
3317 bool nulls = PG_GETARG_BOOL(1);
3318 bool tableforest = PG_GETARG_BOOL(2);
3319 const char *targetns = text_to_cstring(PG_GETARG_TEXT_PP(3));
3320
3321 PG_RETURN_XML_P(stringinfo_to_xmltype(schema_to_xmlschema_internal(NameStr(*name),
3322 nulls, tableforest, targetns)));
3323 }
3324
3325
3326 Datum
3327 schema_to_xml_and_xmlschema(PG_FUNCTION_ARGS)
3328 {
3329 Name name = PG_GETARG_NAME(0);
3330 bool nulls = PG_GETARG_BOOL(1);
3331 bool tableforest = PG_GETARG_BOOL(2);
3332 const char *targetns = text_to_cstring(PG_GETARG_TEXT_PP(3));
3333 char *schemaname;
3334 Oid nspid;
3335 StringInfo xmlschema;
3336
3337 schemaname = NameStr(*name);
3338 nspid = LookupExplicitNamespace(schemaname, false);
3339
3340 xmlschema = schema_to_xmlschema_internal(schemaname, nulls,
3341 tableforest, targetns);
3342
3343 PG_RETURN_XML_P(stringinfo_to_xmltype(schema_to_xml_internal(nspid,
3344 xmlschema->data, nulls,
3345 tableforest, targetns, true)));
3346 }
3347
3348
3349 /*
3350 * Map SQL database to XML and/or XML Schema document; see SQL/XML:2008
3351 * sections 9.16, 9.17.
3352 */
3353
3354 static StringInfo
3355 database_to_xml_internal(const char *xmlschema, bool nulls,
3356 bool tableforest, const char *targetns)
3357 {
3358 StringInfo result;
3359 List *nspid_list;
3360 ListCell *cell;
3361 char *xmlcn;
3362
3363 xmlcn = map_sql_identifier_to_xml_name(get_database_name(MyDatabaseId),
3364 true, false);
3365 result = makeStringInfo();
3366
3367 xmldata_root_element_start(result, xmlcn, xmlschema, targetns, true);
3368 appendStringInfoChar(result, '\n');
3369
3370 if (xmlschema)
3371 appendStringInfo(result, "%s\n\n", xmlschema);
3372
3373 SPI_connect();
3374
3375 nspid_list = database_get_xml_visible_schemas();
3376
3377 foreach(cell, nspid_list)
3378 {
3379 Oid nspid = lfirst_oid(cell);
3380 StringInfo subres;
3381
3382 subres = schema_to_xml_internal(nspid, NULL, nulls,
3383 tableforest, targetns, false);
3384
3385 appendBinaryStringInfo(result, subres->data, subres->len);
3386 appendStringInfoChar(result, '\n');
3387 }
3388
3389 SPI_finish();
3390
3391 xmldata_root_element_end(result, xmlcn);
3392
3393 return result;
3394 }
3395
3396
3397 Datum
3398 database_to_xml(PG_FUNCTION_ARGS)
3399 {
3400 bool nulls = PG_GETARG_BOOL(0);
3401 bool tableforest = PG_GETARG_BOOL(1);
3402 const char *targetns = text_to_cstring(PG_GETARG_TEXT_PP(2));
3403
3404 PG_RETURN_XML_P(stringinfo_to_xmltype(database_to_xml_internal(NULL, nulls,
3405 tableforest, targetns)));
3406 }
3407
3408
3409 static StringInfo
3410 database_to_xmlschema_internal(bool nulls, bool tableforest,
3411 const char *targetns)
3412 {
3413 List *relid_list;
3414 List *nspid_list;
3415 List *tupdesc_list;
3416 ListCell *cell;
3417 StringInfo result;
3418
3419 result = makeStringInfo();
3420
3421 xsd_schema_element_start(result, targetns);
3422
3423 SPI_connect();
3424
3425 relid_list = database_get_xml_visible_tables();
3426 nspid_list = database_get_xml_visible_schemas();
3427
3428 tupdesc_list = NIL;
3429 foreach(cell, relid_list)
3430 {
3431 Relation rel;
3432
3433 rel = table_open(lfirst_oid(cell), AccessShareLock);
3434 tupdesc_list = lappend(tupdesc_list, CreateTupleDescCopy(rel->rd_att));
3435 table_close(rel, NoLock);
3436 }
3437
3438 appendStringInfoString(result,
3439 map_sql_typecoll_to_xmlschema_types(tupdesc_list));
3440
3441 appendStringInfoString(result,
3442 map_sql_catalog_to_xmlschema_types(nspid_list, nulls, tableforest, targetns));
3443
3444 xsd_schema_element_end(result);
3445
3446 SPI_finish();
3447
3448 return result;
3449 }
3450
3451
3452 Datum
3453 database_to_xmlschema(PG_FUNCTION_ARGS)
3454 {
3455 bool nulls = PG_GETARG_BOOL(0);
3456 bool tableforest = PG_GETARG_BOOL(1);
3457 const char *targetns = text_to_cstring(PG_GETARG_TEXT_PP(2));
3458
3459 PG_RETURN_XML_P(stringinfo_to_xmltype(database_to_xmlschema_internal(nulls,
3460 tableforest, targetns)));
3461 }
3462
3463
3464 Datum
3465 database_to_xml_and_xmlschema(PG_FUNCTION_ARGS)
3466 {
3467 bool nulls = PG_GETARG_BOOL(0);
3468 bool tableforest = PG_GETARG_BOOL(1);
3469 const char *targetns = text_to_cstring(PG_GETARG_TEXT_PP(2));
3470 StringInfo xmlschema;
3471
3472 xmlschema = database_to_xmlschema_internal(nulls, tableforest, targetns);
3473
3474 PG_RETURN_XML_P(stringinfo_to_xmltype(database_to_xml_internal(xmlschema->data,
3475 nulls, tableforest, targetns)));
3476 }
3477
3478
3479 /*
3480 * Map a multi-part SQL name to an XML name; see SQL/XML:2008 section
3481 * 9.2.
3482 */
3483 static char *
3484 map_multipart_sql_identifier_to_xml_name(const char *a, const char *b, const char *c, const char *d)
3485 {
3486 StringInfoData result;
3487
3488 initStringInfo(&result);
3489
3490 if (a)
3491 appendStringInfoString(&result,
3492 map_sql_identifier_to_xml_name(a, true, true));
3493 if (b)
3494 appendStringInfo(&result, ".%s",
3495 map_sql_identifier_to_xml_name(b, true, true));
3496 if (c)
3497 appendStringInfo(&result, ".%s",
3498 map_sql_identifier_to_xml_name(c, true, true));
3499 if (d)
3500 appendStringInfo(&result, ".%s",
3501 map_sql_identifier_to_xml_name(d, true, true));
3502
3503 return result.data;
3504 }
3505
3506
3507 /*
3508 * Map an SQL table to an XML Schema document; see SQL/XML:2008
3509 * section 9.11.
3510 *
3511 * Map an SQL table to XML Schema data types; see SQL/XML:2008 section
3512 * 9.9.
3513 */
3514 static const char *
3515 map_sql_table_to_xmlschema(TupleDesc tupdesc, Oid relid, bool nulls,
3516 bool tableforest, const char *targetns)
3517 {
3518 int i;
3519 char *xmltn;
3520 char *tabletypename;
3521 char *rowtypename;
3522 StringInfoData result;
3523
3524 initStringInfo(&result);
3525
3526 if (OidIsValid(relid))
3527 {
3528 HeapTuple tuple;
3529 Form_pg_class reltuple;
3530
3531 tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
3532 if (!HeapTupleIsValid(tuple))
3533 elog(ERROR, "cache lookup failed for relation %u", relid);
3534 reltuple = (Form_pg_class) GETSTRUCT(tuple);
3535
3536 xmltn = map_sql_identifier_to_xml_name(NameStr(reltuple->relname),
3537 true, false);
3538
3539 tabletypename = map_multipart_sql_identifier_to_xml_name("TableType",
3540 get_database_name(MyDatabaseId),
3541 get_namespace_name(reltuple->relnamespace),
3542 NameStr(reltuple->relname));
3543
3544 rowtypename = map_multipart_sql_identifier_to_xml_name("RowType",
3545 get_database_name(MyDatabaseId),
3546 get_namespace_name(reltuple->relnamespace),
3547 NameStr(reltuple->relname));
3548
3549 ReleaseSysCache(tuple);
3550 }
3551 else
3552 {
3553 if (tableforest)
3554 xmltn = "row";
3555 else
3556 xmltn = "table";
3557
3558 tabletypename = "TableType";
3559 rowtypename = "RowType";
3560 }
3561
3562 xsd_schema_element_start(&result, targetns);
3563
3564 appendStringInfoString(&result,
3565 map_sql_typecoll_to_xmlschema_types(list_make1(tupdesc)));
3566
3567 appendStringInfo(&result,
3568 "<xsd:complexType name=\"%s\">\n"
3569 " <xsd:sequence>\n",
3570 rowtypename);
3571
3572 for (i = 0; i < tupdesc->natts; i++)
3573 {
3574 Form_pg_attribute att = TupleDescAttr(tupdesc, i);
3575
3576 if (att->attisdropped)
3577 continue;
3578 appendStringInfo(&result,
3579 " <xsd:element name=\"%s\" type=\"%s\"%s></xsd:element>\n",
3580 map_sql_identifier_to_xml_name(NameStr(att->attname),
3581 true, false),
3582 map_sql_type_to_xml_name(att->atttypid, -1),
3583 nulls ? " nillable=\"true\"" : " minOccurs=\"0\"");
3584 }
3585
3586 appendStringInfoString(&result,
3587 " </xsd:sequence>\n"
3588 "</xsd:complexType>\n\n");
3589
3590 if (!tableforest)
3591 {
3592 appendStringInfo(&result,
3593 "<xsd:complexType name=\"%s\">\n"
3594 " <xsd:sequence>\n"
3595 " <xsd:element name=\"row\" type=\"%s\" minOccurs=\"0\" maxOccurs=\"unbounded\"/>\n"
3596 " </xsd:sequence>\n"
3597 "</xsd:complexType>\n\n",
3598 tabletypename, rowtypename);
3599
3600 appendStringInfo(&result,
3601 "<xsd:element name=\"%s\" type=\"%s\"/>\n\n",
3602 xmltn, tabletypename);
3603 }
3604 else
3605 appendStringInfo(&result,
3606 "<xsd:element name=\"%s\" type=\"%s\"/>\n\n",
3607 xmltn, rowtypename);
3608
3609 xsd_schema_element_end(&result);
3610
3611 return result.data;
3612 }
3613
3614
3615 /*
3616 * Map an SQL schema to XML Schema data types; see SQL/XML:2008
3617 * section 9.12.
3618 */
3619 static const char *
3620 map_sql_schema_to_xmlschema_types(Oid nspid, List *relid_list, bool nulls,
3621 bool tableforest, const char *targetns)
3622 {
3623 char *dbname;
3624 char *nspname;
3625 char *xmlsn;
3626 char *schematypename;
3627 StringInfoData result;
3628 ListCell *cell;
3629
3630 dbname = get_database_name(MyDatabaseId);
3631 nspname = get_namespace_name(nspid);
3632
3633 initStringInfo(&result);
3634
3635 xmlsn = map_sql_identifier_to_xml_name(nspname, true, false);
3636
3637 schematypename = map_multipart_sql_identifier_to_xml_name("SchemaType",
3638 dbname,
3639 nspname,
3640 NULL);
3641
3642 appendStringInfo(&result,
3643 "<xsd:complexType name=\"%s\">\n", schematypename);
3644 if (!tableforest)
3645 appendStringInfoString(&result,
3646 " <xsd:all>\n");
3647 else
3648 appendStringInfoString(&result,
3649 " <xsd:sequence>\n");
3650
3651 foreach(cell, relid_list)
3652 {
3653 Oid relid = lfirst_oid(cell);
3654 char *relname = get_rel_name(relid);
3655 char *xmltn = map_sql_identifier_to_xml_name(relname, true, false);
3656 char *tabletypename = map_multipart_sql_identifier_to_xml_name(tableforest ? "RowType" : "TableType",
3657 dbname,
3658 nspname,
3659 relname);
3660
3661 if (!tableforest)
3662 appendStringInfo(&result,
3663 " <xsd:element name=\"%s\" type=\"%s\"/>\n",
3664 xmltn, tabletypename);
3665 else
3666 appendStringInfo(&result,
3667 " <xsd:element name=\"%s\" type=\"%s\" minOccurs=\"0\" maxOccurs=\"unbounded\"/>\n",
3668 xmltn, tabletypename);
3669 }
3670
3671 if (!tableforest)
3672 appendStringInfoString(&result,
3673 " </xsd:all>\n");
3674 else
3675 appendStringInfoString(&result,
3676 " </xsd:sequence>\n");
3677 appendStringInfoString(&result,
3678 "</xsd:complexType>\n\n");
3679
3680 appendStringInfo(&result,
3681 "<xsd:element name=\"%s\" type=\"%s\"/>\n\n",
3682 xmlsn, schematypename);
3683
3684 return result.data;
3685 }
3686
3687
3688 /*
3689 * Map an SQL catalog to XML Schema data types; see SQL/XML:2008
3690 * section 9.15.
3691 */
3692 static const char *
3693 map_sql_catalog_to_xmlschema_types(List *nspid_list, bool nulls,
3694 bool tableforest, const char *targetns)
3695 {
3696 char *dbname;
3697 char *xmlcn;
3698 char *catalogtypename;
3699 StringInfoData result;
3700 ListCell *cell;
3701
3702 dbname = get_database_name(MyDatabaseId);
3703
3704 initStringInfo(&result);
3705
3706 xmlcn = map_sql_identifier_to_xml_name(dbname, true, false);
3707
3708 catalogtypename = map_multipart_sql_identifier_to_xml_name("CatalogType",
3709 dbname,
3710 NULL,
3711 NULL);
3712
3713 appendStringInfo(&result,
3714 "<xsd:complexType name=\"%s\">\n", catalogtypename);
3715 appendStringInfoString(&result,
3716 " <xsd:all>\n");
3717
3718 foreach(cell, nspid_list)
3719 {
3720 Oid nspid = lfirst_oid(cell);
3721 char *nspname = get_namespace_name(nspid);
3722 char *xmlsn = map_sql_identifier_to_xml_name(nspname, true, false);
3723 char *schematypename = map_multipart_sql_identifier_to_xml_name("SchemaType",
3724 dbname,
3725 nspname,
3726 NULL);
3727
3728 appendStringInfo(&result,
3729 " <xsd:element name=\"%s\" type=\"%s\"/>\n",
3730 xmlsn, schematypename);
3731 }
3732
3733 appendStringInfoString(&result,
3734 " </xsd:all>\n");
3735 appendStringInfoString(&result,
3736 "</xsd:complexType>\n\n");
3737
3738 appendStringInfo(&result,
3739 "<xsd:element name=\"%s\" type=\"%s\"/>\n\n",
3740 xmlcn, catalogtypename);
3741
3742 return result.data;
3743 }
3744
3745
3746 /*
3747 * Map an SQL data type to an XML name; see SQL/XML:2008 section 9.4.
3748 */
3749 static const char *
3750 map_sql_type_to_xml_name(Oid typeoid, int typmod)
3751 {
3752 StringInfoData result;
3753
3754 initStringInfo(&result);
3755
3756 switch (typeoid)
3757 {
3758 case BPCHAROID:
3759 if (typmod == -1)
3760 appendStringInfoString(&result, "CHAR");
3761 else
3762 appendStringInfo(&result, "CHAR_%d", typmod - VARHDRSZ);
3763 break;
3764 case VARCHAROID:
3765 if (typmod == -1)
3766 appendStringInfoString(&result, "VARCHAR");
3767 else
3768 appendStringInfo(&result, "VARCHAR_%d", typmod - VARHDRSZ);
3769 break;
3770 case NUMERICOID:
3771 if (typmod == -1)
3772 appendStringInfoString(&result, "NUMERIC");
3773 else
3774 appendStringInfo(&result, "NUMERIC_%d_%d",
3775 ((typmod - VARHDRSZ) >> 16) & 0xffff,
3776 (typmod - VARHDRSZ) & 0xffff);
3777 break;
3778 case INT4OID:
3779 appendStringInfoString(&result, "INTEGER");
3780 break;
3781 case INT2OID:
3782 appendStringInfoString(&result, "SMALLINT");
3783 break;
3784 case INT8OID:
3785 appendStringInfoString(&result, "BIGINT");
3786 break;
3787 case FLOAT4OID:
3788 appendStringInfoString(&result, "REAL");
3789 break;
3790 case FLOAT8OID:
3791 appendStringInfoString(&result, "DOUBLE");
3792 break;
3793 case BOOLOID:
3794 appendStringInfoString(&result, "BOOLEAN");
3795 break;
3796 case TIMEOID:
3797 if (typmod == -1)
3798 appendStringInfoString(&result, "TIME");
3799 else
3800 appendStringInfo(&result, "TIME_%d", typmod);
3801 break;
3802 case TIMETZOID:
3803 if (typmod == -1)
3804 appendStringInfoString(&result, "TIME_WTZ");
3805 else
3806 appendStringInfo(&result, "TIME_WTZ_%d", typmod);
3807 break;
3808 case TIMESTAMPOID:
3809 if (typmod == -1)
3810 appendStringInfoString(&result, "TIMESTAMP");
3811 else
3812 appendStringInfo(&result, "TIMESTAMP_%d", typmod);
3813 break;
3814 case TIMESTAMPTZOID:
3815 if (typmod == -1)
3816 appendStringInfoString(&result, "TIMESTAMP_WTZ");
3817 else
3818 appendStringInfo(&result, "TIMESTAMP_WTZ_%d", typmod);
3819 break;
3820 case DATEOID:
3821 appendStringInfoString(&result, "DATE");
3822 break;
3823 case XMLOID:
3824 appendStringInfoString(&result, "XML");
3825 break;
3826 default:
3827 {
3828 HeapTuple tuple;
3829 Form_pg_type typtuple;
3830
3831 tuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typeoid));
3832 if (!HeapTupleIsValid(tuple))
3833 elog(ERROR, "cache lookup failed for type %u", typeoid);
3834 typtuple = (Form_pg_type) GETSTRUCT(tuple);
3835
3836 appendStringInfoString(&result,
3837 map_multipart_sql_identifier_to_xml_name((typtuple->typtype == TYPTYPE_DOMAIN) ? "Domain" : "UDT",
3838 get_database_name(MyDatabaseId),
3839 get_namespace_name(typtuple->typnamespace),
3840 NameStr(typtuple->typname)));
3841
3842 ReleaseSysCache(tuple);
3843 }
3844 }
3845
3846 return result.data;
3847 }
3848
3849
3850 /*
3851 * Map a collection of SQL data types to XML Schema data types; see
3852 * SQL/XML:2008 section 9.7.
3853 */
3854 static const char *
3855 map_sql_typecoll_to_xmlschema_types(List *tupdesc_list)
3856 {
3857 List *uniquetypes = NIL;
3858 int i;
3859 StringInfoData result;
3860 ListCell *cell0;
3861
3862 /* extract all column types used in the set of TupleDescs */
3863 foreach(cell0, tupdesc_list)
3864 {
3865 TupleDesc tupdesc = (TupleDesc) lfirst(cell0);
3866
3867 for (i = 0; i < tupdesc->natts; i++)
3868 {
3869 Form_pg_attribute att = TupleDescAttr(tupdesc, i);
3870
3871 if (att->attisdropped)
3872 continue;
3873 uniquetypes = list_append_unique_oid(uniquetypes, att->atttypid);
3874 }
3875 }
3876
3877 /* add base types of domains */
3878 foreach(cell0, uniquetypes)
3879 {
3880 Oid typid = lfirst_oid(cell0);
3881 Oid basetypid = getBaseType(typid);
3882
3883 if (basetypid != typid)
3884 uniquetypes = list_append_unique_oid(uniquetypes, basetypid);
3885 }
3886
3887 /* Convert to textual form */
3888 initStringInfo(&result);
3889
3890 foreach(cell0, uniquetypes)
3891 {
3892 appendStringInfo(&result, "%s\n",
3893 map_sql_type_to_xmlschema_type(lfirst_oid(cell0),
3894 -1));
3895 }
3896
3897 return result.data;
3898 }
3899
3900
3901 /*
3902 * Map an SQL data type to a named XML Schema data type; see
3903 * SQL/XML:2008 sections 9.5 and 9.6.
3904 *
3905 * (The distinction between 9.5 and 9.6 is basically that 9.6 adds
3906 * a name attribute, which this function does. The name-less version
3907 * 9.5 doesn't appear to be required anywhere.)
3908 */
3909 static const char *
3910 map_sql_type_to_xmlschema_type(Oid typeoid, int typmod)
3911 {
3912 StringInfoData result;
3913 const char *typename = map_sql_type_to_xml_name(typeoid, typmod);
3914
3915 initStringInfo(&result);
3916
3917 if (typeoid == XMLOID)
3918 {
3919 appendStringInfoString(&result,
3920 "<xsd:complexType mixed=\"true\">\n"
3921 " <xsd:sequence>\n"
3922 " <xsd:any name=\"element\" minOccurs=\"0\" maxOccurs=\"unbounded\" processContents=\"skip\"/>\n"
3923 " </xsd:sequence>\n"
3924 "</xsd:complexType>\n");
3925 }
3926 else
3927 {
3928 appendStringInfo(&result,
3929 "<xsd:simpleType name=\"%s\">\n", typename);
3930
3931 switch (typeoid)
3932 {
3933 case BPCHAROID:
3934 case VARCHAROID:
3935 case TEXTOID:
3936 appendStringInfoString(&result,
3937 " <xsd:restriction base=\"xsd:string\">\n");
3938 if (typmod != -1)
3939 appendStringInfo(&result,
3940 " <xsd:maxLength value=\"%d\"/>\n",
3941 typmod - VARHDRSZ);
3942 appendStringInfoString(&result, " </xsd:restriction>\n");
3943 break;
3944
3945 case BYTEAOID:
3946 appendStringInfo(&result,
3947 " <xsd:restriction base=\"xsd:%s\">\n"
3948 " </xsd:restriction>\n",
3949 xmlbinary == XMLBINARY_BASE64 ? "base64Binary" : "hexBinary");
3950 break;
3951
3952 case NUMERICOID:
3953 if (typmod != -1)
3954 appendStringInfo(&result,
3955 " <xsd:restriction base=\"xsd:decimal\">\n"
3956 " <xsd:totalDigits value=\"%d\"/>\n"
3957 " <xsd:fractionDigits value=\"%d\"/>\n"
3958 " </xsd:restriction>\n",
3959 ((typmod - VARHDRSZ) >> 16) & 0xffff,
3960 (typmod - VARHDRSZ) & 0xffff);
3961 break;
3962
3963 case INT2OID:
3964 appendStringInfo(&result,
3965 " <xsd:restriction base=\"xsd:short\">\n"
3966 " <xsd:maxInclusive value=\"%d\"/>\n"
3967 " <xsd:minInclusive value=\"%d\"/>\n"
3968 " </xsd:restriction>\n",
3969 SHRT_MAX, SHRT_MIN);
3970 break;
3971
3972 case INT4OID:
3973 appendStringInfo(&result,
3974 " <xsd:restriction base=\"xsd:int\">\n"
3975 " <xsd:maxInclusive value=\"%d\"/>\n"
3976 " <xsd:minInclusive value=\"%d\"/>\n"
3977 " </xsd:restriction>\n",
3978 INT_MAX, INT_MIN);
3979 break;
3980
3981 case INT8OID:
3982 appendStringInfo(&result,
3983 " <xsd:restriction base=\"xsd:long\">\n"
3984 " <xsd:maxInclusive value=\"" INT64_FORMAT "\"/>\n"
3985 " <xsd:minInclusive value=\"" INT64_FORMAT "\"/>\n"
3986 " </xsd:restriction>\n",
3987 PG_INT64_MAX,
3988 PG_INT64_MIN);
3989 break;
3990
3991 case FLOAT4OID:
3992 appendStringInfoString(&result,
3993 " <xsd:restriction base=\"xsd:float\"></xsd:restriction>\n");
3994 break;
3995
3996 case FLOAT8OID:
3997 appendStringInfoString(&result,
3998 " <xsd:restriction base=\"xsd:double\"></xsd:restriction>\n");
3999 break;
4000
4001 case BOOLOID:
4002 appendStringInfoString(&result,
4003 " <xsd:restriction base=\"xsd:boolean\"></xsd:restriction>\n");
4004 break;
4005
4006 case TIMEOID:
4007 case TIMETZOID:
4008 {
4009 const char *tz = (typeoid == TIMETZOID ? "(\\+|-)\\p{Nd}{2}:\\p{Nd}{2}" : "");
4010
4011 if (typmod == -1)
4012 appendStringInfo(&result,
4013 " <xsd:restriction base=\"xsd:time\">\n"
4014 " <xsd:pattern value=\"\\p{Nd}{2}:\\p{Nd}{2}:\\p{Nd}{2}(.\\p{Nd}+)?%s\"/>\n"
4015 " </xsd:restriction>\n", tz);
4016 else if (typmod == 0)
4017 appendStringInfo(&result,
4018 " <xsd:restriction base=\"xsd:time\">\n"
4019 " <xsd:pattern value=\"\\p{Nd}{2}:\\p{Nd}{2}:\\p{Nd}{2}%s\"/>\n"
4020 " </xsd:restriction>\n", tz);
4021 else
4022 appendStringInfo(&result,
4023 " <xsd:restriction base=\"xsd:time\">\n"
4024 " <xsd:pattern value=\"\\p{Nd}{2}:\\p{Nd}{2}:\\p{Nd}{2}.\\p{Nd}{%d}%s\"/>\n"
4025 " </xsd:restriction>\n", typmod - VARHDRSZ, tz);
4026 break;
4027 }
4028
4029 case TIMESTAMPOID:
4030 case TIMESTAMPTZOID:
4031 {
4032 const char *tz = (typeoid == TIMESTAMPTZOID ? "(\\+|-)\\p{Nd}{2}:\\p{Nd}{2}" : "");
4033
4034 if (typmod == -1)
4035 appendStringInfo(&result,
4036 " <xsd:restriction base=\"xsd:dateTime\">\n"
4037 " <xsd:pattern value=\"\\p{Nd}{4}-\\p{Nd}{2}-\\p{Nd}{2}T\\p{Nd}{2}:\\p{Nd}{2}:\\p{Nd}{2}(.\\p{Nd}+)?%s\"/>\n"
4038 " </xsd:restriction>\n", tz);
4039 else if (typmod == 0)
4040 appendStringInfo(&result,
4041 " <xsd:restriction base=\"xsd:dateTime\">\n"
4042 " <xsd:pattern value=\"\\p{Nd}{4}-\\p{Nd}{2}-\\p{Nd}{2}T\\p{Nd}{2}:\\p{Nd}{2}:\\p{Nd}{2}%s\"/>\n"
4043 " </xsd:restriction>\n", tz);
4044 else
4045 appendStringInfo(&result,
4046 " <xsd:restriction base=\"xsd:dateTime\">\n"
4047 " <xsd:pattern value=\"\\p{Nd}{4}-\\p{Nd}{2}-\\p{Nd}{2}T\\p{Nd}{2}:\\p{Nd}{2}:\\p{Nd}{2}.\\p{Nd}{%d}%s\"/>\n"
4048 " </xsd:restriction>\n", typmod - VARHDRSZ, tz);
4049 break;
4050 }
4051
4052 case DATEOID:
4053 appendStringInfoString(&result,
4054 " <xsd:restriction base=\"xsd:date\">\n"
4055 " <xsd:pattern value=\"\\p{Nd}{4}-\\p{Nd}{2}-\\p{Nd}{2}\"/>\n"
4056 " </xsd:restriction>\n");
4057 break;
4058
4059 default:
4060 if (get_typtype(typeoid) == TYPTYPE_DOMAIN)
4061 {
4062 Oid base_typeoid;
4063 int32 base_typmod = -1;
4064
4065 base_typeoid = getBaseTypeAndTypmod(typeoid, &base_typmod);
4066
4067 appendStringInfo(&result,
4068 " <xsd:restriction base=\"%s\"/>\n",
4069 map_sql_type_to_xml_name(base_typeoid, base_typmod));
4070 }
4071 break;
4072 }
4073 appendStringInfoString(&result, "</xsd:simpleType>\n");
4074 }
4075
4076 return result.data;
4077 }
4078
4079
4080 /*
4081 * Map an SQL row to an XML element, taking the row from the active
4082 * SPI cursor. See also SQL/XML:2008 section 9.10.
4083 */
4084 static void
4085 SPI_sql_row_to_xmlelement(uint64 rownum, StringInfo result, char *tablename,
4086 bool nulls, bool tableforest,
4087 const char *targetns, bool top_level)
4088 {
4089 int i;
4090 char *xmltn;
4091
4092 if (tablename)
4093 xmltn = map_sql_identifier_to_xml_name(tablename, true, false);
4094 else
4095 {
4096 if (tableforest)
4097 xmltn = "row";
4098 else
4099 xmltn = "table";
4100 }
4101
4102 if (tableforest)
4103 xmldata_root_element_start(result, xmltn, NULL, targetns, top_level);
4104 else
4105 appendStringInfoString(result, "<row>\n");
4106
4107 for (i = 1; i <= SPI_tuptable->tupdesc->natts; i++)
4108 {
4109 char *colname;
4110 Datum colval;
4111 bool isnull;
4112
4113 colname = map_sql_identifier_to_xml_name(SPI_fname(SPI_tuptable->tupdesc, i),
4114 true, false);
4115 colval = SPI_getbinval(SPI_tuptable->vals[rownum],
4116 SPI_tuptable->tupdesc,
4117 i,
4118 &isnull);
4119 if (isnull)
4120 {
4121 if (nulls)
4122 appendStringInfo(result, " <%s xsi:nil=\"true\"/>\n", colname);
4123 }
4124 else
4125 appendStringInfo(result, " <%s>%s</%s>\n",
4126 colname,
4127 map_sql_value_to_xml_value(colval,
4128 SPI_gettypeid(SPI_tuptable->tupdesc, i), true),
4129 colname);
4130 }
4131
4132 if (tableforest)
4133 {
4134 xmldata_root_element_end(result, xmltn);
4135 appendStringInfoChar(result, '\n');
4136 }
4137 else
4138 appendStringInfoString(result, "</row>\n\n");
4139 }
4140
4141
4142 /*
4143 * XPath related functions
4144 */
4145
4146 #ifdef USE_LIBXML
4147
4148 /*
4149 * Convert XML node to text.
4150 *
4151 * For attribute and text nodes, return the escaped text. For anything else,
4152 * dump the whole subtree.
4153 */
4154 static text *
4155 xml_xmlnodetoxmltype(xmlNodePtr cur, PgXmlErrorContext *xmlerrcxt)
4156 {
4157 xmltype *result = NULL;
4158
4159 if (cur->type != XML_ATTRIBUTE_NODE &&
4160 cur->type != XML_TEXT_NODE &&
4161 cur->type != XML_NAMESPACE_DECL)
4162 {
4163 void (*volatile nodefree) (xmlNodePtr) = NULL;
4164 volatile xmlBufferPtr buf = NULL;
4165 volatile xmlNodePtr cur_copy = NULL;
4166
4167 PG_TRY();
4168 {
4169 int bytes;
4170
4171 buf = xmlBufferCreate();
4172 if (buf == NULL || xmlerrcxt->err_occurred)
4173 xml_ereport(xmlerrcxt, ERROR, ERRCODE_OUT_OF_MEMORY,
4174 "could not allocate xmlBuffer");
4175
4176 /*
4177 * Produce a dump of the node that we can serialize. xmlNodeDump
4178 * does that, but the result of that function won't contain
4179 * namespace definitions from ancestor nodes, so we first do a
4180 * xmlCopyNode() which duplicates the node along with its required
4181 * namespace definitions.
4182 *
4183 * Some old libxml2 versions such as 2.7.6 produce partially
4184 * broken XML_DOCUMENT_NODE nodes (unset content field) when
4185 * copying them. xmlNodeDump of such a node works fine, but
4186 * xmlFreeNode crashes; set us up to call xmlFreeDoc instead.
4187 */
4188 cur_copy = xmlCopyNode(cur, 1);
4189 if (cur_copy == NULL || xmlerrcxt->err_occurred)
4190 xml_ereport(xmlerrcxt, ERROR, ERRCODE_OUT_OF_MEMORY,
4191 "could not copy node");
4192 nodefree = (cur_copy->type == XML_DOCUMENT_NODE) ?
4193 (void (*) (xmlNodePtr)) xmlFreeDoc : xmlFreeNode;
4194
4195 bytes = xmlNodeDump(buf, NULL, cur_copy, 0, 0);
4196 if (bytes == -1 || xmlerrcxt->err_occurred)
4197 xml_ereport(xmlerrcxt, ERROR, ERRCODE_OUT_OF_MEMORY,
4198 "could not dump node");
4199
4200 result = xmlBuffer_to_xmltype(buf);
4201 }
4202 PG_FINALLY();
4203 {
4204 if (nodefree)
4205 nodefree(cur_copy);
4206 if (buf)
4207 xmlBufferFree(buf);
4208 }
4209 PG_END_TRY();
4210 }
4211 else
4212 {
4213 xmlChar *str;
4214
4215 str = xmlXPathCastNodeToString(cur);
4216 PG_TRY();
4217 {
4218 /* Here we rely on XML having the same representation as TEXT */
4219 char *escaped = escape_xml((char *) str);
4220
4221 result = (xmltype *) cstring_to_text(escaped);
4222 pfree(escaped);
4223 }
4224 PG_FINALLY();
4225 {
4226 xmlFree(str);
4227 }
4228 PG_END_TRY();
4229 }
4230
4231 return result;
4232 }
4233
4234 /*
4235 * Convert an XML XPath object (the result of evaluating an XPath expression)
4236 * to an array of xml values, which are appended to astate. The function
4237 * result value is the number of elements in the array.
4238 *
4239 * If "astate" is NULL then we don't generate the array value, but we still
4240 * return the number of elements it would have had.
4241 *
4242 * Nodesets are converted to an array containing the nodes' textual
4243 * representations. Primitive values (float, double, string) are converted
4244 * to a single-element array containing the value's string representation.
4245 */
4246 static int
4247 xml_xpathobjtoxmlarray(xmlXPathObjectPtr xpathobj,
4248 ArrayBuildState *astate,
4249 PgXmlErrorContext *xmlerrcxt)
4250 {
4251 int result = 0;
4252 Datum datum;
4253 Oid datumtype;
4254 char *result_str;
4255
4256 switch (xpathobj->type)
4257 {
4258 case XPATH_NODESET:
4259 if (xpathobj->nodesetval != NULL)
4260 {
4261 result = xpathobj->nodesetval->nodeNr;
4262 if (astate != NULL)
4263 {
4264 int i;
4265
4266 for (i = 0; i < result; i++)
4267 {
4268 datum = PointerGetDatum(xml_xmlnodetoxmltype(xpathobj->nodesetval->nodeTab[i],
4269 xmlerrcxt));
4270 (void) accumArrayResult(astate, datum, false,
4271 XMLOID, CurrentMemoryContext);
4272 }
4273 }
4274 }
4275 return result;
4276
4277 case XPATH_BOOLEAN:
4278 if (astate == NULL)
4279 return 1;
4280 datum = BoolGetDatum(xpathobj->boolval);
4281 datumtype = BOOLOID;
4282 break;
4283
4284 case XPATH_NUMBER:
4285 if (astate == NULL)
4286 return 1;
4287 datum = Float8GetDatum(xpathobj->floatval);
4288 datumtype = FLOAT8OID;
4289 break;
4290
4291 case XPATH_STRING:
4292 if (astate == NULL)
4293 return 1;
4294 datum = CStringGetDatum((char *) xpathobj->stringval);
4295 datumtype = CSTRINGOID;
4296 break;
4297
4298 default:
4299 elog(ERROR, "xpath expression result type %d is unsupported",
4300 xpathobj->type);
4301 return 0; /* keep compiler quiet */
4302 }
4303
4304 /* Common code for scalar-value cases */
4305 result_str = map_sql_value_to_xml_value(datum, datumtype, true);
4306 datum = PointerGetDatum(cstring_to_xmltype(result_str));
4307 (void) accumArrayResult(astate, datum, false,
4308 XMLOID, CurrentMemoryContext);
4309 return 1;
4310 }
4311
4312
4313 /*
4314 * Common code for xpath() and xmlexists()
4315 *
4316 * Evaluate XPath expression and return number of nodes in res_nitems
4317 * and array of XML values in astate. Either of those pointers can be
4318 * NULL if the corresponding result isn't wanted.
4319 *
4320 * It is up to the user to ensure that the XML passed is in fact
4321 * an XML document - XPath doesn't work easily on fragments without
4322 * a context node being known.
4323 */
4324 static void
4325 xpath_internal(text *xpath_expr_text, xmltype *data, ArrayType *namespaces,
4326 int *res_nitems, ArrayBuildState *astate)
4327 {
4328 PgXmlErrorContext *xmlerrcxt;
4329 volatile xmlParserCtxtPtr ctxt = NULL;
4330 volatile xmlDocPtr doc = NULL;
4331 volatile xmlXPathContextPtr xpathctx = NULL;
4332 volatile xmlXPathCompExprPtr xpathcomp = NULL;
4333 volatile xmlXPathObjectPtr xpathobj = NULL;
4334 char *datastr;
4335 int32 len;
4336 int32 xpath_len;
4337 xmlChar *string;
4338 xmlChar *xpath_expr;
4339 size_t xmldecl_len = 0;
4340 int i;
4341 int ndim;
4342 Datum *ns_names_uris;
4343 bool *ns_names_uris_nulls;
4344 int ns_count;
4345
4346 /*
4347 * Namespace mappings are passed as text[]. If an empty array is passed
4348 * (ndim = 0, "0-dimensional"), then there are no namespace mappings.
4349 * Else, a 2-dimensional array with length of the second axis being equal
4350 * to 2 should be passed, i.e., every subarray contains 2 elements, the
4351 * first element defining the name, the second one the URI. Example:
4352 * ARRAY[ARRAY['myns', 'http://example.com'], ARRAY['myns2',
4353 * 'http://example2.com']].
4354 */
4355 ndim = namespaces ? ARR_NDIM(namespaces) : 0;
4356 if (ndim != 0)
4357 {
4358 int *dims;
4359
4360 dims = ARR_DIMS(namespaces);
4361
4362 if (ndim != 2 || dims[1] != 2)
4363 ereport(ERROR,
4364 (errcode(ERRCODE_DATA_EXCEPTION),
4365 errmsg("invalid array for XML namespace mapping"),
4366 errdetail("The array must be two-dimensional with length of the second axis equal to 2.")));
4367
4368 Assert(ARR_ELEMTYPE(namespaces) == TEXTOID);
4369
4370 deconstruct_array_builtin(namespaces, TEXTOID,
4371 &ns_names_uris, &ns_names_uris_nulls,
4372 &ns_count);
4373
4374 Assert((ns_count % 2) == 0); /* checked above */
4375 ns_count /= 2; /* count pairs only */
4376 }
4377 else
4378 {
4379 ns_names_uris = NULL;
4380 ns_names_uris_nulls = NULL;
4381 ns_count = 0;
4382 }
4383
4384 datastr = VARDATA(data);
4385 len = VARSIZE(data) - VARHDRSZ;
4386 xpath_len = VARSIZE_ANY_EXHDR(xpath_expr_text);
4387 if (xpath_len == 0)
4388 ereport(ERROR,
4389 (errcode(ERRCODE_INVALID_ARGUMENT_FOR_XQUERY),
4390 errmsg("empty XPath expression")));
4391
4392 string = pg_xmlCharStrndup(datastr, len);
4393 xpath_expr = pg_xmlCharStrndup(VARDATA_ANY(xpath_expr_text), xpath_len);
4394
4395 /*
4396 * In a UTF8 database, skip any xml declaration, which might assert
4397 * another encoding. Ignore parse_xml_decl() failure, letting
4398 * xmlCtxtReadMemory() report parse errors. Documentation disclaims
4399 * xpath() support for non-ASCII data in non-UTF8 databases, so leave
4400 * those scenarios bug-compatible with historical behavior.
4401 */
4402 if (GetDatabaseEncoding() == PG_UTF8)
4403 parse_xml_decl(string, &xmldecl_len, NULL, NULL, NULL);
4404
4405 xmlerrcxt = pg_xml_init(PG_XML_STRICTNESS_ALL);
4406
4407 PG_TRY();
4408 {
4409 xmlInitParser();
4410
4411 /*
4412 * redundant XML parsing (two parsings for the same value during one
4413 * command execution are possible)
4414 */
4415 ctxt = xmlNewParserCtxt();
4416 if (ctxt == NULL || xmlerrcxt->err_occurred)
4417 xml_ereport(xmlerrcxt, ERROR, ERRCODE_OUT_OF_MEMORY,
4418 "could not allocate parser context");
4419 doc = xmlCtxtReadMemory(ctxt, (char *) string + xmldecl_len,
4420 len - xmldecl_len, NULL, NULL, 0);
4421 if (doc == NULL || xmlerrcxt->err_occurred)
4422 xml_ereport(xmlerrcxt, ERROR, ERRCODE_INVALID_XML_DOCUMENT,
4423 "could not parse XML document");
4424 xpathctx = xmlXPathNewContext(doc);
4425 if (xpathctx == NULL || xmlerrcxt->err_occurred)
4426 xml_ereport(xmlerrcxt, ERROR, ERRCODE_OUT_OF_MEMORY,
4427 "could not allocate XPath context");
4428 xpathctx->node = (xmlNodePtr) doc;
4429
4430 /* register namespaces, if any */
4431 if (ns_count > 0)
4432 {
4433 for (i = 0; i < ns_count; i++)
4434 {
4435 char *ns_name;
4436 char *ns_uri;
4437
4438 if (ns_names_uris_nulls[i * 2] ||
4439 ns_names_uris_nulls[i * 2 + 1])
4440 ereport(ERROR,
4441 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
4442 errmsg("neither namespace name nor URI may be null")));
4443 ns_name = TextDatumGetCString(ns_names_uris[i * 2]);
4444 ns_uri = TextDatumGetCString(ns_names_uris[i * 2 + 1]);
4445 if (xmlXPathRegisterNs(xpathctx,
4446 (xmlChar *) ns_name,
4447 (xmlChar *) ns_uri) != 0)
4448 ereport(ERROR, /* is this an internal error??? */
4449 (errmsg("could not register XML namespace with name \"%s\" and URI \"%s\"",
4450 ns_name, ns_uri)));
4451 }
4452 }
4453
4454 /*
4455 * Note: here and elsewhere, be careful to use xmlXPathCtxtCompile not
4456 * xmlXPathCompile. In libxml2 2.13.3 and older, the latter function
4457 * fails to defend itself against recursion-to-stack-overflow. See
4458 * https://gitlab.gnome.org/GNOME/libxml2/-/issues/799
4459 */
4460 xpathcomp = xmlXPathCtxtCompile(xpathctx, xpath_expr);
4461 if (xpathcomp == NULL || xmlerrcxt->err_occurred)
4462 xml_ereport(xmlerrcxt, ERROR, ERRCODE_INVALID_ARGUMENT_FOR_XQUERY,
4463 "invalid XPath expression");
4464
4465 /*
4466 * Version 2.6.27 introduces a function named
4467 * xmlXPathCompiledEvalToBoolean, which would be enough for xmlexists,
4468 * but we can derive the existence by whether any nodes are returned,
4469 * thereby preventing a library version upgrade and keeping the code
4470 * the same.
4471 */
4472 xpathobj = xmlXPathCompiledEval(xpathcomp, xpathctx);
4473 if (xpathobj == NULL || xmlerrcxt->err_occurred)
4474 xml_ereport(xmlerrcxt, ERROR, ERRCODE_INVALID_ARGUMENT_FOR_XQUERY,
4475 "could not create XPath object");
4476
4477 /*
4478 * Extract the results as requested.
4479 */
4480 if (res_nitems != NULL)
4481 *res_nitems = xml_xpathobjtoxmlarray(xpathobj, astate, xmlerrcxt);
4482 else
4483 (void) xml_xpathobjtoxmlarray(xpathobj, astate, xmlerrcxt);
4484 }
4485 PG_CATCH();
4486 {
4487 if (xpathobj)
4488 xmlXPathFreeObject(xpathobj);
4489 if (xpathcomp)
4490 xmlXPathFreeCompExpr(xpathcomp);
4491 if (xpathctx)
4492 xmlXPathFreeContext(xpathctx);
4493 if (doc)
4494 xmlFreeDoc(doc);
4495 if (ctxt)
4496 xmlFreeParserCtxt(ctxt);
4497
4498 pg_xml_done(xmlerrcxt, true);
4499
4500 PG_RE_THROW();
4501 }
4502 PG_END_TRY();
4503
4504 xmlXPathFreeObject(xpathobj);
4505 xmlXPathFreeCompExpr(xpathcomp);
4506 xmlXPathFreeContext(xpathctx);
4507 xmlFreeDoc(doc);
4508 xmlFreeParserCtxt(ctxt);
4509
4510 pg_xml_done(xmlerrcxt, false);
4511 }
4512 #endif /* USE_LIBXML */
4513
4514 /*
4515 * Evaluate XPath expression and return array of XML values.
4516 *
4517 * As we have no support of XQuery sequences yet, this function seems
4518 * to be the most useful one (array of XML functions plays a role of
4519 * some kind of substitution for XQuery sequences).
4520 */
4521 Datum
4522 xpath(PG_FUNCTION_ARGS)
4523 {
4524 #ifdef USE_LIBXML
4525 text *xpath_expr_text = PG_GETARG_TEXT_PP(0);
4526 xmltype *data = PG_GETARG_XML_P(1);
4527 ArrayType *namespaces = PG_GETARG_ARRAYTYPE_P(2);
4528 ArrayBuildState *astate;
4529
4530 astate = initArrayResult(XMLOID, CurrentMemoryContext, true);
4531 xpath_internal(xpath_expr_text, data, namespaces,
4532 NULL, astate);
4533 PG_RETURN_DATUM(makeArrayResult(astate, CurrentMemoryContext));
4534 #else
4535 NO_XML_SUPPORT();
4536 return 0;
4537 #endif
4538 }
4539
4540 /*
4541 * Determines if the node specified by the supplied XPath exists
4542 * in a given XML document, returning a boolean.
4543 */
4544 Datum
4545 xmlexists(PG_FUNCTION_ARGS)
4546 {
4547 #ifdef USE_LIBXML
4548 text *xpath_expr_text = PG_GETARG_TEXT_PP(0);
4549 xmltype *data = PG_GETARG_XML_P(1);
4550 int res_nitems;
4551
4552 xpath_internal(xpath_expr_text, data, NULL,
4553 &res_nitems, NULL);
4554
4555 PG_RETURN_BOOL(res_nitems > 0);
4556 #else
4557 NO_XML_SUPPORT();
4558 return 0;
4559 #endif
4560 }
4561
4562 /*
4563 * Determines if the node specified by the supplied XPath exists
4564 * in a given XML document, returning a boolean. Differs from
4565 * xmlexists as it supports namespaces and is not defined in SQL/XML.
4566 */
4567 Datum
4568 xpath_exists(PG_FUNCTION_ARGS)
4569 {
4570 #ifdef USE_LIBXML
4571 text *xpath_expr_text = PG_GETARG_TEXT_PP(0);
4572 xmltype *data = PG_GETARG_XML_P(1);
4573 ArrayType *namespaces = PG_GETARG_ARRAYTYPE_P(2);
4574 int res_nitems;
4575
4576 xpath_internal(xpath_expr_text, data, namespaces,
4577 &res_nitems, NULL);
4578
4579 PG_RETURN_BOOL(res_nitems > 0);
4580 #else
4581 NO_XML_SUPPORT();
4582 return 0;
4583 #endif
4584 }
4585
4586 /*
4587 * Functions for checking well-formed-ness
4588 */
4589
4590 #ifdef USE_LIBXML
4591 static bool
4592 wellformed_xml(text *data, XmlOptionType xmloption_arg)
4593 {
4594 xmlDocPtr doc;
4595 ErrorSaveContext escontext = {T_ErrorSaveContext};
4596
4597 /*
4598 * We'll report "true" if no soft error is reported by xml_parse().
4599 */
4600 doc = xml_parse(data, xmloption_arg, true,
4601 GetDatabaseEncoding(), NULL, NULL, (Node *) &escontext);
4602 if (doc)
4603 xmlFreeDoc(doc);
4604
4605 return !escontext.error_occurred;
4606 }
4607 #endif
4608
4609 Datum
4610 xml_is_well_formed(PG_FUNCTION_ARGS)
4611 {
4612 #ifdef USE_LIBXML
4613 text *data = PG_GETARG_TEXT_PP(0);
4614
4615 PG_RETURN_BOOL(wellformed_xml(data, xmloption));
4616 #else
4617 NO_XML_SUPPORT();
4618 return 0;
4619 #endif /* not USE_LIBXML */
4620 }
4621
4622 Datum
4623 xml_is_well_formed_document(PG_FUNCTION_ARGS)
4624 {
4625 #ifdef USE_LIBXML
4626 text *data = PG_GETARG_TEXT_PP(0);
4627
4628 PG_RETURN_BOOL(wellformed_xml(data, XMLOPTION_DOCUMENT));
4629 #else
4630 NO_XML_SUPPORT();
4631 return 0;
4632 #endif /* not USE_LIBXML */
4633 }
4634
4635 Datum
4636 xml_is_well_formed_content(PG_FUNCTION_ARGS)
4637 {
4638 #ifdef USE_LIBXML
4639 text *data = PG_GETARG_TEXT_PP(0);
4640
4641 PG_RETURN_BOOL(wellformed_xml(data, XMLOPTION_CONTENT));
4642 #else
4643 NO_XML_SUPPORT();
4644 return 0;
4645 #endif /* not USE_LIBXML */
4646 }
4647
4648 /*
4649 * support functions for XMLTABLE
4650 *
4651 */
4652 #ifdef USE_LIBXML
4653
4654 /*
4655 * Returns private data from executor state. Ensure validity by check with
4656 * MAGIC number.
4657 */
4658 static inline XmlTableBuilderData *
4659 GetXmlTableBuilderPrivateData(TableFuncScanState *state, const char *fname)
4660 {
4661 XmlTableBuilderData *result;
4662
4663 if (!IsA(state, TableFuncScanState))
4664 elog(ERROR, "%s called with invalid TableFuncScanState", fname);
4665 result = (XmlTableBuilderData *) state->opaque;
4666 if (result->magic != XMLTABLE_CONTEXT_MAGIC)
4667 elog(ERROR, "%s called with invalid TableFuncScanState", fname);
4668
4669 return result;
4670 }
4671 #endif
4672
4673 /*
4674 * XmlTableInitOpaque
4675 * Fill in TableFuncScanState->opaque for XmlTable processor; initialize
4676 * the XML parser.
4677 *
4678 * Note: Because we call pg_xml_init() here and pg_xml_done() in
4679 * XmlTableDestroyOpaque, it is critical for robustness that no other
4680 * executor nodes run until this node is processed to completion. Caller
4681 * must execute this to completion (probably filling a tuplestore to exhaust
4682 * this node in a single pass) instead of using row-per-call mode.
4683 */
4684 static void
4685 XmlTableInitOpaque(TableFuncScanState *state, int natts)
4686 {
4687 #ifdef USE_LIBXML
4688 volatile xmlParserCtxtPtr ctxt = NULL;
4689 XmlTableBuilderData *xtCxt;
4690 PgXmlErrorContext *xmlerrcxt;
4691
4692 xtCxt = palloc0(sizeof(XmlTableBuilderData));
4693 xtCxt->magic = XMLTABLE_CONTEXT_MAGIC;
4694 xtCxt->natts = natts;
4695 xtCxt->xpathscomp = palloc0(sizeof(xmlXPathCompExprPtr) * natts);
4696
4697 xmlerrcxt = pg_xml_init(PG_XML_STRICTNESS_ALL);
4698
4699 PG_TRY();
4700 {
4701 xmlInitParser();
4702
4703 ctxt = xmlNewParserCtxt();
4704 if (ctxt == NULL || xmlerrcxt->err_occurred)
4705 xml_ereport(xmlerrcxt, ERROR, ERRCODE_OUT_OF_MEMORY,
4706 "could not allocate parser context");
4707 }
4708 PG_CATCH();
4709 {
4710 if (ctxt != NULL)
4711 xmlFreeParserCtxt(ctxt);
4712
4713 pg_xml_done(xmlerrcxt, true);
4714
4715 PG_RE_THROW();
4716 }
4717 PG_END_TRY();
4718
4719 xtCxt->xmlerrcxt = xmlerrcxt;
4720 xtCxt->ctxt = ctxt;
4721
4722 state->opaque = xtCxt;
4723 #else
4724 NO_XML_SUPPORT();
4725 #endif /* not USE_LIBXML */
4726 }
4727
4728 /*
4729 * XmlTableSetDocument
4730 * Install the input document
4731 */
4732 static void
4733 XmlTableSetDocument(TableFuncScanState *state, Datum value)
4734 {
4735 #ifdef USE_LIBXML
4736 XmlTableBuilderData *xtCxt;
4737 xmltype *xmlval = DatumGetXmlP(value);
4738 char *str;
4739 xmlChar *xstr;
4740 int length;
4741 volatile xmlDocPtr doc = NULL;
4742 volatile xmlXPathContextPtr xpathcxt = NULL;
4743
4744 xtCxt = GetXmlTableBuilderPrivateData(state, "XmlTableSetDocument");
4745
4746 /*
4747 * Use out function for casting to string (remove encoding property). See
4748 * comment in xml_out.
4749 */
4750 str = xml_out_internal(xmlval, 0);
4751
4752 length = strlen(str);
4753 xstr = pg_xmlCharStrndup(str, length);
4754
4755 PG_TRY();
4756 {
4757 doc = xmlCtxtReadMemory(xtCxt->ctxt, (char *) xstr, length, NULL, NULL, 0);
4758 if (doc == NULL || xtCxt->xmlerrcxt->err_occurred)
4759 xml_ereport(xtCxt->xmlerrcxt, ERROR, ERRCODE_INVALID_XML_DOCUMENT,
4760 "could not parse XML document");
4761 xpathcxt = xmlXPathNewContext(doc);
4762 if (xpathcxt == NULL || xtCxt->xmlerrcxt->err_occurred)
4763 xml_ereport(xtCxt->xmlerrcxt, ERROR, ERRCODE_OUT_OF_MEMORY,
4764 "could not allocate XPath context");
4765 xpathcxt->node = (xmlNodePtr) doc;
4766 }
4767 PG_CATCH();
4768 {
4769 if (xpathcxt != NULL)
4770 xmlXPathFreeContext(xpathcxt);
4771 if (doc != NULL)
4772 xmlFreeDoc(doc);
4773
4774 PG_RE_THROW();
4775 }
4776 PG_END_TRY();
4777
4778 xtCxt->doc = doc;
4779 xtCxt->xpathcxt = xpathcxt;
4780 #else
4781 NO_XML_SUPPORT();
4782 #endif /* not USE_LIBXML */
4783 }
4784
4785 /*
4786 * XmlTableSetNamespace
4787 * Add a namespace declaration
4788 */
4789 static void
4790 XmlTableSetNamespace(TableFuncScanState *state, const char *name, const char *uri)
4791 {
4792 #ifdef USE_LIBXML
4793 XmlTableBuilderData *xtCxt;
4794
4795 if (name == NULL)
4796 ereport(ERROR,
4797 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4798 errmsg("DEFAULT namespace is not supported")));
4799 xtCxt = GetXmlTableBuilderPrivateData(state, "XmlTableSetNamespace");
4800
4801 if (xmlXPathRegisterNs(xtCxt->xpathcxt,
4802 pg_xmlCharStrndup(name, strlen(name)),
4803 pg_xmlCharStrndup(uri, strlen(uri))))
4804 xml_ereport(xtCxt->xmlerrcxt, ERROR, ERRCODE_INVALID_ARGUMENT_FOR_XQUERY,
4805 "could not set XML namespace");
4806 #else
4807 NO_XML_SUPPORT();
4808 #endif /* not USE_LIBXML */
4809 }
4810
4811 /*
4812 * XmlTableSetRowFilter
4813 * Install the row-filter Xpath expression.
4814 */
4815 static void
4816 XmlTableSetRowFilter(TableFuncScanState *state, const char *path)
4817 {
4818 #ifdef USE_LIBXML
4819 XmlTableBuilderData *xtCxt;
4820 xmlChar *xstr;
4821
4822 xtCxt = GetXmlTableBuilderPrivateData(state, "XmlTableSetRowFilter");
4823
4824 if (*path == '\0')
4825 ereport(ERROR,
4826 (errcode(ERRCODE_INVALID_ARGUMENT_FOR_XQUERY),
4827 errmsg("row path filter must not be empty string")));
4828
4829 xstr = pg_xmlCharStrndup(path, strlen(path));
4830
4831 /* We require XmlTableSetDocument to have been done already */
4832 Assert(xtCxt->xpathcxt != NULL);
4833
4834 xtCxt->xpathcomp = xmlXPathCtxtCompile(xtCxt->xpathcxt, xstr);
4835 if (xtCxt->xpathcomp == NULL || xtCxt->xmlerrcxt->err_occurred)
4836 xml_ereport(xtCxt->xmlerrcxt, ERROR, ERRCODE_INVALID_ARGUMENT_FOR_XQUERY,
4837 "invalid XPath expression");
4838 #else
4839 NO_XML_SUPPORT();
4840 #endif /* not USE_LIBXML */
4841 }
4842
4843 /*
4844 * XmlTableSetColumnFilter
4845 * Install the column-filter Xpath expression, for the given column.
4846 */
4847 static void
4848 XmlTableSetColumnFilter(TableFuncScanState *state, const char *path, int colnum)
4849 {
4850 #ifdef USE_LIBXML
4851 XmlTableBuilderData *xtCxt;
4852 xmlChar *xstr;
4853
4854 Assert(PointerIsValid(path));
4855
4856 xtCxt = GetXmlTableBuilderPrivateData(state, "XmlTableSetColumnFilter");
4857
4858 if (*path == '\0')
4859 ereport(ERROR,
4860 (errcode(ERRCODE_INVALID_ARGUMENT_FOR_XQUERY),
4861 errmsg("column path filter must not be empty string")));
4862
4863 xstr = pg_xmlCharStrndup(path, strlen(path));
4864
4865 /* We require XmlTableSetDocument to have been done already */
4866 Assert(xtCxt->xpathcxt != NULL);
4867
4868 xtCxt->xpathscomp[colnum] = xmlXPathCtxtCompile(xtCxt->xpathcxt, xstr);
4869 if (xtCxt->xpathscomp[colnum] == NULL || xtCxt->xmlerrcxt->err_occurred)
4870 xml_ereport(xtCxt->xmlerrcxt, ERROR, ERRCODE_INVALID_ARGUMENT_FOR_XQUERY,
4871 "invalid XPath expression");
4872 #else
4873 NO_XML_SUPPORT();
4874 #endif /* not USE_LIBXML */
4875 }
4876
4877 /*
4878 * XmlTableFetchRow
4879 * Prepare the next "current" tuple for upcoming GetValue calls.
4880 * Returns false if the row-filter expression returned no more rows.
4881 */
4882 static bool
4883 XmlTableFetchRow(TableFuncScanState *state)
4884 {
4885 #ifdef USE_LIBXML
4886 XmlTableBuilderData *xtCxt;
4887
4888 xtCxt = GetXmlTableBuilderPrivateData(state, "XmlTableFetchRow");
4889
4890 /* Propagate our own error context to libxml2 */
4891 xmlSetStructuredErrorFunc(xtCxt->xmlerrcxt, xml_errorHandler);
4892
4893 if (xtCxt->xpathobj == NULL)
4894 {
4895 xtCxt->xpathobj = xmlXPathCompiledEval(xtCxt->xpathcomp, xtCxt->xpathcxt);
4896 if (xtCxt->xpathobj == NULL || xtCxt->xmlerrcxt->err_occurred)
4897 xml_ereport(xtCxt->xmlerrcxt, ERROR, ERRCODE_INVALID_ARGUMENT_FOR_XQUERY,
4898 "could not create XPath object");
4899
4900 xtCxt->row_count = 0;
4901 }
4902
4903 if (xtCxt->xpathobj->type == XPATH_NODESET)
4904 {
4905 if (xtCxt->xpathobj->nodesetval != NULL)
4906 {
4907 if (xtCxt->row_count++ < xtCxt->xpathobj->nodesetval->nodeNr)
4908 return true;
4909 }
4910 }
4911
4912 return false;
4913 #else
4914 NO_XML_SUPPORT();
4915 return false;
4916 #endif /* not USE_LIBXML */
4917 }
4918
4919 /*
4920 * XmlTableGetValue
4921 * Return the value for column number 'colnum' for the current row. If
4922 * column -1 is requested, return representation of the whole row.
4923 *
4924 * This leaks memory, so be sure to reset often the context in which it's
4925 * called.
4926 */
4927 static Datum
4928 XmlTableGetValue(TableFuncScanState *state, int colnum,
4929 Oid typid, int32 typmod, bool *isnull)
4930 {
4931 #ifdef USE_LIBXML
4932 Datum result = (Datum) 0;
4933 XmlTableBuilderData *xtCxt;
4934 volatile xmlXPathObjectPtr xpathobj = NULL;
4935
4936 xtCxt = GetXmlTableBuilderPrivateData(state, "XmlTableGetValue");
4937
4938 Assert(xtCxt->xpathobj &&
4939 xtCxt->xpathobj->type == XPATH_NODESET &&
4940 xtCxt->xpathobj->nodesetval != NULL);
4941
4942 /* Propagate our own error context to libxml2 */
4943 xmlSetStructuredErrorFunc(xtCxt->xmlerrcxt, xml_errorHandler);
4944
4945 *isnull = false;
4946
4947 Assert(xtCxt->xpathscomp[colnum] != NULL);
4948
4949 PG_TRY();
4950 {
4951 xmlNodePtr cur;
4952 char *cstr = NULL;
4953
4954 /* Set current node as entry point for XPath evaluation */
4955 cur = xtCxt->xpathobj->nodesetval->nodeTab[xtCxt->row_count - 1];
4956 xtCxt->xpathcxt->node = cur;
4957
4958 /* Evaluate column path */
4959 xpathobj = xmlXPathCompiledEval(xtCxt->xpathscomp[colnum], xtCxt->xpathcxt);
4960 if (xpathobj == NULL || xtCxt->xmlerrcxt->err_occurred)
4961 xml_ereport(xtCxt->xmlerrcxt, ERROR, ERRCODE_INVALID_ARGUMENT_FOR_XQUERY,
4962 "could not create XPath object");
4963
4964 /*
4965 * There are four possible cases, depending on the number of nodes
4966 * returned by the XPath expression and the type of the target column:
4967 * a) XPath returns no nodes. b) The target type is XML (return all
4968 * as XML). For non-XML return types: c) One node (return content).
4969 * d) Multiple nodes (error).
4970 */
4971 if (xpathobj->type == XPATH_NODESET)
4972 {
4973 int count = 0;
4974
4975 if (xpathobj->nodesetval != NULL)
4976 count = xpathobj->nodesetval->nodeNr;
4977
4978 if (xpathobj->nodesetval == NULL || count == 0)
4979 {
4980 *isnull = true;
4981 }
4982 else
4983 {
4984 if (typid == XMLOID)
4985 {
4986 text *textstr;
4987 StringInfoData str;
4988
4989 /* Concatenate serialized values */
4990 initStringInfo(&str);
4991 for (int i = 0; i < count; i++)
4992 {
4993 textstr =
4994 xml_xmlnodetoxmltype(xpathobj->nodesetval->nodeTab[i],
4995 xtCxt->xmlerrcxt);
4996
4997 appendStringInfoText(&str, textstr);
4998 }
4999 cstr = str.data;
5000 }
5001 else
5002 {
5003 xmlChar *str;
5004
5005 if (count > 1)
5006 ereport(ERROR,
5007 (errcode(ERRCODE_CARDINALITY_VIOLATION),
5008 errmsg("more than one value returned by column XPath expression")));
5009
5010 str = xmlXPathCastNodeSetToString(xpathobj->nodesetval);
5011 cstr = str ? xml_pstrdup_and_free(str) : "";
5012 }
5013 }
5014 }
5015 else if (xpathobj->type == XPATH_STRING)
5016 {
5017 /* Content should be escaped when target will be XML */
5018 if (typid == XMLOID)
5019 cstr = escape_xml((char *) xpathobj->stringval);
5020 else
5021 cstr = (char *) xpathobj->stringval;
5022 }
5023 else if (xpathobj->type == XPATH_BOOLEAN)
5024 {
5025 char typcategory;
5026 bool typispreferred;
5027 xmlChar *str;
5028
5029 /* Allow implicit casting from boolean to numbers */
5030 get_type_category_preferred(typid, &typcategory, &typispreferred);
5031
5032 if (typcategory != TYPCATEGORY_NUMERIC)
5033 str = xmlXPathCastBooleanToString(xpathobj->boolval);
5034 else
5035 str = xmlXPathCastNumberToString(xmlXPathCastBooleanToNumber(xpathobj->boolval));
5036
5037 cstr = xml_pstrdup_and_free(str);
5038 }
5039 else if (xpathobj->type == XPATH_NUMBER)
5040 {
5041 xmlChar *str;
5042
5043 str = xmlXPathCastNumberToString(xpathobj->floatval);
5044 cstr = xml_pstrdup_and_free(str);
5045 }
5046 else
5047 elog(ERROR, "unexpected XPath object type %u", xpathobj->type);
5048
5049 /*
5050 * By here, either cstr contains the result value, or the isnull flag
5051 * has been set.
5052 */
5053 Assert(cstr || *isnull);
5054
5055 if (!*isnull)
5056 result = InputFunctionCall(&state->in_functions[colnum],
5057 cstr,
5058 state->typioparams[colnum],
5059 typmod);
5060 }
5061 PG_FINALLY();
5062 {
5063 if (xpathobj != NULL)
5064 xmlXPathFreeObject(xpathobj);
5065 }
5066 PG_END_TRY();
5067
5068 return result;
5069 #else
5070 NO_XML_SUPPORT();
5071 return 0;
5072 #endif /* not USE_LIBXML */
5073 }
5074
5075 /*
5076 * XmlTableDestroyOpaque
5077 * Release all libxml2 resources
5078 */
5079 static void
5080 XmlTableDestroyOpaque(TableFuncScanState *state)
5081 {
5082 #ifdef USE_LIBXML
5083 XmlTableBuilderData *xtCxt;
5084
5085 xtCxt = GetXmlTableBuilderPrivateData(state, "XmlTableDestroyOpaque");
5086
5087 /* Propagate our own error context to libxml2 */
5088 xmlSetStructuredErrorFunc(xtCxt->xmlerrcxt, xml_errorHandler);
5089
5090 if (xtCxt->xpathscomp != NULL)
5091 {
5092 int i;
5093
5094 for (i = 0; i < xtCxt->natts; i++)
5095 if (xtCxt->xpathscomp[i] != NULL)
5096 xmlXPathFreeCompExpr(xtCxt->xpathscomp[i]);
5097 }
5098
5099 if (xtCxt->xpathobj != NULL)
5100 xmlXPathFreeObject(xtCxt->xpathobj);
5101 if (xtCxt->xpathcomp != NULL)
5102 xmlXPathFreeCompExpr(xtCxt->xpathcomp);
5103 if (xtCxt->xpathcxt != NULL)
5104 xmlXPathFreeContext(xtCxt->xpathcxt);
5105 if (xtCxt->doc != NULL)
5106 xmlFreeDoc(xtCxt->doc);
5107 if (xtCxt->ctxt != NULL)
5108 xmlFreeParserCtxt(xtCxt->ctxt);
5109
5110 pg_xml_done(xtCxt->xmlerrcxt, true);
5111
5112 /* not valid anymore */
5113 xtCxt->magic = 0;
5114 state->opaque = NULL;
5115
5116 #else
5117 NO_XML_SUPPORT();
5118 #endif /* not USE_LIBXML */
5119 }