49#include <libxml/chvalid.h>
50#include <libxml/entities.h>
51#include <libxml/parser.h>
52#include <libxml/parserInternals.h>
53#include <libxml/tree.h>
54#include <libxml/uri.h>
55#include <libxml/xmlerror.h>
56#include <libxml/xmlsave.h>
57#include <libxml/xmlversion.h>
58#include <libxml/xmlwriter.h>
59#include <libxml/xpath.h>
60#include <libxml/xpathInternals.h>
67#if LIBXML_VERSION >= 20704
68#define HAVE_XMLSTRUCTUREDERRORCONTEXT 1
74#if LIBXML_VERSION >= 21200
75#define PgXmlErrorPtr const xmlError *
77#define PgXmlErrorPtr xmlErrorPtr
115#define ERRCXT_MAGIC 68275028
126 xmlStructuredErrorFunc saved_errfunc;
129 xmlExternalEntityLoader saved_entityfunc;
132static xmlParserInputPtr xmlPgEntityLoader(
const char *URL,
const char *ID,
133 xmlParserCtxtPtr ctxt);
135 int sqlcode,
const char *msg);
136static void xml_errorHandler(
void *
data, PgXmlErrorPtr
error);
137static int errdetail_for_xml_code(
int code);
141#ifdef USE_LIBXMLCONTEXT
145static void xml_memory_init(
void);
146static void *xml_palloc(
size_t size);
147static void *xml_repalloc(
void *ptr,
size_t size);
148static void xml_pfree(
void *ptr);
149static char *xml_pstrdup(
const char *
string);
152static xmlChar *xml_text2xmlChar(
text *in);
153static int parse_xml_decl(
const xmlChar *
str,
size_t *lenp,
154 xmlChar **version, xmlChar **
encoding,
int *standalone);
155static bool print_xml_decl(
StringInfo buf,
const xmlChar *version,
157static bool xml_doctype_in_content(
const xmlChar *
str);
159 bool preserve_whitespace,
int encoding,
161 xmlNodePtr *parsed_nodes,
164static int xml_xpathobjtoxmlarray(xmlXPathObjectPtr xpathobj,
167static xmlChar *pg_xmlCharStrndup(
const char *
str,
size_t len);
171 const char *xmlschema,
const char *targetns,
175 const char *xmlschema,
bool nulls,
bool tableforest,
176 const char *targetns,
bool top_level);
178 bool nulls,
bool tableforest,
const char *targetns);
180 List *relid_list,
bool nulls,
181 bool tableforest,
const char *targetns);
183 bool nulls,
bool tableforest,
184 const char *targetns);
189 char *tablename,
bool nulls,
bool tableforest,
190 const char *targetns,
bool top_level);
195#define XMLTABLE_CONTEXT_MAGIC 46922182
196typedef struct XmlTableBuilderData
202 xmlParserCtxtPtr ctxt;
204 xmlXPathContextPtr xpathcxt;
205 xmlXPathCompExprPtr xpathcomp;
206 xmlXPathObjectPtr xpathobj;
207 xmlXPathCompExprPtr *xpathscomp;
208} XmlTableBuilderData;
217 const char *path,
int colnum);
220 Oid typid,
int32 typmod,
bool *isnull);
235#define NO_XML_SUPPORT() \
237 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), \
238 errmsg("unsupported XML feature"), \
239 errdetail("This functionality requires the server to be built with libxml support.")))
243#define NAMESPACE_XSD "http://www.w3.org/2001/XMLSchema"
244#define NAMESPACE_XSI "http://www.w3.org/2001/XMLSchema-instance"
245#define NAMESPACE_SQLXML "http://standards.iso.org/iso/9075/2003/sqlxml"
251xmlChar_to_encoding(
const xmlChar *encoding_name)
257 (
errcode(ERRCODE_INVALID_PARAMETER_VALUE),
258 errmsg(
"invalid encoding name \"%s\"",
259 (
const char *) encoding_name)));
289 NULL, NULL, fcinfo->context);
301#define PG_XML_DEFAULT_VERSION "1.0"
322 if ((res_code = parse_xml_decl((xmlChar *)
str,
323 &
len, &version, NULL, &standalone)) == 0)
329 if (!print_xml_decl(&
buf, version, target_encoding, standalone))
349 errdetail_for_xml_code(res_code));
380 xmlChar *encodingStr = NULL;
388 nbytes =
buf->len -
buf->cursor;
402 parse_xml_decl((
const xmlChar *)
str, NULL, NULL, &encodingStr, NULL);
482xmlBuffer_to_xmltype(xmlBufferPtr
buf)
485 xmlBufferLength(
buf));
503 if (argdata[
i] ==
'-' && argdata[
i - 1] ==
'-')
505 (
errcode(ERRCODE_INVALID_XML_COMMENT),
506 errmsg(
"invalid XML comment")));
508 if (
len > 0 && argdata[
len - 1] ==
'-')
510 (
errcode(ERRCODE_INVALID_XML_COMMENT),
511 errmsg(
"invalid XML comment")));
532 xmlChar *xmlbuf = NULL;
534 xmlbuf = xmlEncodeSpecialChars(NULL, xml_text2xmlChar(
arg));
556 int global_standalone = 1;
557 xmlChar *global_version = NULL;
558 bool global_version_no_value =
false;
574 parse_xml_decl((xmlChar *)
str, &
len, &version, NULL, &standalone);
576 if (standalone == 0 && global_standalone == 1)
577 global_standalone = 0;
579 global_standalone = -1;
582 global_version_no_value =
true;
583 else if (!global_version)
584 global_version = version;
585 else if (xmlStrcmp(version, global_version) != 0)
586 global_version_no_value =
true;
592 if (!global_version_no_value || global_standalone >= 0)
598 print_xml_decl(&buf2,
599 (!global_version_no_value) ? global_version : NULL,
659 text *
volatile result;
662 xmlNodePtr content_nodes;
663 volatile xmlBufferPtr
buf = NULL;
664 volatile xmlSaveCtxtPtr ctxt = NULL;
688 &parsed_xmloptiontype, &content_nodes,
689 (
Node *) &escontext);
696 (
errcode(ERRCODE_NOT_AN_XML_DOCUMENT),
697 errmsg(
"not an XML document")));
715 buf = xmlBufferCreate();
717 if (
buf == NULL || xmlerrcxt->err_occurred)
719 "could not allocate xmlBuffer");
722 parse_xml_decl(xml_text2xmlChar(
data), &decl_len, NULL, NULL, NULL);
731 ctxt = xmlSaveToBuffer(
buf, NULL,
732 XML_SAVE_NO_DECL | XML_SAVE_FORMAT);
734 ctxt = xmlSaveToBuffer(
buf, NULL,
737 if (ctxt == NULL || xmlerrcxt->err_occurred)
739 "could not allocate xmlSaveCtxt");
744 if (xmlSaveDoc(ctxt, doc) == -1 || xmlerrcxt->err_occurred)
746 "could not save document to xmlBuffer");
748 else if (content_nodes != NULL)
760 root = xmlNewNode(NULL, (
const xmlChar *)
"content-root");
761 if (
root == NULL || xmlerrcxt->err_occurred)
763 "could not allocate xml node");
769 oldroot = xmlDocSetRootElement(doc,
root);
771 xmlFreeNode(oldroot);
773 xmlAddChildList(
root, content_nodes);
782 newline = xmlNewDocText(NULL, (
const xmlChar *)
"\n");
783 if (
newline == NULL || xmlerrcxt->err_occurred)
785 "could not allocate xml node");
787 for (xmlNodePtr node =
root->children; node; node = node->next)
790 if (node->type != XML_TEXT_NODE && node->prev != NULL)
792 if (xmlSaveTree(ctxt,
newline) == -1 || xmlerrcxt->err_occurred)
796 "could not save newline to xmlBuffer");
800 if (xmlSaveTree(ctxt, node) == -1 || xmlerrcxt->err_occurred)
804 "could not save content to xmlBuffer");
811 if (xmlSaveClose(ctxt) == -1 || xmlerrcxt->err_occurred)
815 "could not close xmlSaveCtxtPtr");
823 const char *
str = (
const char *) xmlBufferContent(
buf);
824 int len = xmlBufferLength(
buf);
826 while (
len > 0 && (
str[
len - 1] ==
'\n' ||
833 result = (
text *) xmlBuffer_to_xmltype(
buf);
865 Datum *named_argvalue,
bool *named_argnull,
866 Datum *argvalue,
bool *argnull)
870 List *named_arg_strings;
876 volatile xmlBufferPtr
buf = NULL;
877 volatile xmlTextWriterPtr writer = NULL;
886 named_arg_strings =
NIL;
893 if (named_argnull[
i])
899 named_arg_strings =
lappend(named_arg_strings,
str);
925 buf = xmlBufferCreate();
926 if (
buf == NULL || xmlerrcxt->err_occurred)
928 "could not allocate xmlBuffer");
929 writer = xmlNewTextWriterMemory(
buf, 0);
930 if (writer == NULL || xmlerrcxt->err_occurred)
932 "could not allocate xmlTextWriter");
934 xmlTextWriterStartElement(writer, (xmlChar *) xexpr->name);
936 forboth(
arg, named_arg_strings, narg, xexpr->arg_names)
942 xmlTextWriterWriteAttribute(writer,
947 foreach(
arg, arg_strings)
951 xmlTextWriterWriteRaw(writer, (xmlChar *)
str);
954 xmlTextWriterEndElement(writer);
957 xmlFreeTextWriter(writer);
960 result = xmlBuffer_to_xmltype(
buf);
965 xmlFreeTextWriter(writer);
993 doc = xml_parse(
data, xmloption_arg, preserve_whitespace,
1006xmlpi(
const char *target,
text *
arg,
bool arg_is_null,
bool *result_is_null)
1014 (
errcode(ERRCODE_INVALID_XML_PROCESSING_INSTRUCTION),
1015 errmsg(
"invalid XML processing instruction"),
1016 errdetail(
"XML processing instruction target name cannot be \"%s\".", target)));
1022 *result_is_null = arg_is_null;
1023 if (*result_is_null)
1035 if (strstr(
string,
"?>") != NULL)
1037 (
errcode(ERRCODE_INVALID_XML_PROCESSING_INSTRUCTION),
1038 errmsg(
"invalid XML processing instruction"),
1039 errdetail(
"XML processing instruction cannot contain \"?>\".")));
1063 xmlChar *orig_version;
1064 int orig_standalone;
1070 parse_xml_decl((xmlChar *)
str, &
len, &orig_version, NULL, &orig_standalone);
1073 orig_version = xml_text2xmlChar(version);
1075 orig_version = NULL;
1080 orig_standalone = 1;
1083 orig_standalone = 0;
1086 orig_standalone = -1;
1094 print_xml_decl(&
buf, orig_version, 0, orig_standalone);
1117 (
errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1118 errmsg(
"xmlvalidate is not implemented")));
1162 static bool first_time =
true;
1172 if (
sizeof(
char) !=
sizeof(xmlChar))
1174 (
errmsg(
"could not initialize XML library"),
1175 errdetail(
"libxml2 has incompatible char type: sizeof(char)=%zu, sizeof(xmlChar)=%zu.",
1176 sizeof(
char),
sizeof(xmlChar))));
1178#ifdef USE_LIBXMLCONTEXT
1184 LIBXML_TEST_VERSION;
1216 errcxt->magic = ERRCXT_MAGIC;
1217 errcxt->strictness = strictness;
1218 errcxt->err_occurred =
false;
1228 errcxt->saved_errfunc = xmlStructuredError;
1230#ifdef HAVE_XMLSTRUCTUREDERRORCONTEXT
1231 errcxt->saved_errcxt = xmlStructuredErrorContext;
1233 errcxt->saved_errcxt = xmlGenericErrorContext;
1236 xmlSetStructuredErrorFunc(errcxt, xml_errorHandler);
1252#ifdef HAVE_XMLSTRUCTUREDERRORCONTEXT
1253 new_errcxt = xmlStructuredErrorContext;
1255 new_errcxt = xmlGenericErrorContext;
1258 if (new_errcxt != errcxt)
1260 (
errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1261 errmsg(
"could not set up XML error handler"),
1262 errhint(
"This probably indicates that the version of libxml2"
1263 " being used is not compatible with the libxml2"
1264 " header files that PostgreSQL was built with.")));
1270 errcxt->saved_entityfunc = xmlGetExternalEntityLoader();
1271 xmlSetExternalEntityLoader(xmlPgEntityLoader);
1292 Assert(errcxt->magic == ERRCXT_MAGIC);
1299 Assert(!errcxt->err_occurred || isError);
1306#ifdef HAVE_XMLSTRUCTUREDERRORCONTEXT
1307 cur_errcxt = xmlStructuredErrorContext;
1309 cur_errcxt = xmlGenericErrorContext;
1312 if (cur_errcxt != errcxt)
1313 elog(
WARNING,
"libxml error handling state is out of sync with xml.c");
1316 xmlSetStructuredErrorFunc(errcxt->saved_errcxt, errcxt->saved_errfunc);
1317 xmlSetExternalEntityLoader(errcxt->saved_entityfunc);
1326 pfree(errcxt->err_buf.data);
1337 return errcxt->err_occurred;
1350#define CHECK_XML_SPACE(p) \
1352 if (!xmlIsBlank_ch(*(p))) \
1353 return XML_ERR_SPACE_REQUIRED; \
1356#define SKIP_XML_SPACE(p) \
1357 while (xmlIsBlank_ch(*(p))) (p)++
1361#define PG_XMLISNAMECHAR(c) \
1362 (xmlIsBaseChar_ch(c) || xmlIsIdeographicQ(c) \
1363 || xmlIsDigit_ch(c) \
1364 || c == '.' || c == '-' || c == '_' || c == ':' \
1365 || xmlIsCombiningQ(c) \
1366 || xmlIsExtender_ch(c))
1370xml_pnstrdup(
const xmlChar *
str,
size_t len)
1374 result = (xmlChar *)
palloc((
len + 1) *
sizeof(xmlChar));
1375 memcpy(result,
str,
len *
sizeof(xmlChar));
1382pg_xmlCharStrndup(
const char *
str,
size_t len)
1386 result = (xmlChar *)
palloc((
len + 1) *
sizeof(xmlChar));
1387 memcpy(result,
str,
len);
1399xml_pstrdup_and_free(xmlChar *
str)
1428parse_xml_decl(
const xmlChar *
str,
size_t *lenp,
1429 xmlChar **version, xmlChar **
encoding,
int *standalone)
1432 const xmlChar *save_p;
1455 if (xmlStrncmp(p, (xmlChar *)
"<?xml", 5) != 0)
1467 utf8char = xmlGetUTF8Char(p + 5, &utf8len);
1468 if (PG_XMLISNAMECHAR(utf8char))
1476 if (xmlStrncmp(p, (xmlChar *)
"version", 7) != 0)
1477 return XML_ERR_VERSION_MISSING;
1481 return XML_ERR_VERSION_MISSING;
1485 if (*p ==
'\'' || *p ==
'"')
1489 q = xmlStrchr(p + 1, *p);
1491 return XML_ERR_VERSION_MISSING;
1494 *version = xml_pnstrdup(p + 1, q - p - 1);
1498 return XML_ERR_VERSION_MISSING;
1503 if (xmlStrncmp(p, (xmlChar *)
"encoding", 8) == 0)
1505 CHECK_XML_SPACE(save_p);
1509 return XML_ERR_MISSING_ENCODING;
1513 if (*p ==
'\'' || *p ==
'"')
1517 q = xmlStrchr(p + 1, *p);
1519 return XML_ERR_MISSING_ENCODING;
1522 *
encoding = xml_pnstrdup(p + 1, q - p - 1);
1526 return XML_ERR_MISSING_ENCODING;
1536 if (xmlStrncmp(p, (xmlChar *)
"standalone", 10) == 0)
1538 CHECK_XML_SPACE(save_p);
1542 return XML_ERR_STANDALONE_VALUE;
1545 if (xmlStrncmp(p, (xmlChar *)
"'yes'", 5) == 0 ||
1546 xmlStrncmp(p, (xmlChar *)
"\"yes\"", 5) == 0)
1552 else if (xmlStrncmp(p, (xmlChar *)
"'no'", 4) == 0 ||
1553 xmlStrncmp(p, (xmlChar *)
"\"no\"", 4) == 0)
1560 return XML_ERR_STANDALONE_VALUE;
1568 if (xmlStrncmp(p, (xmlChar *)
"?>", 2) != 0)
1569 return XML_ERR_XMLDECL_NOT_FINISHED;
1577 return XML_ERR_INVALID_CHAR;
1606 || standalone != -1)
1625 if (standalone == 1)
1627 else if (standalone == 0)
1667xml_doctype_in_content(
const xmlChar *
str)
1669 const xmlChar *p =
str;
1685 if (xmlStrncmp(p, (xmlChar *)
"DOCTYPE", 7) == 0)
1689 if (xmlStrncmp(p, (xmlChar *)
"--", 2) != 0)
1692 p = xmlStrstr(p + 2, (xmlChar *)
"--");
1693 if (!p || p[2] !=
'>')
1706 e = xmlStrstr(p, (xmlChar *)
"?>");
1744 bool preserve_whitespace,
int encoding,
1745 XmlOptionType *parsed_xmloptiontype, xmlNodePtr *parsed_nodes,
1750 xmlChar *utf8string;
1752 volatile xmlParserCtxtPtr ctxt = NULL;
1753 volatile xmlDocPtr doc = NULL;
1760 string = xml_text2xmlChar(
data);
1780 bool parse_as_document =
false;
1784 xmlChar *version = NULL;
1792 parse_as_document =
true;
1796 res_code = parse_xml_decl(utf8string,
1797 &count, &version, NULL, &standalone);
1801 errcode(ERRCODE_INVALID_XML_CONTENT),
1803 errdetail_for_xml_code(res_code));
1808 if (xml_doctype_in_content(utf8string + count))
1809 parse_as_document =
true;
1821 options = XML_PARSE_NOENT | XML_PARSE_DTDATTR
1822 | (preserve_whitespace ? 0 : XML_PARSE_NOBLANKS);
1825 if (parsed_xmloptiontype != NULL)
1828 if (parsed_nodes != NULL)
1829 *parsed_nodes = NULL;
1831 if (parse_as_document)
1833 ctxt = xmlNewParserCtxt();
1834 if (ctxt == NULL || xmlerrcxt->err_occurred)
1836 "could not allocate parser context");
1838 doc = xmlCtxtReadDoc(ctxt, utf8string,
1843 if (doc == NULL || xmlerrcxt->err_occurred)
1847 xml_errsave(escontext, xmlerrcxt,
1848 ERRCODE_INVALID_XML_DOCUMENT,
1849 "invalid XML document");
1851 xml_errsave(escontext, xmlerrcxt,
1852 ERRCODE_INVALID_XML_CONTENT,
1853 "invalid XML content");
1863 doc = xmlNewDoc(version);
1864 if (doc == NULL || xmlerrcxt->err_occurred)
1866 "could not allocate XML document");
1868 Assert(doc->encoding == NULL);
1869 doc->encoding = xmlStrdup((
const xmlChar *)
"UTF-8");
1870 if (doc->encoding == NULL || xmlerrcxt->err_occurred)
1872 "could not allocate XML document");
1873 doc->standalone = standalone;
1875 root = xmlNewNode(NULL, (
const xmlChar *)
"content-root");
1876 if (
root == NULL || xmlerrcxt->err_occurred)
1878 "could not allocate xml node");
1884 oldroot = xmlDocSetRootElement(doc,
root);
1888 if (*(utf8string + count))
1890 xmlNodePtr node_list = NULL;
1891 xmlParserErrors res;
1893 res = xmlParseInNodeContext(
root,
1894 (
char *) utf8string + count,
1895 strlen((
char *) utf8string + count),
1899 if (res != XML_ERR_OK || xmlerrcxt->err_occurred)
1901 xmlFreeNodeList(node_list);
1902 xml_errsave(escontext, xmlerrcxt,
1903 ERRCODE_INVALID_XML_CONTENT,
1904 "invalid XML content");
1908 if (parsed_nodes != NULL)
1909 *parsed_nodes = node_list;
1911 xmlFreeNodeList(node_list);
1923 xmlFreeParserCtxt(ctxt);
1932 xmlFreeParserCtxt(ctxt);
1944xml_text2xmlChar(
text *in)
1950#ifdef USE_LIBXMLCONTEXT
1957xml_memory_init(
void)
1960 if (LibxmlContext == NULL)
1966 xmlMemSetup(xml_pfree, xml_palloc, xml_repalloc, xml_pstrdup);
1973xml_palloc(
size_t size)
1980xml_repalloc(
void *ptr,
size_t size)
1996xml_pstrdup(
const char *
string)
2014static xmlParserInputPtr
2015xmlPgEntityLoader(
const char *URL,
const char *ID,
2016 xmlParserCtxtPtr ctxt)
2018 return xmlNewStringInputStream(ctxt, (
const xmlChar *)
"");
2038 if (errcxt->magic != ERRCXT_MAGIC)
2039 elog(
ERROR,
"xml_ereport called with invalid PgXmlErrorContext");
2042 errcxt->err_occurred =
false;
2045 if (errcxt->err_buf.len > 0)
2046 detail = errcxt->err_buf.data;
2071 int sqlcode,
const char *msg)
2076 if (errcxt->magic != ERRCXT_MAGIC)
2077 elog(
ERROR,
"xml_errsave called with invalid PgXmlErrorContext");
2080 errcxt->err_occurred =
false;
2083 if (errcxt->err_buf.len > 0)
2084 detail = errcxt->err_buf.data;
2099xml_errorHandler(
void *
data, PgXmlErrorPtr
error)
2102 xmlParserCtxtPtr ctxt = (xmlParserCtxtPtr)
error->ctxt;
2103 xmlParserInputPtr
input = (ctxt != NULL) ? ctxt->input : NULL;
2104 xmlNodePtr node =
error->node;
2105 const xmlChar *
name = (node != NULL &&
2106 node->type == XML_ELEMENT_NODE) ? node->name : NULL;
2107 int domain =
error->domain;
2108 int level =
error->level;
2117 if (xmlerrcxt->magic != ERRCXT_MAGIC)
2118 elog(
FATAL,
"xml_errorHandler called with invalid PgXmlErrorContext");
2128 switch (
error->code)
2130 case XML_WAR_NS_URI:
2131 level = XML_ERR_ERROR;
2132 domain = XML_FROM_NAMESPACE;
2135 case XML_ERR_NS_DECL_ERROR:
2136 case XML_WAR_NS_URI_RELATIVE:
2137 case XML_WAR_NS_COLUMN:
2138 case XML_NS_ERR_XML_NAMESPACE:
2139 case XML_NS_ERR_UNDEFINED_NAMESPACE:
2140 case XML_NS_ERR_QNAME:
2141 case XML_NS_ERR_ATTRIBUTE_REDEFINED:
2142 case XML_NS_ERR_EMPTY:
2143 domain = XML_FROM_NAMESPACE;
2150 case XML_FROM_PARSER:
2159 if (
error->code == XML_ERR_NOT_WELL_BALANCED &&
2160 xmlerrcxt->err_occurred)
2165 case XML_FROM_MEMORY:
2172 if (
error->code == XML_WAR_UNDECLARED_ENTITY)
2188 if (
error->line > 0)
2192 if (
error->message != NULL)
2210 xmlGenericErrorFunc errFuncSaved = xmlGenericError;
2211 void *errCtxSaved = xmlGenericErrorContext;
2213 xmlSetGenericErrorFunc(errorBuf,
2217 appendStringInfoLineSeparator(errorBuf);
2219 xmlParserPrintFileContext(
input);
2222 xmlSetGenericErrorFunc(errCtxSaved, errFuncSaved);
2226 chopStringInfoNewlines(errorBuf);
2238 appendStringInfoLineSeparator(&xmlerrcxt->err_buf);
2254 if (level >= XML_ERR_ERROR)
2256 appendStringInfoLineSeparator(&xmlerrcxt->err_buf);
2260 xmlerrcxt->err_occurred =
true;
2262 else if (level >= XML_ERR_WARNING)
2287errdetail_for_xml_code(
int code)
2293 case XML_ERR_INVALID_CHAR:
2296 case XML_ERR_SPACE_REQUIRED:
2299 case XML_ERR_STANDALONE_VALUE:
2300 det =
gettext_noop(
"standalone accepts only 'yes' or 'no'.");
2302 case XML_ERR_VERSION_MISSING:
2303 det =
gettext_noop(
"Malformed declaration: missing version.");
2305 case XML_ERR_MISSING_ENCODING:
2306 det =
gettext_noop(
"Missing encoding in text declaration.");
2308 case XML_ERR_XMLDECL_NOT_FINISHED:
2309 det =
gettext_noop(
"Parsing XML declaration: '?>' expected.");
2312 det =
gettext_noop(
"Unrecognized libxml error code: %d.");
2326 while (
str->len > 0 &&
str->data[
str->len - 1] ==
'\n')
2327 str->data[--
str->len] =
'\0';
2337 chopStringInfoNewlines(
str);
2347sqlchar_to_unicode(
const char *s)
2358 if (utf8string != s)
2369 return (xmlIsBaseCharQ(
c) || xmlIsIdeographicQ(
c)
2370 ||
c ==
'_' ||
c ==
':');
2378 return (xmlIsBaseCharQ(
c) || xmlIsIdeographicQ(
c)
2380 ||
c ==
'.' ||
c ==
'-' ||
c ==
'_' ||
c ==
':'
2381 || xmlIsCombiningQ(
c)
2382 || xmlIsExtenderQ(
c));
2402 Assert(fully_escaped || !escape_period);
2408 if (*p ==
':' && (p ==
ident || fully_escaped))
2410 else if (*p ==
'_' && *(p + 1) ==
'x')
2412 else if (fully_escaped && p ==
ident &&
2420 else if (escape_period && *p ==
'.')
2424 pg_wchar u = sqlchar_to_unicode(p);
2427 ? !is_valid_xml_namefirst(u)
2428 : !is_valid_xml_namechar(u))
2456 if (*p ==
'_' && *(p + 1) ==
'x'
2457 && isxdigit((
unsigned char) *(p + 2))
2458 && isxdigit((
unsigned char) *(p + 3))
2459 && isxdigit((
unsigned char) *(p + 4))
2460 && isxdigit((
unsigned char) *(p + 5))
2466 sscanf(p + 2,
"%X", &u);
2509 elmlen, elmbyval, elmalign,
2510 &elem_values, &elem_nulls,
2515 for (
i = 0;
i < num_elems;
i++)
2564 (
errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2565 errmsg(
"date out of range"),
2566 errdetail(
"XML does not support infinite date values.")));
2586 (
errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2587 errmsg(
"timestamp out of range"),
2588 errdetail(
"XML does not support infinite timestamp values.")));
2593 (
errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2594 errmsg(
"timestamp out of range")));
2599 case TIMESTAMPTZOID:
2605 const char *tzn = NULL;
2613 (
errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2614 errmsg(
"timestamp out of range"),
2615 errdetail(
"XML does not support infinite timestamp values.")));
2620 (
errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2621 errmsg(
"timestamp out of range")));
2631 volatile xmlBufferPtr
buf = NULL;
2632 volatile xmlTextWriterPtr writer = NULL;
2639 buf = xmlBufferCreate();
2640 if (
buf == NULL || xmlerrcxt->err_occurred)
2642 "could not allocate xmlBuffer");
2643 writer = xmlNewTextWriterMemory(
buf, 0);
2644 if (writer == NULL || xmlerrcxt->err_occurred)
2646 "could not allocate xmlTextWriter");
2649 xmlTextWriterWriteBase64(writer,
VARDATA_ANY(bstr),
2652 xmlTextWriterWriteBinHex(writer,
VARDATA_ANY(bstr),
2656 xmlFreeTextWriter(writer);
2659 result =
pstrdup((
const char *) xmlBufferContent(
buf));
2664 xmlFreeTextWriter(writer);
2691 if (
type == XMLOID || !xml_escape_strings)
2714 for (p =
str; *p; p++)
2742 size_t len = strlen(s) + 1;
2745 memcpy(ret, s,
len);
2805 elog(
ERROR,
"SPI_execute returned %s for %s",
2832 " WHERE relnamespace = %u AND relkind IN ("
2836 " AND pg_catalog.has_table_privilege (oid, 'SELECT')"
2837 " ORDER BY relname;",
nspid);
2847#define XML_VISIBLE_SCHEMAS_EXCLUDE "(nspname ~ '^pg_' OR nspname = 'information_schema')"
2849#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
2864 " WHERE relkind IN ("
2868 " AND pg_catalog.has_table_privilege(pg_class.oid, 'SELECT')"
2880 const char *xmlschema,
bool nulls,
bool tableforest,
2881 const char *targetns,
bool top_level)
2890 xmlschema, nulls, tableforest,
2891 targetns, top_level);
2918 NULL, nulls, tableforest,
2948 (
errcode(ERRCODE_UNDEFINED_CURSOR),
2949 errmsg(
"cursor \"%s\" does not exist",
name)));
2954 tableforest, targetns,
true);
2979 const char *xmlschema,
const char *targetns,
2983 Assert(top_level || !xmlschema);
2989 if (strlen(targetns) > 0)
2995 if (strlen(targetns) > 0)
3013 const char *xmlschema,
bool nulls,
bool tableforest,
3014 const char *targetns,
bool top_level)
3030 (
errcode(ERRCODE_DATA_EXCEPTION),
3031 errmsg(
"invalid query")));
3036 targetns, top_level);
3045 tableforest, targetns, top_level);
3068 tableforest, targetns);
3089 elog(
ERROR,
"SPI_prepare(\"%s\") failed", query);
3092 elog(
ERROR,
"SPI_cursor_open(\"%s\") failed", query);
3096 tableforest, targetns));
3111 const char *xmlschema;
3118 (
errcode(ERRCODE_UNDEFINED_CURSOR),
3119 errmsg(
"cursor \"%s\" does not exist",
name)));
3122 (
errcode(ERRCODE_INVALID_CURSOR_STATE),
3123 errmsg(
"portal \"%s\" does not return tuples",
name)));
3127 tableforest, targetns));
3142 const char *xmlschema;
3146 tableforest, targetns);
3150 xmlschema, nulls, tableforest,
3163 const char *xmlschema;
3170 elog(
ERROR,
"SPI_prepare(\"%s\") failed", query);
3173 elog(
ERROR,
"SPI_cursor_open(\"%s\") failed", query);
3181 xmlschema, nulls, tableforest,
3193 bool tableforest,
const char *targetns,
bool top_level)
3214 foreach(cell, relid_list)
3249 nulls, tableforest, targetns,
true)));
3262 if (strlen(targetns) > 0)
3265 " targetNamespace=\"%s\"\n"
3266 " elementFormDefault=\"qualified\"",
3282 bool tableforest,
const char *targetns)
3301 foreach(cell, relid_list)
3315 nulls, tableforest, targetns));
3334 nulls, tableforest, targetns)));
3353 tableforest, targetns);
3356 xmlschema->
data, nulls,
3357 tableforest, targetns,
true)));
3368 bool tableforest,
const char *targetns)
3389 foreach(cell, nspid_list)
3395 tableforest, targetns,
false);
3417 tableforest, targetns)));
3423 const char *targetns)
3441 foreach(cell, relid_list)
3472 tableforest, targetns)));
3487 nulls, tableforest, targetns)));
3528 bool tableforest,
const char *targetns)
3532 char *tabletypename;
3545 elog(
ERROR,
"cache lookup failed for relation %u", relid);
3570 tabletypename =
"TableType";
3571 rowtypename =
"RowType";
3580 "<xsd:complexType name=\"%s\">\n"
3581 " <xsd:sequence>\n",
3584 for (
i = 0;
i < tupdesc->
natts;
i++)
3588 if (att->attisdropped)
3591 " <xsd:element name=\"%s\" type=\"%s\"%s></xsd:element>\n",
3595 nulls ?
" nillable=\"true\"" :
" minOccurs=\"0\"");
3599 " </xsd:sequence>\n"
3600 "</xsd:complexType>\n\n");
3605 "<xsd:complexType name=\"%s\">\n"
3607 " <xsd:element name=\"row\" type=\"%s\" minOccurs=\"0\" maxOccurs=\"unbounded\"/>\n"
3608 " </xsd:sequence>\n"
3609 "</xsd:complexType>\n\n",
3610 tabletypename, rowtypename);
3613 "<xsd:element name=\"%s\" type=\"%s\"/>\n\n",
3614 xmltn, tabletypename);
3618 "<xsd:element name=\"%s\" type=\"%s\"/>\n\n",
3619 xmltn, rowtypename);
3633 bool tableforest,
const char *targetns)
3638 char *schematypename;
3655 "<xsd:complexType name=\"%s\">\n", schematypename);
3661 " <xsd:sequence>\n");
3663 foreach(cell, relid_list)
3675 " <xsd:element name=\"%s\" type=\"%s\"/>\n",
3676 xmltn, tabletypename);
3679 " <xsd:element name=\"%s\" type=\"%s\" minOccurs=\"0\" maxOccurs=\"unbounded\"/>\n",
3680 xmltn, tabletypename);
3688 " </xsd:sequence>\n");
3690 "</xsd:complexType>\n\n");
3693 "<xsd:element name=\"%s\" type=\"%s\"/>\n\n",
3694 xmlsn, schematypename);
3706 bool tableforest,
const char *targetns)
3710 char *catalogtypename;
3726 "<xsd:complexType name=\"%s\">\n", catalogtypename);
3730 foreach(cell, nspid_list)
3741 " <xsd:element name=\"%s\" type=\"%s\"/>\n",
3742 xmlsn, schematypename);
3748 "</xsd:complexType>\n\n");
3751 "<xsd:element name=\"%s\" type=\"%s\"/>\n\n",
3752 xmlcn, catalogtypename);
3787 ((typmod -
VARHDRSZ) >> 16) & 0xffff,
3826 case TIMESTAMPTZOID:
3845 elog(
ERROR,
"cache lookup failed for type %u", typeoid);
3875 foreach(cell0, tupdesc_list)
3879 for (
i = 0;
i < tupdesc->
natts;
i++)
3883 if (att->attisdropped)
3890 foreach(cell0, uniquetypes)
3895 if (basetypid != typid)
3902 foreach(cell0, uniquetypes)
3929 if (typeoid == XMLOID)
3932 "<xsd:complexType mixed=\"true\">\n"
3934 " <xsd:any name=\"element\" minOccurs=\"0\" maxOccurs=\"unbounded\" processContents=\"skip\"/>\n"
3935 " </xsd:sequence>\n"
3936 "</xsd:complexType>\n");
3941 "<xsd:simpleType name=\"%s\">\n",
typename);
3949 " <xsd:restriction base=\"xsd:string\">\n");
3952 " <xsd:maxLength value=\"%d\"/>\n",
3959 " <xsd:restriction base=\"xsd:%s\">\n"
3960 " </xsd:restriction>\n",
3967 " <xsd:restriction base=\"xsd:decimal\">\n"
3968 " <xsd:totalDigits value=\"%d\"/>\n"
3969 " <xsd:fractionDigits value=\"%d\"/>\n"
3970 " </xsd:restriction>\n",
3971 ((typmod -
VARHDRSZ) >> 16) & 0xffff,
3977 " <xsd:restriction base=\"xsd:short\">\n"
3978 " <xsd:maxInclusive value=\"%d\"/>\n"
3979 " <xsd:minInclusive value=\"%d\"/>\n"
3980 " </xsd:restriction>\n",
3981 SHRT_MAX, SHRT_MIN);
3986 " <xsd:restriction base=\"xsd:int\">\n"
3987 " <xsd:maxInclusive value=\"%d\"/>\n"
3988 " <xsd:minInclusive value=\"%d\"/>\n"
3989 " </xsd:restriction>\n",
3995 " <xsd:restriction base=\"xsd:long\">\n"
3998 " </xsd:restriction>\n",
4005 " <xsd:restriction base=\"xsd:float\"></xsd:restriction>\n");
4010 " <xsd:restriction base=\"xsd:double\"></xsd:restriction>\n");
4015 " <xsd:restriction base=\"xsd:boolean\"></xsd:restriction>\n");
4021 const char *tz = (typeoid == TIMETZOID ?
"(\\+|-)\\p{Nd}{2}:\\p{Nd}{2}" :
"");
4025 " <xsd:restriction base=\"xsd:time\">\n"
4026 " <xsd:pattern value=\"\\p{Nd}{2}:\\p{Nd}{2}:\\p{Nd}{2}(.\\p{Nd}+)?%s\"/>\n"
4027 " </xsd:restriction>\n", tz);
4028 else if (typmod == 0)
4030 " <xsd:restriction base=\"xsd:time\">\n"
4031 " <xsd:pattern value=\"\\p{Nd}{2}:\\p{Nd}{2}:\\p{Nd}{2}%s\"/>\n"
4032 " </xsd:restriction>\n", tz);
4035 " <xsd:restriction base=\"xsd:time\">\n"
4036 " <xsd:pattern value=\"\\p{Nd}{2}:\\p{Nd}{2}:\\p{Nd}{2}.\\p{Nd}{%d}%s\"/>\n"
4037 " </xsd:restriction>\n", typmod -
VARHDRSZ, tz);
4042 case TIMESTAMPTZOID:
4044 const char *tz = (typeoid == TIMESTAMPTZOID ?
"(\\+|-)\\p{Nd}{2}:\\p{Nd}{2}" :
"");
4048 " <xsd:restriction base=\"xsd:dateTime\">\n"
4049 " <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"
4050 " </xsd:restriction>\n", tz);
4051 else if (typmod == 0)
4053 " <xsd:restriction base=\"xsd:dateTime\">\n"
4054 " <xsd:pattern value=\"\\p{Nd}{4}-\\p{Nd}{2}-\\p{Nd}{2}T\\p{Nd}{2}:\\p{Nd}{2}:\\p{Nd}{2}%s\"/>\n"
4055 " </xsd:restriction>\n", tz);
4058 " <xsd:restriction base=\"xsd:dateTime\">\n"
4059 " <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"
4060 " </xsd:restriction>\n", typmod -
VARHDRSZ, tz);
4066 " <xsd:restriction base=\"xsd:date\">\n"
4067 " <xsd:pattern value=\"\\p{Nd}{4}-\\p{Nd}{2}-\\p{Nd}{2}\"/>\n"
4068 " </xsd:restriction>\n");
4075 int32 base_typmod = -1;
4080 " <xsd:restriction base=\"%s\"/>\n",
4098 bool nulls,
bool tableforest,
4099 const char *targetns,
bool top_level)
4171 if (
cur->type != XML_ATTRIBUTE_NODE &&
cur->type != XML_TEXT_NODE)
4173 void (*
volatile nodefree) (xmlNodePtr) = NULL;
4174 volatile xmlBufferPtr
buf = NULL;
4175 volatile xmlNodePtr cur_copy = NULL;
4181 buf = xmlBufferCreate();
4182 if (
buf == NULL || xmlerrcxt->err_occurred)
4184 "could not allocate xmlBuffer");
4198 cur_copy = xmlCopyNode(
cur, 1);
4199 if (cur_copy == NULL || xmlerrcxt->err_occurred)
4201 "could not copy node");
4202 nodefree = (cur_copy->type == XML_DOCUMENT_NODE) ?
4203 (
void (*) (xmlNodePtr)) xmlFreeDoc : xmlFreeNode;
4205 bytes = xmlNodeDump(
buf, NULL, cur_copy, 0, 0);
4206 if (bytes == -1 || xmlerrcxt->err_occurred)
4208 "could not dump node");
4210 result = xmlBuffer_to_xmltype(
buf);
4225 str = xmlXPathCastNodeToString(
cur);
4257xml_xpathobjtoxmlarray(xmlXPathObjectPtr xpathobj,
4266 switch (xpathobj->type)
4269 if (xpathobj->nodesetval != NULL)
4271 result = xpathobj->nodesetval->nodeNr;
4276 for (
i = 0;
i < result;
i++)
4278 datum =
PointerGetDatum(xml_xmlnodetoxmltype(xpathobj->nodesetval->nodeTab[
i],
4291 datumtype = BOOLOID;
4298 datumtype = FLOAT8OID;
4305 datumtype = CSTRINGOID;
4309 elog(
ERROR,
"xpath expression result type %d is unsupported",
4339 volatile xmlParserCtxtPtr ctxt = NULL;
4340 volatile xmlDocPtr doc = NULL;
4341 volatile xmlXPathContextPtr xpathctx = NULL;
4342 volatile xmlXPathCompExprPtr xpathcomp = NULL;
4343 volatile xmlXPathObjectPtr xpathobj = NULL;
4348 xmlChar *xpath_expr;
4349 size_t xmldecl_len = 0;
4352 Datum *ns_names_uris;
4353 bool *ns_names_uris_nulls;
4365 ndim = namespaces ?
ARR_NDIM(namespaces) : 0;
4372 if (ndim != 2 || dims[1] != 2)
4374 (
errcode(ERRCODE_DATA_EXCEPTION),
4375 errmsg(
"invalid array for XML namespace mapping"),
4376 errdetail(
"The array must be two-dimensional with length of the second axis equal to 2.")));
4381 &ns_names_uris, &ns_names_uris_nulls,
4384 Assert((ns_count % 2) == 0);
4389 ns_names_uris = NULL;
4390 ns_names_uris_nulls = NULL;
4399 (
errcode(ERRCODE_INVALID_ARGUMENT_FOR_XQUERY),
4400 errmsg(
"empty XPath expression")));
4402 string = pg_xmlCharStrndup(datastr,
len);
4403 xpath_expr = pg_xmlCharStrndup(
VARDATA_ANY(xpath_expr_text), xpath_len);
4413 parse_xml_decl(
string, &xmldecl_len, NULL, NULL, NULL);
4425 ctxt = xmlNewParserCtxt();
4426 if (ctxt == NULL || xmlerrcxt->err_occurred)
4428 "could not allocate parser context");
4429 doc = xmlCtxtReadMemory(ctxt, (
char *)
string + xmldecl_len,
4430 len - xmldecl_len, NULL, NULL, 0);
4431 if (doc == NULL || xmlerrcxt->err_occurred)
4433 "could not parse XML document");
4434 xpathctx = xmlXPathNewContext(doc);
4435 if (xpathctx == NULL || xmlerrcxt->err_occurred)
4437 "could not allocate XPath context");
4438 xpathctx->node = (xmlNodePtr) doc;
4443 for (
i = 0;
i < ns_count;
i++)
4448 if (ns_names_uris_nulls[
i * 2] ||
4449 ns_names_uris_nulls[
i * 2 + 1])
4451 (
errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
4452 errmsg(
"neither namespace name nor URI may be null")));
4455 if (xmlXPathRegisterNs(xpathctx,
4456 (xmlChar *) ns_name,
4457 (xmlChar *) ns_uri) != 0)
4459 (
errmsg(
"could not register XML namespace with name \"%s\" and URI \"%s\"",
4470 xpathcomp = xmlXPathCtxtCompile(xpathctx, xpath_expr);
4471 if (xpathcomp == NULL || xmlerrcxt->err_occurred)
4473 "invalid XPath expression");
4482 xpathobj = xmlXPathCompiledEval(xpathcomp, xpathctx);
4483 if (xpathobj == NULL || xmlerrcxt->err_occurred)
4485 "could not create XPath object");
4490 if (res_nitems != NULL)
4491 *res_nitems = xml_xpathobjtoxmlarray(xpathobj, astate, xmlerrcxt);
4493 (
void) xml_xpathobjtoxmlarray(xpathobj, astate, xmlerrcxt);
4498 xmlXPathFreeObject(xpathobj);
4500 xmlXPathFreeCompExpr(xpathcomp);
4502 xmlXPathFreeContext(xpathctx);
4506 xmlFreeParserCtxt(ctxt);
4514 xmlXPathFreeObject(xpathobj);
4515 xmlXPathFreeCompExpr(xpathcomp);
4516 xmlXPathFreeContext(xpathctx);
4518 xmlFreeParserCtxt(ctxt);
4541 xpath_internal(xpath_expr_text,
data, namespaces,
4562 xpath_internal(xpath_expr_text,
data, NULL,
4586 xpath_internal(xpath_expr_text,
data, namespaces,
4610 doc = xml_parse(
data, xmloption_arg,
true,
4668static inline XmlTableBuilderData *
4671 XmlTableBuilderData *result;
4674 elog(
ERROR,
"%s called with invalid TableFuncScanState", fname);
4675 result = (XmlTableBuilderData *)
state->opaque;
4676 if (result->magic != XMLTABLE_CONTEXT_MAGIC)
4677 elog(
ERROR,
"%s called with invalid TableFuncScanState", fname);
4698 volatile xmlParserCtxtPtr ctxt = NULL;
4699 XmlTableBuilderData *xtCxt;
4702 xtCxt =
palloc0(
sizeof(XmlTableBuilderData));
4703 xtCxt->magic = XMLTABLE_CONTEXT_MAGIC;
4704 xtCxt->natts = natts;
4705 xtCxt->xpathscomp =
palloc0(
sizeof(xmlXPathCompExprPtr) * natts);
4713 ctxt = xmlNewParserCtxt();
4714 if (ctxt == NULL || xmlerrcxt->err_occurred)
4716 "could not allocate parser context");
4721 xmlFreeParserCtxt(ctxt);
4729 xtCxt->xmlerrcxt = xmlerrcxt;
4732 state->opaque = xtCxt;
4746 XmlTableBuilderData *xtCxt;
4751 volatile xmlDocPtr doc = NULL;
4752 volatile xmlXPathContextPtr xpathcxt = NULL;
4754 xtCxt = GetXmlTableBuilderPrivateData(
state,
"XmlTableSetDocument");
4762 length = strlen(
str);
4763 xstr = pg_xmlCharStrndup(
str, length);
4767 doc = xmlCtxtReadMemory(xtCxt->ctxt, (
char *) xstr, length, NULL, NULL, 0);
4768 if (doc == NULL || xtCxt->xmlerrcxt->err_occurred)
4770 "could not parse XML document");
4771 xpathcxt = xmlXPathNewContext(doc);
4772 if (xpathcxt == NULL || xtCxt->xmlerrcxt->err_occurred)
4774 "could not allocate XPath context");
4775 xpathcxt->node = (xmlNodePtr) doc;
4779 if (xpathcxt != NULL)
4780 xmlXPathFreeContext(xpathcxt);
4789 xtCxt->xpathcxt = xpathcxt;
4803 XmlTableBuilderData *xtCxt;
4807 (
errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4808 errmsg(
"DEFAULT namespace is not supported")));
4809 xtCxt = GetXmlTableBuilderPrivateData(
state,
"XmlTableSetNamespace");
4811 if (xmlXPathRegisterNs(xtCxt->xpathcxt,
4812 pg_xmlCharStrndup(
name, strlen(
name)),
4813 pg_xmlCharStrndup(uri, strlen(uri))))
4815 "could not set XML namespace");
4829 XmlTableBuilderData *xtCxt;
4832 xtCxt = GetXmlTableBuilderPrivateData(
state,
"XmlTableSetRowFilter");
4836 (
errcode(ERRCODE_INVALID_ARGUMENT_FOR_XQUERY),
4837 errmsg(
"row path filter must not be empty string")));
4839 xstr = pg_xmlCharStrndup(path, strlen(path));
4842 Assert(xtCxt->xpathcxt != NULL);
4844 xtCxt->xpathcomp = xmlXPathCtxtCompile(xtCxt->xpathcxt, xstr);
4845 if (xtCxt->xpathcomp == NULL || xtCxt->xmlerrcxt->err_occurred)
4847 "invalid XPath expression");
4861 XmlTableBuilderData *xtCxt;
4866 xtCxt = GetXmlTableBuilderPrivateData(
state,
"XmlTableSetColumnFilter");
4870 (
errcode(ERRCODE_INVALID_ARGUMENT_FOR_XQUERY),
4871 errmsg(
"column path filter must not be empty string")));
4873 xstr = pg_xmlCharStrndup(path, strlen(path));
4876 Assert(xtCxt->xpathcxt != NULL);
4878 xtCxt->xpathscomp[colnum] = xmlXPathCtxtCompile(xtCxt->xpathcxt, xstr);
4879 if (xtCxt->xpathscomp[colnum] == NULL || xtCxt->xmlerrcxt->err_occurred)
4881 "invalid XPath expression");
4896 XmlTableBuilderData *xtCxt;
4898 xtCxt = GetXmlTableBuilderPrivateData(
state,
"XmlTableFetchRow");
4901 xmlSetStructuredErrorFunc(xtCxt->xmlerrcxt, xml_errorHandler);
4903 if (xtCxt->xpathobj == NULL)
4905 xtCxt->xpathobj = xmlXPathCompiledEval(xtCxt->xpathcomp, xtCxt->xpathcxt);
4906 if (xtCxt->xpathobj == NULL || xtCxt->xmlerrcxt->err_occurred)
4908 "could not create XPath object");
4910 xtCxt->row_count = 0;
4913 if (xtCxt->xpathobj->type == XPATH_NODESET)
4915 if (xtCxt->xpathobj->nodesetval != NULL)
4917 if (xtCxt->row_count++ < xtCxt->xpathobj->nodesetval->nodeNr)
4939 Oid typid,
int32 typmod,
bool *isnull)
4943 XmlTableBuilderData *xtCxt;
4944 volatile xmlXPathObjectPtr xpathobj = NULL;
4946 xtCxt = GetXmlTableBuilderPrivateData(
state,
"XmlTableGetValue");
4948 Assert(xtCxt->xpathobj &&
4949 xtCxt->xpathobj->type == XPATH_NODESET &&
4950 xtCxt->xpathobj->nodesetval != NULL);
4953 xmlSetStructuredErrorFunc(xtCxt->xmlerrcxt, xml_errorHandler);
4957 Assert(xtCxt->xpathscomp[colnum] != NULL);
4965 cur = xtCxt->xpathobj->nodesetval->nodeTab[xtCxt->row_count - 1];
4966 xtCxt->xpathcxt->node =
cur;
4969 xpathobj = xmlXPathCompiledEval(xtCxt->xpathscomp[colnum], xtCxt->xpathcxt);
4970 if (xpathobj == NULL || xtCxt->xmlerrcxt->err_occurred)
4972 "could not create XPath object");
4981 if (xpathobj->type == XPATH_NODESET)
4985 if (xpathobj->nodesetval != NULL)
4986 count = xpathobj->nodesetval->nodeNr;
4988 if (xpathobj->nodesetval == NULL || count == 0)
4994 if (typid == XMLOID)
5001 for (
int i = 0;
i < count;
i++)
5004 xml_xmlnodetoxmltype(xpathobj->nodesetval->nodeTab[
i],
5017 (
errcode(ERRCODE_CARDINALITY_VIOLATION),
5018 errmsg(
"more than one value returned by column XPath expression")));
5020 str = xmlXPathCastNodeSetToString(xpathobj->nodesetval);
5021 cstr =
str ? xml_pstrdup_and_free(
str) :
"";
5025 else if (xpathobj->type == XPATH_STRING)
5028 if (typid == XMLOID)
5029 cstr =
escape_xml((
char *) xpathobj->stringval);
5031 cstr = (
char *) xpathobj->stringval;
5033 else if (xpathobj->type == XPATH_BOOLEAN)
5036 bool typispreferred;
5042 if (typcategory != TYPCATEGORY_NUMERIC)
5043 str = xmlXPathCastBooleanToString(xpathobj->boolval);
5045 str = xmlXPathCastNumberToString(xmlXPathCastBooleanToNumber(xpathobj->boolval));
5047 cstr = xml_pstrdup_and_free(
str);
5049 else if (xpathobj->type == XPATH_NUMBER)
5053 str = xmlXPathCastNumberToString(xpathobj->floatval);
5054 cstr = xml_pstrdup_and_free(
str);
5057 elog(
ERROR,
"unexpected XPath object type %u", xpathobj->type);
5068 state->typioparams[colnum],
5073 if (xpathobj != NULL)
5074 xmlXPathFreeObject(xpathobj);
5093 XmlTableBuilderData *xtCxt;
5095 xtCxt = GetXmlTableBuilderPrivateData(
state,
"XmlTableDestroyOpaque");
5098 xmlSetStructuredErrorFunc(xtCxt->xmlerrcxt, xml_errorHandler);
5100 if (xtCxt->xpathscomp != NULL)
5104 for (
i = 0;
i < xtCxt->natts;
i++)
5105 if (xtCxt->xpathscomp[
i] != NULL)
5106 xmlXPathFreeCompExpr(xtCxt->xpathscomp[
i]);
5109 if (xtCxt->xpathobj != NULL)
5110 xmlXPathFreeObject(xtCxt->xpathobj);
5111 if (xtCxt->xpathcomp != NULL)
5112 xmlXPathFreeCompExpr(xtCxt->xpathcomp);
5113 if (xtCxt->xpathcxt != NULL)
5114 xmlXPathFreeContext(xtCxt->xpathcxt);
5115 if (xtCxt->doc != NULL)
5116 xmlFreeDoc(xtCxt->doc);
5117 if (xtCxt->ctxt != NULL)
5118 xmlFreeParserCtxt(xtCxt->ctxt);
5124 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)
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)
ArrayBuildState * initArrayResult(Oid element_type, MemoryContext rcontext, bool subcontext)
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 PG_USED_FOR_ASSERTS_ONLY
#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)
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)
char * OidOutputFunctionCall(Oid functionId, Datum val)
Datum Float8GetDatum(float8 X)
#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)
Assert(PointerIsAligned(start, uint64))
#define HeapTupleIsValid(tuple)
static void * GETSTRUCT(const HeapTupleData *tuple)
if(TABLE==NULL||TABLE_index==NULL)
List * lappend(List *list, void *datum)
List * lappend_oid(List *list, Oid datum)
List * list_append_unique_oid(List *list, Oid datum)
char * get_rel_name(Oid relid)
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
void get_typlenbyvalalign(Oid typid, int16 *typlen, bool *typbyval, char *typalign)
char get_typtype(Oid typid)
Oid getBaseTypeAndTypmod(Oid typid, int32 *typmod)
Oid getBaseType(Oid typid)
char * get_namespace_name(Oid nspid)
void get_type_category_preferred(Oid typid, char *typcategory, bool *typispreferred)
#define type_is_array_domain(typid)
int GetDatabaseEncoding(void)
char * pg_any_to_server(const char *s, int len, int encoding)
unsigned char * pg_do_encoding_conversion(unsigned char *src, int len, int src_encoding, int dest_encoding)
void pg_unicode_to_server(pg_wchar c, unsigned char *s)
int pg_get_client_encoding(void)
char * pg_server_to_any(const char *s, int len, int encoding)
int pg_encoding_mb2wchar_with_len(int encoding, const char *from, pg_wchar *to, int len)
int pg_mblen(const char *mbstr)
char * MemoryContextStrdup(MemoryContext context, const char *string)
void * MemoryContextAlloc(MemoryContext context, Size size)
char * pstrdup(const char *in)
void * repalloc(void *pointer, Size size)
void pfree(void *pointer)
void * palloc0(Size size)
MemoryContext TopMemoryContext
MemoryContext CurrentMemoryContext
#define AllocSetContextCreate
#define ALLOCSET_DEFAULT_SIZES
Oid LookupExplicitNamespace(const char *nspname, bool missing_ok)
Oid exprType(const Node *expr)
#define IsA(nodeptr, _type_)
FormData_pg_attribute * Form_pg_attribute
#define ERRCODE_DATA_CORRUPTED
FormData_pg_class * Form_pg_class
#define forboth(cell1, list1, cell2, list2)
#define list_make2(x1, x2)
FormData_pg_type * Form_pg_type
#define MAX_MULTIBYTE_CHAR_LEN
#define MAX_UNICODE_EQUIVALENT_STRING
#define pg_encoding_to_char
#define pg_char_to_encoding
int pg_strcasecmp(const char *s1, const char *s2)
size_t strnlen(const char *str, size_t maxlen)
int pg_strncasecmp(const char *s1, const char *s2, size_t n)
static bool DatumGetBool(Datum X)
static Datum PointerGetDatum(const void *X)
static Oid DatumGetObjectId(Datum X)
static Datum BoolGetDatum(bool X)
static Datum ObjectIdGetDatum(Oid X)
static char * DatumGetCString(Datum X)
static Datum CStringGetDatum(const char *X)
Datum regclassout(PG_FUNCTION_ARGS)
Oid SPI_gettypeid(TupleDesc tupdesc, int fnumber)
const char * SPI_result_code_string(int code)
SPITupleTable * SPI_tuptable
Portal SPI_cursor_find(const char *name)
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)
int SPI_execute(const char *src, bool read_only, long tcount)
Datum SPI_getbinval(HeapTuple tuple, TupleDesc tupdesc, int fnumber, bool *isnull)
char * SPI_fname(TupleDesc tupdesc, int fnumber)
void destroyStringInfo(StringInfo str)
StringInfo makeStringInfo(void)
void appendStringInfo(StringInfo str, const char *fmt,...)
void appendBinaryStringInfo(StringInfo str, const void *data, int datalen)
void appendStringInfoString(StringInfo str, const char *s)
void appendStringInfoChar(StringInfo str, char ch)
void initStringInfo(StringInfo str)
StringInfoData * StringInfo
#define appendStringInfoCharMacro(str, ch)
void(* InitOpaque)(struct TableFuncScanState *state, int natts)
void ReleaseSysCache(HeapTuple tuple)
HeapTuple SearchSysCache1(int cacheId, Datum key1)
void table_close(Relation relation, LOCKMODE lockmode)
Relation table_open(Oid relationId, LOCKMODE lockmode)
TupleDesc CreateTupleDescCopy(TupleDesc tupdesc)
static FormData_pg_attribute * TupleDescAttr(TupleDesc tupdesc, int i)
struct TupleDescData * TupleDesc
static Timestamp DatumGetTimestamp(Datum X)
#define SET_VARSIZE(PTR, len)
#define VARSIZE_ANY_EXHDR(PTR)
static void appendStringInfoText(StringInfo str, const text *t)
text * cstring_to_text_with_len(const char *s, int len)
text * cstring_to_text(const char *s)
char * text_to_cstring(const text *t)
int pg_encoding_mblen(int encoding, const char *mbstr)
Datum xml_in(PG_FUNCTION_ARGS)
Datum cursor_to_xmlschema(PG_FUNCTION_ARGS)
Datum table_to_xml(PG_FUNCTION_ARGS)
Datum query_to_xmlschema(PG_FUNCTION_ARGS)
Datum database_to_xml(PG_FUNCTION_ARGS)
static const char * map_sql_catalog_to_xmlschema_types(List *nspid_list, bool nulls, bool tableforest, const char *targetns)
xmltype * xmlroot(xmltype *data, text *version, int standalone)
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 char * xml_out_internal(xmltype *x, pg_enc target_encoding)
char * map_sql_identifier_to_xml_name(const char *ident, bool fully_escaped, bool escape_period)
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 char * map_multipart_sql_identifier_to_xml_name(const char *a, const char *b, const char *c, const char *d)
static StringInfo database_to_xmlschema_internal(bool nulls, bool tableforest, const char *targetns)
Datum database_to_xmlschema(PG_FUNCTION_ARGS)
static List * schema_get_xml_visible_tables(Oid nspid)
Datum schema_to_xmlschema(PG_FUNCTION_ARGS)
text * xmltotext_with_options(xmltype *data, XmlOptionType xmloption_arg, bool indent)
static void xmldata_root_element_start(StringInfo result, const char *eltname, const char *xmlschema, const char *targetns, bool top_level)
char * map_sql_value_to_xml_value(Datum value, Oid type, bool xml_escape_strings)
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 List * database_get_xml_visible_schemas(void)
static void xmldata_root_element_end(StringInfo result, const char *eltname)
xmltype * xmlconcat(List *args)
static Datum XmlTableGetValue(struct TableFuncScanState *state, int colnum, Oid typid, int32 typmod, bool *isnull)
char * escape_xml(const char *str)
Datum xml_is_well_formed_document(PG_FUNCTION_ARGS)
Datum query_to_xml(PG_FUNCTION_ARGS)
static StringInfo database_to_xml_internal(const char *xmlschema, bool nulls, bool tableforest, const char *targetns)
static xmltype * stringinfo_to_xmltype(StringInfo buf)
Datum xml_is_well_formed_content(PG_FUNCTION_ARGS)
#define XML_VISIBLE_SCHEMAS
static List * database_get_xml_visible_tables(void)
bool xml_is_document(xmltype *arg)
static StringInfo schema_to_xmlschema_internal(const char *schemaname, bool nulls, bool tableforest, const char *targetns)
Datum table_to_xml_and_xmlschema(PG_FUNCTION_ARGS)
Datum xmlvalidate(PG_FUNCTION_ARGS)
xmltype * xmlparse(text *data, XmlOptionType xmloption_arg, bool preserve_whitespace)
static xmltype * cstring_to_xmltype(const char *string)
static List * query_to_oid_list(const char *query)
xmltype * xmlelement(XmlExpr *xexpr, Datum *named_argvalue, bool *named_argnull, Datum *argvalue, bool *argnull)
static void XmlTableSetDocument(struct TableFuncScanState *state, Datum value)
static void XmlTableDestroyOpaque(struct TableFuncScanState *state)
static const char * map_sql_typecoll_to_xmlschema_types(List *tupdesc_list)
#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)
char * map_xml_name_to_sql_identifier(const char *name)
Datum database_to_xml_and_xmlschema(PG_FUNCTION_ARGS)
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)
static char * _SPI_strdup(const char *s)
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 * xmlpi(const char *target, text *arg, bool arg_is_null, bool *result_is_null)
Datum xpath(PG_FUNCTION_ARGS)
static void xsd_schema_element_end(StringInfo result)
@ XML_STANDALONE_NO_VALUE
struct PgXmlErrorContext PgXmlErrorContext
PgXmlErrorContext * pg_xml_init(PgXmlStrictness strictness)
#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)
static xmltype * DatumGetXmlP(Datum X)
void pg_xml_done(PgXmlErrorContext *errcxt, bool isError)
#define PG_GETARG_XML_P(n)
void pg_xml_init_library(void)
@ PG_XML_STRICTNESS_LEGACY
@ PG_XML_STRICTNESS_WELLFORMED