1 /*-------------------------------------------------------------------------
4 * XML data type support.
7 * Portions Copyright (c) 1996-2007, PostgreSQL Global Development Group
8 * Portions Copyright (c) 1994, Regents of the University of California
10 * $PostgreSQL: pgsql/src/backend/utils/adt/xml.c,v 1.54 2007/11/09 15:52:51 petere Exp $
12 *-------------------------------------------------------------------------
16 * Generally, XML type support is only available when libxml use was
17 * configured during the build. But even if that is not done, the
18 * type and all the functions are available, but most of them will
19 * fail. For one thing, this avoids having to manage variant catalog
20 * installations. But it also has nice effects such as that you can
21 * dump a database containing XML type data even if the server is not
22 * linked with libxml. Thus, make sure xml_out() works even if nothing
27 * Note on memory management: Via callbacks, libxml is told to use
28 * palloc and friends for memory management. Sometimes, libxml
29 * allocates global structures in the hope that it can reuse them
30 * later on, but if "later" is much later, the memory context
31 * management of PostgreSQL will have blown those structures away
32 * without telling libxml about it. Therefore, it is important to
33 * call xmlCleanupParser() or perhaps some other cleanup function
34 * after using such functions, for example something from
35 * libxml/parser.h or libxml/xmlsave.h. Unfortunately, you cannot
36 * readily tell from the API documentation when that happens, so
37 * careful evaluation is necessary when introducing new libxml APIs
44 #include <libxml/chvalid.h>
45 #include <libxml/parser.h>
46 #include <libxml/tree.h>
47 #include <libxml/uri.h>
48 #include <libxml/xmlerror.h>
49 #include <libxml/xmlwriter.h>
50 #include <libxml/xpath.h>
51 #include <libxml/xpathInternals.h>
52 #endif /* USE_LIBXML */
54 #include "catalog/namespace.h"
55 #include "catalog/pg_type.h"
56 #include "commands/dbcommands.h"
57 #include "executor/executor.h"
58 #include "executor/spi.h"
60 #include "lib/stringinfo.h"
61 #include "libpq/pqformat.h"
62 #include "mb/pg_wchar.h"
63 #include "miscadmin.h"
64 #include "nodes/execnodes.h"
65 #include "parser/parse_expr.h"
66 #include "utils/array.h"
67 #include "utils/builtins.h"
68 #include "utils/date.h"
69 #include "utils/datetime.h"
70 #include "utils/lsyscache.h"
71 #include "utils/memutils.h"
72 #include "access/tupmacs.h"
73 #include "utils/xml.h"
77 XmlBinaryType xmlbinary;
78 XmlOptionType xmloption;
82 static StringInfo xml_err_buf = NULL;
84 static void xml_init(void);
85 static void *xml_palloc(size_t size);
86 static void *xml_repalloc(void *ptr, size_t size);
87 static void xml_pfree(void *ptr);
88 static char *xml_pstrdup(const char *string);
89 static void xml_ereport(int level, int sqlcode, const char *msg);
90 static void xml_errorHandler(void *ctxt, const char *msg, ...);
91 static void xml_ereport_by_code(int level, int sqlcode,
92 const char *msg, int errcode);
93 static xmlChar *xml_text2xmlChar(text *in);
94 static int parse_xml_decl(const xmlChar *str, size_t *lenp,
95 xmlChar **version, xmlChar **encoding, int *standalone);
96 static bool print_xml_decl(StringInfo buf, const xmlChar *version,
97 pg_enc encoding, int standalone);
98 static xmlDocPtr xml_parse(text *data, XmlOptionType xmloption_arg,
99 bool preserve_whitespace, xmlChar *encoding);
100 static text *xml_xmlnodetoxmltype(xmlNodePtr cur);
102 #endif /* USE_LIBXML */
104 static StringInfo query_to_xml_internal(const char *query, char *tablename,
105 const char *xmlschema, bool nulls, bool tableforest,
106 const char *targetns, bool top_level);
107 static const char *map_sql_table_to_xmlschema(TupleDesc tupdesc, Oid relid,
108 bool nulls, bool tableforest, const char *targetns);
109 static const char *map_sql_schema_to_xmlschema_types(Oid nspid,
110 List *relid_list, bool nulls,
111 bool tableforest, const char *targetns);
112 static const char *map_sql_catalog_to_xmlschema_types(List *nspid_list,
113 bool nulls, bool tableforest,
114 const char *targetns);
115 static const char * map_sql_type_to_xml_name(Oid typeoid, int typmod);
116 static const char * map_sql_typecoll_to_xmlschema_types(List *tupdesc_list);
117 static const char * map_sql_type_to_xmlschema_type(Oid typeoid, int typmod);
118 static void SPI_sql_row_to_xmlelement(int rownum, StringInfo result,
119 char *tablename, bool nulls, bool tableforest,
120 const char *targetns, bool top_level);
122 #define NO_XML_SUPPORT() \
124 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), \
125 errmsg("unsupported XML feature"), \
126 errdetail("This functionality requires the server to be built with libxml support."), \
127 errhint("You need to rebuild PostgreSQL using --with-libxml.")))
130 #define _textin(str) DirectFunctionCall1(textin, CStringGetDatum(str))
131 #define _textout(x) DatumGetCString(DirectFunctionCall1(textout, PointerGetDatum(x)))
134 /* from SQL/XML:2003 section 4.7 */
135 #define NAMESPACE_XSD "http://www.w3.org/2001/XMLSchema"
136 #define NAMESPACE_XSI "http://www.w3.org/2001/XMLSchema-instance"
137 #define NAMESPACE_SQLXML "http://standards.iso.org/iso/9075/2003/sqlxml"
143 xmlChar_to_encoding(xmlChar *encoding_name)
145 int encoding = pg_char_to_encoding((char *) encoding_name);
149 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
150 errmsg("invalid encoding name \"%s\"",
151 (char *) encoding_name)));
159 xml_in(PG_FUNCTION_ARGS)
162 char *s = PG_GETARG_CSTRING(0);
168 vardata = palloc(len + VARHDRSZ);
169 SET_VARSIZE(vardata, len + VARHDRSZ);
170 memcpy(VARDATA(vardata), s, len);
173 * Parse the data to check if it is well-formed XML data. Assume
174 * that ERROR occurred if parsing failed.
176 doc = xml_parse(vardata, xmloption, true, NULL);
179 PG_RETURN_XML_P(vardata);
187 #define PG_XML_DEFAULT_VERSION "1.0"
191 xml_out_internal(xmltype *x, pg_enc target_encoding)
202 len = VARSIZE(x) - VARHDRSZ;
203 str = palloc(len + 1);
204 memcpy(str, VARDATA(x), len);
208 if ((res_code = parse_xml_decl((xmlChar *) str,
209 &len, &version, &encoding, &standalone)) == 0)
213 initStringInfo(&buf);
215 if (!print_xml_decl(&buf, version, target_encoding, standalone))
218 * If we are not going to produce an XML declaration, eat
219 * a single newline in the original string to prevent
220 * empty first lines in the output.
222 if (*(str + len) == '\n')
225 appendStringInfoString(&buf, str + len);
230 xml_ereport_by_code(WARNING, ERRCODE_INTERNAL_ERROR,
231 "could not parse XML declaration in stored value",
239 xml_out(PG_FUNCTION_ARGS)
241 xmltype *x = PG_GETARG_XML_P(0);
244 * xml_out removes the encoding property in all cases. This is
245 * because we cannot control from here whether the datum will be
246 * converted to a different client encoding, so we'd do more harm
247 * than good by including it.
249 PG_RETURN_CSTRING(xml_out_internal(x, 0));
254 xml_recv(PG_FUNCTION_ARGS)
257 StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
263 xmlChar *encoding = NULL;
266 * Read the data in raw format. We don't know yet what the encoding
267 * is, as that information is embedded in the xml declaration; so we
268 * have to parse that before converting to server encoding.
270 nbytes = buf->len - buf->cursor;
271 str = (char *) pq_getmsgbytes(buf, nbytes);
274 * We need a null-terminated string to pass to parse_xml_decl(). Rather
275 * than make a separate copy, make the temporary result one byte bigger
276 * than it needs to be.
278 result = palloc(nbytes + 1 + VARHDRSZ);
279 SET_VARSIZE(result, nbytes + VARHDRSZ);
280 memcpy(VARDATA(result), str, nbytes);
281 str = VARDATA(result);
284 parse_xml_decl((xmlChar *) str, NULL, NULL, &encoding, NULL);
287 * Parse the data to check if it is well-formed XML data. Assume
288 * that xml_parse will throw ERROR if not.
290 doc = xml_parse(result, xmloption, true, encoding);
293 /* Now that we know what we're dealing with, convert to server encoding */
294 newstr = (char *) pg_do_encoding_conversion((unsigned char *) str,
297 xmlChar_to_encoding(encoding) :
299 GetDatabaseEncoding());
305 nbytes = strlen(newstr);
307 result = palloc(nbytes + VARHDRSZ);
308 SET_VARSIZE(result, nbytes + VARHDRSZ);
309 memcpy(VARDATA(result), newstr, nbytes);
314 PG_RETURN_XML_P(result);
323 xml_send(PG_FUNCTION_ARGS)
325 xmltype *x = PG_GETARG_XML_P(0);
330 * xml_out_internal doesn't convert the encoding, it just prints
331 * the right declaration. pq_sendtext will do the conversion.
333 outval = xml_out_internal(x, pg_get_client_encoding());
335 pq_begintypsend(&buf);
336 pq_sendtext(&buf, outval, strlen(outval));
338 PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
344 appendStringInfoText(StringInfo str, const text *t)
346 appendBinaryStringInfo(str, VARDATA(t), VARSIZE(t) - VARHDRSZ);
352 stringinfo_to_xmltype(StringInfo buf)
357 len = buf->len + VARHDRSZ;
358 result = palloc(len);
359 SET_VARSIZE(result, len);
360 memcpy(VARDATA(result), buf->data, buf->len);
367 cstring_to_xmltype(const char *string)
372 len = strlen(string) + VARHDRSZ;
373 result = palloc(len);
374 SET_VARSIZE(result, len);
375 memcpy(VARDATA(result), string, len - VARHDRSZ);
383 xmlBuffer_to_xmltype(xmlBufferPtr buf)
388 len = xmlBufferLength(buf) + VARHDRSZ;
389 result = palloc(len);
390 SET_VARSIZE(result, len);
391 memcpy(VARDATA(result), xmlBufferContent(buf), len - VARHDRSZ);
399 xmlcomment(PG_FUNCTION_ARGS)
402 text *arg = PG_GETARG_TEXT_P(0);
403 char *argdata = VARDATA(arg);
404 int len = VARSIZE(arg) - VARHDRSZ;
408 /* check for "--" in string or "-" at the end */
409 for (i = 1; i < len; i++)
411 if (argdata[i] == '-' && argdata[i - 1] == '-')
413 (errcode(ERRCODE_INVALID_XML_COMMENT),
414 errmsg("invalid XML comment")));
416 if (len > 0 && argdata[len - 1] == '-')
418 (errcode(ERRCODE_INVALID_XML_COMMENT),
419 errmsg("invalid XML comment")));
421 initStringInfo(&buf);
422 appendStringInfo(&buf, "<!--");
423 appendStringInfoText(&buf, arg);
424 appendStringInfo(&buf, "-->");
426 PG_RETURN_XML_P(stringinfo_to_xmltype(&buf));
436 * TODO: xmlconcat needs to merge the notations and unparsed entities
437 * of the argument values. Not very important in practice, though.
440 xmlconcat(List *args)
443 int global_standalone = 1;
444 xmlChar *global_version = NULL;
445 bool global_version_no_value = false;
449 initStringInfo(&buf);
452 xmltype *x = DatumGetXmlP(PointerGetDatum(lfirst(v)));
458 len = VARSIZE(x) - VARHDRSZ;
459 str = palloc(len + 1);
460 memcpy(str, VARDATA(x), len);
463 parse_xml_decl((xmlChar *) str, &len, &version, NULL, &standalone);
465 if (standalone == 0 && global_standalone == 1)
466 global_standalone = 0;
468 global_standalone = -1;
471 global_version_no_value = true;
472 else if (!global_version)
473 global_version = xmlStrdup(version);
474 else if (xmlStrcmp(version, global_version) != 0)
475 global_version_no_value = true;
477 appendStringInfoString(&buf, str + len);
481 if (!global_version_no_value || global_standalone >= 0)
485 initStringInfo(&buf2);
487 print_xml_decl(&buf2,
488 (!global_version_no_value) ? global_version : NULL,
492 appendStringInfoString(&buf2, buf.data);
496 return stringinfo_to_xmltype(&buf);
508 xmlconcat2(PG_FUNCTION_ARGS)
515 PG_RETURN_XML_P(PG_GETARG_XML_P(1));
517 else if (PG_ARGISNULL(1))
518 PG_RETURN_XML_P(PG_GETARG_XML_P(0));
520 PG_RETURN_XML_P(xmlconcat(list_make2(PG_GETARG_XML_P(0),
521 PG_GETARG_XML_P(1))));
526 texttoxml(PG_FUNCTION_ARGS)
528 text *data = PG_GETARG_TEXT_P(0);
530 PG_RETURN_XML_P(xmlparse(data, xmloption, true));
535 xmltotext(PG_FUNCTION_ARGS)
537 xmltype *data = PG_GETARG_XML_P(0);
539 PG_RETURN_TEXT_P(xmltotext_with_xmloption(data, xmloption));
544 xmltotext_with_xmloption(xmltype *data, XmlOptionType xmloption_arg)
546 if (xmloption_arg == XMLOPTION_DOCUMENT && !xml_is_document(data))
548 (errcode(ERRCODE_NOT_AN_XML_DOCUMENT),
549 errmsg("not an XML document")));
551 /* It's actually binary compatible, save for the above check. */
552 return (text *) data;
557 xmlelement(XmlExprState *xmlExpr, ExprContext *econtext)
560 XmlExpr *xexpr = (XmlExpr *) xmlExpr->xprstate.expr;
562 List *named_arg_strings;
568 xmlTextWriterPtr writer;
571 * We first evaluate all the arguments, then start up libxml and
572 * create the result. This avoids issues if one of the arguments
573 * involves a call to some other function or subsystem that wants to use
574 * libxml on its own terms.
576 named_arg_strings = NIL;
578 foreach(arg, xmlExpr->named_args)
580 ExprState *e = (ExprState *) lfirst(arg);
585 value = ExecEvalExpr(e, econtext, &isnull, NULL);
589 str = OutputFunctionCall(&xmlExpr->named_outfuncs[i], value);
590 named_arg_strings = lappend(named_arg_strings, str);
595 foreach(arg, xmlExpr->args)
597 ExprState *e = (ExprState *) lfirst(arg);
602 value = ExecEvalExpr(e, econtext, &isnull, NULL);
603 /* here we can just forget NULL elements immediately */
606 str = map_sql_value_to_xml_value(value,
607 exprType((Node *) e->expr));
608 arg_strings = lappend(arg_strings, str);
612 /* now safe to run libxml */
615 buf = xmlBufferCreate();
616 writer = xmlNewTextWriterMemory(buf, 0);
618 xmlTextWriterStartElement(writer, (xmlChar *) xexpr->name);
620 forboth(arg, named_arg_strings, narg, xexpr->arg_names)
622 char *str = (char *) lfirst(arg);
623 char *argname = strVal(lfirst(narg));
627 xmlTextWriterWriteAttribute(writer,
634 foreach(arg, arg_strings)
636 char *str = (char *) lfirst(arg);
638 xmlTextWriterWriteRaw(writer, (xmlChar *) str);
641 xmlTextWriterEndElement(writer);
642 xmlFreeTextWriter(writer);
644 result = xmlBuffer_to_xmltype(buf);
656 xmlparse(text *data, XmlOptionType xmloption_arg, bool preserve_whitespace)
661 doc = xml_parse(data, xmloption_arg, preserve_whitespace, NULL);
664 return (xmltype *) data;
673 xmlpi(char *target, text *arg, bool arg_is_null, bool *result_is_null)
679 if (pg_strcasecmp(target, "xml") == 0)
681 (errcode(ERRCODE_SYNTAX_ERROR), /* really */
682 errmsg("invalid XML processing instruction"),
683 errdetail("XML processing instruction target name cannot be \"%s\".", target)));
686 * Following the SQL standard, the null check comes after the
687 * syntax check above.
689 *result_is_null = arg_is_null;
693 initStringInfo(&buf);
695 appendStringInfo(&buf, "<?%s", target);
701 string = _textout(arg);
702 if (strstr(string, "?>") != NULL)
704 (errcode(ERRCODE_INVALID_XML_PROCESSING_INSTRUCTION),
705 errmsg("invalid XML processing instruction"),
706 errdetail("XML processing instruction cannot contain \"?>\".")));
708 appendStringInfoChar(&buf, ' ');
709 appendStringInfoString(&buf, string + strspn(string, " "));
712 appendStringInfoString(&buf, "?>");
714 result = stringinfo_to_xmltype(&buf);
725 xmlroot(xmltype *data, text *version, int standalone)
730 xmlChar *orig_version;
734 len = VARSIZE(data) - VARHDRSZ;
735 str = palloc(len + 1);
736 memcpy(str, VARDATA(data), len);
739 parse_xml_decl((xmlChar *) str, &len, &orig_version, NULL, &orig_standalone);
742 orig_version = xml_text2xmlChar(version);
748 case XML_STANDALONE_YES:
751 case XML_STANDALONE_NO:
754 case XML_STANDALONE_NO_VALUE:
755 orig_standalone = -1;
757 case XML_STANDALONE_OMITTED:
758 /* leave original value */
762 initStringInfo(&buf);
763 print_xml_decl(&buf, orig_version, 0, orig_standalone);
764 appendStringInfoString(&buf, str + len);
766 return stringinfo_to_xmltype(&buf);
775 * Validate document (given as string) against DTD (given as external link)
776 * TODO !!! use text instead of cstring for second arg
777 * TODO allow passing DTD as a string value (not only as an URI)
778 * TODO redesign (see comment with '!!!' below)
781 xmlvalidate(PG_FUNCTION_ARGS)
784 text *data = PG_GETARG_TEXT_P(0);
785 text *dtdOrUri = PG_GETARG_TEXT_P(1);
787 xmlParserCtxtPtr ctxt = NULL;
788 xmlDocPtr doc = NULL;
789 xmlDtdPtr dtd = NULL;
793 /* We use a PG_TRY block to ensure libxml parser is cleaned up on error */
797 ctxt = xmlNewParserCtxt();
799 xml_ereport(ERROR, ERRCODE_INTERNAL_ERROR,
800 "could not allocate parser context");
802 doc = xmlCtxtReadMemory(ctxt, (char *) VARDATA(data),
803 VARSIZE(data) - VARHDRSZ,
806 xml_ereport(ERROR, ERRCODE_INVALID_XML_DOCUMENT,
807 "could not parse XML data");
810 uri = xmlCreateURI();
811 elog(NOTICE, "dtd - %s", dtdOrUri);
812 dtd = palloc(sizeof(xmlDtdPtr));
813 uri = xmlParseURI(dtdOrUri);
815 xml_ereport(ERROR, ERRCODE_INTERNAL_ERROR,
816 "not implemented yet... (TODO)");
819 dtd = xmlParseDTD(NULL, xml_text2xmlChar(dtdOrUri));
822 xml_ereport(ERROR, ERRCODE_INVALID_XML_DOCUMENT,
823 "could not load DTD");
825 if (xmlValidateDtd(xmlNewValidCtxt(), doc, dtd) == 1)
829 xml_ereport(NOTICE, ERRCODE_INVALID_XML_DOCUMENT,
830 "validation against DTD failed");
844 xmlFreeParserCtxt(ctxt);
859 xmlFreeParserCtxt(ctxt);
866 PG_RETURN_BOOL(result);
867 #else /* not USE_LIBXML */
870 #endif /* not USE_LIBXML */
875 xml_is_document(xmltype *arg)
879 xmlDocPtr doc = NULL;
880 MemoryContext ccxt = CurrentMemoryContext;
884 doc = xml_parse((text *) arg, XMLOPTION_DOCUMENT, true, NULL);
892 ecxt = MemoryContextSwitchTo(ccxt);
893 errdata = CopyErrorData();
894 if (errdata->sqlerrcode == ERRCODE_INVALID_XML_DOCUMENT)
901 MemoryContextSwitchTo(ecxt);
911 #else /* not USE_LIBXML */
914 #endif /* not USE_LIBXML */
921 * Set up for use of libxml --- this should be called by each function that
922 * is about to use libxml facilities.
924 * TODO: xmlChar is utf8-char, make proper tuning (initdb with enc!=utf8 and
930 static bool first_time = true;
934 /* Stuff we need do only once per session */
935 MemoryContext oldcontext;
938 * Currently, we have no pure UTF-8 support for internals -- check
941 if (sizeof(char) != sizeof(xmlChar))
943 (errmsg("could not initialize XML library"),
944 errdetail("libxml2 has incompatible char type: sizeof(char)=%u, sizeof(xmlChar)=%u.",
945 (int) sizeof(char), (int) sizeof(xmlChar))));
947 /* create error buffer in permanent context */
948 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
949 xml_err_buf = makeStringInfo();
950 MemoryContextSwitchTo(oldcontext);
952 /* Now that xml_err_buf exists, safe to call xml_errorHandler */
953 xmlSetGenericErrorFunc(NULL, xml_errorHandler);
955 /* Set up memory allocation our way, too */
956 xmlMemSetup(xml_pfree, xml_palloc, xml_repalloc, xml_pstrdup);
958 /* Check library compatibility */
965 /* Reset pre-existing buffer to empty */
966 Assert(xml_err_buf != NULL);
967 resetStringInfo(xml_err_buf);
970 * We re-establish the callback functions every time. This makes it
971 * safe for other subsystems (PL/Perl, say) to also use libxml with
972 * their own callbacks ... so long as they likewise set up the
973 * callbacks on every use. It's cheap enough to not be worth
974 * worrying about, anyway.
976 xmlSetGenericErrorFunc(NULL, xml_errorHandler);
977 xmlMemSetup(xml_pfree, xml_palloc, xml_repalloc, xml_pstrdup);
983 * SQL/XML allows storing "XML documents" or "XML content". "XML
984 * documents" are specified by the XML specification and are parsed
985 * easily by libxml. "XML content" is specified by SQL/XML as the
986 * production "XMLDecl? content". But libxml can only parse the
987 * "content" part, so we have to parse the XML declaration ourselves
991 #define CHECK_XML_SPACE(p) \
993 if (!xmlIsBlank_ch(*(p))) \
994 return XML_ERR_SPACE_REQUIRED; \
997 #define SKIP_XML_SPACE(p) \
998 while (xmlIsBlank_ch(*(p))) (p)++
1000 /* Letter | Digit | '.' | '-' | '_' | ':' | CombiningChar | Extender */
1001 #define pg_xmlIsNameChar(c) \
1002 (xmlIsBaseChar_ch(c) || xmlIsIdeographicQ(c) \
1003 || xmlIsDigit_ch(c) \
1004 || c == '.' || c == '-' || c == '_' || c == ':' \
1005 || xmlIsCombiningQ(c) \
1006 || xmlIsExtender_ch(c))
1009 parse_xml_decl(const xmlChar *str,size_t *lenp,
1010 xmlChar **version, xmlChar **encoding, int *standalone)
1013 const xmlChar *save_p;
1028 if (xmlStrncmp(p, (xmlChar *)"<?xml", 5) != 0)
1031 /* This means it's a PI like <?xml-stylesheet ...?>. */
1032 if (pg_xmlIsNameChar(xmlGetUTF8Char(&p[5], &utf8len)))
1040 if (xmlStrncmp(p, (xmlChar *)"version", 7) != 0)
1041 return XML_ERR_VERSION_MISSING;
1045 return XML_ERR_VERSION_MISSING;
1049 if (*p == '\'' || *p == '"')
1053 q = xmlStrchr(p + 1, *p);
1055 return XML_ERR_VERSION_MISSING;
1058 *version = xmlStrndup(p + 1, q - p - 1);
1062 return XML_ERR_VERSION_MISSING;
1067 if (xmlStrncmp(p, (xmlChar *)"encoding", 8) == 0)
1069 CHECK_XML_SPACE(save_p);
1073 return XML_ERR_MISSING_ENCODING;
1077 if (*p == '\'' || *p == '"')
1081 q = xmlStrchr(p + 1, *p);
1083 return XML_ERR_MISSING_ENCODING;
1086 *encoding = xmlStrndup(p + 1, q - p - 1);
1090 return XML_ERR_MISSING_ENCODING;
1100 if (xmlStrncmp(p, (xmlChar *)"standalone", 10) == 0)
1102 CHECK_XML_SPACE(save_p);
1106 return XML_ERR_STANDALONE_VALUE;
1109 if (xmlStrncmp(p, (xmlChar *)"'yes'", 5) == 0 || xmlStrncmp(p, (xmlChar *)"\"yes\"", 5) == 0)
1114 else if (xmlStrncmp(p, (xmlChar *)"'no'", 4) == 0 || xmlStrncmp(p, (xmlChar *)"\"no\"", 4) == 0)
1120 return XML_ERR_STANDALONE_VALUE;
1128 if (xmlStrncmp(p, (xmlChar *)"?>", 2) != 0)
1129 return XML_ERR_XMLDECL_NOT_FINISHED;
1135 for (p = str; p < str + len; p++)
1137 return XML_ERR_INVALID_CHAR;
1147 * Write an XML declaration. On output, we adjust the XML declaration
1148 * as follows. (These rules are the moral equivalent of the clause
1149 * "Serialization of an XML value" in the SQL standard.)
1151 * We try to avoid generating an XML declaration if possible. This is
1152 * so that you don't get trivial things like xml '<foo/>' resulting in
1153 * '<?xml version="1.0"?><foo/>', which would surely be annoying. We
1154 * must provide a declaration if the standalone property is specified
1155 * or if we include an encoding declaration. If we have a
1156 * declaration, we must specify a version (XML requires this).
1157 * Otherwise we only make a declaration if the version is not "1.0",
1158 * which is the default version specified in SQL:2003.
1161 print_xml_decl(StringInfo buf, const xmlChar *version,
1162 pg_enc encoding, int standalone)
1166 if ((version && strcmp((char *) version, PG_XML_DEFAULT_VERSION) != 0)
1167 || (encoding && encoding != PG_UTF8)
1168 || standalone != -1)
1170 appendStringInfoString(buf, "<?xml");
1173 appendStringInfo(buf, " version=\"%s\"", version);
1175 appendStringInfo(buf, " version=\"%s\"", PG_XML_DEFAULT_VERSION);
1177 if (encoding && encoding != PG_UTF8)
1180 * XXX might be useful to convert this to IANA names
1181 * (ISO-8859-1 instead of LATIN1 etc.); needs field experience
1183 appendStringInfo(buf, " encoding=\"%s\"",
1184 pg_encoding_to_char(encoding));
1187 if (standalone == 1)
1188 appendStringInfoString(buf, " standalone=\"yes\"");
1189 else if (standalone == 0)
1190 appendStringInfoString(buf, " standalone=\"no\"");
1191 appendStringInfoString(buf, "?>");
1201 * Convert a C string to XML internal representation
1203 * TODO maybe, libxml2's xmlreader is better? (do not construct DOM,
1204 * yet do not use SAX - see xml_reader.c)
1207 xml_parse(text *data, XmlOptionType xmloption_arg, bool preserve_whitespace,
1212 xmlChar *utf8string;
1213 xmlParserCtxtPtr ctxt = NULL;
1214 xmlDocPtr doc = NULL;
1216 len = VARSIZE(data) - VARHDRSZ; /* will be useful later */
1217 string = xml_text2xmlChar(data);
1219 utf8string = pg_do_encoding_conversion(string,
1222 xmlChar_to_encoding(encoding) :
1223 GetDatabaseEncoding(),
1228 /* We use a PG_TRY block to ensure libxml parser is cleaned up on error */
1232 ctxt = xmlNewParserCtxt();
1234 xml_ereport(ERROR, ERRCODE_INTERNAL_ERROR,
1235 "could not allocate parser context");
1237 if (xmloption_arg == XMLOPTION_DOCUMENT)
1240 * Note, that here we try to apply DTD defaults
1241 * (XML_PARSE_DTDATTR) according to SQL/XML:10.16.7.d:
1242 * 'Default valies defined by internal DTD are applied'.
1243 * As for external DTDs, we try to support them too, (see
1244 * SQL/XML:10.16.7.e)
1246 doc = xmlCtxtReadDoc(ctxt, utf8string,
1249 XML_PARSE_NOENT | XML_PARSE_DTDATTR
1250 | (preserve_whitespace ? 0 : XML_PARSE_NOBLANKS));
1252 xml_ereport(ERROR, ERRCODE_INVALID_XML_DOCUMENT,
1253 "invalid XML document");
1259 xmlChar *version = NULL;
1260 int standalone = -1;
1262 doc = xmlNewDoc(NULL);
1264 res_code = parse_xml_decl(utf8string, &count, &version, NULL, &standalone);
1266 xml_ereport_by_code(ERROR, ERRCODE_INVALID_XML_CONTENT,
1267 "invalid XML content: invalid XML declaration", res_code);
1269 res_code = xmlParseBalancedChunkMemory(doc, NULL, NULL, 0, utf8string + count, NULL);
1271 xml_ereport(ERROR, ERRCODE_INVALID_XML_CONTENT,
1272 "invalid XML content");
1274 doc->version = xmlStrdup(version);
1275 doc->encoding = xmlStrdup((xmlChar *) "UTF-8");
1276 doc->standalone = standalone;
1280 xmlFreeParserCtxt(ctxt);
1289 xmlFreeParserCtxt(ctxt);
1301 * xmlChar<->text convertions
1304 xml_text2xmlChar(text *in)
1306 int32 len = VARSIZE(in) - VARHDRSZ;
1309 res = palloc(len + 1);
1310 memcpy(res, VARDATA(in), len);
1318 * Wrappers for memory management functions
1321 xml_palloc(size_t size)
1323 return palloc(size);
1328 xml_repalloc(void *ptr, size_t size)
1330 return repalloc(ptr, size);
1335 xml_pfree(void *ptr)
1342 xml_pstrdup(const char *string)
1344 return pstrdup(string);
1349 * Wrapper for "ereport" function for XML-related errors. The "msg"
1350 * is the SQL-level message; some can be adopted from the SQL/XML
1351 * standard. This function adds libxml's native error messages, if
1355 xml_ereport(int level, int sqlcode, const char *msg)
1359 if (xml_err_buf->len > 0)
1361 detail = pstrdup(xml_err_buf->data);
1362 resetStringInfo(xml_err_buf);
1367 /* libxml error messages end in '\n'; get rid of it */
1372 len = strlen(detail);
1373 if (len > 0 && detail[len-1] == '\n')
1374 detail[len-1] = '\0';
1379 errdetail("%s", detail)));
1385 errmsg("%s", msg)));
1391 * Error handler for libxml error messages
1394 xml_errorHandler(void *ctxt, const char *msg,...)
1396 /* Append the formatted text to xml_err_buf */
1402 /* Try to format the data. */
1403 va_start(args, msg);
1404 success = appendStringInfoVA(xml_err_buf, msg, args);
1410 /* Double the buffer size and try again. */
1411 enlargeStringInfo(xml_err_buf, xml_err_buf->maxlen);
1417 * Wrapper for "ereport" function for XML-related errors. The "msg"
1418 * is the SQL-level message; some can be adopted from the SQL/XML
1419 * standard. This function uses "code" to create a textual detail
1420 * message. At the moment, we only need to cover those codes that we
1421 * may raise in this file.
1424 xml_ereport_by_code(int level, int sqlcode,
1425 const char *msg, int code)
1431 case XML_ERR_INVALID_CHAR:
1432 det = "Invalid character value";
1434 case XML_ERR_SPACE_REQUIRED:
1435 det = "Space required";
1437 case XML_ERR_STANDALONE_VALUE:
1438 det = "standalone accepts only 'yes' or 'no'";
1440 case XML_ERR_VERSION_MISSING:
1441 det = "Malformed declaration expecting version";
1443 case XML_ERR_MISSING_ENCODING:
1444 det = "Missing encoding in text declaration";
1446 case XML_ERR_XMLDECL_NOT_FINISHED:
1447 det = "Parsing XML declaration: '?>' expected";
1450 det = "Unrecognized libxml error code: %d";
1457 errdetail(det, code)));
1462 * Convert one char in the current server encoding to a Unicode codepoint.
1465 sqlchar_to_unicode(char *s)
1468 pg_wchar ret[2]; /* need space for trailing zero */
1470 utf8string = (char *) pg_do_encoding_conversion((unsigned char *) s,
1472 GetDatabaseEncoding(),
1475 pg_encoding_mb2wchar_with_len(PG_UTF8, utf8string, ret, pg_mblen(s));
1482 is_valid_xml_namefirst(pg_wchar c)
1484 /* (Letter | '_' | ':') */
1485 return (xmlIsBaseCharQ(c) || xmlIsIdeographicQ(c)
1486 || c == '_' || c == ':');
1491 is_valid_xml_namechar(pg_wchar c)
1493 /* Letter | Digit | '.' | '-' | '_' | ':' | CombiningChar | Extender */
1494 return (xmlIsBaseCharQ(c) || xmlIsIdeographicQ(c)
1496 || c == '.' || c == '-' || c == '_' || c == ':'
1497 || xmlIsCombiningQ(c)
1498 || xmlIsExtenderQ(c));
1500 #endif /* USE_LIBXML */
1504 * Map SQL identifier to XML name; see SQL/XML:2003 section 9.1.
1507 map_sql_identifier_to_xml_name(char *ident, bool fully_escaped,
1515 * SQL/XML doesn't make use of this case anywhere, so it's
1516 * probably a mistake.
1518 Assert(fully_escaped || !escape_period);
1520 initStringInfo(&buf);
1522 for (p = ident; *p; p += pg_mblen(p))
1524 if (*p == ':' && (p == ident || fully_escaped))
1525 appendStringInfo(&buf, "_x003A_");
1526 else if (*p == '_' && *(p+1) == 'x')
1527 appendStringInfo(&buf, "_x005F_");
1528 else if (fully_escaped && p == ident &&
1529 pg_strncasecmp(p, "xml", 3) == 0)
1532 appendStringInfo(&buf, "_x0078_");
1534 appendStringInfo(&buf, "_x0058_");
1536 else if (escape_period && *p == '.')
1537 appendStringInfo(&buf, "_x002E_");
1540 pg_wchar u = sqlchar_to_unicode(p);
1543 ? !is_valid_xml_namefirst(u)
1544 : !is_valid_xml_namechar(u))
1545 appendStringInfo(&buf, "_x%04X_", (unsigned int) u);
1547 appendBinaryStringInfo(&buf, p, pg_mblen(p));
1552 #else /* not USE_LIBXML */
1555 #endif /* not USE_LIBXML */
1560 * Map a Unicode codepoint into the current server encoding.
1563 unicode_to_sqlchar(pg_wchar c)
1565 static unsigned char utf8string[5]; /* need trailing zero */
1571 else if (c <= 0x7FF)
1573 utf8string[0] = 0xC0 | ((c >> 6) & 0x1F);
1574 utf8string[1] = 0x80 | (c & 0x3F);
1576 else if (c <= 0xFFFF)
1578 utf8string[0] = 0xE0 | ((c >> 12) & 0x0F);
1579 utf8string[1] = 0x80 | ((c >> 6) & 0x3F);
1580 utf8string[2] = 0x80 | (c & 0x3F);
1584 utf8string[0] = 0xF0 | ((c >> 18) & 0x07);
1585 utf8string[1] = 0x80 | ((c >> 12) & 0x3F);
1586 utf8string[2] = 0x80 | ((c >> 6) & 0x3F);
1587 utf8string[3] = 0x80 | (c & 0x3F);
1590 return (char *) pg_do_encoding_conversion(utf8string,
1591 pg_mblen((char *) utf8string),
1593 GetDatabaseEncoding());
1598 * Map XML name to SQL identifier; see SQL/XML:2003 section 9.17.
1601 map_xml_name_to_sql_identifier(char *name)
1606 initStringInfo(&buf);
1608 for (p = name; *p; p += pg_mblen(p))
1610 if (*p == '_' && *(p+1) == 'x'
1611 && isxdigit((unsigned char) *(p+2))
1612 && isxdigit((unsigned char) *(p+3))
1613 && isxdigit((unsigned char) *(p+4))
1614 && isxdigit((unsigned char) *(p+5))
1619 sscanf(p + 2, "%X", &u);
1620 appendStringInfoString(&buf, unicode_to_sqlchar(u));
1624 appendBinaryStringInfo(&buf, p, pg_mblen(p));
1631 * Map SQL value to XML value; see SQL/XML:2003 section 9.16.
1634 map_sql_value_to_xml_value(Datum value, Oid type)
1638 initStringInfo(&buf);
1640 if (type_is_array(type))
1652 array = DatumGetArrayTypeP(value);
1653 elmtype = ARR_ELEMTYPE(array);
1654 get_typlenbyvalalign(elmtype, &elmlen, &elmbyval, &elmalign);
1656 deconstruct_array(array, elmtype,
1657 elmlen, elmbyval, elmalign,
1658 &elem_values, &elem_nulls,
1661 for (i = 0; i < num_elems; i++)
1665 appendStringInfoString(&buf, "<element>");
1666 appendStringInfoString(&buf,
1667 map_sql_value_to_xml_value(elem_values[i],
1669 appendStringInfoString(&buf, "</element>");
1682 * Special XSD formatting for some data types
1687 if (DatumGetBool(value))
1696 char buf[MAXDATELEN + 1];
1698 date = DatumGetDateADT(value);
1699 j2date(date + POSTGRES_EPOCH_JDATE,
1700 &(tm.tm_year), &(tm.tm_mon), &(tm.tm_mday));
1701 EncodeDateOnly(&tm, USE_XSD_DATES, buf);
1703 return pstrdup(buf);
1708 Timestamp timestamp;
1712 char buf[MAXDATELEN + 1];
1714 timestamp = DatumGetTimestamp(value);
1716 /* XSD doesn't support infinite values */
1717 if (TIMESTAMP_NOT_FINITE(timestamp))
1719 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
1720 errmsg("timestamp out of range")));
1721 else if (timestamp2tm(timestamp, NULL, &tm, &fsec, NULL, NULL) == 0)
1722 EncodeDateTime(&tm, fsec, NULL, &tzn, USE_XSD_DATES, buf);
1725 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
1726 errmsg("timestamp out of range")));
1728 return pstrdup(buf);
1731 case TIMESTAMPTZOID:
1733 TimestampTz timestamp;
1738 char buf[MAXDATELEN + 1];
1740 timestamp = DatumGetTimestamp(value);
1742 /* XSD doesn't support infinite values */
1743 if (TIMESTAMP_NOT_FINITE(timestamp))
1745 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
1746 errmsg("timestamp out of range")));
1747 else if (timestamp2tm(timestamp, &tz, &tm, &fsec, &tzn, NULL) == 0)
1748 EncodeDateTime(&tm, fsec, &tz, &tzn, USE_XSD_DATES, buf);
1751 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
1752 errmsg("timestamp out of range")));
1754 return pstrdup(buf);
1758 getTypeOutputInfo(type, &typeOut, &isvarlena);
1759 str = OidOutputFunctionCall(typeOut, value);
1765 if (type == BYTEAOID)
1768 xmlTextWriterPtr writer;
1773 buf = xmlBufferCreate();
1774 writer = xmlNewTextWriterMemory(buf, 0);
1776 if (xmlbinary == XMLBINARY_BASE64)
1777 xmlTextWriterWriteBase64(writer, VARDATA(value), 0, VARSIZE(value) - VARHDRSZ);
1779 xmlTextWriterWriteBinHex(writer, VARDATA(value), 0, VARSIZE(value) - VARHDRSZ);
1781 xmlFreeTextWriter(writer);
1782 result = pstrdup((const char *) xmlBufferContent(buf));
1786 #endif /* USE_LIBXML */
1788 for (p = str; *p; p += pg_mblen(p))
1793 appendStringInfo(&buf, "&");
1796 appendStringInfo(&buf, "<");
1799 appendStringInfo(&buf, ">");
1802 appendStringInfo(&buf, "
");
1805 appendBinaryStringInfo(&buf, p, pg_mblen(p));
1816 _SPI_strdup(const char *s)
1818 char *ret = SPI_palloc(strlen(s) + 1);
1825 * SQL to XML mapping functions
1827 * What follows below is intentionally organized so that you can read
1828 * along in the SQL/XML:2003 standard. The functions are mostly split
1829 * up and ordered they way the clauses lay out in the standards
1830 * document, and the identifiers are also aligned with the standard
1831 * text. (SQL/XML:2006 appears to be ordered differently,
1834 * There are many things going on there:
1836 * There are two kinds of mappings: Mapping SQL data (table contents)
1837 * to XML documents, and mapping SQL structure (the "schema") to XML
1838 * Schema. And there are functions that do both at the same time.
1840 * Then you can map a database, a schema, or a table, each in both
1841 * ways. This breaks down recursively: Mapping a database invokes
1842 * mapping schemas, which invokes mapping tables, which invokes
1843 * mapping rows, which invokes mapping columns, although you can't
1844 * call the last two from the outside. Because of this, there are a
1845 * number of xyz_internal() functions which are to be called both from
1846 * the function manager wrapper and from some upper layer in a
1849 * See the documentation about what the common function arguments
1850 * nulls, tableforest, and targetns mean.
1852 * Some style guidelines for XML output: Use double quotes for quoting
1853 * XML attributes. Indent XML elements by two spaces, but remember
1854 * that a lot of code is called recursively at different levels, so
1855 * it's better not to indent rather than create output that indents
1856 * and outdents weirdly. Add newlines to make the output look nice.
1861 * Visibility of objects for XML mappings; see SQL/XML:2003 section
1866 * Given a query, which must return type oid as first column, produce
1867 * a list of Oids with the query results.
1870 query_to_oid_list(const char *query)
1875 SPI_execute(query, true, 0);
1877 for (i = 0; i < SPI_processed; i++)
1882 oid = SPI_getbinval(SPI_tuptable->vals[i],
1883 SPI_tuptable->tupdesc,
1887 list = lappend_oid(list, DatumGetObjectId(oid));
1895 schema_get_xml_visible_tables(Oid nspid)
1897 StringInfoData query;
1899 initStringInfo(&query);
1900 appendStringInfo(&query, "SELECT oid FROM pg_catalog.pg_class WHERE relnamespace = %u AND relkind IN ('r', 'v') AND pg_catalog.has_table_privilege (oid, 'SELECT') ORDER BY relname;", nspid);
1902 return query_to_oid_list(query.data);
1907 * Including the system schemas is probably not useful for a database
1910 #define XML_VISIBLE_SCHEMAS_EXCLUDE "(nspname ~ '^pg_' OR nspname = 'information_schema')"
1912 #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
1916 database_get_xml_visible_schemas(void)
1918 return query_to_oid_list(XML_VISIBLE_SCHEMAS " ORDER BY nspname;");
1923 database_get_xml_visible_tables(void)
1925 /* At the moment there is no order required here. */
1926 return query_to_oid_list("SELECT oid FROM pg_catalog.pg_class WHERE relkind IN ('r', 'v') AND pg_catalog.has_table_privilege (pg_class.oid, 'SELECT') AND relnamespace IN (" XML_VISIBLE_SCHEMAS ");");
1931 * Map SQL table to XML and/or XML Schema document; see SQL/XML:2003
1936 table_to_xml_internal(Oid relid,
1937 const char *xmlschema, bool nulls, bool tableforest,
1938 const char *targetns, bool top_level)
1940 StringInfoData query;
1942 initStringInfo(&query);
1943 appendStringInfo(&query, "SELECT * FROM %s",
1944 DatumGetCString(DirectFunctionCall1(regclassout,
1945 ObjectIdGetDatum(relid))));
1946 return query_to_xml_internal(query.data, get_rel_name(relid),
1947 xmlschema, nulls, tableforest,
1948 targetns, top_level);
1953 table_to_xml(PG_FUNCTION_ARGS)
1955 Oid relid = PG_GETARG_OID(0);
1956 bool nulls = PG_GETARG_BOOL(1);
1957 bool tableforest = PG_GETARG_BOOL(2);
1958 const char *targetns = _textout(PG_GETARG_TEXT_P(3));
1960 PG_RETURN_XML_P(stringinfo_to_xmltype(table_to_xml_internal(relid, NULL,
1967 query_to_xml(PG_FUNCTION_ARGS)
1969 char *query = _textout(PG_GETARG_TEXT_P(0));
1970 bool nulls = PG_GETARG_BOOL(1);
1971 bool tableforest = PG_GETARG_BOOL(2);
1972 const char *targetns = _textout(PG_GETARG_TEXT_P(3));
1974 PG_RETURN_XML_P(stringinfo_to_xmltype(query_to_xml_internal(query, NULL,
1975 NULL, nulls, tableforest,
1981 cursor_to_xml(PG_FUNCTION_ARGS)
1983 char *name = _textout(PG_GETARG_TEXT_P(0));
1984 int32 count = PG_GETARG_INT32(1);
1985 bool nulls = PG_GETARG_BOOL(2);
1986 bool tableforest = PG_GETARG_BOOL(3);
1987 const char *targetns = _textout(PG_GETARG_TEXT_P(4));
1989 StringInfoData result;
1993 initStringInfo(&result);
1996 portal = SPI_cursor_find(name);
1999 (errcode(ERRCODE_UNDEFINED_CURSOR),
2000 errmsg("cursor \"%s\" does not exist", name)));
2002 SPI_cursor_fetch(portal, true, count);
2003 for (i = 0; i < SPI_processed; i++)
2004 SPI_sql_row_to_xmlelement(i, &result, NULL, nulls,
2005 tableforest, targetns, true);
2009 PG_RETURN_XML_P(stringinfo_to_xmltype(&result));
2014 * Write the start tag of the root element of a data mapping.
2016 * top_level means that this is the very top level of the eventual
2017 * output. For example, when the user calls table_to_xml, then a call
2018 * with a table name to this function is the top level. When the user
2019 * calls database_to_xml, then a call with a schema name to this
2020 * function is not the top level. If top_level is false, then the XML
2021 * namespace declarations are omitted, because they supposedly already
2022 * appeared earlier in the output. Repeating them is not wrong, but
2026 xmldata_root_element_start(StringInfo result, const char *eltname,
2027 const char *xmlschema, const char *targetns,
2030 /* This isn't really wrong but currently makes no sense. */
2031 Assert(top_level || !xmlschema);
2033 appendStringInfo(result, "<%s", eltname);
2036 appendStringInfoString(result, " xmlns:xsi=\"" NAMESPACE_XSI "\"");
2037 if (strlen(targetns) > 0)
2038 appendStringInfo(result, " xmlns=\"%s\"", targetns);
2042 /* FIXME: better targets */
2043 if (strlen(targetns) > 0)
2044 appendStringInfo(result, " xsi:schemaLocation=\"%s #\"", targetns);
2046 appendStringInfo(result, " xsi:noNamespaceSchemaLocation=\"#\"");
2048 appendStringInfo(result, ">\n\n");
2053 xmldata_root_element_end(StringInfo result, const char *eltname)
2055 appendStringInfo(result, "</%s>\n", eltname);
2060 query_to_xml_internal(const char *query, char *tablename,
2061 const char *xmlschema, bool nulls, bool tableforest,
2062 const char *targetns, bool top_level)
2069 xmltn = map_sql_identifier_to_xml_name(tablename, true, false);
2073 result = makeStringInfo();
2076 if (SPI_execute(query, true, 0) != SPI_OK_SELECT)
2078 (errcode(ERRCODE_DATA_EXCEPTION),
2079 errmsg("invalid query")));
2082 xmldata_root_element_start(result, xmltn, xmlschema,
2083 targetns, top_level);
2086 appendStringInfo(result, "%s\n\n", xmlschema);
2088 for(i = 0; i < SPI_processed; i++)
2089 SPI_sql_row_to_xmlelement(i, result, tablename, nulls,
2090 tableforest, targetns, top_level);
2093 xmldata_root_element_end(result, xmltn);
2102 table_to_xmlschema(PG_FUNCTION_ARGS)
2104 Oid relid = PG_GETARG_OID(0);
2105 bool nulls = PG_GETARG_BOOL(1);
2106 bool tableforest = PG_GETARG_BOOL(2);
2107 const char *targetns = _textout(PG_GETARG_TEXT_P(3));
2111 rel = heap_open(relid, AccessShareLock);
2112 result = map_sql_table_to_xmlschema(rel->rd_att, relid, nulls,
2113 tableforest, targetns);
2114 heap_close(rel, NoLock);
2116 PG_RETURN_XML_P(cstring_to_xmltype(result));
2121 query_to_xmlschema(PG_FUNCTION_ARGS)
2123 char *query = _textout(PG_GETARG_TEXT_P(0));
2124 bool nulls = PG_GETARG_BOOL(1);
2125 bool tableforest = PG_GETARG_BOOL(2);
2126 const char *targetns = _textout(PG_GETARG_TEXT_P(3));
2132 plan = SPI_prepare(query, 0, NULL);
2133 portal = SPI_cursor_open(NULL, plan, NULL, NULL, true);
2134 result = _SPI_strdup(map_sql_table_to_xmlschema(portal->tupDesc,
2136 tableforest, targetns));
2137 SPI_cursor_close(portal);
2140 PG_RETURN_XML_P(cstring_to_xmltype(result));
2145 cursor_to_xmlschema(PG_FUNCTION_ARGS)
2147 char *name = _textout(PG_GETARG_TEXT_P(0));
2148 bool nulls = PG_GETARG_BOOL(1);
2149 bool tableforest = PG_GETARG_BOOL(2);
2150 const char *targetns = _textout(PG_GETARG_TEXT_P(3));
2151 const char *xmlschema;
2155 portal = SPI_cursor_find(name);
2158 (errcode(ERRCODE_UNDEFINED_CURSOR),
2159 errmsg("cursor \"%s\" does not exist", name)));
2161 xmlschema = _SPI_strdup(map_sql_table_to_xmlschema(portal->tupDesc,
2163 tableforest, targetns));
2166 PG_RETURN_XML_P(cstring_to_xmltype(xmlschema));
2171 table_to_xml_and_xmlschema(PG_FUNCTION_ARGS)
2173 Oid relid = PG_GETARG_OID(0);
2174 bool nulls = PG_GETARG_BOOL(1);
2175 bool tableforest = PG_GETARG_BOOL(2);
2176 const char *targetns = _textout(PG_GETARG_TEXT_P(3));
2178 const char *xmlschema;
2180 rel = heap_open(relid, AccessShareLock);
2181 xmlschema = map_sql_table_to_xmlschema(rel->rd_att, relid, nulls,
2182 tableforest, targetns);
2183 heap_close(rel, NoLock);
2185 PG_RETURN_XML_P(stringinfo_to_xmltype(table_to_xml_internal(relid,
2186 xmlschema, nulls, tableforest,
2192 query_to_xml_and_xmlschema(PG_FUNCTION_ARGS)
2194 char *query = _textout(PG_GETARG_TEXT_P(0));
2195 bool nulls = PG_GETARG_BOOL(1);
2196 bool tableforest = PG_GETARG_BOOL(2);
2197 const char *targetns = _textout(PG_GETARG_TEXT_P(3));
2199 const char *xmlschema;
2204 plan = SPI_prepare(query, 0, NULL);
2205 portal = SPI_cursor_open(NULL, plan, NULL, NULL, true);
2206 xmlschema = _SPI_strdup(map_sql_table_to_xmlschema(portal->tupDesc,
2207 InvalidOid, nulls, tableforest, targetns));
2208 SPI_cursor_close(portal);
2211 PG_RETURN_XML_P(stringinfo_to_xmltype(query_to_xml_internal(query, NULL,
2212 xmlschema, nulls, tableforest,
2218 * Map SQL schema to XML and/or XML Schema document; see SQL/XML:2003
2223 schema_to_xml_internal(Oid nspid, const char *xmlschema, bool nulls,
2224 bool tableforest, const char *targetns, bool top_level)
2231 xmlsn = map_sql_identifier_to_xml_name(get_namespace_name(nspid),
2233 result = makeStringInfo();
2235 xmldata_root_element_start(result, xmlsn, xmlschema, targetns, top_level);
2238 appendStringInfo(result, "%s\n\n", xmlschema);
2242 relid_list = schema_get_xml_visible_tables(nspid);
2246 foreach(cell, relid_list)
2248 Oid relid = lfirst_oid(cell);
2251 subres = table_to_xml_internal(relid, NULL, nulls, tableforest,
2254 appendStringInfoString(result, subres->data);
2255 appendStringInfoChar(result, '\n');
2261 xmldata_root_element_end(result, xmlsn);
2268 schema_to_xml(PG_FUNCTION_ARGS)
2270 Name name = PG_GETARG_NAME(0);
2271 bool nulls = PG_GETARG_BOOL(1);
2272 bool tableforest = PG_GETARG_BOOL(2);
2273 const char *targetns = _textout(PG_GETARG_TEXT_P(3));
2278 schemaname = NameStr(*name);
2279 nspid = LookupExplicitNamespace(schemaname);
2281 PG_RETURN_XML_P(stringinfo_to_xmltype(schema_to_xml_internal(nspid, NULL,
2282 nulls, tableforest, targetns, true)));
2287 * Write the start element of the root element of an XML Schema mapping.
2290 xsd_schema_element_start(StringInfo result, const char *targetns)
2292 appendStringInfoString(result,
2294 " xmlns:xsd=\"" NAMESPACE_XSD "\"");
2295 if (strlen(targetns) > 0)
2296 appendStringInfo(result,
2298 " targetNamespace=\"%s\"\n"
2299 " elementFormDefault=\"qualified\"",
2301 appendStringInfoString(result,
2307 xsd_schema_element_end(StringInfo result)
2309 appendStringInfoString(result, "</xsd:schema>");
2314 schema_to_xmlschema_internal(const char *schemaname, bool nulls,
2315 bool tableforest, const char *targetns)
2323 result = makeStringInfo();
2325 nspid = LookupExplicitNamespace(schemaname);
2327 xsd_schema_element_start(result, targetns);
2331 relid_list = schema_get_xml_visible_tables(nspid);
2334 foreach (cell, relid_list)
2338 rel = heap_open(lfirst_oid(cell), AccessShareLock);
2339 tupdesc_list = lappend(tupdesc_list, CreateTupleDescCopy(rel->rd_att));
2340 heap_close(rel, NoLock);
2343 appendStringInfoString(result,
2344 map_sql_typecoll_to_xmlschema_types(tupdesc_list));
2346 appendStringInfoString(result,
2347 map_sql_schema_to_xmlschema_types(nspid, relid_list,
2348 nulls, tableforest, targetns));
2350 xsd_schema_element_end(result);
2359 schema_to_xmlschema(PG_FUNCTION_ARGS)
2361 Name name = PG_GETARG_NAME(0);
2362 bool nulls = PG_GETARG_BOOL(1);
2363 bool tableforest = PG_GETARG_BOOL(2);
2364 const char *targetns = _textout(PG_GETARG_TEXT_P(3));
2366 PG_RETURN_XML_P(stringinfo_to_xmltype(schema_to_xmlschema_internal(NameStr(*name),
2367 nulls, tableforest, targetns)));
2372 schema_to_xml_and_xmlschema(PG_FUNCTION_ARGS)
2374 Name name = PG_GETARG_NAME(0);
2375 bool nulls = PG_GETARG_BOOL(1);
2376 bool tableforest = PG_GETARG_BOOL(2);
2377 const char *targetns = _textout(PG_GETARG_TEXT_P(3));
2380 StringInfo xmlschema;
2382 schemaname = NameStr(*name);
2383 nspid = LookupExplicitNamespace(schemaname);
2385 xmlschema = schema_to_xmlschema_internal(schemaname, nulls,
2386 tableforest, targetns);
2388 PG_RETURN_XML_P(stringinfo_to_xmltype(schema_to_xml_internal(nspid,
2389 xmlschema->data, nulls,
2390 tableforest, targetns, true)));
2395 * Map SQL database to XML and/or XML Schema document; see SQL/XML:2003
2400 database_to_xml_internal(const char *xmlschema, bool nulls,
2401 bool tableforest, const char *targetns)
2408 xmlcn = map_sql_identifier_to_xml_name(get_database_name(MyDatabaseId),
2410 result = makeStringInfo();
2412 xmldata_root_element_start(result, xmlcn, xmlschema, targetns, true);
2415 appendStringInfo(result, "%s\n\n", xmlschema);
2419 nspid_list = database_get_xml_visible_schemas();
2423 foreach(cell, nspid_list)
2425 Oid nspid = lfirst_oid(cell);
2428 subres = schema_to_xml_internal(nspid, NULL, nulls,
2429 tableforest, targetns, false);
2431 appendStringInfoString(result, subres->data);
2432 appendStringInfoChar(result, '\n');
2438 xmldata_root_element_end(result, xmlcn);
2445 database_to_xml(PG_FUNCTION_ARGS)
2447 bool nulls = PG_GETARG_BOOL(0);
2448 bool tableforest = PG_GETARG_BOOL(1);
2449 const char *targetns = _textout(PG_GETARG_TEXT_P(2));
2451 PG_RETURN_XML_P(stringinfo_to_xmltype(database_to_xml_internal(NULL, nulls,
2452 tableforest, targetns)));
2457 database_to_xmlschema_internal(bool nulls, bool tableforest,
2458 const char *targetns)
2466 result = makeStringInfo();
2468 xsd_schema_element_start(result, targetns);
2472 relid_list = database_get_xml_visible_tables();
2473 nspid_list = database_get_xml_visible_schemas();
2476 foreach (cell, relid_list)
2480 rel = heap_open(lfirst_oid(cell), AccessShareLock);
2481 tupdesc_list = lappend(tupdesc_list, CreateTupleDescCopy(rel->rd_att));
2482 heap_close(rel, NoLock);
2485 appendStringInfoString(result,
2486 map_sql_typecoll_to_xmlschema_types(tupdesc_list));
2488 appendStringInfoString(result,
2489 map_sql_catalog_to_xmlschema_types(nspid_list, nulls, tableforest, targetns));
2491 xsd_schema_element_end(result);
2500 database_to_xmlschema(PG_FUNCTION_ARGS)
2502 bool nulls = PG_GETARG_BOOL(0);
2503 bool tableforest = PG_GETARG_BOOL(1);
2504 const char *targetns = _textout(PG_GETARG_TEXT_P(2));
2506 PG_RETURN_XML_P(stringinfo_to_xmltype(database_to_xmlschema_internal(nulls,
2507 tableforest, targetns)));
2512 database_to_xml_and_xmlschema(PG_FUNCTION_ARGS)
2514 bool nulls = PG_GETARG_BOOL(0);
2515 bool tableforest = PG_GETARG_BOOL(1);
2516 const char *targetns = _textout(PG_GETARG_TEXT_P(2));
2517 StringInfo xmlschema;
2519 xmlschema = database_to_xmlschema_internal(nulls, tableforest, targetns);
2521 PG_RETURN_XML_P(stringinfo_to_xmltype(database_to_xml_internal(xmlschema->data,
2522 nulls, tableforest, targetns)));
2527 * Map a multi-part SQL name to an XML name; see SQL/XML:2003 section
2531 map_multipart_sql_identifier_to_xml_name(char *a, char *b, char *c, char *d)
2533 StringInfoData result;
2535 initStringInfo(&result);
2538 appendStringInfo(&result, "%s",
2539 map_sql_identifier_to_xml_name(a, true, true));
2541 appendStringInfo(&result, ".%s",
2542 map_sql_identifier_to_xml_name(b, true, true));
2544 appendStringInfo(&result, ".%s",
2545 map_sql_identifier_to_xml_name(c, true, true));
2547 appendStringInfo(&result, ".%s",
2548 map_sql_identifier_to_xml_name(d, true, true));
2555 * Map an SQL table to an XML Schema document; see SQL/XML:2003
2558 * Map an SQL table to XML Schema data types; see SQL/XML:2003 section
2562 map_sql_table_to_xmlschema(TupleDesc tupdesc, Oid relid, bool nulls,
2563 bool tableforest, const char *targetns)
2567 char *tabletypename;
2569 StringInfoData result;
2571 initStringInfo(&result);
2573 if (OidIsValid(relid))
2576 Form_pg_class reltuple;
2578 tuple = SearchSysCache(RELOID,
2579 ObjectIdGetDatum(relid),
2581 if (!HeapTupleIsValid(tuple))
2582 elog(ERROR, "cache lookup failed for relation %u", relid);
2583 reltuple = (Form_pg_class) GETSTRUCT(tuple);
2585 xmltn = map_sql_identifier_to_xml_name(NameStr(reltuple->relname),
2588 tabletypename = map_multipart_sql_identifier_to_xml_name("TableType",
2589 get_database_name(MyDatabaseId),
2590 get_namespace_name(reltuple->relnamespace),
2591 NameStr(reltuple->relname));
2593 rowtypename = map_multipart_sql_identifier_to_xml_name("RowType",
2594 get_database_name(MyDatabaseId),
2595 get_namespace_name(reltuple->relnamespace),
2596 NameStr(reltuple->relname));
2598 ReleaseSysCache(tuple);
2607 tabletypename = "TableType";
2608 rowtypename = "RowType";
2611 xsd_schema_element_start(&result, targetns);
2613 appendStringInfoString(&result,
2614 map_sql_typecoll_to_xmlschema_types(list_make1(tupdesc)));
2616 appendStringInfo(&result,
2617 "<xsd:complexType name=\"%s\">\n"
2618 " <xsd:sequence>\n",
2621 for (i = 0; i < tupdesc->natts; i++)
2622 appendStringInfo(&result,
2623 " <xsd:element name=\"%s\" type=\"%s\"%s></xsd:element>\n",
2624 map_sql_identifier_to_xml_name(NameStr(tupdesc->attrs[i]->attname),
2626 map_sql_type_to_xml_name(tupdesc->attrs[i]->atttypid, -1),
2627 nulls ? " nillable=\"true\"" : " minOccurs=\"0\"");
2629 appendStringInfoString(&result,
2630 " </xsd:sequence>\n"
2631 "</xsd:complexType>\n\n");
2635 appendStringInfo(&result,
2636 "<xsd:complexType name=\"%s\">\n"
2638 " <xsd:element name=\"row\" type=\"%s\" minOccurs=\"0\" maxOccurs=\"unbounded\"/>\n"
2639 " </xsd:sequence>\n"
2640 "</xsd:complexType>\n\n",
2641 tabletypename, rowtypename);
2643 appendStringInfo(&result,
2644 "<xsd:element name=\"%s\" type=\"%s\"/>\n\n",
2645 xmltn, tabletypename);
2648 appendStringInfo(&result,
2649 "<xsd:element name=\"%s\" type=\"%s\"/>\n\n",
2650 xmltn, rowtypename);
2652 xsd_schema_element_end(&result);
2659 * Map an SQL schema to XML Schema data types; see SQL/XML section
2663 map_sql_schema_to_xmlschema_types(Oid nspid, List *relid_list, bool nulls,
2664 bool tableforest, const char *targetns)
2669 char *schematypename;
2670 StringInfoData result;
2673 dbname = get_database_name(MyDatabaseId);
2674 nspname = get_namespace_name(nspid);
2676 initStringInfo(&result);
2678 xmlsn = map_sql_identifier_to_xml_name(nspname, true, false);
2680 schematypename = map_multipart_sql_identifier_to_xml_name("SchemaType",
2685 appendStringInfo(&result,
2686 "<xsd:complexType name=\"%s\">\n", schematypename);
2688 appendStringInfoString(&result,
2691 appendStringInfoString(&result,
2692 " <xsd:sequence>\n");
2694 foreach (cell, relid_list)
2696 Oid relid = lfirst_oid(cell);
2697 char *relname = get_rel_name(relid);
2698 char *xmltn = map_sql_identifier_to_xml_name(relname, true, false);
2699 char *tabletypename = map_multipart_sql_identifier_to_xml_name(tableforest ? "RowType" : "TableType",
2705 appendStringInfo(&result,
2706 " <xsd:element name=\"%s\" type=\"%s\" />\n",
2707 xmltn, tabletypename);
2709 appendStringInfo(&result,
2710 " <xsd:element name=\"%s\" type=\"%s\" minOccurs=\"0\" maxOccurs=\"unbounded\" />\n",
2711 xmltn, tabletypename);
2715 appendStringInfoString(&result,
2718 appendStringInfoString(&result,
2719 " </xsd:sequence>\n");
2720 appendStringInfoString(&result,
2721 "</xsd:complexType>\n\n");
2723 appendStringInfo(&result,
2724 "<xsd:element name=\"%s\" type=\"%s\"/>\n\n",
2725 xmlsn, schematypename);
2732 * Map an SQL catalog to XML Schema data types; see SQL/XML section
2736 map_sql_catalog_to_xmlschema_types(List *nspid_list, bool nulls,
2737 bool tableforest, const char *targetns)
2741 char *catalogtypename;
2742 StringInfoData result;
2745 dbname = get_database_name(MyDatabaseId);
2747 initStringInfo(&result);
2749 xmlcn = map_sql_identifier_to_xml_name(dbname, true, false);
2751 catalogtypename = map_multipart_sql_identifier_to_xml_name("CatalogType",
2756 appendStringInfo(&result,
2757 "<xsd:complexType name=\"%s\">\n", catalogtypename);
2758 appendStringInfoString(&result,
2761 foreach (cell, nspid_list)
2763 Oid nspid = lfirst_oid(cell);
2764 char *nspname = get_namespace_name(nspid);
2765 char *xmlsn = map_sql_identifier_to_xml_name(nspname, true, false);
2766 char *schematypename = map_multipart_sql_identifier_to_xml_name("SchemaType",
2771 appendStringInfo(&result,
2772 " <xsd:element name=\"%s\" type=\"%s\" />\n",
2773 xmlsn, schematypename);
2776 appendStringInfoString(&result,
2778 appendStringInfoString(&result,
2779 "</xsd:complexType>\n\n");
2781 appendStringInfo(&result,
2782 "<xsd:element name=\"%s\" type=\"%s\"/>\n\n",
2783 xmlcn, catalogtypename);
2790 * Map an SQL data type to an XML name; see SQL/XML:2003 section 9.9.
2793 map_sql_type_to_xml_name(Oid typeoid, int typmod)
2795 StringInfoData result;
2797 initStringInfo(&result);
2803 appendStringInfo(&result, "CHAR");
2805 appendStringInfo(&result, "CHAR_%d", typmod - VARHDRSZ);
2809 appendStringInfo(&result, "VARCHAR");
2811 appendStringInfo(&result, "VARCHAR_%d", typmod - VARHDRSZ);
2815 appendStringInfo(&result, "NUMERIC");
2817 appendStringInfo(&result, "NUMERIC_%d_%d",
2818 ((typmod - VARHDRSZ) >> 16) & 0xffff,
2819 (typmod - VARHDRSZ) & 0xffff);
2822 appendStringInfo(&result, "INTEGER");
2825 appendStringInfo(&result, "SMALLINT");
2828 appendStringInfo(&result, "BIGINT");
2831 appendStringInfo(&result, "REAL");
2834 appendStringInfo(&result, "DOUBLE");
2837 appendStringInfo(&result, "BOOLEAN");
2841 appendStringInfo(&result, "TIME");
2843 appendStringInfo(&result, "TIME_%d", typmod);
2847 appendStringInfo(&result, "TIME_WTZ");
2849 appendStringInfo(&result, "TIME_WTZ_%d", typmod);
2853 appendStringInfo(&result, "TIMESTAMP");
2855 appendStringInfo(&result, "TIMESTAMP_%d", typmod);
2857 case TIMESTAMPTZOID:
2859 appendStringInfo(&result, "TIMESTAMP_WTZ");
2861 appendStringInfo(&result, "TIMESTAMP_WTZ_%d", typmod);
2864 appendStringInfo(&result, "DATE");
2867 appendStringInfo(&result, "XML");
2872 Form_pg_type typtuple;
2874 tuple = SearchSysCache(TYPEOID,
2875 ObjectIdGetDatum(typeoid),
2877 if (!HeapTupleIsValid(tuple))
2878 elog(ERROR, "cache lookup failed for type %u", typeoid);
2879 typtuple = (Form_pg_type) GETSTRUCT(tuple);
2881 appendStringInfoString(&result,
2882 map_multipart_sql_identifier_to_xml_name((typtuple->typtype == TYPTYPE_DOMAIN) ? "Domain" : "UDT",
2883 get_database_name(MyDatabaseId),
2884 get_namespace_name(typtuple->typnamespace),
2885 NameStr(typtuple->typname)));
2887 ReleaseSysCache(tuple);
2896 * Map a collection of SQL data types to XML Schema data types; see
2897 * SQL/XML:2002 section 9.10.
2900 map_sql_typecoll_to_xmlschema_types(List *tupdesc_list)
2902 List *uniquetypes = NIL;
2904 StringInfoData result;
2907 /* extract all column types used in the set of TupleDescs */
2908 foreach(cell0, tupdesc_list)
2910 TupleDesc tupdesc = (TupleDesc) lfirst(cell0);
2912 for (i = 0; i < tupdesc->natts; i++)
2914 if (tupdesc->attrs[i]->attisdropped)
2916 uniquetypes = list_append_unique_oid(uniquetypes,
2917 tupdesc->attrs[i]->atttypid);
2921 /* add base types of domains */
2922 foreach(cell0, uniquetypes)
2924 Oid typid = lfirst_oid(cell0);
2925 Oid basetypid = getBaseType(typid);
2927 if (basetypid != typid)
2928 uniquetypes = list_append_unique_oid(uniquetypes, basetypid);
2931 /* Convert to textual form */
2932 initStringInfo(&result);
2934 foreach(cell0, uniquetypes)
2936 appendStringInfo(&result, "%s\n",
2937 map_sql_type_to_xmlschema_type(lfirst_oid(cell0),
2946 * Map an SQL data type to a named XML Schema data type; see SQL/XML
2947 * sections 9.11 and 9.15.
2949 * (The distinction between 9.11 and 9.15 is basically that 9.15 adds
2950 * a name attribute, which this function does. The name-less version
2951 * 9.11 doesn't appear to be required anywhere.)
2954 map_sql_type_to_xmlschema_type(Oid typeoid, int typmod)
2956 StringInfoData result;
2957 const char *typename = map_sql_type_to_xml_name(typeoid, typmod);
2959 initStringInfo(&result);
2961 if (typeoid == XMLOID)
2963 appendStringInfo(&result,
2964 "<xsd:complexType mixed=\"true\">\n"
2966 " <xsd:any name=\"element\" minOccurs=\"0\" maxOccurs=\"unbounded\" processContents=\"skip\"/>\n"
2967 " </xsd:sequence>\n"
2968 "</xsd:complexType>\n");
2972 appendStringInfo(&result,
2973 "<xsd:simpleType name=\"%s\">\n", typename);
2981 appendStringInfo(&result,
2982 " <xsd:restriction base=\"xsd:string\">\n"
2983 " <xsd:maxLength value=\"%d\"/>\n"
2984 " </xsd:restriction>\n",
2989 appendStringInfo(&result,
2990 " <xsd:restriction base=\"xsd:%s\">\n"
2991 " </xsd:restriction>\n",
2992 xmlbinary == XMLBINARY_BASE64 ? "base64Binary" : "hexBinary");
2996 appendStringInfo(&result,
2997 " <xsd:restriction base=\"xsd:decimal\">\n"
2998 " <xsd:totalDigits value=\"%d\"/>\n"
2999 " <xsd:fractionDigits value=\"%d\"/>\n"
3000 " </xsd:restriction>\n",
3001 ((typmod - VARHDRSZ) >> 16) & 0xffff,
3002 (typmod - VARHDRSZ) & 0xffff);
3006 appendStringInfo(&result,
3007 " <xsd:restriction base=\"xsd:short\">\n"
3008 " <xsd:maxInclusive value=\"%d\"/>\n"
3009 " <xsd:minInclusive value=\"%d\"/>\n"
3010 " </xsd:restriction>\n",
3011 SHRT_MAX, SHRT_MIN);
3015 appendStringInfo(&result,
3016 " <xsd:restriction base='xsd:int'>\n"
3017 " <xsd:maxInclusive value=\"%d\"/>\n"
3018 " <xsd:minInclusive value=\"%d\"/>\n"
3019 " </xsd:restriction>\n",
3024 appendStringInfo(&result,
3025 " <xsd:restriction base=\"xsd:long\">\n"
3026 " <xsd:maxInclusive value=\"" INT64_FORMAT "\"/>\n"
3027 " <xsd:minInclusive value=\"" INT64_FORMAT "\"/>\n"
3028 " </xsd:restriction>\n",
3029 (((uint64) 1) << (sizeof(int64) * 8 - 1)) - 1,
3030 (((uint64) 1) << (sizeof(int64) * 8 - 1)));
3034 appendStringInfo(&result,
3035 " <xsd:restriction base=\"xsd:float\"></xsd:restriction>\n");
3039 appendStringInfo(&result,
3040 " <xsd:restriction base=\"xsd:double\"></xsd:restriction>\n");
3044 appendStringInfo(&result,
3045 " <xsd:restriction base=\"xsd:boolean\"></xsd:restriction>\n");
3051 const char *tz = (typeoid == TIMETZOID ? "(+|-)\\p{Nd}{2}:\\p{Nd}{2}" : "");
3054 appendStringInfo(&result,
3055 " <xsd:restriction base=\"xsd:time\">\n"
3056 " <xsd:pattern value=\"\\p{Nd}{2}:\\p{Nd}{2}:\\p{Nd}{2}(.\\p{Nd}+)?%s\"/>\n"
3057 " </xsd:restriction>\n", tz);
3058 else if (typmod == 0)
3059 appendStringInfo(&result,
3060 " <xsd:restriction base=\"xsd:time\">\n"
3061 " <xsd:pattern value=\"\\p{Nd}{2}:\\p{Nd}{2}:\\p{Nd}{2}%s\"/>\n"
3062 " </xsd:restriction>\n", tz);
3064 appendStringInfo(&result,
3065 " <xsd:restriction base=\"xsd:time\">\n"
3066 " <xsd:pattern value=\"\\p{Nd}{2}:\\p{Nd}{2}:\\p{Nd}{2}.\\p{Nd}{%d}%s\"/>\n"
3067 " </xsd:restriction>\n", typmod - VARHDRSZ, tz);
3072 case TIMESTAMPTZOID:
3074 const char *tz = (typeoid == TIMESTAMPTZOID ? "(+|-)\\p{Nd}{2}:\\p{Nd}{2}" : "");
3077 appendStringInfo(&result,
3078 " <xsd:restriction base=\"xsd:dateTime\">\n"
3079 " <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"
3080 " </xsd:restriction>\n", tz);
3081 else if (typmod == 0)
3082 appendStringInfo(&result,
3083 " <xsd:restriction base=\"xsd:dateTime\">\n"
3084 " <xsd:pattern value=\"\\p{Nd}{4}-\\p{Nd}{2}-\\p{Nd}{2}T\\p{Nd}{2}:\\p{Nd}{2}:\\p{Nd}{2}%s\"/>\n"
3085 " </xsd:restriction>\n", tz);
3087 appendStringInfo(&result,
3088 " <xsd:restriction base=\"xsd:dateTime\">\n"
3089 " <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"
3090 " </xsd:restriction>\n", typmod - VARHDRSZ, tz);
3095 appendStringInfo(&result,
3096 " <xsd:restriction base=\"xsd:date\">\n"
3097 " <xsd:pattern value=\"\\p{Nd}{4}-\\p{Nd}{2}-\\p{Nd}{2}\"/>\n"
3098 " </xsd:restriction>\n");
3102 if (get_typtype(typeoid) == TYPTYPE_DOMAIN)
3105 int32 base_typmod = -1;
3107 base_typeoid = getBaseTypeAndTypmod(typeoid, &base_typmod);
3109 appendStringInfo(&result,
3110 " <xsd:restriction base=\"%s\">\n",
3111 map_sql_type_to_xml_name(base_typeoid, base_typmod));
3115 appendStringInfo(&result,
3116 "</xsd:simpleType>\n");
3124 * Map an SQL row to an XML element, taking the row from the active
3125 * SPI cursor. See also SQL/XML:2003 section 9.12.
3128 SPI_sql_row_to_xmlelement(int rownum, StringInfo result, char *tablename,
3129 bool nulls, bool tableforest,
3130 const char *targetns, bool top_level)
3136 xmltn = map_sql_identifier_to_xml_name(tablename, true, false);
3146 xmldata_root_element_start(result, xmltn, NULL, targetns, top_level);
3148 appendStringInfoString(result, "<row>\n");
3150 for(i = 1; i <= SPI_tuptable->tupdesc->natts; i++)
3156 colname = map_sql_identifier_to_xml_name(SPI_fname(SPI_tuptable->tupdesc, i),
3158 colval = SPI_getbinval(SPI_tuptable->vals[rownum],
3159 SPI_tuptable->tupdesc,
3165 appendStringInfo(result, " <%s xsi:nil='true'/>\n", colname);
3168 appendStringInfo(result, " <%s>%s</%s>\n",
3170 map_sql_value_to_xml_value(colval,
3171 SPI_gettypeid(SPI_tuptable->tupdesc, i)),
3177 xmldata_root_element_end(result, xmltn);
3178 appendStringInfoChar(result, '\n');
3181 appendStringInfoString(result, "</row>\n\n");
3186 * XPath related functions
3191 * Convert XML node to text (dump subtree in case of element,
3192 * return value otherwise)
3195 xml_xmlnodetoxmltype(xmlNodePtr cur)
3202 if (cur->type == XML_ELEMENT_NODE)
3204 buf = xmlBufferCreate();
3205 xmlNodeDump(buf, NULL, cur, 0, 1);
3206 result = xmlBuffer_to_xmltype(buf);
3211 str = xmlXPathCastNodeToString(cur);
3212 len = strlen((char *) str);
3213 result = (text *) palloc(len + VARHDRSZ);
3214 SET_VARSIZE(result, len + VARHDRSZ);
3215 memcpy(VARDATA(result), str, len);
3224 * Evaluate XPath expression and return array of XML values.
3226 * As we have no support of XQuery sequences yet, this function seems
3227 * to be the most useful one (array of XML functions plays a role of
3228 * some kind of substitution for XQuery sequences).
3230 * Workaround here: we parse XML data in different way to allow XPath for
3231 * fragments (see "XPath for fragment" TODO comment inside).
3234 xpath(PG_FUNCTION_ARGS)
3237 text *xpath_expr_text = PG_GETARG_TEXT_P(0);
3238 xmltype *data = PG_GETARG_XML_P(1);
3239 ArrayType *namespaces = PG_GETARG_ARRAYTYPE_P(2);
3240 ArrayBuildState *astate = NULL;
3241 xmlParserCtxtPtr ctxt = NULL;
3242 xmlDocPtr doc = NULL;
3243 xmlXPathContextPtr xpathctx = NULL;
3244 xmlXPathCompExprPtr xpathcomp = NULL;
3245 xmlXPathObjectPtr xpathobj = NULL;
3250 xmlChar *xpath_expr;
3254 Datum *ns_names_uris;
3255 bool *ns_names_uris_nulls;
3259 * Namespace mappings are passed as text[]. If an empty array is
3260 * passed (ndim = 0, "0-dimensional"), then there are no namespace
3261 * mappings. Else, a 2-dimensional array with length of the
3262 * second axis being equal to 2 should be passed, i.e., every
3263 * subarray contains 2 elements, the first element defining the
3264 * name, the second one the URI. Example: ARRAY[ARRAY['myns',
3265 * 'http://example.com'], ARRAY['myns2', 'http://example2.com']].
3267 ndim = ARR_NDIM(namespaces);
3272 dims = ARR_DIMS(namespaces);
3274 if (ndim != 2 || dims[1] != 2)
3276 (errcode(ERRCODE_DATA_EXCEPTION),
3277 errmsg("invalid array for XML namespace mapping"),
3278 errdetail("The array must be two-dimensional with length of the second axis equal to 2.")));
3280 Assert(ARR_ELEMTYPE(namespaces) == TEXTOID);
3282 deconstruct_array(namespaces, TEXTOID, -1, false, 'i',
3283 &ns_names_uris, &ns_names_uris_nulls,
3286 Assert((ns_count % 2) == 0); /* checked above */
3287 ns_count /= 2; /* count pairs only */
3291 ns_names_uris = NULL;
3292 ns_names_uris_nulls = NULL;
3296 datastr = VARDATA(data);
3297 len = VARSIZE(data) - VARHDRSZ;
3298 xpath_len = VARSIZE(xpath_expr_text) - VARHDRSZ;
3301 (errcode(ERRCODE_DATA_EXCEPTION),
3302 errmsg("empty XPath expression")));
3305 * To handle both documents and fragments, regardless of the fact
3306 * whether the XML datum has a single root (XML well-formedness),
3307 * we wrap the XML datum in a dummy element (<x>...</x>) and
3308 * extend the XPath expression accordingly. To do it, throw away
3309 * the XML prolog, if any.
3312 xmlStrncmp((xmlChar *) datastr, (xmlChar *) "<?xml", 5) == 0)
3316 !(datastr[i - 1] == '?' && datastr[i] == '>'))
3320 xml_ereport(ERROR, ERRCODE_INTERNAL_ERROR,
3321 "could not parse XML data");
3324 string = xmlStrncatNew((xmlChar *) "<x>",
3325 (xmlChar *) datastr + i, len - i);
3328 string = xmlStrncatNew((xmlChar *) "<x>",
3329 (xmlChar *) datastr, len);
3331 string = xmlStrncat(string, (xmlChar *) "</x>", 5);
3333 xpath_expr = xmlStrncatNew((xmlChar *) "/x",
3334 (xmlChar *) VARDATA(xpath_expr_text), xpath_len);
3339 /* We use a PG_TRY block to ensure libxml parser is cleaned up on error */
3344 * redundant XML parsing (two parsings for the same value
3345 * during one command execution are possible)
3347 ctxt = xmlNewParserCtxt();
3349 xml_ereport(ERROR, ERRCODE_INTERNAL_ERROR,
3350 "could not allocate parser context");
3351 doc = xmlCtxtReadMemory(ctxt, (char *) string, len, NULL, NULL, 0);
3353 xml_ereport(ERROR, ERRCODE_INVALID_XML_DOCUMENT,
3354 "could not parse XML data");
3355 xpathctx = xmlXPathNewContext(doc);
3356 if (xpathctx == NULL)
3357 xml_ereport(ERROR, ERRCODE_INTERNAL_ERROR,
3358 "could not allocate XPath context");
3359 xpathctx->node = xmlDocGetRootElement(doc);
3360 if (xpathctx->node == NULL)
3361 xml_ereport(ERROR, ERRCODE_INTERNAL_ERROR,
3362 "could not find root XML element");
3364 /* register namespaces, if any */
3367 for (i = 0; i < ns_count; i++)
3372 if (ns_names_uris_nulls[i * 2] ||
3373 ns_names_uris_nulls[i * 2 + 1])
3375 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3376 errmsg("neither namespace name nor URI may be null")));
3377 ns_name = _textout(ns_names_uris[i * 2]);
3378 ns_uri = _textout(ns_names_uris[i * 2 + 1]);
3379 if (xmlXPathRegisterNs(xpathctx,
3380 (xmlChar *) ns_name,
3381 (xmlChar *) ns_uri) != 0)
3382 ereport(ERROR, /* is this an internal error??? */
3383 (errmsg("could not register XML namespace with name \"%s\" and URI \"%s\"",
3388 xpathcomp = xmlXPathCompile(xpath_expr);
3389 if (xpathcomp == NULL) /* TODO: show proper XPath error details */
3390 xml_ereport(ERROR, ERRCODE_INTERNAL_ERROR,
3391 "invalid XPath expression");
3393 xpathobj = xmlXPathCompiledEval(xpathcomp, xpathctx);
3394 if (xpathobj == NULL) /* TODO: reason? */
3396 (errmsg("could not create XPath object")));
3398 xmlXPathFreeCompExpr(xpathcomp);
3401 /* return empty array in cases when nothing is found */
3402 if (xpathobj->nodesetval == NULL)
3405 res_nitems = xpathobj->nodesetval->nodeNr;
3408 for (i = 0; i < xpathobj->nodesetval->nodeNr; i++)
3411 bool elemisnull = false;
3412 elem = PointerGetDatum(xml_xmlnodetoxmltype(xpathobj->nodesetval->nodeTab[i]));
3413 astate = accumArrayResult(astate, elem,
3415 CurrentMemoryContext);
3418 xmlXPathFreeObject(xpathobj);
3420 xmlXPathFreeContext(xpathctx);
3424 xmlFreeParserCtxt(ctxt);
3431 xmlXPathFreeCompExpr(xpathcomp);
3433 xmlXPathFreeObject(xpathobj);
3435 xmlXPathFreeContext(xpathctx);
3439 xmlFreeParserCtxt(ctxt);
3446 if (res_nitems == 0)
3447 PG_RETURN_ARRAYTYPE_P(construct_empty_array(XMLOID));
3449 PG_RETURN_ARRAYTYPE_P(makeArrayResult(astate, CurrentMemoryContext));