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