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>
67 #if LIBXML_VERSION >= 20704
68 #define HAVE_XMLSTRUCTUREDERRORCONTEXT 1
74 #if LIBXML_VERSION >= 21200
75 #define PgXmlErrorPtr const xmlError *
77 #define PgXmlErrorPtr xmlErrorPtr
115 #define ERRCXT_MAGIC 68275028
126 xmlStructuredErrorFunc saved_errfunc;
129 xmlExternalEntityLoader saved_entityfunc;
132 static xmlParserInputPtr xmlPgEntityLoader(
const char *URL,
const char *ID,
133 xmlParserCtxtPtr ctxt);
135 int sqlcode,
const char *msg);
136 static void xml_errorHandler(
void *
data, PgXmlErrorPtr
error);
137 static int errdetail_for_xml_code(
int code);
141 #ifdef USE_LIBXMLCONTEXT
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);
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,
157 static bool xml_doctype_in_content(
const xmlChar *
str);
159 bool preserve_whitespace,
int encoding,
161 xmlNodePtr *parsed_nodes,
164 static int xml_xpathobjtoxmlarray(xmlXPathObjectPtr xpathobj,
167 static xmlChar *pg_xmlCharStrndup(
const char *
str,
size_t len);
171 const char *xmlschema,
const char *targetns,
175 const char *xmlschema,
bool nulls,
bool tableforest,
176 const char *targetns,
bool top_level);
178 bool nulls,
bool tableforest,
const char *targetns);
180 List *relid_list,
bool nulls,
181 bool tableforest,
const char *targetns);
183 bool nulls,
bool tableforest,
184 const char *targetns);
189 char *tablename,
bool nulls,
bool tableforest,
190 const char *targetns,
bool top_level);
195 #define XMLTABLE_CONTEXT_MAGIC 46922182
196 typedef struct XmlTableBuilderData
202 xmlParserCtxtPtr ctxt;
204 xmlXPathContextPtr xpathcxt;
205 xmlXPathCompExprPtr xpathcomp;
206 xmlXPathObjectPtr xpathobj;
207 xmlXPathCompExprPtr *xpathscomp;
208 } XmlTableBuilderData;
217 const char *path,
int colnum);
220 Oid typid,
int32 typmod,
bool *isnull);
235 #define NO_XML_SUPPORT() \
237 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), \
238 errmsg("unsupported XML feature"), \
239 errdetail("This functionality requires the server to be built with libxml support.")))
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"
251 xmlChar_to_encoding(
const xmlChar *encoding_name)
257 (
errcode(ERRCODE_INVALID_PARAMETER_VALUE),
258 errmsg(
"invalid encoding name \"%s\"",
259 (
const char *) encoding_name)));
289 NULL, NULL, fcinfo->context);
301 #define PG_XML_DEFAULT_VERSION "1.0"
322 if ((res_code = parse_xml_decl((xmlChar *)
str,
323 &
len, &version, NULL, &standalone)) == 0)
329 if (!print_xml_decl(&
buf, version, target_encoding, standalone))
349 errdetail_for_xml_code(res_code));
380 xmlChar *encodingStr = NULL;
388 nbytes =
buf->len -
buf->cursor;
402 parse_xml_decl((
const xmlChar *)
str, NULL, NULL, &encodingStr, NULL);
482 xmlBuffer_to_xmltype(xmlBufferPtr
buf)
485 xmlBufferLength(
buf));
503 if (argdata[
i] ==
'-' && argdata[
i - 1] ==
'-')
505 (
errcode(ERRCODE_INVALID_XML_COMMENT),
506 errmsg(
"invalid XML comment")));
508 if (
len > 0 && argdata[
len - 1] ==
'-')
510 (
errcode(ERRCODE_INVALID_XML_COMMENT),
511 errmsg(
"invalid XML comment")));
532 xmlChar *xmlbuf = NULL;
534 xmlbuf = xmlEncodeSpecialChars(NULL, xml_text2xmlChar(
arg));
556 int global_standalone = 1;
557 xmlChar *global_version = NULL;
558 bool global_version_no_value =
false;
574 parse_xml_decl((xmlChar *)
str, &
len, &version, NULL, &standalone);
576 if (standalone == 0 && global_standalone == 1)
577 global_standalone = 0;
579 global_standalone = -1;
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;
592 if (!global_version_no_value || global_standalone >= 0)
598 print_xml_decl(&buf2,
599 (!global_version_no_value) ? global_version : NULL,
659 text *
volatile result;
662 xmlNodePtr content_nodes;
663 volatile xmlBufferPtr
buf = NULL;
664 volatile xmlSaveCtxtPtr ctxt = NULL;
688 &parsed_xmloptiontype, &content_nodes,
689 (
Node *) &escontext);
696 (
errcode(ERRCODE_NOT_AN_XML_DOCUMENT),
697 errmsg(
"not an XML document")));
715 buf = xmlBufferCreate();
717 if (
buf == NULL || xmlerrcxt->err_occurred)
719 "could not allocate xmlBuffer");
722 parse_xml_decl(xml_text2xmlChar(
data), &decl_len, NULL, NULL, NULL);
731 ctxt = xmlSaveToBuffer(
buf, NULL,
732 XML_SAVE_NO_DECL | XML_SAVE_FORMAT);
734 ctxt = xmlSaveToBuffer(
buf, NULL,
737 if (ctxt == NULL || xmlerrcxt->err_occurred)
739 "could not allocate xmlSaveCtxt");
744 if (xmlSaveDoc(ctxt, doc) == -1 || xmlerrcxt->err_occurred)
746 "could not save document to xmlBuffer");
748 else if (content_nodes != NULL)
759 root = xmlNewNode(NULL, (
const xmlChar *)
"content-root");
760 if (
root == NULL || xmlerrcxt->err_occurred)
762 "could not allocate xml node");
765 xmlDocSetRootElement(doc,
root);
766 xmlAddChildList(
root, content_nodes);
775 newline = xmlNewDocText(NULL, (
const xmlChar *)
"\n");
776 if (
newline == NULL || xmlerrcxt->err_occurred)
778 "could not allocate xml node");
780 for (xmlNodePtr node =
root->children; node; node = node->next)
783 if (node->type != XML_TEXT_NODE && node->prev != NULL)
785 if (xmlSaveTree(ctxt,
newline) == -1 || xmlerrcxt->err_occurred)
789 "could not save newline to xmlBuffer");
793 if (xmlSaveTree(ctxt, node) == -1 || xmlerrcxt->err_occurred)
797 "could not save content to xmlBuffer");
804 if (xmlSaveClose(ctxt) == -1 || xmlerrcxt->err_occurred)
808 "could not close xmlSaveCtxtPtr");
816 const char *
str = (
const char *) xmlBufferContent(
buf);
817 int len = xmlBufferLength(
buf);
819 while (
len > 0 && (
str[
len - 1] ==
'\n' ||
826 result = (
text *) xmlBuffer_to_xmltype(
buf);
858 Datum *named_argvalue,
bool *named_argnull,
859 Datum *argvalue,
bool *argnull)
863 List *named_arg_strings;
869 volatile xmlBufferPtr
buf = NULL;
870 volatile xmlTextWriterPtr writer = NULL;
879 named_arg_strings =
NIL;
886 if (named_argnull[
i])
892 named_arg_strings =
lappend(named_arg_strings,
str);
918 buf = xmlBufferCreate();
919 if (
buf == NULL || xmlerrcxt->err_occurred)
921 "could not allocate xmlBuffer");
922 writer = xmlNewTextWriterMemory(
buf, 0);
923 if (writer == NULL || xmlerrcxt->err_occurred)
925 "could not allocate xmlTextWriter");
927 xmlTextWriterStartElement(writer, (xmlChar *) xexpr->name);
929 forboth(
arg, named_arg_strings, narg, xexpr->arg_names)
935 xmlTextWriterWriteAttribute(writer,
940 foreach(
arg, arg_strings)
944 xmlTextWriterWriteRaw(writer, (xmlChar *)
str);
947 xmlTextWriterEndElement(writer);
950 xmlFreeTextWriter(writer);
953 result = xmlBuffer_to_xmltype(
buf);
958 xmlFreeTextWriter(writer);
986 doc = xml_parse(
data, xmloption_arg, preserve_whitespace,
999 xmlpi(
const char *target,
text *
arg,
bool arg_is_null,
bool *result_is_null)
1007 (
errcode(ERRCODE_INVALID_XML_PROCESSING_INSTRUCTION),
1008 errmsg(
"invalid XML processing instruction"),
1009 errdetail(
"XML processing instruction target name cannot be \"%s\".", target)));
1015 *result_is_null = arg_is_null;
1016 if (*result_is_null)
1028 if (strstr(
string,
"?>") != NULL)
1030 (
errcode(ERRCODE_INVALID_XML_PROCESSING_INSTRUCTION),
1031 errmsg(
"invalid XML processing instruction"),
1032 errdetail(
"XML processing instruction cannot contain \"?>\".")));
1056 xmlChar *orig_version;
1057 int orig_standalone;
1063 parse_xml_decl((xmlChar *)
str, &
len, &orig_version, NULL, &orig_standalone);
1066 orig_version = xml_text2xmlChar(version);
1068 orig_version = NULL;
1073 orig_standalone = 1;
1076 orig_standalone = 0;
1079 orig_standalone = -1;
1087 print_xml_decl(&
buf, orig_version, 0, orig_standalone);
1110 (
errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1111 errmsg(
"xmlvalidate is not implemented")));
1155 static bool first_time =
true;
1165 if (
sizeof(
char) !=
sizeof(xmlChar))
1167 (
errmsg(
"could not initialize XML library"),
1168 errdetail(
"libxml2 has incompatible char type: sizeof(char)=%zu, sizeof(xmlChar)=%zu.",
1169 sizeof(
char),
sizeof(xmlChar))));
1171 #ifdef USE_LIBXMLCONTEXT
1177 LIBXML_TEST_VERSION;
1209 errcxt->magic = ERRCXT_MAGIC;
1210 errcxt->strictness = strictness;
1211 errcxt->err_occurred =
false;
1221 errcxt->saved_errfunc = xmlStructuredError;
1223 #ifdef HAVE_XMLSTRUCTUREDERRORCONTEXT
1224 errcxt->saved_errcxt = xmlStructuredErrorContext;
1226 errcxt->saved_errcxt = xmlGenericErrorContext;
1229 xmlSetStructuredErrorFunc(errcxt, xml_errorHandler);
1245 #ifdef HAVE_XMLSTRUCTUREDERRORCONTEXT
1246 new_errcxt = xmlStructuredErrorContext;
1248 new_errcxt = xmlGenericErrorContext;
1251 if (new_errcxt != errcxt)
1253 (
errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1254 errmsg(
"could not set up XML error handler"),
1255 errhint(
"This probably indicates that the version of libxml2"
1256 " being used is not compatible with the libxml2"
1257 " header files that PostgreSQL was built with.")));
1263 errcxt->saved_entityfunc = xmlGetExternalEntityLoader();
1264 xmlSetExternalEntityLoader(xmlPgEntityLoader);
1285 Assert(errcxt->magic == ERRCXT_MAGIC);
1292 Assert(!errcxt->err_occurred || isError);
1299 #ifdef HAVE_XMLSTRUCTUREDERRORCONTEXT
1300 cur_errcxt = xmlStructuredErrorContext;
1302 cur_errcxt = xmlGenericErrorContext;
1305 if (cur_errcxt != errcxt)
1306 elog(
WARNING,
"libxml error handling state is out of sync with xml.c");
1309 xmlSetStructuredErrorFunc(errcxt->saved_errcxt, errcxt->saved_errfunc);
1310 xmlSetExternalEntityLoader(errcxt->saved_entityfunc);
1319 pfree(errcxt->err_buf.data);
1330 return errcxt->err_occurred;
1343 #define CHECK_XML_SPACE(p) \
1345 if (!xmlIsBlank_ch(*(p))) \
1346 return XML_ERR_SPACE_REQUIRED; \
1349 #define SKIP_XML_SPACE(p) \
1350 while (xmlIsBlank_ch(*(p))) (p)++
1354 #define PG_XMLISNAMECHAR(c) \
1355 (xmlIsBaseChar_ch(c) || xmlIsIdeographicQ(c) \
1356 || xmlIsDigit_ch(c) \
1357 || c == '.' || c == '-' || c == '_' || c == ':' \
1358 || xmlIsCombiningQ(c) \
1359 || xmlIsExtender_ch(c))
1363 xml_pnstrdup(
const xmlChar *
str,
size_t len)
1367 result = (xmlChar *)
palloc((
len + 1) *
sizeof(xmlChar));
1368 memcpy(result,
str,
len *
sizeof(xmlChar));
1375 pg_xmlCharStrndup(
const char *
str,
size_t len)
1379 result = (xmlChar *)
palloc((
len + 1) *
sizeof(xmlChar));
1380 memcpy(result,
str,
len);
1392 xml_pstrdup_and_free(xmlChar *
str)
1421 parse_xml_decl(
const xmlChar *
str,
size_t *lenp,
1422 xmlChar **version, xmlChar **
encoding,
int *standalone)
1425 const xmlChar *save_p;
1448 if (xmlStrncmp(p, (xmlChar *)
"<?xml", 5) != 0)
1460 utf8char = xmlGetUTF8Char(p + 5, &utf8len);
1461 if (PG_XMLISNAMECHAR(utf8char))
1469 if (xmlStrncmp(p, (xmlChar *)
"version", 7) != 0)
1470 return XML_ERR_VERSION_MISSING;
1474 return XML_ERR_VERSION_MISSING;
1478 if (*p ==
'\'' || *p ==
'"')
1482 q = xmlStrchr(p + 1, *p);
1484 return XML_ERR_VERSION_MISSING;
1487 *version = xml_pnstrdup(p + 1, q - p - 1);
1491 return XML_ERR_VERSION_MISSING;
1496 if (xmlStrncmp(p, (xmlChar *)
"encoding", 8) == 0)
1498 CHECK_XML_SPACE(save_p);
1502 return XML_ERR_MISSING_ENCODING;
1506 if (*p ==
'\'' || *p ==
'"')
1510 q = xmlStrchr(p + 1, *p);
1512 return XML_ERR_MISSING_ENCODING;
1515 *
encoding = xml_pnstrdup(p + 1, q - p - 1);
1519 return XML_ERR_MISSING_ENCODING;
1529 if (xmlStrncmp(p, (xmlChar *)
"standalone", 10) == 0)
1531 CHECK_XML_SPACE(save_p);
1535 return XML_ERR_STANDALONE_VALUE;
1538 if (xmlStrncmp(p, (xmlChar *)
"'yes'", 5) == 0 ||
1539 xmlStrncmp(p, (xmlChar *)
"\"yes\"", 5) == 0)
1545 else if (xmlStrncmp(p, (xmlChar *)
"'no'", 4) == 0 ||
1546 xmlStrncmp(p, (xmlChar *)
"\"no\"", 4) == 0)
1553 return XML_ERR_STANDALONE_VALUE;
1561 if (xmlStrncmp(p, (xmlChar *)
"?>", 2) != 0)
1562 return XML_ERR_XMLDECL_NOT_FINISHED;
1570 return XML_ERR_INVALID_CHAR;
1599 || standalone != -1)
1618 if (standalone == 1)
1620 else if (standalone == 0)
1660 xml_doctype_in_content(
const xmlChar *
str)
1662 const xmlChar *p =
str;
1678 if (xmlStrncmp(p, (xmlChar *)
"DOCTYPE", 7) == 0)
1682 if (xmlStrncmp(p, (xmlChar *)
"--", 2) != 0)
1685 p = xmlStrstr(p + 2, (xmlChar *)
"--");
1686 if (!p || p[2] !=
'>')
1699 e = xmlStrstr(p, (xmlChar *)
"?>");
1737 bool preserve_whitespace,
int encoding,
1738 XmlOptionType *parsed_xmloptiontype, xmlNodePtr *parsed_nodes,
1743 xmlChar *utf8string;
1745 volatile xmlParserCtxtPtr ctxt = NULL;
1746 volatile xmlDocPtr doc = NULL;
1753 string = xml_text2xmlChar(
data);
1773 bool parse_as_document =
false;
1777 xmlChar *version = NULL;
1785 parse_as_document =
true;
1789 res_code = parse_xml_decl(utf8string,
1790 &count, &version, NULL, &standalone);
1794 errcode(ERRCODE_INVALID_XML_CONTENT),
1796 errdetail_for_xml_code(res_code));
1801 if (xml_doctype_in_content(utf8string + count))
1802 parse_as_document =
true;
1814 options = XML_PARSE_NOENT | XML_PARSE_DTDATTR
1815 | (preserve_whitespace ? 0 : XML_PARSE_NOBLANKS);
1818 if (parsed_xmloptiontype != NULL)
1821 if (parsed_nodes != NULL)
1822 *parsed_nodes = NULL;
1824 if (parse_as_document)
1826 ctxt = xmlNewParserCtxt();
1827 if (ctxt == NULL || xmlerrcxt->err_occurred)
1829 "could not allocate parser context");
1831 doc = xmlCtxtReadDoc(ctxt, utf8string,
1836 if (doc == NULL || xmlerrcxt->err_occurred)
1840 xml_errsave(escontext, xmlerrcxt,
1841 ERRCODE_INVALID_XML_DOCUMENT,
1842 "invalid XML document");
1844 xml_errsave(escontext, xmlerrcxt,
1845 ERRCODE_INVALID_XML_CONTENT,
1846 "invalid XML content");
1855 doc = xmlNewDoc(version);
1856 if (doc == NULL || xmlerrcxt->err_occurred)
1858 "could not allocate XML document");
1860 Assert(doc->encoding == NULL);
1861 doc->encoding = xmlStrdup((
const xmlChar *)
"UTF-8");
1862 if (doc->encoding == NULL || xmlerrcxt->err_occurred)
1864 "could not allocate XML document");
1865 doc->standalone = standalone;
1867 root = xmlNewNode(NULL, (
const xmlChar *)
"content-root");
1868 if (
root == NULL || xmlerrcxt->err_occurred)
1870 "could not allocate xml node");
1872 xmlDocSetRootElement(doc,
root);
1875 if (*(utf8string + count))
1877 xmlNodePtr node_list = NULL;
1878 xmlParserErrors
res;
1880 res = xmlParseInNodeContext(
root,
1881 (
char *) utf8string + count,
1882 strlen((
char *) utf8string + count),
1886 if (
res != XML_ERR_OK || xmlerrcxt->err_occurred)
1888 xmlFreeNodeList(node_list);
1889 xml_errsave(escontext, xmlerrcxt,
1890 ERRCODE_INVALID_XML_CONTENT,
1891 "invalid XML content");
1895 if (parsed_nodes != NULL)
1896 *parsed_nodes = node_list;
1898 xmlFreeNodeList(node_list);
1910 xmlFreeParserCtxt(ctxt);
1919 xmlFreeParserCtxt(ctxt);
1931 xml_text2xmlChar(
text *in)
1937 #ifdef USE_LIBXMLCONTEXT
1944 xml_memory_init(
void)
1947 if (LibxmlContext == NULL)
1953 xmlMemSetup(xml_pfree, xml_palloc, xml_repalloc, xml_pstrdup);
1960 xml_palloc(
size_t size)
1967 xml_repalloc(
void *ptr,
size_t size)
1974 xml_pfree(
void *ptr)
1983 xml_pstrdup(
const char *
string)
2001 static xmlParserInputPtr
2002 xmlPgEntityLoader(
const char *URL,
const char *ID,
2003 xmlParserCtxtPtr ctxt)
2005 return xmlNewStringInputStream(ctxt, (
const xmlChar *)
"");
2025 if (errcxt->magic != ERRCXT_MAGIC)
2026 elog(
ERROR,
"xml_ereport called with invalid PgXmlErrorContext");
2029 errcxt->err_occurred =
false;
2032 if (errcxt->err_buf.len > 0)
2033 detail = errcxt->err_buf.data;
2058 int sqlcode,
const char *msg)
2063 if (errcxt->magic != ERRCXT_MAGIC)
2064 elog(
ERROR,
"xml_errsave called with invalid PgXmlErrorContext");
2067 errcxt->err_occurred =
false;
2070 if (errcxt->err_buf.len > 0)
2071 detail = errcxt->err_buf.data;
2086 xml_errorHandler(
void *
data, PgXmlErrorPtr
error)
2089 xmlParserCtxtPtr ctxt = (xmlParserCtxtPtr)
error->ctxt;
2090 xmlParserInputPtr
input = (ctxt != NULL) ? ctxt->input : NULL;
2091 xmlNodePtr node =
error->node;
2092 const xmlChar *
name = (node != NULL &&
2093 node->type == XML_ELEMENT_NODE) ? node->name : NULL;
2094 int domain =
error->domain;
2095 int level =
error->level;
2104 if (xmlerrcxt->magic != ERRCXT_MAGIC)
2105 elog(
FATAL,
"xml_errorHandler called with invalid PgXmlErrorContext");
2115 switch (
error->code)
2117 case XML_WAR_NS_URI:
2118 level = XML_ERR_ERROR;
2119 domain = XML_FROM_NAMESPACE;
2122 case XML_ERR_NS_DECL_ERROR:
2123 case XML_WAR_NS_URI_RELATIVE:
2124 case XML_WAR_NS_COLUMN:
2125 case XML_NS_ERR_XML_NAMESPACE:
2126 case XML_NS_ERR_UNDEFINED_NAMESPACE:
2127 case XML_NS_ERR_QNAME:
2128 case XML_NS_ERR_ATTRIBUTE_REDEFINED:
2129 case XML_NS_ERR_EMPTY:
2130 domain = XML_FROM_NAMESPACE;
2137 case XML_FROM_PARSER:
2146 if (
error->code == XML_ERR_NOT_WELL_BALANCED &&
2147 xmlerrcxt->err_occurred)
2152 case XML_FROM_MEMORY:
2159 if (
error->code == XML_WAR_UNDECLARED_ENTITY)
2175 if (
error->line > 0)
2179 if (
error->message != NULL)
2197 xmlGenericErrorFunc errFuncSaved = xmlGenericError;
2198 void *errCtxSaved = xmlGenericErrorContext;
2200 xmlSetGenericErrorFunc(errorBuf,
2204 appendStringInfoLineSeparator(errorBuf);
2206 xmlParserPrintFileContext(
input);
2209 xmlSetGenericErrorFunc(errCtxSaved, errFuncSaved);
2213 chopStringInfoNewlines(errorBuf);
2225 appendStringInfoLineSeparator(&xmlerrcxt->err_buf);
2241 if (level >= XML_ERR_ERROR)
2243 appendStringInfoLineSeparator(&xmlerrcxt->err_buf);
2247 xmlerrcxt->err_occurred =
true;
2249 else if (level >= XML_ERR_WARNING)
2274 errdetail_for_xml_code(
int code)
2280 case XML_ERR_INVALID_CHAR:
2283 case XML_ERR_SPACE_REQUIRED:
2286 case XML_ERR_STANDALONE_VALUE:
2287 det =
gettext_noop(
"standalone accepts only 'yes' or 'no'.");
2289 case XML_ERR_VERSION_MISSING:
2290 det =
gettext_noop(
"Malformed declaration: missing version.");
2292 case XML_ERR_MISSING_ENCODING:
2293 det =
gettext_noop(
"Missing encoding in text declaration.");
2295 case XML_ERR_XMLDECL_NOT_FINISHED:
2296 det =
gettext_noop(
"Parsing XML declaration: '?>' expected.");
2299 det =
gettext_noop(
"Unrecognized libxml error code: %d.");
2313 while (
str->len > 0 &&
str->data[
str->len - 1] ==
'\n')
2314 str->data[--
str->len] =
'\0';
2324 chopStringInfoNewlines(
str);
2334 sqlchar_to_unicode(
const char *s)
2345 if (utf8string != s)
2356 return (xmlIsBaseCharQ(
c) || xmlIsIdeographicQ(
c)
2357 ||
c ==
'_' ||
c ==
':');
2365 return (xmlIsBaseCharQ(
c) || xmlIsIdeographicQ(
c)
2367 ||
c ==
'.' ||
c ==
'-' ||
c ==
'_' ||
c ==
':'
2368 || xmlIsCombiningQ(
c)
2369 || xmlIsExtenderQ(
c));
2389 Assert(fully_escaped || !escape_period);
2395 if (*p ==
':' && (p ==
ident || fully_escaped))
2397 else if (*p ==
'_' && *(p + 1) ==
'x')
2399 else if (fully_escaped && p ==
ident &&
2407 else if (escape_period && *p ==
'.')
2411 pg_wchar u = sqlchar_to_unicode(p);
2414 ? !is_valid_xml_namefirst(u)
2415 : !is_valid_xml_namechar(u))
2443 if (*p ==
'_' && *(p + 1) ==
'x'
2444 && isxdigit((
unsigned char) *(p + 2))
2445 && isxdigit((
unsigned char) *(p + 3))
2446 && isxdigit((
unsigned char) *(p + 4))
2447 && isxdigit((
unsigned char) *(p + 5))
2453 sscanf(p + 2,
"%X", &u);
2496 elmlen, elmbyval, elmalign,
2497 &elem_values, &elem_nulls,
2502 for (
i = 0;
i < num_elems;
i++)
2551 (
errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2552 errmsg(
"date out of range"),
2553 errdetail(
"XML does not support infinite date values.")));
2573 (
errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2574 errmsg(
"timestamp out of range"),
2575 errdetail(
"XML does not support infinite timestamp values.")));
2580 (
errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2581 errmsg(
"timestamp out of range")));
2586 case TIMESTAMPTZOID:
2592 const char *tzn = NULL;
2600 (
errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2601 errmsg(
"timestamp out of range"),
2602 errdetail(
"XML does not support infinite timestamp values.")));
2607 (
errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2608 errmsg(
"timestamp out of range")));
2618 volatile xmlBufferPtr
buf = NULL;
2619 volatile xmlTextWriterPtr writer = NULL;
2626 buf = xmlBufferCreate();
2627 if (
buf == NULL || xmlerrcxt->err_occurred)
2629 "could not allocate xmlBuffer");
2630 writer = xmlNewTextWriterMemory(
buf, 0);
2631 if (writer == NULL || xmlerrcxt->err_occurred)
2633 "could not allocate xmlTextWriter");
2636 xmlTextWriterWriteBase64(writer,
VARDATA_ANY(bstr),
2639 xmlTextWriterWriteBinHex(writer,
VARDATA_ANY(bstr),
2643 xmlFreeTextWriter(writer);
2646 result =
pstrdup((
const char *) xmlBufferContent(
buf));
2651 xmlFreeTextWriter(writer);
2678 if (
type == XMLOID || !xml_escape_strings)
2701 for (p =
str; *p; p++)
2729 size_t len = strlen(s) + 1;
2732 memcpy(ret, s,
len);
2792 elog(
ERROR,
"SPI_execute returned %s for %s",
2819 " WHERE relnamespace = %u AND relkind IN ("
2823 " AND pg_catalog.has_table_privilege (oid, 'SELECT')"
2824 " ORDER BY relname;",
nspid);
2834 #define XML_VISIBLE_SCHEMAS_EXCLUDE "(nspname ~ '^pg_' OR nspname = 'information_schema')"
2836 #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
2851 " WHERE relkind IN ("
2855 " AND pg_catalog.has_table_privilege(pg_class.oid, 'SELECT')"
2867 const char *xmlschema,
bool nulls,
bool tableforest,
2868 const char *targetns,
bool top_level)
2877 xmlschema, nulls, tableforest,
2878 targetns, top_level);
2905 NULL, nulls, tableforest,
2935 (
errcode(ERRCODE_UNDEFINED_CURSOR),
2936 errmsg(
"cursor \"%s\" does not exist",
name)));
2941 tableforest, targetns,
true);
2966 const char *xmlschema,
const char *targetns,
2970 Assert(top_level || !xmlschema);
2976 if (strlen(targetns) > 0)
2982 if (strlen(targetns) > 0)
3000 const char *xmlschema,
bool nulls,
bool tableforest,
3001 const char *targetns,
bool top_level)
3017 (
errcode(ERRCODE_DATA_EXCEPTION),
3018 errmsg(
"invalid query")));
3023 targetns, top_level);
3032 tableforest, targetns, top_level);
3055 tableforest, targetns);
3076 elog(
ERROR,
"SPI_prepare(\"%s\") failed", query);
3079 elog(
ERROR,
"SPI_cursor_open(\"%s\") failed", query);
3083 tableforest, targetns));
3098 const char *xmlschema;
3105 (
errcode(ERRCODE_UNDEFINED_CURSOR),
3106 errmsg(
"cursor \"%s\" does not exist",
name)));
3109 (
errcode(ERRCODE_INVALID_CURSOR_STATE),
3110 errmsg(
"portal \"%s\" does not return tuples",
name)));
3114 tableforest, targetns));
3129 const char *xmlschema;
3133 tableforest, targetns);
3137 xmlschema, nulls, tableforest,
3150 const char *xmlschema;
3157 elog(
ERROR,
"SPI_prepare(\"%s\") failed", query);
3160 elog(
ERROR,
"SPI_cursor_open(\"%s\") failed", query);
3168 xmlschema, nulls, tableforest,
3180 bool tableforest,
const char *targetns,
bool top_level)
3201 foreach(cell, relid_list)
3236 nulls, tableforest, targetns,
true)));
3249 if (strlen(targetns) > 0)
3252 " targetNamespace=\"%s\"\n"
3253 " elementFormDefault=\"qualified\"",
3269 bool tableforest,
const char *targetns)
3288 foreach(cell, relid_list)
3302 nulls, tableforest, targetns));
3321 nulls, tableforest, targetns)));
3340 tableforest, targetns);
3343 xmlschema->
data, nulls,
3344 tableforest, targetns,
true)));
3355 bool tableforest,
const char *targetns)
3376 foreach(cell, nspid_list)
3382 tableforest, targetns,
false);
3404 tableforest, targetns)));
3410 const char *targetns)
3428 foreach(cell, relid_list)
3459 tableforest, targetns)));
3474 nulls, tableforest, targetns)));
3515 bool tableforest,
const char *targetns)
3519 char *tabletypename;
3532 elog(
ERROR,
"cache lookup failed for relation %u", relid);
3557 tabletypename =
"TableType";
3558 rowtypename =
"RowType";
3567 "<xsd:complexType name=\"%s\">\n"
3568 " <xsd:sequence>\n",
3571 for (
i = 0;
i < tupdesc->
natts;
i++)
3575 if (att->attisdropped)
3578 " <xsd:element name=\"%s\" type=\"%s\"%s></xsd:element>\n",
3582 nulls ?
" nillable=\"true\"" :
" minOccurs=\"0\"");
3586 " </xsd:sequence>\n"
3587 "</xsd:complexType>\n\n");
3592 "<xsd:complexType name=\"%s\">\n"
3594 " <xsd:element name=\"row\" type=\"%s\" minOccurs=\"0\" maxOccurs=\"unbounded\"/>\n"
3595 " </xsd:sequence>\n"
3596 "</xsd:complexType>\n\n",
3597 tabletypename, rowtypename);
3600 "<xsd:element name=\"%s\" type=\"%s\"/>\n\n",
3601 xmltn, tabletypename);
3605 "<xsd:element name=\"%s\" type=\"%s\"/>\n\n",
3606 xmltn, rowtypename);
3620 bool tableforest,
const char *targetns)
3625 char *schematypename;
3642 "<xsd:complexType name=\"%s\">\n", schematypename);
3648 " <xsd:sequence>\n");
3650 foreach(cell, relid_list)
3662 " <xsd:element name=\"%s\" type=\"%s\"/>\n",
3663 xmltn, tabletypename);
3666 " <xsd:element name=\"%s\" type=\"%s\" minOccurs=\"0\" maxOccurs=\"unbounded\"/>\n",
3667 xmltn, tabletypename);
3675 " </xsd:sequence>\n");
3677 "</xsd:complexType>\n\n");
3680 "<xsd:element name=\"%s\" type=\"%s\"/>\n\n",
3681 xmlsn, schematypename);
3693 bool tableforest,
const char *targetns)
3697 char *catalogtypename;
3713 "<xsd:complexType name=\"%s\">\n", catalogtypename);
3717 foreach(cell, nspid_list)
3728 " <xsd:element name=\"%s\" type=\"%s\"/>\n",
3729 xmlsn, schematypename);
3735 "</xsd:complexType>\n\n");
3738 "<xsd:element name=\"%s\" type=\"%s\"/>\n\n",
3739 xmlcn, catalogtypename);
3774 ((typmod -
VARHDRSZ) >> 16) & 0xffff,
3813 case TIMESTAMPTZOID:
3832 elog(
ERROR,
"cache lookup failed for type %u", typeoid);
3862 foreach(cell0, tupdesc_list)
3866 for (
i = 0;
i < tupdesc->
natts;
i++)
3870 if (att->attisdropped)
3877 foreach(cell0, uniquetypes)
3882 if (basetypid != typid)
3889 foreach(cell0, uniquetypes)
3916 if (typeoid == XMLOID)
3919 "<xsd:complexType mixed=\"true\">\n"
3921 " <xsd:any name=\"element\" minOccurs=\"0\" maxOccurs=\"unbounded\" processContents=\"skip\"/>\n"
3922 " </xsd:sequence>\n"
3923 "</xsd:complexType>\n");
3928 "<xsd:simpleType name=\"%s\">\n",
typename);
3936 " <xsd:restriction base=\"xsd:string\">\n");
3939 " <xsd:maxLength value=\"%d\"/>\n",
3946 " <xsd:restriction base=\"xsd:%s\">\n"
3947 " </xsd:restriction>\n",
3954 " <xsd:restriction base=\"xsd:decimal\">\n"
3955 " <xsd:totalDigits value=\"%d\"/>\n"
3956 " <xsd:fractionDigits value=\"%d\"/>\n"
3957 " </xsd:restriction>\n",
3958 ((typmod -
VARHDRSZ) >> 16) & 0xffff,
3964 " <xsd:restriction base=\"xsd:short\">\n"
3965 " <xsd:maxInclusive value=\"%d\"/>\n"
3966 " <xsd:minInclusive value=\"%d\"/>\n"
3967 " </xsd:restriction>\n",
3968 SHRT_MAX, SHRT_MIN);
3973 " <xsd:restriction base=\"xsd:int\">\n"
3974 " <xsd:maxInclusive value=\"%d\"/>\n"
3975 " <xsd:minInclusive value=\"%d\"/>\n"
3976 " </xsd:restriction>\n",
3982 " <xsd:restriction base=\"xsd:long\">\n"
3985 " </xsd:restriction>\n",
3992 " <xsd:restriction base=\"xsd:float\"></xsd:restriction>\n");
3997 " <xsd:restriction base=\"xsd:double\"></xsd:restriction>\n");
4002 " <xsd:restriction base=\"xsd:boolean\"></xsd:restriction>\n");
4008 const char *tz = (typeoid == TIMETZOID ?
"(\\+|-)\\p{Nd}{2}:\\p{Nd}{2}" :
"");
4012 " <xsd:restriction base=\"xsd:time\">\n"
4013 " <xsd:pattern value=\"\\p{Nd}{2}:\\p{Nd}{2}:\\p{Nd}{2}(.\\p{Nd}+)?%s\"/>\n"
4014 " </xsd:restriction>\n", tz);
4015 else if (typmod == 0)
4017 " <xsd:restriction base=\"xsd:time\">\n"
4018 " <xsd:pattern value=\"\\p{Nd}{2}:\\p{Nd}{2}:\\p{Nd}{2}%s\"/>\n"
4019 " </xsd:restriction>\n", tz);
4022 " <xsd:restriction base=\"xsd:time\">\n"
4023 " <xsd:pattern value=\"\\p{Nd}{2}:\\p{Nd}{2}:\\p{Nd}{2}.\\p{Nd}{%d}%s\"/>\n"
4024 " </xsd:restriction>\n", typmod -
VARHDRSZ, tz);
4029 case TIMESTAMPTZOID:
4031 const char *tz = (typeoid == TIMESTAMPTZOID ?
"(\\+|-)\\p{Nd}{2}:\\p{Nd}{2}" :
"");
4035 " <xsd:restriction base=\"xsd:dateTime\">\n"
4036 " <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"
4037 " </xsd:restriction>\n", tz);
4038 else if (typmod == 0)
4040 " <xsd:restriction base=\"xsd:dateTime\">\n"
4041 " <xsd:pattern value=\"\\p{Nd}{4}-\\p{Nd}{2}-\\p{Nd}{2}T\\p{Nd}{2}:\\p{Nd}{2}:\\p{Nd}{2}%s\"/>\n"
4042 " </xsd:restriction>\n", tz);
4045 " <xsd:restriction base=\"xsd:dateTime\">\n"
4046 " <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"
4047 " </xsd:restriction>\n", typmod -
VARHDRSZ, tz);
4053 " <xsd:restriction base=\"xsd:date\">\n"
4054 " <xsd:pattern value=\"\\p{Nd}{4}-\\p{Nd}{2}-\\p{Nd}{2}\"/>\n"
4055 " </xsd:restriction>\n");
4062 int32 base_typmod = -1;
4067 " <xsd:restriction base=\"%s\"/>\n",
4085 bool nulls,
bool tableforest,
4086 const char *targetns,
bool top_level)
4158 if (
cur->type != XML_ATTRIBUTE_NODE &&
cur->type != XML_TEXT_NODE)
4160 void (*
volatile nodefree) (xmlNodePtr) = NULL;
4161 volatile xmlBufferPtr
buf = NULL;
4162 volatile xmlNodePtr cur_copy = NULL;
4168 buf = xmlBufferCreate();
4169 if (
buf == NULL || xmlerrcxt->err_occurred)
4171 "could not allocate xmlBuffer");
4185 cur_copy = xmlCopyNode(
cur, 1);
4186 if (cur_copy == NULL || xmlerrcxt->err_occurred)
4188 "could not copy node");
4189 nodefree = (cur_copy->type == XML_DOCUMENT_NODE) ?
4190 (
void (*) (xmlNodePtr)) xmlFreeDoc : xmlFreeNode;
4192 bytes = xmlNodeDump(
buf, NULL, cur_copy, 0, 0);
4193 if (bytes == -1 || xmlerrcxt->err_occurred)
4195 "could not dump node");
4197 result = xmlBuffer_to_xmltype(
buf);
4212 str = xmlXPathCastNodeToString(
cur);
4244 xml_xpathobjtoxmlarray(xmlXPathObjectPtr xpathobj,
4253 switch (xpathobj->type)
4256 if (xpathobj->nodesetval != NULL)
4258 result = xpathobj->nodesetval->nodeNr;
4263 for (
i = 0;
i < result;
i++)
4265 datum =
PointerGetDatum(xml_xmlnodetoxmltype(xpathobj->nodesetval->nodeTab[
i],
4278 datumtype = BOOLOID;
4285 datumtype = FLOAT8OID;
4292 datumtype = CSTRINGOID;
4296 elog(
ERROR,
"xpath expression result type %d is unsupported",
4326 volatile xmlParserCtxtPtr ctxt = NULL;
4327 volatile xmlDocPtr doc = NULL;
4328 volatile xmlXPathContextPtr xpathctx = NULL;
4329 volatile xmlXPathCompExprPtr xpathcomp = NULL;
4330 volatile xmlXPathObjectPtr xpathobj = NULL;
4335 xmlChar *xpath_expr;
4336 size_t xmldecl_len = 0;
4339 Datum *ns_names_uris;
4340 bool *ns_names_uris_nulls;
4352 ndim = namespaces ?
ARR_NDIM(namespaces) : 0;
4359 if (ndim != 2 || dims[1] != 2)
4361 (
errcode(ERRCODE_DATA_EXCEPTION),
4362 errmsg(
"invalid array for XML namespace mapping"),
4363 errdetail(
"The array must be two-dimensional with length of the second axis equal to 2.")));
4368 &ns_names_uris, &ns_names_uris_nulls,
4371 Assert((ns_count % 2) == 0);
4376 ns_names_uris = NULL;
4377 ns_names_uris_nulls = NULL;
4386 (
errcode(ERRCODE_INVALID_ARGUMENT_FOR_XQUERY),
4387 errmsg(
"empty XPath expression")));
4389 string = pg_xmlCharStrndup(datastr,
len);
4390 xpath_expr = pg_xmlCharStrndup(
VARDATA_ANY(xpath_expr_text), xpath_len);
4400 parse_xml_decl(
string, &xmldecl_len, NULL, NULL, NULL);
4412 ctxt = xmlNewParserCtxt();
4413 if (ctxt == NULL || xmlerrcxt->err_occurred)
4415 "could not allocate parser context");
4416 doc = xmlCtxtReadMemory(ctxt, (
char *)
string + xmldecl_len,
4417 len - xmldecl_len, NULL, NULL, 0);
4418 if (doc == NULL || xmlerrcxt->err_occurred)
4420 "could not parse XML document");
4421 xpathctx = xmlXPathNewContext(doc);
4422 if (xpathctx == NULL || xmlerrcxt->err_occurred)
4424 "could not allocate XPath context");
4425 xpathctx->node = (xmlNodePtr) doc;
4430 for (
i = 0;
i < ns_count;
i++)
4435 if (ns_names_uris_nulls[
i * 2] ||
4436 ns_names_uris_nulls[
i * 2 + 1])
4438 (
errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
4439 errmsg(
"neither namespace name nor URI may be null")));
4442 if (xmlXPathRegisterNs(xpathctx,
4443 (xmlChar *) ns_name,
4444 (xmlChar *) ns_uri) != 0)
4446 (
errmsg(
"could not register XML namespace with name \"%s\" and URI \"%s\"",
4457 xpathcomp = xmlXPathCtxtCompile(xpathctx, xpath_expr);
4458 if (xpathcomp == NULL || xmlerrcxt->err_occurred)
4460 "invalid XPath expression");
4469 xpathobj = xmlXPathCompiledEval(xpathcomp, xpathctx);
4470 if (xpathobj == NULL || xmlerrcxt->err_occurred)
4472 "could not create XPath object");
4477 if (res_nitems != NULL)
4478 *res_nitems = xml_xpathobjtoxmlarray(xpathobj, astate, xmlerrcxt);
4480 (
void) xml_xpathobjtoxmlarray(xpathobj, astate, xmlerrcxt);
4485 xmlXPathFreeObject(xpathobj);
4487 xmlXPathFreeCompExpr(xpathcomp);
4489 xmlXPathFreeContext(xpathctx);
4493 xmlFreeParserCtxt(ctxt);
4501 xmlXPathFreeObject(xpathobj);
4502 xmlXPathFreeCompExpr(xpathcomp);
4503 xmlXPathFreeContext(xpathctx);
4505 xmlFreeParserCtxt(ctxt);
4528 xpath_internal(xpath_expr_text,
data, namespaces,
4549 xpath_internal(xpath_expr_text,
data, NULL,
4573 xpath_internal(xpath_expr_text,
data, namespaces,
4597 doc = xml_parse(
data, xmloption_arg,
true,
4655 static inline XmlTableBuilderData *
4658 XmlTableBuilderData *result;
4661 elog(
ERROR,
"%s called with invalid TableFuncScanState", fname);
4662 result = (XmlTableBuilderData *)
state->opaque;
4663 if (result->magic != XMLTABLE_CONTEXT_MAGIC)
4664 elog(
ERROR,
"%s called with invalid TableFuncScanState", fname);
4685 volatile xmlParserCtxtPtr ctxt = NULL;
4686 XmlTableBuilderData *xtCxt;
4689 xtCxt =
palloc0(
sizeof(XmlTableBuilderData));
4690 xtCxt->magic = XMLTABLE_CONTEXT_MAGIC;
4691 xtCxt->natts = natts;
4692 xtCxt->xpathscomp =
palloc0(
sizeof(xmlXPathCompExprPtr) * natts);
4700 ctxt = xmlNewParserCtxt();
4701 if (ctxt == NULL || xmlerrcxt->err_occurred)
4703 "could not allocate parser context");
4708 xmlFreeParserCtxt(ctxt);
4716 xtCxt->xmlerrcxt = xmlerrcxt;
4719 state->opaque = xtCxt;
4733 XmlTableBuilderData *xtCxt;
4738 volatile xmlDocPtr doc = NULL;
4739 volatile xmlXPathContextPtr xpathcxt = NULL;
4741 xtCxt = GetXmlTableBuilderPrivateData(
state,
"XmlTableSetDocument");
4749 length = strlen(
str);
4750 xstr = pg_xmlCharStrndup(
str, length);
4754 doc = xmlCtxtReadMemory(xtCxt->ctxt, (
char *) xstr, length, NULL, NULL, 0);
4755 if (doc == NULL || xtCxt->xmlerrcxt->err_occurred)
4757 "could not parse XML document");
4758 xpathcxt = xmlXPathNewContext(doc);
4759 if (xpathcxt == NULL || xtCxt->xmlerrcxt->err_occurred)
4761 "could not allocate XPath context");
4762 xpathcxt->node = (xmlNodePtr) doc;
4766 if (xpathcxt != NULL)
4767 xmlXPathFreeContext(xpathcxt);
4776 xtCxt->xpathcxt = xpathcxt;
4790 XmlTableBuilderData *xtCxt;
4794 (
errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4795 errmsg(
"DEFAULT namespace is not supported")));
4796 xtCxt = GetXmlTableBuilderPrivateData(
state,
"XmlTableSetNamespace");
4798 if (xmlXPathRegisterNs(xtCxt->xpathcxt,
4799 pg_xmlCharStrndup(
name, strlen(
name)),
4800 pg_xmlCharStrndup(uri, strlen(uri))))
4802 "could not set XML namespace");
4816 XmlTableBuilderData *xtCxt;
4819 xtCxt = GetXmlTableBuilderPrivateData(
state,
"XmlTableSetRowFilter");
4823 (
errcode(ERRCODE_INVALID_ARGUMENT_FOR_XQUERY),
4824 errmsg(
"row path filter must not be empty string")));
4826 xstr = pg_xmlCharStrndup(path, strlen(path));
4829 Assert(xtCxt->xpathcxt != NULL);
4831 xtCxt->xpathcomp = xmlXPathCtxtCompile(xtCxt->xpathcxt, xstr);
4832 if (xtCxt->xpathcomp == NULL || xtCxt->xmlerrcxt->err_occurred)
4834 "invalid XPath expression");
4848 XmlTableBuilderData *xtCxt;
4853 xtCxt = GetXmlTableBuilderPrivateData(
state,
"XmlTableSetColumnFilter");
4857 (
errcode(ERRCODE_INVALID_ARGUMENT_FOR_XQUERY),
4858 errmsg(
"column path filter must not be empty string")));
4860 xstr = pg_xmlCharStrndup(path, strlen(path));
4863 Assert(xtCxt->xpathcxt != NULL);
4865 xtCxt->xpathscomp[colnum] = xmlXPathCtxtCompile(xtCxt->xpathcxt, xstr);
4866 if (xtCxt->xpathscomp[colnum] == NULL || xtCxt->xmlerrcxt->err_occurred)
4868 "invalid XPath expression");
4883 XmlTableBuilderData *xtCxt;
4885 xtCxt = GetXmlTableBuilderPrivateData(
state,
"XmlTableFetchRow");
4888 xmlSetStructuredErrorFunc(xtCxt->xmlerrcxt, xml_errorHandler);
4890 if (xtCxt->xpathobj == NULL)
4892 xtCxt->xpathobj = xmlXPathCompiledEval(xtCxt->xpathcomp, xtCxt->xpathcxt);
4893 if (xtCxt->xpathobj == NULL || xtCxt->xmlerrcxt->err_occurred)
4895 "could not create XPath object");
4897 xtCxt->row_count = 0;
4900 if (xtCxt->xpathobj->type == XPATH_NODESET)
4902 if (xtCxt->xpathobj->nodesetval != NULL)
4904 if (xtCxt->row_count++ < xtCxt->xpathobj->nodesetval->nodeNr)
4926 Oid typid,
int32 typmod,
bool *isnull)
4929 XmlTableBuilderData *xtCxt;
4933 volatile xmlXPathObjectPtr xpathobj = NULL;
4935 xtCxt = GetXmlTableBuilderPrivateData(
state,
"XmlTableGetValue");
4937 Assert(xtCxt->xpathobj &&
4938 xtCxt->xpathobj->type == XPATH_NODESET &&
4939 xtCxt->xpathobj->nodesetval != NULL);
4942 xmlSetStructuredErrorFunc(xtCxt->xmlerrcxt, xml_errorHandler);
4946 cur = xtCxt->xpathobj->nodesetval->nodeTab[xtCxt->row_count - 1];
4948 Assert(xtCxt->xpathscomp[colnum] != NULL);
4953 xtCxt->xpathcxt->node =
cur;
4956 xpathobj = xmlXPathCompiledEval(xtCxt->xpathscomp[colnum], xtCxt->xpathcxt);
4957 if (xpathobj == NULL || xtCxt->xmlerrcxt->err_occurred)
4959 "could not create XPath object");
4968 if (xpathobj->type == XPATH_NODESET)
4972 if (xpathobj->nodesetval != NULL)
4973 count = xpathobj->nodesetval->nodeNr;
4975 if (xpathobj->nodesetval == NULL || count == 0)
4981 if (typid == XMLOID)
4988 for (
int i = 0;
i < count;
i++)
4991 xml_xmlnodetoxmltype(xpathobj->nodesetval->nodeTab[
i],
5004 (
errcode(ERRCODE_CARDINALITY_VIOLATION),
5005 errmsg(
"more than one value returned by column XPath expression")));
5007 str = xmlXPathCastNodeSetToString(xpathobj->nodesetval);
5008 cstr =
str ? xml_pstrdup_and_free(
str) :
"";
5012 else if (xpathobj->type == XPATH_STRING)
5015 if (typid == XMLOID)
5016 cstr =
escape_xml((
char *) xpathobj->stringval);
5018 cstr = (
char *) xpathobj->stringval;
5020 else if (xpathobj->type == XPATH_BOOLEAN)
5023 bool typispreferred;
5029 if (typcategory != TYPCATEGORY_NUMERIC)
5030 str = xmlXPathCastBooleanToString(xpathobj->boolval);
5032 str = xmlXPathCastNumberToString(xmlXPathCastBooleanToNumber(xpathobj->boolval));
5034 cstr = xml_pstrdup_and_free(
str);
5036 else if (xpathobj->type == XPATH_NUMBER)
5040 str = xmlXPathCastNumberToString(xpathobj->floatval);
5041 cstr = xml_pstrdup_and_free(
str);
5044 elog(
ERROR,
"unexpected XPath object type %u", xpathobj->type);
5055 state->typioparams[colnum],
5060 if (xpathobj != NULL)
5061 xmlXPathFreeObject(xpathobj);
5080 XmlTableBuilderData *xtCxt;
5082 xtCxt = GetXmlTableBuilderPrivateData(
state,
"XmlTableDestroyOpaque");
5085 xmlSetStructuredErrorFunc(xtCxt->xmlerrcxt, xml_errorHandler);
5087 if (xtCxt->xpathscomp != NULL)
5091 for (
i = 0;
i < xtCxt->natts;
i++)
5092 if (xtCxt->xpathscomp[
i] != NULL)
5093 xmlXPathFreeCompExpr(xtCxt->xpathscomp[
i]);
5096 if (xtCxt->xpathobj != NULL)
5097 xmlXPathFreeObject(xtCxt->xpathobj);
5098 if (xtCxt->xpathcomp != NULL)
5099 xmlXPathFreeCompExpr(xtCxt->xpathcomp);
5100 if (xtCxt->xpathcxt != NULL)
5101 xmlXPathFreeContext(xtCxt->xpathcxt);
5102 if (xtCxt->doc != NULL)
5103 xmlFreeDoc(xtCxt->doc);
5104 if (xtCxt->ctxt != NULL)
5105 xmlFreeParserCtxt(xtCxt->ctxt);
5111 state->opaque = NULL;
#define PG_GETARG_ARRAYTYPE_P(n)
#define DatumGetArrayTypeP(X)
ArrayBuildState * accumArrayResult(ArrayBuildState *astate, Datum dvalue, bool disnull, Oid element_type, MemoryContext rcontext)
ArrayBuildState * initArrayResult(Oid element_type, MemoryContext rcontext, bool subcontext)
void deconstruct_array(ArrayType *array, Oid elmtype, int elmlen, bool elmbyval, char elmalign, Datum **elemsp, bool **nullsp, int *nelemsp)
void deconstruct_array_builtin(ArrayType *array, Oid elmtype, Datum **elemsp, bool **nullsp, int *nelemsp)
Datum makeArrayResult(ArrayBuildState *astate, MemoryContext rcontext)
void j2date(int jd, int *year, int *month, int *day)
void EncodeDateTime(struct pg_tm *tm, fsec_t fsec, bool print_tz, int tz, const char *tzn, int style, char *str)
void EncodeDateOnly(struct pg_tm *tm, int style, char *str)
int timestamp2tm(Timestamp dt, int *tzp, struct pg_tm *tm, fsec_t *fsec, const char **tzn, pg_tz *attimezone)
#define TextDatumGetCString(d)
#define Assert(condition)
#define PointerIsValid(pointer)
#define OidIsValid(objectId)
#define TIMESTAMP_NOT_FINITE(j)
#define POSTGRES_EPOCH_JDATE
#define DATE_NOT_FINITE(j)
static DateADT DatumGetDateADT(Datum X)
char * get_database_name(Oid dbid)
static void PGresult * res
int errmsg_internal(const char *fmt,...)
int errdetail_internal(const char *fmt,...)
int errdetail(const char *fmt,...)
int errhint(const char *fmt,...)
int errcode(int sqlerrcode)
int errmsg(const char *fmt,...)
#define errsave(context,...)
#define ereport(elevel,...)
Datum InputFunctionCall(FmgrInfo *flinfo, char *str, Oid typioparam, int32 typmod)
Datum Float8GetDatum(float8 X)
char * OidOutputFunctionCall(Oid functionId, Datum val)
#define PG_GETARG_TEXT_PP(n)
#define PG_RETURN_BYTEA_P(x)
#define DatumGetByteaPP(X)
#define PG_GETARG_POINTER(n)
#define PG_RETURN_CSTRING(x)
#define DirectFunctionCall1(func, arg1)
#define PG_GETARG_CSTRING(n)
#define PG_GETARG_NAME(n)
#define PG_RETURN_TEXT_P(x)
#define PG_GETARG_INT32(n)
#define PG_GETARG_BOOL(n)
#define PG_RETURN_DATUM(x)
#define PG_RETURN_BOOL(x)
#define HeapTupleIsValid(tuple)
if(TABLE==NULL||TABLE_index==NULL)
List * lappend(List *list, void *datum)
List * lappend_oid(List *list, Oid datum)
List * list_append_unique_oid(List *list, Oid datum)
char * get_namespace_name(Oid nspid)
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
void get_typlenbyvalalign(Oid typid, int16 *typlen, bool *typbyval, char *typalign)
char * get_rel_name(Oid relid)
char get_typtype(Oid typid)
Oid getBaseTypeAndTypmod(Oid typid, int32 *typmod)
Oid getBaseType(Oid typid)
void get_type_category_preferred(Oid typid, char *typcategory, bool *typispreferred)
#define type_is_array_domain(typid)
unsigned char * pg_do_encoding_conversion(unsigned char *src, int len, int src_encoding, int dest_encoding)
char * pg_any_to_server(const char *s, int len, int encoding)
int GetDatabaseEncoding(void)
void pg_unicode_to_server(pg_wchar c, unsigned char *s)
int pg_get_client_encoding(void)
int pg_encoding_mb2wchar_with_len(int encoding, const char *from, pg_wchar *to, int len)
char * pg_server_to_any(const char *s, int len, int encoding)
int pg_mblen(const char *mbstr)
char * pstrdup(const char *in)
void pfree(void *pointer)
MemoryContext TopMemoryContext
void * palloc0(Size size)
MemoryContext CurrentMemoryContext
void * repalloc(void *pointer, Size size)
void * MemoryContextAlloc(MemoryContext context, Size size)
char * MemoryContextStrdup(MemoryContext context, const char *string)
#define AllocSetContextCreate
#define ALLOCSET_DEFAULT_SIZES
Oid LookupExplicitNamespace(const char *nspname, bool missing_ok)
Oid exprType(const Node *expr)
#define IsA(nodeptr, _type_)
FormData_pg_attribute * Form_pg_attribute
#define ERRCODE_DATA_CORRUPTED
FormData_pg_class * Form_pg_class
#define forboth(cell1, list1, cell2, list2)
#define list_make2(x1, x2)
FormData_pg_type * Form_pg_type
#define MAX_MULTIBYTE_CHAR_LEN
#define MAX_UNICODE_EQUIVALENT_STRING
#define pg_encoding_to_char
#define pg_char_to_encoding
int pg_strcasecmp(const char *s1, const char *s2)
size_t strnlen(const char *str, size_t maxlen)
int pg_strncasecmp(const char *s1, const char *s2, size_t n)
static bool DatumGetBool(Datum X)
static Datum PointerGetDatum(const void *X)
static char * DatumGetCString(Datum X)
static Oid DatumGetObjectId(Datum X)
static Datum BoolGetDatum(bool X)
static Datum ObjectIdGetDatum(Oid X)
static Datum CStringGetDatum(const char *X)
Datum regclassout(PG_FUNCTION_ARGS)
static pg_noinline void Size size
Oid SPI_gettypeid(TupleDesc tupdesc, int fnumber)
SPITupleTable * SPI_tuptable
Portal SPI_cursor_find(const char *name)
const char * SPI_result_code_string(int code)
void SPI_cursor_fetch(Portal portal, bool forward, long count)
Portal SPI_cursor_open(const char *name, SPIPlanPtr plan, Datum *Values, const char *Nulls, bool read_only)
SPIPlanPtr SPI_prepare(const char *src, int nargs, Oid *argtypes)
void SPI_cursor_close(Portal portal)
void * SPI_palloc(Size size)
char * SPI_fname(TupleDesc tupdesc, int fnumber)
int SPI_execute(const char *src, bool read_only, long tcount)
Datum SPI_getbinval(HeapTuple tuple, TupleDesc tupdesc, int fnumber, bool *isnull)
void destroyStringInfo(StringInfo str)
StringInfo makeStringInfo(void)
void appendStringInfo(StringInfo str, const char *fmt,...)
void appendBinaryStringInfo(StringInfo str, const void *data, int datalen)
void appendStringInfoString(StringInfo str, const char *s)
void appendStringInfoChar(StringInfo str, char ch)
void initStringInfo(StringInfo str)
StringInfoData * StringInfo
#define appendStringInfoCharMacro(str, ch)
void(* InitOpaque)(struct TableFuncScanState *state, int natts)
void ReleaseSysCache(HeapTuple tuple)
HeapTuple SearchSysCache1(int cacheId, Datum key1)
void table_close(Relation relation, LOCKMODE lockmode)
Relation table_open(Oid relationId, LOCKMODE lockmode)
TupleDesc CreateTupleDescCopy(TupleDesc tupdesc)
struct TupleDescData * TupleDesc
#define TupleDescAttr(tupdesc, i)
static Timestamp DatumGetTimestamp(Datum X)
#define SET_VARSIZE(PTR, len)
#define VARSIZE_ANY_EXHDR(PTR)
static void appendStringInfoText(StringInfo str, const text *t)
char * text_to_cstring(const text *t)
text * cstring_to_text_with_len(const char *s, int len)
text * cstring_to_text(const char *s)
int pg_encoding_mblen(int encoding, const char *mbstr)
Datum xml_in(PG_FUNCTION_ARGS)
Datum cursor_to_xmlschema(PG_FUNCTION_ARGS)
static char * _SPI_strdup(const char *s)
xmltype * xmlconcat(List *args)
Datum table_to_xml(PG_FUNCTION_ARGS)
Datum query_to_xmlschema(PG_FUNCTION_ARGS)
Datum database_to_xml(PG_FUNCTION_ARGS)
static List * database_get_xml_visible_tables(void)
static const char * map_sql_catalog_to_xmlschema_types(List *nspid_list, bool nulls, bool tableforest, const char *targetns)
static char * map_multipart_sql_identifier_to_xml_name(const char *a, const char *b, const char *c, const char *d)
static void XmlTableInitOpaque(struct TableFuncScanState *state, int natts)
static const char * map_sql_type_to_xml_name(Oid typeoid, int typmod)
static const char * map_sql_type_to_xmlschema_type(Oid typeoid, int typmod)
Datum texttoxml(PG_FUNCTION_ARGS)
static void xsd_schema_element_start(StringInfo result, const char *targetns)
Datum query_to_xml_and_xmlschema(PG_FUNCTION_ARGS)
Datum xmltotext(PG_FUNCTION_ARGS)
Datum schema_to_xml_and_xmlschema(PG_FUNCTION_ARGS)
Datum xmlexists(PG_FUNCTION_ARGS)
Datum xmltext(PG_FUNCTION_ARGS)
static List * query_to_oid_list(const char *query)
static char * xml_out_internal(xmltype *x, pg_enc target_encoding)
static xmltype * stringinfo_to_xmltype(StringInfo buf)
static StringInfo database_to_xmlschema_internal(bool nulls, bool tableforest, const char *targetns)
Datum database_to_xmlschema(PG_FUNCTION_ARGS)
Datum schema_to_xmlschema(PG_FUNCTION_ARGS)
static void xmldata_root_element_start(StringInfo result, const char *eltname, const char *xmlschema, const char *targetns, bool top_level)
Datum xml_send(PG_FUNCTION_ARGS)
static const char * map_sql_schema_to_xmlschema_types(Oid nspid, List *relid_list, bool nulls, bool tableforest, const char *targetns)
const TableFuncRoutine XmlTableRoutine
Datum xmlcomment(PG_FUNCTION_ARGS)
static void XmlTableSetNamespace(struct TableFuncScanState *state, const char *name, const char *uri)
Datum xmlconcat2(PG_FUNCTION_ARGS)
static void XmlTableSetRowFilter(struct TableFuncScanState *state, const char *path)
static void xmldata_root_element_end(StringInfo result, const char *eltname)
text * xmltotext_with_options(xmltype *data, XmlOptionType xmloption_arg, bool indent)
xmltype * xmlparse(text *data, XmlOptionType xmloption_arg, bool preserve_whitespace)
static Datum XmlTableGetValue(struct TableFuncScanState *state, int colnum, Oid typid, int32 typmod, bool *isnull)
static xmltype * cstring_to_xmltype(const char *string)
Datum xml_is_well_formed_document(PG_FUNCTION_ARGS)
Datum query_to_xml(PG_FUNCTION_ARGS)
char * map_sql_identifier_to_xml_name(const char *ident, bool fully_escaped, bool escape_period)
static StringInfo database_to_xml_internal(const char *xmlschema, bool nulls, bool tableforest, const char *targetns)
Datum xml_is_well_formed_content(PG_FUNCTION_ARGS)
#define XML_VISIBLE_SCHEMAS
bool xml_is_document(xmltype *arg)
static StringInfo schema_to_xmlschema_internal(const char *schemaname, bool nulls, bool tableforest, const char *targetns)
static List * schema_get_xml_visible_tables(Oid nspid)
char * escape_xml(const char *str)
Datum table_to_xml_and_xmlschema(PG_FUNCTION_ARGS)
Datum xmlvalidate(PG_FUNCTION_ARGS)
static void XmlTableSetDocument(struct TableFuncScanState *state, Datum value)
static void XmlTableDestroyOpaque(struct TableFuncScanState *state)
char * map_xml_name_to_sql_identifier(const char *name)
static const char * map_sql_typecoll_to_xmlschema_types(List *tupdesc_list)
xmltype * xmlpi(const char *target, text *arg, bool arg_is_null, bool *result_is_null)
#define PG_XML_DEFAULT_VERSION
Datum table_to_xmlschema(PG_FUNCTION_ARGS)
static StringInfo query_to_xml_internal(const char *query, char *tablename, const char *xmlschema, bool nulls, bool tableforest, const char *targetns, bool top_level)
static void SPI_sql_row_to_xmlelement(uint64 rownum, StringInfo result, char *tablename, bool nulls, bool tableforest, const char *targetns, bool top_level)
static StringInfo schema_to_xml_internal(Oid nspid, const char *xmlschema, bool nulls, bool tableforest, const char *targetns, bool top_level)
static StringInfo table_to_xml_internal(Oid relid, const char *xmlschema, bool nulls, bool tableforest, const char *targetns, bool top_level)
Datum schema_to_xml(PG_FUNCTION_ARGS)
Datum database_to_xml_and_xmlschema(PG_FUNCTION_ARGS)
char * map_sql_value_to_xml_value(Datum value, Oid type, bool xml_escape_strings)
static bool XmlTableFetchRow(struct TableFuncScanState *state)
Datum cursor_to_xml(PG_FUNCTION_ARGS)
Datum xpath_exists(PG_FUNCTION_ARGS)
Datum xml_is_well_formed(PG_FUNCTION_ARGS)
xmltype * xmlelement(XmlExpr *xexpr, Datum *named_argvalue, bool *named_argnull, Datum *argvalue, bool *argnull)
static void XmlTableSetColumnFilter(struct TableFuncScanState *state, const char *path, int colnum)
static const char * map_sql_table_to_xmlschema(TupleDesc tupdesc, Oid relid, bool nulls, bool tableforest, const char *targetns)
Datum xml_out(PG_FUNCTION_ARGS)
Datum xml_recv(PG_FUNCTION_ARGS)
xmltype * xmlroot(xmltype *data, text *version, int standalone)
Datum xpath(PG_FUNCTION_ARGS)
static void xsd_schema_element_end(StringInfo result)
static List * database_get_xml_visible_schemas(void)
@ XML_STANDALONE_NO_VALUE
struct PgXmlErrorContext PgXmlErrorContext
static xmltype * DatumGetXmlP(Datum X)
#define PG_RETURN_XML_P(x)
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)
void pg_xml_init_library(void)
@ PG_XML_STRICTNESS_LEGACY
@ PG_XML_STRICTNESS_WELLFORMED