49 #include <libxml/chvalid.h>
50 #include <libxml/parser.h>
51 #include <libxml/parserInternals.h>
52 #include <libxml/tree.h>
53 #include <libxml/uri.h>
54 #include <libxml/xmlerror.h>
55 #include <libxml/xmlsave.h>
56 #include <libxml/xmlversion.h>
57 #include <libxml/xmlwriter.h>
58 #include <libxml/xpath.h>
59 #include <libxml/xpathInternals.h>
66 #if LIBXML_VERSION >= 20704
67 #define HAVE_XMLSTRUCTUREDERRORCONTEXT 1
105 #define ERRCXT_MAGIC 68275028
116 xmlStructuredErrorFunc saved_errfunc;
119 xmlExternalEntityLoader saved_entityfunc;
122 static xmlParserInputPtr xmlPgEntityLoader(
const char *URL,
const char *ID,
123 xmlParserCtxtPtr ctxt);
125 int sqlcode,
const char *msg);
126 static void xml_errorHandler(
void *
data, xmlErrorPtr
error);
127 static int errdetail_for_xml_code(
int code);
131 #ifdef USE_LIBXMLCONTEXT
135 static void xml_memory_init(
void);
136 static void *xml_palloc(
size_t size);
137 static void *xml_repalloc(
void *ptr,
size_t size);
138 static void xml_pfree(
void *ptr);
139 static char *xml_pstrdup(
const char *
string);
142 static xmlChar *xml_text2xmlChar(
text *in);
143 static int parse_xml_decl(
const xmlChar *
str,
size_t *lenp,
144 xmlChar **version, xmlChar **
encoding,
int *standalone);
145 static bool print_xml_decl(
StringInfo buf,
const xmlChar *version,
147 static bool xml_doctype_in_content(
const xmlChar *
str);
149 bool preserve_whitespace,
int encoding,
151 xmlNodePtr *parsed_nodes,
154 static int xml_xpathobjtoxmlarray(xmlXPathObjectPtr xpathobj,
157 static xmlChar *pg_xmlCharStrndup(
const char *
str,
size_t len);
161 const char *xmlschema,
const char *targetns,
165 const char *xmlschema,
bool nulls,
bool tableforest,
166 const char *targetns,
bool top_level);
168 bool nulls,
bool tableforest,
const char *targetns);
170 List *relid_list,
bool nulls,
171 bool tableforest,
const char *targetns);
173 bool nulls,
bool tableforest,
174 const char *targetns);
179 char *tablename,
bool nulls,
bool tableforest,
180 const char *targetns,
bool top_level);
185 #define XMLTABLE_CONTEXT_MAGIC 46922182
186 typedef struct XmlTableBuilderData
192 xmlParserCtxtPtr ctxt;
194 xmlXPathContextPtr xpathcxt;
195 xmlXPathCompExprPtr xpathcomp;
196 xmlXPathObjectPtr xpathobj;
197 xmlXPathCompExprPtr *xpathscomp;
198 } XmlTableBuilderData;
207 const char *path,
int colnum);
210 Oid typid,
int32 typmod,
bool *isnull);
225 #define NO_XML_SUPPORT() \
227 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), \
228 errmsg("unsupported XML feature"), \
229 errdetail("This functionality requires the server to be built with libxml support.")))
233 #define NAMESPACE_XSD "http://www.w3.org/2001/XMLSchema"
234 #define NAMESPACE_XSI "http://www.w3.org/2001/XMLSchema-instance"
235 #define NAMESPACE_SQLXML "http://standards.iso.org/iso/9075/2003/sqlxml"
241 xmlChar_to_encoding(
const xmlChar *encoding_name)
247 (
errcode(ERRCODE_INVALID_PARAMETER_VALUE),
248 errmsg(
"invalid encoding name \"%s\"",
249 (
const char *) encoding_name)));
279 NULL, NULL, fcinfo->context);
291 #define PG_XML_DEFAULT_VERSION "1.0"
312 if ((res_code = parse_xml_decl((xmlChar *)
str,
313 &
len, &version, NULL, &standalone)) == 0)
319 if (!print_xml_decl(&
buf, version, target_encoding, standalone))
337 errcode(ERRCODE_INTERNAL_ERROR),
339 errdetail_for_xml_code(res_code));
370 xmlChar *encodingStr = NULL;
378 nbytes =
buf->len -
buf->cursor;
392 parse_xml_decl((
const xmlChar *)
str, NULL, NULL, &encodingStr, NULL);
472 xmlBuffer_to_xmltype(xmlBufferPtr
buf)
475 xmlBufferLength(
buf));
493 if (argdata[
i] ==
'-' && argdata[
i - 1] ==
'-')
495 (
errcode(ERRCODE_INVALID_XML_COMMENT),
496 errmsg(
"invalid XML comment")));
498 if (
len > 0 && argdata[
len - 1] ==
'-')
500 (
errcode(ERRCODE_INVALID_XML_COMMENT),
501 errmsg(
"invalid XML comment")));
525 int global_standalone = 1;
526 xmlChar *global_version = NULL;
527 bool global_version_no_value =
false;
543 parse_xml_decl((xmlChar *)
str, &
len, &version, NULL, &standalone);
545 if (standalone == 0 && global_standalone == 1)
546 global_standalone = 0;
548 global_standalone = -1;
551 global_version_no_value =
true;
552 else if (!global_version)
553 global_version = version;
554 else if (xmlStrcmp(version, global_version) != 0)
555 global_version_no_value =
true;
561 if (!global_version_no_value || global_standalone >= 0)
567 print_xml_decl(&buf2,
568 (!global_version_no_value) ? global_version : NULL,
628 text *
volatile result;
631 xmlNodePtr content_nodes;
632 volatile xmlBufferPtr
buf = NULL;
633 volatile xmlSaveCtxtPtr ctxt = NULL;
651 &parsed_xmloptiontype, &content_nodes,
652 (
Node *) &escontext);
659 (
errcode(ERRCODE_NOT_AN_XML_DOCUMENT),
660 errmsg(
"not an XML document")));
678 buf = xmlBufferCreate();
680 if (
buf == NULL || xmlerrcxt->err_occurred)
682 "could not allocate xmlBuffer");
685 parse_xml_decl(xml_text2xmlChar(
data), &decl_len, NULL, NULL, NULL);
694 ctxt = xmlSaveToBuffer(
buf, NULL,
695 XML_SAVE_NO_DECL | XML_SAVE_FORMAT);
697 ctxt = xmlSaveToBuffer(
buf, NULL,
700 if (ctxt == NULL || xmlerrcxt->err_occurred)
702 "could not allocate xmlSaveCtxt");
707 if (xmlSaveDoc(ctxt, doc) == -1 || xmlerrcxt->err_occurred)
709 "could not save document to xmlBuffer");
711 else if (content_nodes != NULL)
722 root = xmlNewNode(NULL, (
const xmlChar *)
"content-root");
723 if (root == NULL || xmlerrcxt->err_occurred)
725 "could not allocate xml node");
728 xmlDocSetRootElement(doc, root);
729 xmlAddChild(root, content_nodes);
738 newline = xmlNewDocText(NULL, (
const xmlChar *)
"\n");
739 if (
newline == NULL || xmlerrcxt->err_occurred)
741 "could not allocate xml node");
743 for (xmlNodePtr node = root->children; node; node = node->next)
746 if (node->type != XML_TEXT_NODE && node->prev != NULL)
748 if (xmlSaveTree(ctxt,
newline) == -1 || xmlerrcxt->err_occurred)
752 "could not save newline to xmlBuffer");
756 if (xmlSaveTree(ctxt, node) == -1 || xmlerrcxt->err_occurred)
760 "could not save content to xmlBuffer");
767 if (xmlSaveClose(ctxt) == -1 || xmlerrcxt->err_occurred)
771 "could not close xmlSaveCtxtPtr");
774 result = (
text *) xmlBuffer_to_xmltype(
buf);
806 Datum *named_argvalue,
bool *named_argnull,
807 Datum *argvalue,
bool *argnull)
811 List *named_arg_strings;
817 volatile xmlBufferPtr
buf = NULL;
818 volatile xmlTextWriterPtr writer = NULL;
827 named_arg_strings =
NIL;
834 if (named_argnull[
i])
840 named_arg_strings =
lappend(named_arg_strings,
str);
866 buf = xmlBufferCreate();
867 if (
buf == NULL || xmlerrcxt->err_occurred)
869 "could not allocate xmlBuffer");
870 writer = xmlNewTextWriterMemory(
buf, 0);
871 if (writer == NULL || xmlerrcxt->err_occurred)
873 "could not allocate xmlTextWriter");
875 xmlTextWriterStartElement(writer, (xmlChar *) xexpr->name);
877 forboth(
arg, named_arg_strings, narg, xexpr->arg_names)
883 xmlTextWriterWriteAttribute(writer,
888 foreach(
arg, arg_strings)
892 xmlTextWriterWriteRaw(writer, (xmlChar *)
str);
895 xmlTextWriterEndElement(writer);
898 xmlFreeTextWriter(writer);
901 result = xmlBuffer_to_xmltype(
buf);
906 xmlFreeTextWriter(writer);
934 doc = xml_parse(
data, xmloption_arg, preserve_whitespace,
947 xmlpi(
const char *target,
text *
arg,
bool arg_is_null,
bool *result_is_null)
955 (
errcode(ERRCODE_SYNTAX_ERROR),
956 errmsg(
"invalid XML processing instruction"),
957 errdetail(
"XML processing instruction target name cannot be \"%s\".", target)));
963 *result_is_null = arg_is_null;
976 if (strstr(
string,
"?>") != NULL)
978 (
errcode(ERRCODE_INVALID_XML_PROCESSING_INSTRUCTION),
979 errmsg(
"invalid XML processing instruction"),
980 errdetail(
"XML processing instruction cannot contain \"?>\".")));
1004 xmlChar *orig_version;
1005 int orig_standalone;
1011 parse_xml_decl((xmlChar *)
str, &
len, &orig_version, NULL, &orig_standalone);
1014 orig_version = xml_text2xmlChar(version);
1016 orig_version = NULL;
1021 orig_standalone = 1;
1024 orig_standalone = 0;
1027 orig_standalone = -1;
1035 print_xml_decl(&
buf, orig_version, 0, orig_standalone);
1058 (
errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1059 errmsg(
"xmlvalidate is not implemented")));
1103 static bool first_time =
true;
1113 if (
sizeof(
char) !=
sizeof(xmlChar))
1115 (
errmsg(
"could not initialize XML library"),
1116 errdetail(
"libxml2 has incompatible char type: sizeof(char)=%zu, sizeof(xmlChar)=%zu.",
1117 sizeof(
char),
sizeof(xmlChar))));
1119 #ifdef USE_LIBXMLCONTEXT
1125 LIBXML_TEST_VERSION;
1157 errcxt->magic = ERRCXT_MAGIC;
1158 errcxt->strictness = strictness;
1159 errcxt->err_occurred =
false;
1169 errcxt->saved_errfunc = xmlStructuredError;
1171 #ifdef HAVE_XMLSTRUCTUREDERRORCONTEXT
1172 errcxt->saved_errcxt = xmlStructuredErrorContext;
1174 errcxt->saved_errcxt = xmlGenericErrorContext;
1177 xmlSetStructuredErrorFunc((
void *) errcxt, xml_errorHandler);
1193 #ifdef HAVE_XMLSTRUCTUREDERRORCONTEXT
1194 new_errcxt = xmlStructuredErrorContext;
1196 new_errcxt = xmlGenericErrorContext;
1199 if (new_errcxt != (
void *) errcxt)
1201 (
errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1202 errmsg(
"could not set up XML error handler"),
1203 errhint(
"This probably indicates that the version of libxml2"
1204 " being used is not compatible with the libxml2"
1205 " header files that PostgreSQL was built with.")));
1211 errcxt->saved_entityfunc = xmlGetExternalEntityLoader();
1212 xmlSetExternalEntityLoader(xmlPgEntityLoader);
1233 Assert(errcxt->magic == ERRCXT_MAGIC);
1240 Assert(!errcxt->err_occurred || isError);
1247 #ifdef HAVE_XMLSTRUCTUREDERRORCONTEXT
1248 cur_errcxt = xmlStructuredErrorContext;
1250 cur_errcxt = xmlGenericErrorContext;
1253 if (cur_errcxt != (
void *) errcxt)
1254 elog(
WARNING,
"libxml error handling state is out of sync with xml.c");
1257 xmlSetStructuredErrorFunc(errcxt->saved_errcxt, errcxt->saved_errfunc);
1258 xmlSetExternalEntityLoader(errcxt->saved_entityfunc);
1267 pfree(errcxt->err_buf.data);
1278 return errcxt->err_occurred;
1291 #define CHECK_XML_SPACE(p) \
1293 if (!xmlIsBlank_ch(*(p))) \
1294 return XML_ERR_SPACE_REQUIRED; \
1297 #define SKIP_XML_SPACE(p) \
1298 while (xmlIsBlank_ch(*(p))) (p)++
1302 #define PG_XMLISNAMECHAR(c) \
1303 (xmlIsBaseChar_ch(c) || xmlIsIdeographicQ(c) \
1304 || xmlIsDigit_ch(c) \
1305 || c == '.' || c == '-' || c == '_' || c == ':' \
1306 || xmlIsCombiningQ(c) \
1307 || xmlIsExtender_ch(c))
1311 xml_pnstrdup(
const xmlChar *
str,
size_t len)
1315 result = (xmlChar *)
palloc((
len + 1) *
sizeof(xmlChar));
1316 memcpy(result,
str,
len *
sizeof(xmlChar));
1323 pg_xmlCharStrndup(
const char *
str,
size_t len)
1327 result = (xmlChar *)
palloc((
len + 1) *
sizeof(xmlChar));
1328 memcpy(result,
str,
len);
1340 xml_pstrdup_and_free(xmlChar *
str)
1369 parse_xml_decl(
const xmlChar *
str,
size_t *lenp,
1370 xmlChar **version, xmlChar **
encoding,
int *standalone)
1373 const xmlChar *save_p;
1396 if (xmlStrncmp(p, (xmlChar *)
"<?xml", 5) != 0)
1408 utf8char = xmlGetUTF8Char(p + 5, &utf8len);
1409 if (PG_XMLISNAMECHAR(utf8char))
1417 if (xmlStrncmp(p, (xmlChar *)
"version", 7) != 0)
1418 return XML_ERR_VERSION_MISSING;
1422 return XML_ERR_VERSION_MISSING;
1426 if (*p ==
'\'' || *p ==
'"')
1430 q = xmlStrchr(p + 1, *p);
1432 return XML_ERR_VERSION_MISSING;
1435 *version = xml_pnstrdup(p + 1, q - p - 1);
1439 return XML_ERR_VERSION_MISSING;
1444 if (xmlStrncmp(p, (xmlChar *)
"encoding", 8) == 0)
1446 CHECK_XML_SPACE(save_p);
1450 return XML_ERR_MISSING_ENCODING;
1454 if (*p ==
'\'' || *p ==
'"')
1458 q = xmlStrchr(p + 1, *p);
1460 return XML_ERR_MISSING_ENCODING;
1463 *
encoding = xml_pnstrdup(p + 1, q - p - 1);
1467 return XML_ERR_MISSING_ENCODING;
1477 if (xmlStrncmp(p, (xmlChar *)
"standalone", 10) == 0)
1479 CHECK_XML_SPACE(save_p);
1483 return XML_ERR_STANDALONE_VALUE;
1486 if (xmlStrncmp(p, (xmlChar *)
"'yes'", 5) == 0 ||
1487 xmlStrncmp(p, (xmlChar *)
"\"yes\"", 5) == 0)
1493 else if (xmlStrncmp(p, (xmlChar *)
"'no'", 4) == 0 ||
1494 xmlStrncmp(p, (xmlChar *)
"\"no\"", 4) == 0)
1501 return XML_ERR_STANDALONE_VALUE;
1509 if (xmlStrncmp(p, (xmlChar *)
"?>", 2) != 0)
1510 return XML_ERR_XMLDECL_NOT_FINISHED;
1518 return XML_ERR_INVALID_CHAR;
1547 || standalone != -1)
1566 if (standalone == 1)
1568 else if (standalone == 0)
1608 xml_doctype_in_content(
const xmlChar *
str)
1610 const xmlChar *p =
str;
1626 if (xmlStrncmp(p, (xmlChar *)
"DOCTYPE", 7) == 0)
1630 if (xmlStrncmp(p, (xmlChar *)
"--", 2) != 0)
1633 p = xmlStrstr(p + 2, (xmlChar *)
"--");
1634 if (!p || p[2] !=
'>')
1647 e = xmlStrstr(p, (xmlChar *)
"?>");
1685 bool preserve_whitespace,
int encoding,
1686 XmlOptionType *parsed_xmloptiontype, xmlNodePtr *parsed_nodes,
1691 xmlChar *utf8string;
1693 volatile xmlParserCtxtPtr ctxt = NULL;
1694 volatile xmlDocPtr doc = NULL;
1701 string = xml_text2xmlChar(
data);
1721 bool parse_as_document =
false;
1724 xmlChar *version = NULL;
1730 ctxt = xmlNewParserCtxt();
1731 if (ctxt == NULL || xmlerrcxt->err_occurred)
1733 "could not allocate parser context");
1737 parse_as_document =
true;
1741 res_code = parse_xml_decl(utf8string,
1742 &count, &version, NULL, &standalone);
1746 errcode(ERRCODE_INVALID_XML_CONTENT),
1748 errdetail_for_xml_code(res_code));
1753 if (xml_doctype_in_content(utf8string + count))
1754 parse_as_document =
true;
1758 if (parsed_xmloptiontype != NULL)
1761 if (parsed_nodes != NULL)
1762 *parsed_nodes = NULL;
1764 if (parse_as_document)
1773 doc = xmlCtxtReadDoc(ctxt, utf8string,
1776 XML_PARSE_NOENT | XML_PARSE_DTDATTR
1777 | (preserve_whitespace ? 0 : XML_PARSE_NOBLANKS));
1778 if (doc == NULL || xmlerrcxt->err_occurred)
1782 xml_errsave(escontext, xmlerrcxt,
1783 ERRCODE_INVALID_XML_DOCUMENT,
1784 "invalid XML document");
1786 xml_errsave(escontext, xmlerrcxt,
1787 ERRCODE_INVALID_XML_CONTENT,
1788 "invalid XML content");
1794 doc = xmlNewDoc(version);
1795 if (doc == NULL || xmlerrcxt->err_occurred)
1797 "could not allocate XML document");
1799 Assert(doc->encoding == NULL);
1800 doc->encoding = xmlStrdup((
const xmlChar *)
"UTF-8");
1801 if (doc->encoding == NULL || xmlerrcxt->err_occurred)
1803 "could not allocate XML document");
1804 doc->standalone = standalone;
1807 if (*(utf8string + count))
1809 res_code = xmlParseBalancedChunkMemory(doc, NULL, NULL, 0,
1812 if (res_code != 0 || xmlerrcxt->err_occurred)
1814 xml_errsave(escontext, xmlerrcxt,
1815 ERRCODE_INVALID_XML_CONTENT,
1816 "invalid XML content");
1830 xmlFreeParserCtxt(ctxt);
1838 xmlFreeParserCtxt(ctxt);
1850 xml_text2xmlChar(
text *in)
1856 #ifdef USE_LIBXMLCONTEXT
1863 xml_memory_init(
void)
1866 if (LibxmlContext == NULL)
1872 xmlMemSetup(xml_pfree, xml_palloc, xml_repalloc, xml_pstrdup);
1879 xml_palloc(
size_t size)
1886 xml_repalloc(
void *ptr,
size_t size)
1893 xml_pfree(
void *ptr)
1902 xml_pstrdup(
const char *
string)
1920 static xmlParserInputPtr
1921 xmlPgEntityLoader(
const char *URL,
const char *ID,
1922 xmlParserCtxtPtr ctxt)
1924 return xmlNewStringInputStream(ctxt, (
const xmlChar *)
"");
1944 if (errcxt->magic != ERRCXT_MAGIC)
1945 elog(
ERROR,
"xml_ereport called with invalid PgXmlErrorContext");
1948 errcxt->err_occurred =
false;
1951 if (errcxt->err_buf.len > 0)
1952 detail = errcxt->err_buf.data;
1977 int sqlcode,
const char *msg)
1982 if (errcxt->magic != ERRCXT_MAGIC)
1983 elog(
ERROR,
"xml_errsave called with invalid PgXmlErrorContext");
1986 errcxt->err_occurred =
false;
1989 if (errcxt->err_buf.len > 0)
1990 detail = errcxt->err_buf.data;
2005 xml_errorHandler(
void *
data, xmlErrorPtr
error)
2008 xmlParserCtxtPtr ctxt = (xmlParserCtxtPtr)
error->ctxt;
2009 xmlParserInputPtr
input = (ctxt != NULL) ? ctxt->input : NULL;
2010 xmlNodePtr node =
error->node;
2011 const xmlChar *
name = (node != NULL &&
2012 node->type == XML_ELEMENT_NODE) ? node->name : NULL;
2013 int domain =
error->domain;
2014 int level =
error->level;
2023 if (xmlerrcxt->magic != ERRCXT_MAGIC)
2024 elog(
FATAL,
"xml_errorHandler called with invalid PgXmlErrorContext");
2034 switch (
error->code)
2036 case XML_WAR_NS_URI:
2037 level = XML_ERR_ERROR;
2038 domain = XML_FROM_NAMESPACE;
2041 case XML_ERR_NS_DECL_ERROR:
2042 case XML_WAR_NS_URI_RELATIVE:
2043 case XML_WAR_NS_COLUMN:
2044 case XML_NS_ERR_XML_NAMESPACE:
2045 case XML_NS_ERR_UNDEFINED_NAMESPACE:
2046 case XML_NS_ERR_QNAME:
2047 case XML_NS_ERR_ATTRIBUTE_REDEFINED:
2048 case XML_NS_ERR_EMPTY:
2049 domain = XML_FROM_NAMESPACE;
2056 case XML_FROM_PARSER:
2058 case XML_FROM_MEMORY:
2065 if (
error->code == XML_WAR_UNDECLARED_ENTITY)
2081 if (
error->line > 0)
2085 if (
error->message != NULL)
2103 xmlGenericErrorFunc errFuncSaved = xmlGenericError;
2104 void *errCtxSaved = xmlGenericErrorContext;
2106 xmlSetGenericErrorFunc((
void *) errorBuf,
2110 appendStringInfoLineSeparator(errorBuf);
2112 xmlParserPrintFileContext(
input);
2115 xmlSetGenericErrorFunc(errCtxSaved, errFuncSaved);
2119 chopStringInfoNewlines(errorBuf);
2131 appendStringInfoLineSeparator(&xmlerrcxt->err_buf);
2135 pfree(errorBuf->data);
2148 if (level >= XML_ERR_ERROR)
2150 appendStringInfoLineSeparator(&xmlerrcxt->err_buf);
2154 xmlerrcxt->err_occurred =
true;
2156 else if (level >= XML_ERR_WARNING)
2167 pfree(errorBuf->data);
2182 errdetail_for_xml_code(
int code)
2188 case XML_ERR_INVALID_CHAR:
2191 case XML_ERR_SPACE_REQUIRED:
2194 case XML_ERR_STANDALONE_VALUE:
2195 det =
gettext_noop(
"standalone accepts only 'yes' or 'no'.");
2197 case XML_ERR_VERSION_MISSING:
2198 det =
gettext_noop(
"Malformed declaration: missing version.");
2200 case XML_ERR_MISSING_ENCODING:
2201 det =
gettext_noop(
"Missing encoding in text declaration.");
2203 case XML_ERR_XMLDECL_NOT_FINISHED:
2204 det =
gettext_noop(
"Parsing XML declaration: '?>' expected.");
2207 det =
gettext_noop(
"Unrecognized libxml error code: %d.");
2221 while (
str->len > 0 &&
str->data[
str->len - 1] ==
'\n')
2222 str->data[--
str->len] =
'\0';
2232 chopStringInfoNewlines(
str);
2242 sqlchar_to_unicode(
const char *s)
2253 if (utf8string != s)
2264 return (xmlIsBaseCharQ(
c) || xmlIsIdeographicQ(
c)
2265 ||
c ==
'_' ||
c ==
':');
2273 return (xmlIsBaseCharQ(
c) || xmlIsIdeographicQ(
c)
2275 ||
c ==
'.' ||
c ==
'-' ||
c ==
'_' ||
c ==
':'
2276 || xmlIsCombiningQ(
c)
2277 || xmlIsExtenderQ(
c));
2297 Assert(fully_escaped || !escape_period);
2303 if (*p ==
':' && (p ==
ident || fully_escaped))
2305 else if (*p ==
'_' && *(p + 1) ==
'x')
2307 else if (fully_escaped && p ==
ident &&
2315 else if (escape_period && *p ==
'.')
2319 pg_wchar u = sqlchar_to_unicode(p);
2322 ? !is_valid_xml_namefirst(u)
2323 : !is_valid_xml_namechar(u))
2351 if (*p ==
'_' && *(p + 1) ==
'x'
2352 && isxdigit((
unsigned char) *(p + 2))
2353 && isxdigit((
unsigned char) *(p + 3))
2354 && isxdigit((
unsigned char) *(p + 4))
2355 && isxdigit((
unsigned char) *(p + 5))
2361 sscanf(p + 2,
"%X", &u);
2404 elmlen, elmbyval, elmalign,
2405 &elem_values, &elem_nulls,
2410 for (
i = 0;
i < num_elems;
i++)
2459 (
errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2460 errmsg(
"date out of range"),
2461 errdetail(
"XML does not support infinite date values.")));
2481 (
errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2482 errmsg(
"timestamp out of range"),
2483 errdetail(
"XML does not support infinite timestamp values.")));
2488 (
errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2489 errmsg(
"timestamp out of range")));
2494 case TIMESTAMPTZOID:
2500 const char *tzn = NULL;
2508 (
errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2509 errmsg(
"timestamp out of range"),
2510 errdetail(
"XML does not support infinite timestamp values.")));
2515 (
errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2516 errmsg(
"timestamp out of range")));
2526 volatile xmlBufferPtr
buf = NULL;
2527 volatile xmlTextWriterPtr writer = NULL;
2534 buf = xmlBufferCreate();
2535 if (
buf == NULL || xmlerrcxt->err_occurred)
2537 "could not allocate xmlBuffer");
2538 writer = xmlNewTextWriterMemory(
buf, 0);
2539 if (writer == NULL || xmlerrcxt->err_occurred)
2541 "could not allocate xmlTextWriter");
2544 xmlTextWriterWriteBase64(writer,
VARDATA_ANY(bstr),
2547 xmlTextWriterWriteBinHex(writer,
VARDATA_ANY(bstr),
2551 xmlFreeTextWriter(writer);
2554 result =
pstrdup((
const char *) xmlBufferContent(
buf));
2559 xmlFreeTextWriter(writer);
2586 if (
type == XMLOID || !xml_escape_strings)
2609 for (p =
str; *p; p++)
2637 size_t len = strlen(s) + 1;
2640 memcpy(ret, s,
len);
2700 elog(
ERROR,
"SPI_execute returned %s for %s",
2727 " WHERE relnamespace = %u AND relkind IN ("
2731 " AND pg_catalog.has_table_privilege (oid, 'SELECT')"
2732 " ORDER BY relname;",
nspid);
2742 #define XML_VISIBLE_SCHEMAS_EXCLUDE "(nspname ~ '^pg_' OR nspname = 'information_schema')"
2744 #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
2759 " WHERE relkind IN ("
2763 " AND pg_catalog.has_table_privilege(pg_class.oid, 'SELECT')"
2775 const char *xmlschema,
bool nulls,
bool tableforest,
2776 const char *targetns,
bool top_level)
2785 xmlschema, nulls, tableforest,
2786 targetns, top_level);
2813 NULL, nulls, tableforest,
2843 (
errcode(ERRCODE_UNDEFINED_CURSOR),
2844 errmsg(
"cursor \"%s\" does not exist",
name)));
2849 tableforest, targetns,
true);
2874 const char *xmlschema,
const char *targetns,
2878 Assert(top_level || !xmlschema);
2884 if (strlen(targetns) > 0)
2890 if (strlen(targetns) > 0)
2908 const char *xmlschema,
bool nulls,
bool tableforest,
2909 const char *targetns,
bool top_level)
2925 (
errcode(ERRCODE_DATA_EXCEPTION),
2926 errmsg(
"invalid query")));
2931 targetns, top_level);
2940 tableforest, targetns, top_level);
2963 tableforest, targetns);
2984 elog(
ERROR,
"SPI_prepare(\"%s\") failed", query);
2987 elog(
ERROR,
"SPI_cursor_open(\"%s\") failed", query);
2991 tableforest, targetns));
3006 const char *xmlschema;
3013 (
errcode(ERRCODE_UNDEFINED_CURSOR),
3014 errmsg(
"cursor \"%s\" does not exist",
name)));
3018 tableforest, targetns));
3033 const char *xmlschema;
3037 tableforest, targetns);
3041 xmlschema, nulls, tableforest,
3054 const char *xmlschema;
3061 elog(
ERROR,
"SPI_prepare(\"%s\") failed", query);
3064 elog(
ERROR,
"SPI_cursor_open(\"%s\") failed", query);
3072 xmlschema, nulls, tableforest,
3084 bool tableforest,
const char *targetns,
bool top_level)
3105 foreach(cell, relid_list)
3140 nulls, tableforest, targetns,
true)));
3153 if (strlen(targetns) > 0)
3156 " targetNamespace=\"%s\"\n"
3157 " elementFormDefault=\"qualified\"",
3173 bool tableforest,
const char *targetns)
3192 foreach(cell, relid_list)
3206 nulls, tableforest, targetns));
3225 nulls, tableforest, targetns)));
3244 tableforest, targetns);
3247 xmlschema->
data, nulls,
3248 tableforest, targetns,
true)));
3259 bool tableforest,
const char *targetns)
3280 foreach(cell, nspid_list)
3286 tableforest, targetns,
false);
3308 tableforest, targetns)));
3314 const char *targetns)
3332 foreach(cell, relid_list)
3363 tableforest, targetns)));
3378 nulls, tableforest, targetns)));
3419 bool tableforest,
const char *targetns)
3423 char *tabletypename;
3436 elog(
ERROR,
"cache lookup failed for relation %u", relid);
3461 tabletypename =
"TableType";
3462 rowtypename =
"RowType";
3471 "<xsd:complexType name=\"%s\">\n"
3472 " <xsd:sequence>\n",
3475 for (
i = 0;
i < tupdesc->
natts;
i++)
3479 if (att->attisdropped)
3482 " <xsd:element name=\"%s\" type=\"%s\"%s></xsd:element>\n",
3486 nulls ?
" nillable=\"true\"" :
" minOccurs=\"0\"");
3490 " </xsd:sequence>\n"
3491 "</xsd:complexType>\n\n");
3496 "<xsd:complexType name=\"%s\">\n"
3498 " <xsd:element name=\"row\" type=\"%s\" minOccurs=\"0\" maxOccurs=\"unbounded\"/>\n"
3499 " </xsd:sequence>\n"
3500 "</xsd:complexType>\n\n",
3501 tabletypename, rowtypename);
3504 "<xsd:element name=\"%s\" type=\"%s\"/>\n\n",
3505 xmltn, tabletypename);
3509 "<xsd:element name=\"%s\" type=\"%s\"/>\n\n",
3510 xmltn, rowtypename);
3524 bool tableforest,
const char *targetns)
3529 char *schematypename;
3546 "<xsd:complexType name=\"%s\">\n", schematypename);
3552 " <xsd:sequence>\n");
3554 foreach(cell, relid_list)
3566 " <xsd:element name=\"%s\" type=\"%s\"/>\n",
3567 xmltn, tabletypename);
3570 " <xsd:element name=\"%s\" type=\"%s\" minOccurs=\"0\" maxOccurs=\"unbounded\"/>\n",
3571 xmltn, tabletypename);
3579 " </xsd:sequence>\n");
3581 "</xsd:complexType>\n\n");
3584 "<xsd:element name=\"%s\" type=\"%s\"/>\n\n",
3585 xmlsn, schematypename);
3597 bool tableforest,
const char *targetns)
3601 char *catalogtypename;
3617 "<xsd:complexType name=\"%s\">\n", catalogtypename);
3621 foreach(cell, nspid_list)
3632 " <xsd:element name=\"%s\" type=\"%s\"/>\n",
3633 xmlsn, schematypename);
3639 "</xsd:complexType>\n\n");
3642 "<xsd:element name=\"%s\" type=\"%s\"/>\n\n",
3643 xmlcn, catalogtypename);
3678 ((typmod -
VARHDRSZ) >> 16) & 0xffff,
3717 case TIMESTAMPTZOID:
3736 elog(
ERROR,
"cache lookup failed for type %u", typeoid);
3766 foreach(cell0, tupdesc_list)
3770 for (
i = 0;
i < tupdesc->
natts;
i++)
3774 if (att->attisdropped)
3781 foreach(cell0, uniquetypes)
3786 if (basetypid != typid)
3793 foreach(cell0, uniquetypes)
3820 if (typeoid == XMLOID)
3823 "<xsd:complexType mixed=\"true\">\n"
3825 " <xsd:any name=\"element\" minOccurs=\"0\" maxOccurs=\"unbounded\" processContents=\"skip\"/>\n"
3826 " </xsd:sequence>\n"
3827 "</xsd:complexType>\n");
3832 "<xsd:simpleType name=\"%s\">\n",
typename);
3840 " <xsd:restriction base=\"xsd:string\">\n");
3843 " <xsd:maxLength value=\"%d\"/>\n",
3850 " <xsd:restriction base=\"xsd:%s\">\n"
3851 " </xsd:restriction>\n",
3858 " <xsd:restriction base=\"xsd:decimal\">\n"
3859 " <xsd:totalDigits value=\"%d\"/>\n"
3860 " <xsd:fractionDigits value=\"%d\"/>\n"
3861 " </xsd:restriction>\n",
3862 ((typmod -
VARHDRSZ) >> 16) & 0xffff,
3868 " <xsd:restriction base=\"xsd:short\">\n"
3869 " <xsd:maxInclusive value=\"%d\"/>\n"
3870 " <xsd:minInclusive value=\"%d\"/>\n"
3871 " </xsd:restriction>\n",
3872 SHRT_MAX, SHRT_MIN);
3877 " <xsd:restriction base=\"xsd:int\">\n"
3878 " <xsd:maxInclusive value=\"%d\"/>\n"
3879 " <xsd:minInclusive value=\"%d\"/>\n"
3880 " </xsd:restriction>\n",
3886 " <xsd:restriction base=\"xsd:long\">\n"
3889 " </xsd:restriction>\n",
3896 " <xsd:restriction base=\"xsd:float\"></xsd:restriction>\n");
3901 " <xsd:restriction base=\"xsd:double\"></xsd:restriction>\n");
3906 " <xsd:restriction base=\"xsd:boolean\"></xsd:restriction>\n");
3912 const char *tz = (typeoid == TIMETZOID ?
"(\\+|-)\\p{Nd}{2}:\\p{Nd}{2}" :
"");
3916 " <xsd:restriction base=\"xsd:time\">\n"
3917 " <xsd:pattern value=\"\\p{Nd}{2}:\\p{Nd}{2}:\\p{Nd}{2}(.\\p{Nd}+)?%s\"/>\n"
3918 " </xsd:restriction>\n", tz);
3919 else if (typmod == 0)
3921 " <xsd:restriction base=\"xsd:time\">\n"
3922 " <xsd:pattern value=\"\\p{Nd}{2}:\\p{Nd}{2}:\\p{Nd}{2}%s\"/>\n"
3923 " </xsd:restriction>\n", tz);
3926 " <xsd:restriction base=\"xsd:time\">\n"
3927 " <xsd:pattern value=\"\\p{Nd}{2}:\\p{Nd}{2}:\\p{Nd}{2}.\\p{Nd}{%d}%s\"/>\n"
3928 " </xsd:restriction>\n", typmod -
VARHDRSZ, tz);
3933 case TIMESTAMPTZOID:
3935 const char *tz = (typeoid == TIMESTAMPTZOID ?
"(\\+|-)\\p{Nd}{2}:\\p{Nd}{2}" :
"");
3939 " <xsd:restriction base=\"xsd:dateTime\">\n"
3940 " <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"
3941 " </xsd:restriction>\n", tz);
3942 else if (typmod == 0)
3944 " <xsd:restriction base=\"xsd:dateTime\">\n"
3945 " <xsd:pattern value=\"\\p{Nd}{4}-\\p{Nd}{2}-\\p{Nd}{2}T\\p{Nd}{2}:\\p{Nd}{2}:\\p{Nd}{2}%s\"/>\n"
3946 " </xsd:restriction>\n", tz);
3949 " <xsd:restriction base=\"xsd:dateTime\">\n"
3950 " <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"
3951 " </xsd:restriction>\n", typmod -
VARHDRSZ, tz);
3957 " <xsd:restriction base=\"xsd:date\">\n"
3958 " <xsd:pattern value=\"\\p{Nd}{4}-\\p{Nd}{2}-\\p{Nd}{2}\"/>\n"
3959 " </xsd:restriction>\n");
3966 int32 base_typmod = -1;
3971 " <xsd:restriction base=\"%s\"/>\n",
3989 bool nulls,
bool tableforest,
3990 const char *targetns,
bool top_level)
4062 if (
cur->type != XML_ATTRIBUTE_NODE &&
cur->type != XML_TEXT_NODE)
4064 void (*
volatile nodefree) (xmlNodePtr) = NULL;
4065 volatile xmlBufferPtr
buf = NULL;
4066 volatile xmlNodePtr cur_copy = NULL;
4072 buf = xmlBufferCreate();
4073 if (
buf == NULL || xmlerrcxt->err_occurred)
4075 "could not allocate xmlBuffer");
4089 cur_copy = xmlCopyNode(
cur, 1);
4090 if (cur_copy == NULL || xmlerrcxt->err_occurred)
4092 "could not copy node");
4093 nodefree = (cur_copy->type == XML_DOCUMENT_NODE) ?
4094 (
void (*) (xmlNodePtr)) xmlFreeDoc : xmlFreeNode;
4096 bytes = xmlNodeDump(
buf, NULL, cur_copy, 0, 0);
4097 if (bytes == -1 || xmlerrcxt->err_occurred)
4099 "could not dump node");
4101 result = xmlBuffer_to_xmltype(
buf);
4116 str = xmlXPathCastNodeToString(
cur);
4148 xml_xpathobjtoxmlarray(xmlXPathObjectPtr xpathobj,
4157 switch (xpathobj->type)
4160 if (xpathobj->nodesetval != NULL)
4162 result = xpathobj->nodesetval->nodeNr;
4167 for (
i = 0;
i < result;
i++)
4169 datum =
PointerGetDatum(xml_xmlnodetoxmltype(xpathobj->nodesetval->nodeTab[
i],
4182 datumtype = BOOLOID;
4189 datumtype = FLOAT8OID;
4196 datumtype = CSTRINGOID;
4200 elog(
ERROR,
"xpath expression result type %d is unsupported",
4230 volatile xmlParserCtxtPtr ctxt = NULL;
4231 volatile xmlDocPtr doc = NULL;
4232 volatile xmlXPathContextPtr xpathctx = NULL;
4233 volatile xmlXPathCompExprPtr xpathcomp = NULL;
4234 volatile xmlXPathObjectPtr xpathobj = NULL;
4239 xmlChar *xpath_expr;
4240 size_t xmldecl_len = 0;
4243 Datum *ns_names_uris;
4244 bool *ns_names_uris_nulls;
4256 ndim = namespaces ?
ARR_NDIM(namespaces) : 0;
4263 if (ndim != 2 || dims[1] != 2)
4265 (
errcode(ERRCODE_DATA_EXCEPTION),
4266 errmsg(
"invalid array for XML namespace mapping"),
4267 errdetail(
"The array must be two-dimensional with length of the second axis equal to 2.")));
4272 &ns_names_uris, &ns_names_uris_nulls,
4275 Assert((ns_count % 2) == 0);
4280 ns_names_uris = NULL;
4281 ns_names_uris_nulls = NULL;
4290 (
errcode(ERRCODE_DATA_EXCEPTION),
4291 errmsg(
"empty XPath expression")));
4293 string = pg_xmlCharStrndup(datastr,
len);
4294 xpath_expr = pg_xmlCharStrndup(
VARDATA_ANY(xpath_expr_text), xpath_len);
4304 parse_xml_decl(
string, &xmldecl_len, NULL, NULL, NULL);
4316 ctxt = xmlNewParserCtxt();
4317 if (ctxt == NULL || xmlerrcxt->err_occurred)
4319 "could not allocate parser context");
4320 doc = xmlCtxtReadMemory(ctxt, (
char *)
string + xmldecl_len,
4321 len - xmldecl_len, NULL, NULL, 0);
4322 if (doc == NULL || xmlerrcxt->err_occurred)
4324 "could not parse XML document");
4325 xpathctx = xmlXPathNewContext(doc);
4326 if (xpathctx == NULL || xmlerrcxt->err_occurred)
4328 "could not allocate XPath context");
4329 xpathctx->node = (xmlNodePtr) doc;
4334 for (
i = 0;
i < ns_count;
i++)
4339 if (ns_names_uris_nulls[
i * 2] ||
4340 ns_names_uris_nulls[
i * 2 + 1])
4342 (
errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
4343 errmsg(
"neither namespace name nor URI may be null")));
4346 if (xmlXPathRegisterNs(xpathctx,
4347 (xmlChar *) ns_name,
4348 (xmlChar *) ns_uri) != 0)
4350 (
errmsg(
"could not register XML namespace with name \"%s\" and URI \"%s\"",
4355 xpathcomp = xmlXPathCompile(xpath_expr);
4356 if (xpathcomp == NULL || xmlerrcxt->err_occurred)
4358 "invalid XPath expression");
4367 xpathobj = xmlXPathCompiledEval(xpathcomp, xpathctx);
4368 if (xpathobj == NULL || xmlerrcxt->err_occurred)
4370 "could not create XPath object");
4375 if (res_nitems != NULL)
4376 *res_nitems = xml_xpathobjtoxmlarray(xpathobj, astate, xmlerrcxt);
4378 (
void) xml_xpathobjtoxmlarray(xpathobj, astate, xmlerrcxt);
4383 xmlXPathFreeObject(xpathobj);
4385 xmlXPathFreeCompExpr(xpathcomp);
4387 xmlXPathFreeContext(xpathctx);
4391 xmlFreeParserCtxt(ctxt);
4399 xmlXPathFreeObject(xpathobj);
4400 xmlXPathFreeCompExpr(xpathcomp);
4401 xmlXPathFreeContext(xpathctx);
4403 xmlFreeParserCtxt(ctxt);
4426 xpath_internal(xpath_expr_text,
data, namespaces,
4447 xpath_internal(xpath_expr_text,
data, NULL,
4471 xpath_internal(xpath_expr_text,
data, namespaces,
4495 doc = xml_parse(
data, xmloption_arg,
true,
4553 static inline XmlTableBuilderData *
4556 XmlTableBuilderData *result;
4559 elog(
ERROR,
"%s called with invalid TableFuncScanState", fname);
4560 result = (XmlTableBuilderData *)
state->opaque;
4561 if (result->magic != XMLTABLE_CONTEXT_MAGIC)
4562 elog(
ERROR,
"%s called with invalid TableFuncScanState", fname);
4583 volatile xmlParserCtxtPtr ctxt = NULL;
4584 XmlTableBuilderData *xtCxt;
4587 xtCxt =
palloc0(
sizeof(XmlTableBuilderData));
4588 xtCxt->magic = XMLTABLE_CONTEXT_MAGIC;
4589 xtCxt->natts = natts;
4590 xtCxt->xpathscomp =
palloc0(
sizeof(xmlXPathCompExprPtr) * natts);
4598 ctxt = xmlNewParserCtxt();
4599 if (ctxt == NULL || xmlerrcxt->err_occurred)
4601 "could not allocate parser context");
4606 xmlFreeParserCtxt(ctxt);
4614 xtCxt->xmlerrcxt = xmlerrcxt;
4617 state->opaque = xtCxt;
4631 XmlTableBuilderData *xtCxt;
4636 volatile xmlDocPtr doc = NULL;
4637 volatile xmlXPathContextPtr xpathcxt = NULL;
4639 xtCxt = GetXmlTableBuilderPrivateData(
state,
"XmlTableSetDocument");
4647 length = strlen(
str);
4648 xstr = pg_xmlCharStrndup(
str, length);
4652 doc = xmlCtxtReadMemory(xtCxt->ctxt, (
char *) xstr, length, NULL, NULL, 0);
4653 if (doc == NULL || xtCxt->xmlerrcxt->err_occurred)
4655 "could not parse XML document");
4656 xpathcxt = xmlXPathNewContext(doc);
4657 if (xpathcxt == NULL || xtCxt->xmlerrcxt->err_occurred)
4659 "could not allocate XPath context");
4660 xpathcxt->node = (xmlNodePtr) doc;
4664 if (xpathcxt != NULL)
4665 xmlXPathFreeContext(xpathcxt);
4674 xtCxt->xpathcxt = xpathcxt;
4688 XmlTableBuilderData *xtCxt;
4692 (
errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4693 errmsg(
"DEFAULT namespace is not supported")));
4694 xtCxt = GetXmlTableBuilderPrivateData(
state,
"XmlTableSetNamespace");
4696 if (xmlXPathRegisterNs(xtCxt->xpathcxt,
4697 pg_xmlCharStrndup(
name, strlen(
name)),
4698 pg_xmlCharStrndup(uri, strlen(uri))))
4700 "could not set XML namespace");
4714 XmlTableBuilderData *xtCxt;
4717 xtCxt = GetXmlTableBuilderPrivateData(
state,
"XmlTableSetRowFilter");
4721 (
errcode(ERRCODE_DATA_EXCEPTION),
4722 errmsg(
"row path filter must not be empty string")));
4724 xstr = pg_xmlCharStrndup(path, strlen(path));
4726 xtCxt->xpathcomp = xmlXPathCompile(xstr);
4727 if (xtCxt->xpathcomp == NULL || xtCxt->xmlerrcxt->err_occurred)
4729 "invalid XPath expression");
4743 XmlTableBuilderData *xtCxt;
4748 xtCxt = GetXmlTableBuilderPrivateData(
state,
"XmlTableSetColumnFilter");
4752 (
errcode(ERRCODE_DATA_EXCEPTION),
4753 errmsg(
"column path filter must not be empty string")));
4755 xstr = pg_xmlCharStrndup(path, strlen(path));
4757 xtCxt->xpathscomp[colnum] = xmlXPathCompile(xstr);
4758 if (xtCxt->xpathscomp[colnum] == NULL || xtCxt->xmlerrcxt->err_occurred)
4760 "invalid XPath expression");
4775 XmlTableBuilderData *xtCxt;
4777 xtCxt = GetXmlTableBuilderPrivateData(
state,
"XmlTableFetchRow");
4780 xmlSetStructuredErrorFunc((
void *) xtCxt->xmlerrcxt, xml_errorHandler);
4782 if (xtCxt->xpathobj == NULL)
4784 xtCxt->xpathobj = xmlXPathCompiledEval(xtCxt->xpathcomp, xtCxt->xpathcxt);
4785 if (xtCxt->xpathobj == NULL || xtCxt->xmlerrcxt->err_occurred)
4787 "could not create XPath object");
4789 xtCxt->row_count = 0;
4792 if (xtCxt->xpathobj->type == XPATH_NODESET)
4794 if (xtCxt->xpathobj->nodesetval != NULL)
4796 if (xtCxt->row_count++ < xtCxt->xpathobj->nodesetval->nodeNr)
4818 Oid typid,
int32 typmod,
bool *isnull)
4821 XmlTableBuilderData *xtCxt;
4825 volatile xmlXPathObjectPtr xpathobj = NULL;
4827 xtCxt = GetXmlTableBuilderPrivateData(
state,
"XmlTableGetValue");
4829 Assert(xtCxt->xpathobj &&
4830 xtCxt->xpathobj->type == XPATH_NODESET &&
4831 xtCxt->xpathobj->nodesetval != NULL);
4834 xmlSetStructuredErrorFunc((
void *) xtCxt->xmlerrcxt, xml_errorHandler);
4838 cur = xtCxt->xpathobj->nodesetval->nodeTab[xtCxt->row_count - 1];
4840 Assert(xtCxt->xpathscomp[colnum] != NULL);
4845 xtCxt->xpathcxt->node =
cur;
4848 xpathobj = xmlXPathCompiledEval(xtCxt->xpathscomp[colnum], xtCxt->xpathcxt);
4849 if (xpathobj == NULL || xtCxt->xmlerrcxt->err_occurred)
4851 "could not create XPath object");
4860 if (xpathobj->type == XPATH_NODESET)
4864 if (xpathobj->nodesetval != NULL)
4865 count = xpathobj->nodesetval->nodeNr;
4867 if (xpathobj->nodesetval == NULL || count == 0)
4873 if (typid == XMLOID)
4880 for (
int i = 0;
i < count;
i++)
4883 xml_xmlnodetoxmltype(xpathobj->nodesetval->nodeTab[
i],
4896 (
errcode(ERRCODE_CARDINALITY_VIOLATION),
4897 errmsg(
"more than one value returned by column XPath expression")));
4899 str = xmlXPathCastNodeSetToString(xpathobj->nodesetval);
4900 cstr =
str ? xml_pstrdup_and_free(
str) :
"";
4904 else if (xpathobj->type == XPATH_STRING)
4907 if (typid == XMLOID)
4908 cstr =
escape_xml((
char *) xpathobj->stringval);
4910 cstr = (
char *) xpathobj->stringval;
4912 else if (xpathobj->type == XPATH_BOOLEAN)
4915 bool typispreferred;
4921 if (typcategory != TYPCATEGORY_NUMERIC)
4922 str = xmlXPathCastBooleanToString(xpathobj->boolval);
4924 str = xmlXPathCastNumberToString(xmlXPathCastBooleanToNumber(xpathobj->boolval));
4926 cstr = xml_pstrdup_and_free(
str);
4928 else if (xpathobj->type == XPATH_NUMBER)
4932 str = xmlXPathCastNumberToString(xpathobj->floatval);
4933 cstr = xml_pstrdup_and_free(
str);
4936 elog(
ERROR,
"unexpected XPath object type %u", xpathobj->type);
4947 state->typioparams[colnum],
4952 if (xpathobj != NULL)
4953 xmlXPathFreeObject(xpathobj);
4972 XmlTableBuilderData *xtCxt;
4974 xtCxt = GetXmlTableBuilderPrivateData(
state,
"XmlTableDestroyOpaque");
4977 xmlSetStructuredErrorFunc((
void *) xtCxt->xmlerrcxt, xml_errorHandler);
4979 if (xtCxt->xpathscomp != NULL)
4983 for (
i = 0;
i < xtCxt->natts;
i++)
4984 if (xtCxt->xpathscomp[
i] != NULL)
4985 xmlXPathFreeCompExpr(xtCxt->xpathscomp[
i]);
4988 if (xtCxt->xpathobj != NULL)
4989 xmlXPathFreeObject(xtCxt->xpathobj);
4990 if (xtCxt->xpathcomp != NULL)
4991 xmlXPathFreeCompExpr(xtCxt->xpathcomp);
4992 if (xtCxt->xpathcxt != NULL)
4993 xmlXPathFreeContext(xtCxt->xpathcxt);
4994 if (xtCxt->doc != NULL)
4995 xmlFreeDoc(xtCxt->doc);
4996 if (xtCxt->ctxt != NULL)
4997 xmlFreeParserCtxt(xtCxt->ctxt);
5003 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 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)
elog(ERROR, "%s: %s", p2, msg)
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,...)
int pg_char_to_encoding(const char *name)
const char * pg_encoding_to_char(int encoding)
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)
Assert(fmt[strlen(fmt) - 1] !='\n')
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
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
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)
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)
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 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)
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