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
106 #define ERRCXT_MAGIC 68275028
117 xmlStructuredErrorFunc saved_errfunc;
120 xmlExternalEntityLoader saved_entityfunc;
123 static xmlParserInputPtr xmlPgEntityLoader(
const char *URL,
const char *ID,
124 xmlParserCtxtPtr ctxt);
126 int sqlcode,
const char *msg);
127 static void xml_errorHandler(
void *
data, xmlErrorPtr
error);
128 static int errdetail_for_xml_code(
int code);
132 #ifdef USE_LIBXMLCONTEXT
136 static void xml_memory_init(
void);
137 static void *xml_palloc(
size_t size);
138 static void *xml_repalloc(
void *ptr,
size_t size);
139 static void xml_pfree(
void *ptr);
140 static char *xml_pstrdup(
const char *
string);
143 static xmlChar *xml_text2xmlChar(
text *in);
144 static int parse_xml_decl(
const xmlChar *
str,
size_t *lenp,
145 xmlChar **version, xmlChar **
encoding,
int *standalone);
146 static bool print_xml_decl(
StringInfo buf,
const xmlChar *version,
148 static bool xml_doctype_in_content(
const xmlChar *
str);
150 bool preserve_whitespace,
int encoding,
152 xmlNodePtr *parsed_nodes,
155 static int xml_xpathobjtoxmlarray(xmlXPathObjectPtr xpathobj,
158 static xmlChar *pg_xmlCharStrndup(
const char *
str,
size_t len);
162 const char *xmlschema,
const char *targetns,
166 const char *xmlschema,
bool nulls,
bool tableforest,
167 const char *targetns,
bool top_level);
169 bool nulls,
bool tableforest,
const char *targetns);
171 List *relid_list,
bool nulls,
172 bool tableforest,
const char *targetns);
174 bool nulls,
bool tableforest,
175 const char *targetns);
180 char *tablename,
bool nulls,
bool tableforest,
181 const char *targetns,
bool top_level);
186 #define XMLTABLE_CONTEXT_MAGIC 46922182
187 typedef struct XmlTableBuilderData
193 xmlParserCtxtPtr ctxt;
195 xmlXPathContextPtr xpathcxt;
196 xmlXPathCompExprPtr xpathcomp;
197 xmlXPathObjectPtr xpathobj;
198 xmlXPathCompExprPtr *xpathscomp;
199 } XmlTableBuilderData;
208 const char *path,
int colnum);
211 Oid typid,
int32 typmod,
bool *isnull);
226 #define NO_XML_SUPPORT() \
228 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), \
229 errmsg("unsupported XML feature"), \
230 errdetail("This functionality requires the server to be built with libxml support.")))
234 #define NAMESPACE_XSD "http://www.w3.org/2001/XMLSchema"
235 #define NAMESPACE_XSI "http://www.w3.org/2001/XMLSchema-instance"
236 #define NAMESPACE_SQLXML "http://standards.iso.org/iso/9075/2003/sqlxml"
242 xmlChar_to_encoding(
const xmlChar *encoding_name)
248 (
errcode(ERRCODE_INVALID_PARAMETER_VALUE),
249 errmsg(
"invalid encoding name \"%s\"",
250 (
const char *) encoding_name)));
280 NULL, NULL, fcinfo->context);
292 #define PG_XML_DEFAULT_VERSION "1.0"
313 if ((res_code = parse_xml_decl((xmlChar *)
str,
314 &
len, &version, NULL, &standalone)) == 0)
320 if (!print_xml_decl(&
buf, version, target_encoding, standalone))
338 errcode(ERRCODE_INTERNAL_ERROR),
340 errdetail_for_xml_code(res_code));
371 xmlChar *encodingStr = NULL;
379 nbytes =
buf->len -
buf->cursor;
393 parse_xml_decl((
const xmlChar *)
str, NULL, NULL, &encodingStr, NULL);
473 xmlBuffer_to_xmltype(xmlBufferPtr
buf)
476 xmlBufferLength(
buf));
494 if (argdata[
i] ==
'-' && argdata[
i - 1] ==
'-')
496 (
errcode(ERRCODE_INVALID_XML_COMMENT),
497 errmsg(
"invalid XML comment")));
499 if (
len > 0 && argdata[
len - 1] ==
'-')
501 (
errcode(ERRCODE_INVALID_XML_COMMENT),
502 errmsg(
"invalid XML comment")));
523 xmlChar *xmlbuf = NULL;
525 xmlbuf = xmlEncodeSpecialChars(NULL, xml_text2xmlChar(
arg));
547 int global_standalone = 1;
548 xmlChar *global_version = NULL;
549 bool global_version_no_value =
false;
565 parse_xml_decl((xmlChar *)
str, &
len, &version, NULL, &standalone);
567 if (standalone == 0 && global_standalone == 1)
568 global_standalone = 0;
570 global_standalone = -1;
573 global_version_no_value =
true;
574 else if (!global_version)
575 global_version = version;
576 else if (xmlStrcmp(version, global_version) != 0)
577 global_version_no_value =
true;
583 if (!global_version_no_value || global_standalone >= 0)
589 print_xml_decl(&buf2,
590 (!global_version_no_value) ? global_version : NULL,
650 text *
volatile result;
653 xmlNodePtr content_nodes;
654 volatile xmlBufferPtr
buf = NULL;
655 volatile xmlSaveCtxtPtr ctxt = NULL;
673 &parsed_xmloptiontype, &content_nodes,
674 (
Node *) &escontext);
681 (
errcode(ERRCODE_NOT_AN_XML_DOCUMENT),
682 errmsg(
"not an XML document")));
700 buf = xmlBufferCreate();
702 if (
buf == NULL || xmlerrcxt->err_occurred)
704 "could not allocate xmlBuffer");
707 parse_xml_decl(xml_text2xmlChar(
data), &decl_len, NULL, NULL, NULL);
716 ctxt = xmlSaveToBuffer(
buf, NULL,
717 XML_SAVE_NO_DECL | XML_SAVE_FORMAT);
719 ctxt = xmlSaveToBuffer(
buf, NULL,
722 if (ctxt == NULL || xmlerrcxt->err_occurred)
724 "could not allocate xmlSaveCtxt");
729 if (xmlSaveDoc(ctxt, doc) == -1 || xmlerrcxt->err_occurred)
731 "could not save document to xmlBuffer");
733 else if (content_nodes != NULL)
744 root = xmlNewNode(NULL, (
const xmlChar *)
"content-root");
745 if (root == NULL || xmlerrcxt->err_occurred)
747 "could not allocate xml node");
750 xmlDocSetRootElement(doc, root);
751 xmlAddChild(root, content_nodes);
760 newline = xmlNewDocText(NULL, (
const xmlChar *)
"\n");
761 if (
newline == NULL || xmlerrcxt->err_occurred)
763 "could not allocate xml node");
765 for (xmlNodePtr node = root->children; node; node = node->next)
768 if (node->type != XML_TEXT_NODE && node->prev != NULL)
770 if (xmlSaveTree(ctxt,
newline) == -1 || xmlerrcxt->err_occurred)
774 "could not save newline to xmlBuffer");
778 if (xmlSaveTree(ctxt, node) == -1 || xmlerrcxt->err_occurred)
782 "could not save content to xmlBuffer");
789 if (xmlSaveClose(ctxt) == -1 || xmlerrcxt->err_occurred)
793 "could not close xmlSaveCtxtPtr");
796 result = (
text *) xmlBuffer_to_xmltype(
buf);
828 Datum *named_argvalue,
bool *named_argnull,
829 Datum *argvalue,
bool *argnull)
833 List *named_arg_strings;
839 volatile xmlBufferPtr
buf = NULL;
840 volatile xmlTextWriterPtr writer = NULL;
849 named_arg_strings =
NIL;
856 if (named_argnull[
i])
862 named_arg_strings =
lappend(named_arg_strings,
str);
888 buf = xmlBufferCreate();
889 if (
buf == NULL || xmlerrcxt->err_occurred)
891 "could not allocate xmlBuffer");
892 writer = xmlNewTextWriterMemory(
buf, 0);
893 if (writer == NULL || xmlerrcxt->err_occurred)
895 "could not allocate xmlTextWriter");
897 xmlTextWriterStartElement(writer, (xmlChar *) xexpr->name);
899 forboth(
arg, named_arg_strings, narg, xexpr->arg_names)
905 xmlTextWriterWriteAttribute(writer,
910 foreach(
arg, arg_strings)
914 xmlTextWriterWriteRaw(writer, (xmlChar *)
str);
917 xmlTextWriterEndElement(writer);
920 xmlFreeTextWriter(writer);
923 result = xmlBuffer_to_xmltype(
buf);
928 xmlFreeTextWriter(writer);
956 doc = xml_parse(
data, xmloption_arg, preserve_whitespace,
969 xmlpi(
const char *target,
text *
arg,
bool arg_is_null,
bool *result_is_null)
977 (
errcode(ERRCODE_SYNTAX_ERROR),
978 errmsg(
"invalid XML processing instruction"),
979 errdetail(
"XML processing instruction target name cannot be \"%s\".", target)));
985 *result_is_null = arg_is_null;
998 if (strstr(
string,
"?>") != NULL)
1000 (
errcode(ERRCODE_INVALID_XML_PROCESSING_INSTRUCTION),
1001 errmsg(
"invalid XML processing instruction"),
1002 errdetail(
"XML processing instruction cannot contain \"?>\".")));
1026 xmlChar *orig_version;
1027 int orig_standalone;
1033 parse_xml_decl((xmlChar *)
str, &
len, &orig_version, NULL, &orig_standalone);
1036 orig_version = xml_text2xmlChar(version);
1038 orig_version = NULL;
1043 orig_standalone = 1;
1046 orig_standalone = 0;
1049 orig_standalone = -1;
1057 print_xml_decl(&
buf, orig_version, 0, orig_standalone);
1080 (
errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1081 errmsg(
"xmlvalidate is not implemented")));
1125 static bool first_time =
true;
1135 if (
sizeof(
char) !=
sizeof(xmlChar))
1137 (
errmsg(
"could not initialize XML library"),
1138 errdetail(
"libxml2 has incompatible char type: sizeof(char)=%zu, sizeof(xmlChar)=%zu.",
1139 sizeof(
char),
sizeof(xmlChar))));
1141 #ifdef USE_LIBXMLCONTEXT
1147 LIBXML_TEST_VERSION;
1179 errcxt->magic = ERRCXT_MAGIC;
1180 errcxt->strictness = strictness;
1181 errcxt->err_occurred =
false;
1191 errcxt->saved_errfunc = xmlStructuredError;
1193 #ifdef HAVE_XMLSTRUCTUREDERRORCONTEXT
1194 errcxt->saved_errcxt = xmlStructuredErrorContext;
1196 errcxt->saved_errcxt = xmlGenericErrorContext;
1199 xmlSetStructuredErrorFunc((
void *) errcxt, xml_errorHandler);
1215 #ifdef HAVE_XMLSTRUCTUREDERRORCONTEXT
1216 new_errcxt = xmlStructuredErrorContext;
1218 new_errcxt = xmlGenericErrorContext;
1221 if (new_errcxt != (
void *) errcxt)
1223 (
errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1224 errmsg(
"could not set up XML error handler"),
1225 errhint(
"This probably indicates that the version of libxml2"
1226 " being used is not compatible with the libxml2"
1227 " header files that PostgreSQL was built with.")));
1233 errcxt->saved_entityfunc = xmlGetExternalEntityLoader();
1234 xmlSetExternalEntityLoader(xmlPgEntityLoader);
1255 Assert(errcxt->magic == ERRCXT_MAGIC);
1262 Assert(!errcxt->err_occurred || isError);
1269 #ifdef HAVE_XMLSTRUCTUREDERRORCONTEXT
1270 cur_errcxt = xmlStructuredErrorContext;
1272 cur_errcxt = xmlGenericErrorContext;
1275 if (cur_errcxt != (
void *) errcxt)
1276 elog(
WARNING,
"libxml error handling state is out of sync with xml.c");
1279 xmlSetStructuredErrorFunc(errcxt->saved_errcxt, errcxt->saved_errfunc);
1280 xmlSetExternalEntityLoader(errcxt->saved_entityfunc);
1289 pfree(errcxt->err_buf.data);
1300 return errcxt->err_occurred;
1313 #define CHECK_XML_SPACE(p) \
1315 if (!xmlIsBlank_ch(*(p))) \
1316 return XML_ERR_SPACE_REQUIRED; \
1319 #define SKIP_XML_SPACE(p) \
1320 while (xmlIsBlank_ch(*(p))) (p)++
1324 #define PG_XMLISNAMECHAR(c) \
1325 (xmlIsBaseChar_ch(c) || xmlIsIdeographicQ(c) \
1326 || xmlIsDigit_ch(c) \
1327 || c == '.' || c == '-' || c == '_' || c == ':' \
1328 || xmlIsCombiningQ(c) \
1329 || xmlIsExtender_ch(c))
1333 xml_pnstrdup(
const xmlChar *
str,
size_t len)
1337 result = (xmlChar *)
palloc((
len + 1) *
sizeof(xmlChar));
1338 memcpy(result,
str,
len *
sizeof(xmlChar));
1345 pg_xmlCharStrndup(
const char *
str,
size_t len)
1349 result = (xmlChar *)
palloc((
len + 1) *
sizeof(xmlChar));
1350 memcpy(result,
str,
len);
1362 xml_pstrdup_and_free(xmlChar *
str)
1391 parse_xml_decl(
const xmlChar *
str,
size_t *lenp,
1392 xmlChar **version, xmlChar **
encoding,
int *standalone)
1395 const xmlChar *save_p;
1418 if (xmlStrncmp(p, (xmlChar *)
"<?xml", 5) != 0)
1430 utf8char = xmlGetUTF8Char(p + 5, &utf8len);
1431 if (PG_XMLISNAMECHAR(utf8char))
1439 if (xmlStrncmp(p, (xmlChar *)
"version", 7) != 0)
1440 return XML_ERR_VERSION_MISSING;
1444 return XML_ERR_VERSION_MISSING;
1448 if (*p ==
'\'' || *p ==
'"')
1452 q = xmlStrchr(p + 1, *p);
1454 return XML_ERR_VERSION_MISSING;
1457 *version = xml_pnstrdup(p + 1, q - p - 1);
1461 return XML_ERR_VERSION_MISSING;
1466 if (xmlStrncmp(p, (xmlChar *)
"encoding", 8) == 0)
1468 CHECK_XML_SPACE(save_p);
1472 return XML_ERR_MISSING_ENCODING;
1476 if (*p ==
'\'' || *p ==
'"')
1480 q = xmlStrchr(p + 1, *p);
1482 return XML_ERR_MISSING_ENCODING;
1485 *
encoding = xml_pnstrdup(p + 1, q - p - 1);
1489 return XML_ERR_MISSING_ENCODING;
1499 if (xmlStrncmp(p, (xmlChar *)
"standalone", 10) == 0)
1501 CHECK_XML_SPACE(save_p);
1505 return XML_ERR_STANDALONE_VALUE;
1508 if (xmlStrncmp(p, (xmlChar *)
"'yes'", 5) == 0 ||
1509 xmlStrncmp(p, (xmlChar *)
"\"yes\"", 5) == 0)
1515 else if (xmlStrncmp(p, (xmlChar *)
"'no'", 4) == 0 ||
1516 xmlStrncmp(p, (xmlChar *)
"\"no\"", 4) == 0)
1523 return XML_ERR_STANDALONE_VALUE;
1531 if (xmlStrncmp(p, (xmlChar *)
"?>", 2) != 0)
1532 return XML_ERR_XMLDECL_NOT_FINISHED;
1540 return XML_ERR_INVALID_CHAR;
1569 || standalone != -1)
1588 if (standalone == 1)
1590 else if (standalone == 0)
1630 xml_doctype_in_content(
const xmlChar *
str)
1632 const xmlChar *p =
str;
1648 if (xmlStrncmp(p, (xmlChar *)
"DOCTYPE", 7) == 0)
1652 if (xmlStrncmp(p, (xmlChar *)
"--", 2) != 0)
1655 p = xmlStrstr(p + 2, (xmlChar *)
"--");
1656 if (!p || p[2] !=
'>')
1669 e = xmlStrstr(p, (xmlChar *)
"?>");
1707 bool preserve_whitespace,
int encoding,
1708 XmlOptionType *parsed_xmloptiontype, xmlNodePtr *parsed_nodes,
1713 xmlChar *utf8string;
1715 volatile xmlParserCtxtPtr ctxt = NULL;
1716 volatile xmlDocPtr doc = NULL;
1723 string = xml_text2xmlChar(
data);
1743 bool parse_as_document =
false;
1746 xmlChar *version = NULL;
1752 ctxt = xmlNewParserCtxt();
1753 if (ctxt == NULL || xmlerrcxt->err_occurred)
1755 "could not allocate parser context");
1759 parse_as_document =
true;
1763 res_code = parse_xml_decl(utf8string,
1764 &count, &version, NULL, &standalone);
1768 errcode(ERRCODE_INVALID_XML_CONTENT),
1770 errdetail_for_xml_code(res_code));
1775 if (xml_doctype_in_content(utf8string + count))
1776 parse_as_document =
true;
1780 if (parsed_xmloptiontype != NULL)
1783 if (parsed_nodes != NULL)
1784 *parsed_nodes = NULL;
1786 if (parse_as_document)
1795 doc = xmlCtxtReadDoc(ctxt, utf8string,
1798 XML_PARSE_NOENT | XML_PARSE_DTDATTR
1799 | (preserve_whitespace ? 0 : XML_PARSE_NOBLANKS));
1800 if (doc == NULL || xmlerrcxt->err_occurred)
1804 xml_errsave(escontext, xmlerrcxt,
1805 ERRCODE_INVALID_XML_DOCUMENT,
1806 "invalid XML document");
1808 xml_errsave(escontext, xmlerrcxt,
1809 ERRCODE_INVALID_XML_CONTENT,
1810 "invalid XML content");
1816 doc = xmlNewDoc(version);
1817 if (doc == NULL || xmlerrcxt->err_occurred)
1819 "could not allocate XML document");
1821 Assert(doc->encoding == NULL);
1822 doc->encoding = xmlStrdup((
const xmlChar *)
"UTF-8");
1823 if (doc->encoding == NULL || xmlerrcxt->err_occurred)
1825 "could not allocate XML document");
1826 doc->standalone = standalone;
1829 if (*(utf8string + count))
1831 res_code = xmlParseBalancedChunkMemory(doc, NULL, NULL, 0,
1834 if (res_code != 0 || xmlerrcxt->err_occurred)
1836 xml_errsave(escontext, xmlerrcxt,
1837 ERRCODE_INVALID_XML_CONTENT,
1838 "invalid XML content");
1852 xmlFreeParserCtxt(ctxt);
1860 xmlFreeParserCtxt(ctxt);
1872 xml_text2xmlChar(
text *in)
1878 #ifdef USE_LIBXMLCONTEXT
1885 xml_memory_init(
void)
1888 if (LibxmlContext == NULL)
1894 xmlMemSetup(xml_pfree, xml_palloc, xml_repalloc, xml_pstrdup);
1901 xml_palloc(
size_t size)
1908 xml_repalloc(
void *ptr,
size_t size)
1915 xml_pfree(
void *ptr)
1924 xml_pstrdup(
const char *
string)
1942 static xmlParserInputPtr
1943 xmlPgEntityLoader(
const char *URL,
const char *ID,
1944 xmlParserCtxtPtr ctxt)
1946 return xmlNewStringInputStream(ctxt, (
const xmlChar *)
"");
1966 if (errcxt->magic != ERRCXT_MAGIC)
1967 elog(
ERROR,
"xml_ereport called with invalid PgXmlErrorContext");
1970 errcxt->err_occurred =
false;
1973 if (errcxt->err_buf.len > 0)
1974 detail = errcxt->err_buf.data;
1999 int sqlcode,
const char *msg)
2004 if (errcxt->magic != ERRCXT_MAGIC)
2005 elog(
ERROR,
"xml_errsave called with invalid PgXmlErrorContext");
2008 errcxt->err_occurred =
false;
2011 if (errcxt->err_buf.len > 0)
2012 detail = errcxt->err_buf.data;
2027 xml_errorHandler(
void *
data, xmlErrorPtr
error)
2030 xmlParserCtxtPtr ctxt = (xmlParserCtxtPtr)
error->ctxt;
2031 xmlParserInputPtr
input = (ctxt != NULL) ? ctxt->input : NULL;
2032 xmlNodePtr node =
error->node;
2033 const xmlChar *
name = (node != NULL &&
2034 node->type == XML_ELEMENT_NODE) ? node->name : NULL;
2035 int domain =
error->domain;
2036 int level =
error->level;
2045 if (xmlerrcxt->magic != ERRCXT_MAGIC)
2046 elog(
FATAL,
"xml_errorHandler called with invalid PgXmlErrorContext");
2056 switch (
error->code)
2058 case XML_WAR_NS_URI:
2059 level = XML_ERR_ERROR;
2060 domain = XML_FROM_NAMESPACE;
2063 case XML_ERR_NS_DECL_ERROR:
2064 case XML_WAR_NS_URI_RELATIVE:
2065 case XML_WAR_NS_COLUMN:
2066 case XML_NS_ERR_XML_NAMESPACE:
2067 case XML_NS_ERR_UNDEFINED_NAMESPACE:
2068 case XML_NS_ERR_QNAME:
2069 case XML_NS_ERR_ATTRIBUTE_REDEFINED:
2070 case XML_NS_ERR_EMPTY:
2071 domain = XML_FROM_NAMESPACE;
2078 case XML_FROM_PARSER:
2080 case XML_FROM_MEMORY:
2087 if (
error->code == XML_WAR_UNDECLARED_ENTITY)
2103 if (
error->line > 0)
2107 if (
error->message != NULL)
2125 xmlGenericErrorFunc errFuncSaved = xmlGenericError;
2126 void *errCtxSaved = xmlGenericErrorContext;
2128 xmlSetGenericErrorFunc((
void *) errorBuf,
2132 appendStringInfoLineSeparator(errorBuf);
2134 xmlParserPrintFileContext(
input);
2137 xmlSetGenericErrorFunc(errCtxSaved, errFuncSaved);
2141 chopStringInfoNewlines(errorBuf);
2153 appendStringInfoLineSeparator(&xmlerrcxt->err_buf);
2157 pfree(errorBuf->data);
2170 if (level >= XML_ERR_ERROR)
2172 appendStringInfoLineSeparator(&xmlerrcxt->err_buf);
2176 xmlerrcxt->err_occurred =
true;
2178 else if (level >= XML_ERR_WARNING)
2189 pfree(errorBuf->data);
2204 errdetail_for_xml_code(
int code)
2210 case XML_ERR_INVALID_CHAR:
2213 case XML_ERR_SPACE_REQUIRED:
2216 case XML_ERR_STANDALONE_VALUE:
2217 det =
gettext_noop(
"standalone accepts only 'yes' or 'no'.");
2219 case XML_ERR_VERSION_MISSING:
2220 det =
gettext_noop(
"Malformed declaration: missing version.");
2222 case XML_ERR_MISSING_ENCODING:
2223 det =
gettext_noop(
"Missing encoding in text declaration.");
2225 case XML_ERR_XMLDECL_NOT_FINISHED:
2226 det =
gettext_noop(
"Parsing XML declaration: '?>' expected.");
2229 det =
gettext_noop(
"Unrecognized libxml error code: %d.");
2243 while (
str->len > 0 &&
str->data[
str->len - 1] ==
'\n')
2244 str->data[--
str->len] =
'\0';
2254 chopStringInfoNewlines(
str);
2264 sqlchar_to_unicode(
const char *s)
2275 if (utf8string != s)
2286 return (xmlIsBaseCharQ(
c) || xmlIsIdeographicQ(
c)
2287 ||
c ==
'_' ||
c ==
':');
2295 return (xmlIsBaseCharQ(
c) || xmlIsIdeographicQ(
c)
2297 ||
c ==
'.' ||
c ==
'-' ||
c ==
'_' ||
c ==
':'
2298 || xmlIsCombiningQ(
c)
2299 || xmlIsExtenderQ(
c));
2319 Assert(fully_escaped || !escape_period);
2325 if (*p ==
':' && (p ==
ident || fully_escaped))
2327 else if (*p ==
'_' && *(p + 1) ==
'x')
2329 else if (fully_escaped && p ==
ident &&
2337 else if (escape_period && *p ==
'.')
2341 pg_wchar u = sqlchar_to_unicode(p);
2344 ? !is_valid_xml_namefirst(u)
2345 : !is_valid_xml_namechar(u))
2373 if (*p ==
'_' && *(p + 1) ==
'x'
2374 && isxdigit((
unsigned char) *(p + 2))
2375 && isxdigit((
unsigned char) *(p + 3))
2376 && isxdigit((
unsigned char) *(p + 4))
2377 && isxdigit((
unsigned char) *(p + 5))
2383 sscanf(p + 2,
"%X", &u);
2426 elmlen, elmbyval, elmalign,
2427 &elem_values, &elem_nulls,
2432 for (
i = 0;
i < num_elems;
i++)
2481 (
errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2482 errmsg(
"date out of range"),
2483 errdetail(
"XML does not support infinite date values.")));
2503 (
errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2504 errmsg(
"timestamp out of range"),
2505 errdetail(
"XML does not support infinite timestamp values.")));
2510 (
errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2511 errmsg(
"timestamp out of range")));
2516 case TIMESTAMPTZOID:
2522 const char *tzn = NULL;
2530 (
errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2531 errmsg(
"timestamp out of range"),
2532 errdetail(
"XML does not support infinite timestamp values.")));
2537 (
errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2538 errmsg(
"timestamp out of range")));
2548 volatile xmlBufferPtr
buf = NULL;
2549 volatile xmlTextWriterPtr writer = NULL;
2556 buf = xmlBufferCreate();
2557 if (
buf == NULL || xmlerrcxt->err_occurred)
2559 "could not allocate xmlBuffer");
2560 writer = xmlNewTextWriterMemory(
buf, 0);
2561 if (writer == NULL || xmlerrcxt->err_occurred)
2563 "could not allocate xmlTextWriter");
2566 xmlTextWriterWriteBase64(writer,
VARDATA_ANY(bstr),
2569 xmlTextWriterWriteBinHex(writer,
VARDATA_ANY(bstr),
2573 xmlFreeTextWriter(writer);
2576 result =
pstrdup((
const char *) xmlBufferContent(
buf));
2581 xmlFreeTextWriter(writer);
2608 if (
type == XMLOID || !xml_escape_strings)
2631 for (p =
str; *p; p++)
2659 size_t len = strlen(s) + 1;
2662 memcpy(ret, s,
len);
2722 elog(
ERROR,
"SPI_execute returned %s for %s",
2749 " WHERE relnamespace = %u AND relkind IN ("
2753 " AND pg_catalog.has_table_privilege (oid, 'SELECT')"
2754 " ORDER BY relname;",
nspid);
2764 #define XML_VISIBLE_SCHEMAS_EXCLUDE "(nspname ~ '^pg_' OR nspname = 'information_schema')"
2766 #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
2781 " WHERE relkind IN ("
2785 " AND pg_catalog.has_table_privilege(pg_class.oid, 'SELECT')"
2797 const char *xmlschema,
bool nulls,
bool tableforest,
2798 const char *targetns,
bool top_level)
2807 xmlschema, nulls, tableforest,
2808 targetns, top_level);
2835 NULL, nulls, tableforest,
2865 (
errcode(ERRCODE_UNDEFINED_CURSOR),
2866 errmsg(
"cursor \"%s\" does not exist",
name)));
2871 tableforest, targetns,
true);
2896 const char *xmlschema,
const char *targetns,
2900 Assert(top_level || !xmlschema);
2906 if (strlen(targetns) > 0)
2912 if (strlen(targetns) > 0)
2930 const char *xmlschema,
bool nulls,
bool tableforest,
2931 const char *targetns,
bool top_level)
2947 (
errcode(ERRCODE_DATA_EXCEPTION),
2948 errmsg(
"invalid query")));
2953 targetns, top_level);
2962 tableforest, targetns, top_level);
2985 tableforest, targetns);
3006 elog(
ERROR,
"SPI_prepare(\"%s\") failed", query);
3009 elog(
ERROR,
"SPI_cursor_open(\"%s\") failed", query);
3013 tableforest, targetns));
3028 const char *xmlschema;
3035 (
errcode(ERRCODE_UNDEFINED_CURSOR),
3036 errmsg(
"cursor \"%s\" does not exist",
name)));
3039 (
errcode(ERRCODE_INVALID_CURSOR_STATE),
3040 errmsg(
"portal \"%s\" does not return tuples",
name)));
3044 tableforest, targetns));
3059 const char *xmlschema;
3063 tableforest, targetns);
3067 xmlschema, nulls, tableforest,
3080 const char *xmlschema;
3087 elog(
ERROR,
"SPI_prepare(\"%s\") failed", query);
3090 elog(
ERROR,
"SPI_cursor_open(\"%s\") failed", query);
3098 xmlschema, nulls, tableforest,
3110 bool tableforest,
const char *targetns,
bool top_level)
3131 foreach(cell, relid_list)
3166 nulls, tableforest, targetns,
true)));
3179 if (strlen(targetns) > 0)
3182 " targetNamespace=\"%s\"\n"
3183 " elementFormDefault=\"qualified\"",
3199 bool tableforest,
const char *targetns)
3218 foreach(cell, relid_list)
3232 nulls, tableforest, targetns));
3251 nulls, tableforest, targetns)));
3270 tableforest, targetns);
3273 xmlschema->
data, nulls,
3274 tableforest, targetns,
true)));
3285 bool tableforest,
const char *targetns)
3306 foreach(cell, nspid_list)
3312 tableforest, targetns,
false);
3334 tableforest, targetns)));
3340 const char *targetns)
3358 foreach(cell, relid_list)
3389 tableforest, targetns)));
3404 nulls, tableforest, targetns)));
3445 bool tableforest,
const char *targetns)
3449 char *tabletypename;
3462 elog(
ERROR,
"cache lookup failed for relation %u", relid);
3487 tabletypename =
"TableType";
3488 rowtypename =
"RowType";
3497 "<xsd:complexType name=\"%s\">\n"
3498 " <xsd:sequence>\n",
3501 for (
i = 0;
i < tupdesc->
natts;
i++)
3505 if (att->attisdropped)
3508 " <xsd:element name=\"%s\" type=\"%s\"%s></xsd:element>\n",
3512 nulls ?
" nillable=\"true\"" :
" minOccurs=\"0\"");
3516 " </xsd:sequence>\n"
3517 "</xsd:complexType>\n\n");
3522 "<xsd:complexType name=\"%s\">\n"
3524 " <xsd:element name=\"row\" type=\"%s\" minOccurs=\"0\" maxOccurs=\"unbounded\"/>\n"
3525 " </xsd:sequence>\n"
3526 "</xsd:complexType>\n\n",
3527 tabletypename, rowtypename);
3530 "<xsd:element name=\"%s\" type=\"%s\"/>\n\n",
3531 xmltn, tabletypename);
3535 "<xsd:element name=\"%s\" type=\"%s\"/>\n\n",
3536 xmltn, rowtypename);
3550 bool tableforest,
const char *targetns)
3555 char *schematypename;
3572 "<xsd:complexType name=\"%s\">\n", schematypename);
3578 " <xsd:sequence>\n");
3580 foreach(cell, relid_list)
3592 " <xsd:element name=\"%s\" type=\"%s\"/>\n",
3593 xmltn, tabletypename);
3596 " <xsd:element name=\"%s\" type=\"%s\" minOccurs=\"0\" maxOccurs=\"unbounded\"/>\n",
3597 xmltn, tabletypename);
3605 " </xsd:sequence>\n");
3607 "</xsd:complexType>\n\n");
3610 "<xsd:element name=\"%s\" type=\"%s\"/>\n\n",
3611 xmlsn, schematypename);
3623 bool tableforest,
const char *targetns)
3627 char *catalogtypename;
3643 "<xsd:complexType name=\"%s\">\n", catalogtypename);
3647 foreach(cell, nspid_list)
3658 " <xsd:element name=\"%s\" type=\"%s\"/>\n",
3659 xmlsn, schematypename);
3665 "</xsd:complexType>\n\n");
3668 "<xsd:element name=\"%s\" type=\"%s\"/>\n\n",
3669 xmlcn, catalogtypename);
3704 ((typmod -
VARHDRSZ) >> 16) & 0xffff,
3743 case TIMESTAMPTZOID:
3762 elog(
ERROR,
"cache lookup failed for type %u", typeoid);
3792 foreach(cell0, tupdesc_list)
3796 for (
i = 0;
i < tupdesc->
natts;
i++)
3800 if (att->attisdropped)
3807 foreach(cell0, uniquetypes)
3812 if (basetypid != typid)
3819 foreach(cell0, uniquetypes)
3846 if (typeoid == XMLOID)
3849 "<xsd:complexType mixed=\"true\">\n"
3851 " <xsd:any name=\"element\" minOccurs=\"0\" maxOccurs=\"unbounded\" processContents=\"skip\"/>\n"
3852 " </xsd:sequence>\n"
3853 "</xsd:complexType>\n");
3858 "<xsd:simpleType name=\"%s\">\n",
typename);
3866 " <xsd:restriction base=\"xsd:string\">\n");
3869 " <xsd:maxLength value=\"%d\"/>\n",
3876 " <xsd:restriction base=\"xsd:%s\">\n"
3877 " </xsd:restriction>\n",
3884 " <xsd:restriction base=\"xsd:decimal\">\n"
3885 " <xsd:totalDigits value=\"%d\"/>\n"
3886 " <xsd:fractionDigits value=\"%d\"/>\n"
3887 " </xsd:restriction>\n",
3888 ((typmod -
VARHDRSZ) >> 16) & 0xffff,
3894 " <xsd:restriction base=\"xsd:short\">\n"
3895 " <xsd:maxInclusive value=\"%d\"/>\n"
3896 " <xsd:minInclusive value=\"%d\"/>\n"
3897 " </xsd:restriction>\n",
3898 SHRT_MAX, SHRT_MIN);
3903 " <xsd:restriction base=\"xsd:int\">\n"
3904 " <xsd:maxInclusive value=\"%d\"/>\n"
3905 " <xsd:minInclusive value=\"%d\"/>\n"
3906 " </xsd:restriction>\n",
3912 " <xsd:restriction base=\"xsd:long\">\n"
3915 " </xsd:restriction>\n",
3922 " <xsd:restriction base=\"xsd:float\"></xsd:restriction>\n");
3927 " <xsd:restriction base=\"xsd:double\"></xsd:restriction>\n");
3932 " <xsd:restriction base=\"xsd:boolean\"></xsd:restriction>\n");
3938 const char *tz = (typeoid == TIMETZOID ?
"(\\+|-)\\p{Nd}{2}:\\p{Nd}{2}" :
"");
3942 " <xsd:restriction base=\"xsd:time\">\n"
3943 " <xsd:pattern value=\"\\p{Nd}{2}:\\p{Nd}{2}:\\p{Nd}{2}(.\\p{Nd}+)?%s\"/>\n"
3944 " </xsd:restriction>\n", tz);
3945 else if (typmod == 0)
3947 " <xsd:restriction base=\"xsd:time\">\n"
3948 " <xsd:pattern value=\"\\p{Nd}{2}:\\p{Nd}{2}:\\p{Nd}{2}%s\"/>\n"
3949 " </xsd:restriction>\n", tz);
3952 " <xsd:restriction base=\"xsd:time\">\n"
3953 " <xsd:pattern value=\"\\p{Nd}{2}:\\p{Nd}{2}:\\p{Nd}{2}.\\p{Nd}{%d}%s\"/>\n"
3954 " </xsd:restriction>\n", typmod -
VARHDRSZ, tz);
3959 case TIMESTAMPTZOID:
3961 const char *tz = (typeoid == TIMESTAMPTZOID ?
"(\\+|-)\\p{Nd}{2}:\\p{Nd}{2}" :
"");
3965 " <xsd:restriction base=\"xsd:dateTime\">\n"
3966 " <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"
3967 " </xsd:restriction>\n", tz);
3968 else if (typmod == 0)
3970 " <xsd:restriction base=\"xsd:dateTime\">\n"
3971 " <xsd:pattern value=\"\\p{Nd}{4}-\\p{Nd}{2}-\\p{Nd}{2}T\\p{Nd}{2}:\\p{Nd}{2}:\\p{Nd}{2}%s\"/>\n"
3972 " </xsd:restriction>\n", tz);
3975 " <xsd:restriction base=\"xsd:dateTime\">\n"
3976 " <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"
3977 " </xsd:restriction>\n", typmod -
VARHDRSZ, tz);
3983 " <xsd:restriction base=\"xsd:date\">\n"
3984 " <xsd:pattern value=\"\\p{Nd}{4}-\\p{Nd}{2}-\\p{Nd}{2}\"/>\n"
3985 " </xsd:restriction>\n");
3992 int32 base_typmod = -1;
3997 " <xsd:restriction base=\"%s\"/>\n",
4015 bool nulls,
bool tableforest,
4016 const char *targetns,
bool top_level)
4088 if (
cur->type != XML_ATTRIBUTE_NODE &&
cur->type != XML_TEXT_NODE)
4090 void (*
volatile nodefree) (xmlNodePtr) = NULL;
4091 volatile xmlBufferPtr
buf = NULL;
4092 volatile xmlNodePtr cur_copy = NULL;
4098 buf = xmlBufferCreate();
4099 if (
buf == NULL || xmlerrcxt->err_occurred)
4101 "could not allocate xmlBuffer");
4115 cur_copy = xmlCopyNode(
cur, 1);
4116 if (cur_copy == NULL || xmlerrcxt->err_occurred)
4118 "could not copy node");
4119 nodefree = (cur_copy->type == XML_DOCUMENT_NODE) ?
4120 (
void (*) (xmlNodePtr)) xmlFreeDoc : xmlFreeNode;
4122 bytes = xmlNodeDump(
buf, NULL, cur_copy, 0, 0);
4123 if (bytes == -1 || xmlerrcxt->err_occurred)
4125 "could not dump node");
4127 result = xmlBuffer_to_xmltype(
buf);
4142 str = xmlXPathCastNodeToString(
cur);
4174 xml_xpathobjtoxmlarray(xmlXPathObjectPtr xpathobj,
4183 switch (xpathobj->type)
4186 if (xpathobj->nodesetval != NULL)
4188 result = xpathobj->nodesetval->nodeNr;
4193 for (
i = 0;
i < result;
i++)
4195 datum =
PointerGetDatum(xml_xmlnodetoxmltype(xpathobj->nodesetval->nodeTab[
i],
4208 datumtype = BOOLOID;
4215 datumtype = FLOAT8OID;
4222 datumtype = CSTRINGOID;
4226 elog(
ERROR,
"xpath expression result type %d is unsupported",
4256 volatile xmlParserCtxtPtr ctxt = NULL;
4257 volatile xmlDocPtr doc = NULL;
4258 volatile xmlXPathContextPtr xpathctx = NULL;
4259 volatile xmlXPathCompExprPtr xpathcomp = NULL;
4260 volatile xmlXPathObjectPtr xpathobj = NULL;
4265 xmlChar *xpath_expr;
4266 size_t xmldecl_len = 0;
4269 Datum *ns_names_uris;
4270 bool *ns_names_uris_nulls;
4282 ndim = namespaces ?
ARR_NDIM(namespaces) : 0;
4289 if (ndim != 2 || dims[1] != 2)
4291 (
errcode(ERRCODE_DATA_EXCEPTION),
4292 errmsg(
"invalid array for XML namespace mapping"),
4293 errdetail(
"The array must be two-dimensional with length of the second axis equal to 2.")));
4298 &ns_names_uris, &ns_names_uris_nulls,
4301 Assert((ns_count % 2) == 0);
4306 ns_names_uris = NULL;
4307 ns_names_uris_nulls = NULL;
4316 (
errcode(ERRCODE_DATA_EXCEPTION),
4317 errmsg(
"empty XPath expression")));
4319 string = pg_xmlCharStrndup(datastr,
len);
4320 xpath_expr = pg_xmlCharStrndup(
VARDATA_ANY(xpath_expr_text), xpath_len);
4330 parse_xml_decl(
string, &xmldecl_len, NULL, NULL, NULL);
4342 ctxt = xmlNewParserCtxt();
4343 if (ctxt == NULL || xmlerrcxt->err_occurred)
4345 "could not allocate parser context");
4346 doc = xmlCtxtReadMemory(ctxt, (
char *)
string + xmldecl_len,
4347 len - xmldecl_len, NULL, NULL, 0);
4348 if (doc == NULL || xmlerrcxt->err_occurred)
4350 "could not parse XML document");
4351 xpathctx = xmlXPathNewContext(doc);
4352 if (xpathctx == NULL || xmlerrcxt->err_occurred)
4354 "could not allocate XPath context");
4355 xpathctx->node = (xmlNodePtr) doc;
4360 for (
i = 0;
i < ns_count;
i++)
4365 if (ns_names_uris_nulls[
i * 2] ||
4366 ns_names_uris_nulls[
i * 2 + 1])
4368 (
errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
4369 errmsg(
"neither namespace name nor URI may be null")));
4372 if (xmlXPathRegisterNs(xpathctx,
4373 (xmlChar *) ns_name,
4374 (xmlChar *) ns_uri) != 0)
4376 (
errmsg(
"could not register XML namespace with name \"%s\" and URI \"%s\"",
4381 xpathcomp = xmlXPathCompile(xpath_expr);
4382 if (xpathcomp == NULL || xmlerrcxt->err_occurred)
4384 "invalid XPath expression");
4393 xpathobj = xmlXPathCompiledEval(xpathcomp, xpathctx);
4394 if (xpathobj == NULL || xmlerrcxt->err_occurred)
4396 "could not create XPath object");
4401 if (res_nitems != NULL)
4402 *res_nitems = xml_xpathobjtoxmlarray(xpathobj, astate, xmlerrcxt);
4404 (
void) xml_xpathobjtoxmlarray(xpathobj, astate, xmlerrcxt);
4409 xmlXPathFreeObject(xpathobj);
4411 xmlXPathFreeCompExpr(xpathcomp);
4413 xmlXPathFreeContext(xpathctx);
4417 xmlFreeParserCtxt(ctxt);
4425 xmlXPathFreeObject(xpathobj);
4426 xmlXPathFreeCompExpr(xpathcomp);
4427 xmlXPathFreeContext(xpathctx);
4429 xmlFreeParserCtxt(ctxt);
4452 xpath_internal(xpath_expr_text,
data, namespaces,
4473 xpath_internal(xpath_expr_text,
data, NULL,
4497 xpath_internal(xpath_expr_text,
data, namespaces,
4521 doc = xml_parse(
data, xmloption_arg,
true,
4579 static inline XmlTableBuilderData *
4582 XmlTableBuilderData *result;
4585 elog(
ERROR,
"%s called with invalid TableFuncScanState", fname);
4586 result = (XmlTableBuilderData *)
state->opaque;
4587 if (result->magic != XMLTABLE_CONTEXT_MAGIC)
4588 elog(
ERROR,
"%s called with invalid TableFuncScanState", fname);
4609 volatile xmlParserCtxtPtr ctxt = NULL;
4610 XmlTableBuilderData *xtCxt;
4613 xtCxt =
palloc0(
sizeof(XmlTableBuilderData));
4614 xtCxt->magic = XMLTABLE_CONTEXT_MAGIC;
4615 xtCxt->natts = natts;
4616 xtCxt->xpathscomp =
palloc0(
sizeof(xmlXPathCompExprPtr) * natts);
4624 ctxt = xmlNewParserCtxt();
4625 if (ctxt == NULL || xmlerrcxt->err_occurred)
4627 "could not allocate parser context");
4632 xmlFreeParserCtxt(ctxt);
4640 xtCxt->xmlerrcxt = xmlerrcxt;
4643 state->opaque = xtCxt;
4657 XmlTableBuilderData *xtCxt;
4662 volatile xmlDocPtr doc = NULL;
4663 volatile xmlXPathContextPtr xpathcxt = NULL;
4665 xtCxt = GetXmlTableBuilderPrivateData(
state,
"XmlTableSetDocument");
4673 length = strlen(
str);
4674 xstr = pg_xmlCharStrndup(
str, length);
4678 doc = xmlCtxtReadMemory(xtCxt->ctxt, (
char *) xstr, length, NULL, NULL, 0);
4679 if (doc == NULL || xtCxt->xmlerrcxt->err_occurred)
4681 "could not parse XML document");
4682 xpathcxt = xmlXPathNewContext(doc);
4683 if (xpathcxt == NULL || xtCxt->xmlerrcxt->err_occurred)
4685 "could not allocate XPath context");
4686 xpathcxt->node = (xmlNodePtr) doc;
4690 if (xpathcxt != NULL)
4691 xmlXPathFreeContext(xpathcxt);
4700 xtCxt->xpathcxt = xpathcxt;
4714 XmlTableBuilderData *xtCxt;
4718 (
errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4719 errmsg(
"DEFAULT namespace is not supported")));
4720 xtCxt = GetXmlTableBuilderPrivateData(
state,
"XmlTableSetNamespace");
4722 if (xmlXPathRegisterNs(xtCxt->xpathcxt,
4723 pg_xmlCharStrndup(
name, strlen(
name)),
4724 pg_xmlCharStrndup(uri, strlen(uri))))
4726 "could not set XML namespace");
4740 XmlTableBuilderData *xtCxt;
4743 xtCxt = GetXmlTableBuilderPrivateData(
state,
"XmlTableSetRowFilter");
4747 (
errcode(ERRCODE_DATA_EXCEPTION),
4748 errmsg(
"row path filter must not be empty string")));
4750 xstr = pg_xmlCharStrndup(path, strlen(path));
4752 xtCxt->xpathcomp = xmlXPathCompile(xstr);
4753 if (xtCxt->xpathcomp == NULL || xtCxt->xmlerrcxt->err_occurred)
4755 "invalid XPath expression");
4769 XmlTableBuilderData *xtCxt;
4774 xtCxt = GetXmlTableBuilderPrivateData(
state,
"XmlTableSetColumnFilter");
4778 (
errcode(ERRCODE_DATA_EXCEPTION),
4779 errmsg(
"column path filter must not be empty string")));
4781 xstr = pg_xmlCharStrndup(path, strlen(path));
4783 xtCxt->xpathscomp[colnum] = xmlXPathCompile(xstr);
4784 if (xtCxt->xpathscomp[colnum] == NULL || xtCxt->xmlerrcxt->err_occurred)
4786 "invalid XPath expression");
4801 XmlTableBuilderData *xtCxt;
4803 xtCxt = GetXmlTableBuilderPrivateData(
state,
"XmlTableFetchRow");
4806 xmlSetStructuredErrorFunc((
void *) xtCxt->xmlerrcxt, xml_errorHandler);
4808 if (xtCxt->xpathobj == NULL)
4810 xtCxt->xpathobj = xmlXPathCompiledEval(xtCxt->xpathcomp, xtCxt->xpathcxt);
4811 if (xtCxt->xpathobj == NULL || xtCxt->xmlerrcxt->err_occurred)
4813 "could not create XPath object");
4815 xtCxt->row_count = 0;
4818 if (xtCxt->xpathobj->type == XPATH_NODESET)
4820 if (xtCxt->xpathobj->nodesetval != NULL)
4822 if (xtCxt->row_count++ < xtCxt->xpathobj->nodesetval->nodeNr)
4844 Oid typid,
int32 typmod,
bool *isnull)
4847 XmlTableBuilderData *xtCxt;
4851 volatile xmlXPathObjectPtr xpathobj = NULL;
4853 xtCxt = GetXmlTableBuilderPrivateData(
state,
"XmlTableGetValue");
4855 Assert(xtCxt->xpathobj &&
4856 xtCxt->xpathobj->type == XPATH_NODESET &&
4857 xtCxt->xpathobj->nodesetval != NULL);
4860 xmlSetStructuredErrorFunc((
void *) xtCxt->xmlerrcxt, xml_errorHandler);
4864 cur = xtCxt->xpathobj->nodesetval->nodeTab[xtCxt->row_count - 1];
4866 Assert(xtCxt->xpathscomp[colnum] != NULL);
4871 xtCxt->xpathcxt->node =
cur;
4874 xpathobj = xmlXPathCompiledEval(xtCxt->xpathscomp[colnum], xtCxt->xpathcxt);
4875 if (xpathobj == NULL || xtCxt->xmlerrcxt->err_occurred)
4877 "could not create XPath object");
4886 if (xpathobj->type == XPATH_NODESET)
4890 if (xpathobj->nodesetval != NULL)
4891 count = xpathobj->nodesetval->nodeNr;
4893 if (xpathobj->nodesetval == NULL || count == 0)
4899 if (typid == XMLOID)
4906 for (
int i = 0;
i < count;
i++)
4909 xml_xmlnodetoxmltype(xpathobj->nodesetval->nodeTab[
i],
4922 (
errcode(ERRCODE_CARDINALITY_VIOLATION),
4923 errmsg(
"more than one value returned by column XPath expression")));
4925 str = xmlXPathCastNodeSetToString(xpathobj->nodesetval);
4926 cstr =
str ? xml_pstrdup_and_free(
str) :
"";
4930 else if (xpathobj->type == XPATH_STRING)
4933 if (typid == XMLOID)
4934 cstr =
escape_xml((
char *) xpathobj->stringval);
4936 cstr = (
char *) xpathobj->stringval;
4938 else if (xpathobj->type == XPATH_BOOLEAN)
4941 bool typispreferred;
4947 if (typcategory != TYPCATEGORY_NUMERIC)
4948 str = xmlXPathCastBooleanToString(xpathobj->boolval);
4950 str = xmlXPathCastNumberToString(xmlXPathCastBooleanToNumber(xpathobj->boolval));
4952 cstr = xml_pstrdup_and_free(
str);
4954 else if (xpathobj->type == XPATH_NUMBER)
4958 str = xmlXPathCastNumberToString(xpathobj->floatval);
4959 cstr = xml_pstrdup_and_free(
str);
4962 elog(
ERROR,
"unexpected XPath object type %u", xpathobj->type);
4973 state->typioparams[colnum],
4978 if (xpathobj != NULL)
4979 xmlXPathFreeObject(xpathobj);
4998 XmlTableBuilderData *xtCxt;
5000 xtCxt = GetXmlTableBuilderPrivateData(
state,
"XmlTableDestroyOpaque");
5003 xmlSetStructuredErrorFunc((
void *) xtCxt->xmlerrcxt, xml_errorHandler);
5005 if (xtCxt->xpathscomp != NULL)
5009 for (
i = 0;
i < xtCxt->natts;
i++)
5010 if (xtCxt->xpathscomp[
i] != NULL)
5011 xmlXPathFreeCompExpr(xtCxt->xpathscomp[
i]);
5014 if (xtCxt->xpathobj != NULL)
5015 xmlXPathFreeObject(xtCxt->xpathobj);
5016 if (xtCxt->xpathcomp != NULL)
5017 xmlXPathFreeCompExpr(xtCxt->xpathcomp);
5018 if (xtCxt->xpathcxt != NULL)
5019 xmlXPathFreeContext(xtCxt->xpathcxt);
5020 if (xtCxt->doc != NULL)
5021 xmlFreeDoc(xtCxt->doc);
5022 if (xtCxt->ctxt != NULL)
5023 xmlFreeParserCtxt(xtCxt->ctxt);
5029 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,...)
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
#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)
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)
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