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.56 2007/11/10 19:29:54 tgl 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 /* Beware of multiple evaluations of argument! */
1002 #define PG_XMLISNAMECHAR(c) \
1003 (xmlIsBaseChar_ch(c) || xmlIsIdeographicQ(c) \
1004 || xmlIsDigit_ch(c) \
1005 || c == '.' || c == '-' || c == '_' || c == ':' \
1006 || xmlIsCombiningQ(c) \
1007 || xmlIsExtender_ch(c))
1010 parse_xml_decl(const xmlChar *str, size_t *lenp,
1011 xmlChar **version, xmlChar **encoding, int *standalone)
1014 const xmlChar *save_p;
1030 if (xmlStrncmp(p, (xmlChar *)"<?xml", 5) != 0)
1033 /* if next char is name char, it's a PI like <?xml-stylesheet ...?> */
1034 utf8len = strlen((const char *) (p+5));
1035 utf8char = xmlGetUTF8Char(p+5, &utf8len);
1036 if (PG_XMLISNAMECHAR(utf8char))
1044 if (xmlStrncmp(p, (xmlChar *)"version", 7) != 0)
1045 return XML_ERR_VERSION_MISSING;
1049 return XML_ERR_VERSION_MISSING;
1053 if (*p == '\'' || *p == '"')
1057 q = xmlStrchr(p + 1, *p);
1059 return XML_ERR_VERSION_MISSING;
1062 *version = xmlStrndup(p + 1, q - p - 1);
1066 return XML_ERR_VERSION_MISSING;
1071 if (xmlStrncmp(p, (xmlChar *)"encoding", 8) == 0)
1073 CHECK_XML_SPACE(save_p);
1077 return XML_ERR_MISSING_ENCODING;
1081 if (*p == '\'' || *p == '"')
1085 q = xmlStrchr(p + 1, *p);
1087 return XML_ERR_MISSING_ENCODING;
1090 *encoding = xmlStrndup(p + 1, q - p - 1);
1094 return XML_ERR_MISSING_ENCODING;
1104 if (xmlStrncmp(p, (xmlChar *)"standalone", 10) == 0)
1106 CHECK_XML_SPACE(save_p);
1110 return XML_ERR_STANDALONE_VALUE;
1113 if (xmlStrncmp(p, (xmlChar *)"'yes'", 5) == 0 || xmlStrncmp(p, (xmlChar *)"\"yes\"", 5) == 0)
1118 else if (xmlStrncmp(p, (xmlChar *)"'no'", 4) == 0 || xmlStrncmp(p, (xmlChar *)"\"no\"", 4) == 0)
1124 return XML_ERR_STANDALONE_VALUE;
1132 if (xmlStrncmp(p, (xmlChar *)"?>", 2) != 0)
1133 return XML_ERR_XMLDECL_NOT_FINISHED;
1139 for (p = str; p < str + len; p++)
1141 return XML_ERR_INVALID_CHAR;
1151 * Write an XML declaration. On output, we adjust the XML declaration
1152 * as follows. (These rules are the moral equivalent of the clause
1153 * "Serialization of an XML value" in the SQL standard.)
1155 * We try to avoid generating an XML declaration if possible. This is
1156 * so that you don't get trivial things like xml '<foo/>' resulting in
1157 * '<?xml version="1.0"?><foo/>', which would surely be annoying. We
1158 * must provide a declaration if the standalone property is specified
1159 * or if we include an encoding declaration. If we have a
1160 * declaration, we must specify a version (XML requires this).
1161 * Otherwise we only make a declaration if the version is not "1.0",
1162 * which is the default version specified in SQL:2003.
1165 print_xml_decl(StringInfo buf, const xmlChar *version,
1166 pg_enc encoding, int standalone)
1170 if ((version && strcmp((char *) version, PG_XML_DEFAULT_VERSION) != 0)
1171 || (encoding && encoding != PG_UTF8)
1172 || standalone != -1)
1174 appendStringInfoString(buf, "<?xml");
1177 appendStringInfo(buf, " version=\"%s\"", version);
1179 appendStringInfo(buf, " version=\"%s\"", PG_XML_DEFAULT_VERSION);
1181 if (encoding && encoding != PG_UTF8)
1184 * XXX might be useful to convert this to IANA names
1185 * (ISO-8859-1 instead of LATIN1 etc.); needs field experience
1187 appendStringInfo(buf, " encoding=\"%s\"",
1188 pg_encoding_to_char(encoding));
1191 if (standalone == 1)
1192 appendStringInfoString(buf, " standalone=\"yes\"");
1193 else if (standalone == 0)
1194 appendStringInfoString(buf, " standalone=\"no\"");
1195 appendStringInfoString(buf, "?>");
1205 * Convert a C string to XML internal representation
1207 * TODO maybe, libxml2's xmlreader is better? (do not construct DOM,
1208 * yet do not use SAX - see xml_reader.c)
1211 xml_parse(text *data, XmlOptionType xmloption_arg, bool preserve_whitespace,
1216 xmlChar *utf8string;
1217 xmlParserCtxtPtr ctxt = NULL;
1218 xmlDocPtr doc = NULL;
1220 len = VARSIZE(data) - VARHDRSZ; /* will be useful later */
1221 string = xml_text2xmlChar(data);
1223 utf8string = pg_do_encoding_conversion(string,
1226 xmlChar_to_encoding(encoding) :
1227 GetDatabaseEncoding(),
1232 /* We use a PG_TRY block to ensure libxml parser is cleaned up on error */
1236 ctxt = xmlNewParserCtxt();
1238 xml_ereport(ERROR, ERRCODE_INTERNAL_ERROR,
1239 "could not allocate parser context");
1241 if (xmloption_arg == XMLOPTION_DOCUMENT)
1244 * Note, that here we try to apply DTD defaults
1245 * (XML_PARSE_DTDATTR) according to SQL/XML:10.16.7.d:
1246 * 'Default valies defined by internal DTD are applied'.
1247 * As for external DTDs, we try to support them too, (see
1248 * SQL/XML:10.16.7.e)
1250 doc = xmlCtxtReadDoc(ctxt, utf8string,
1253 XML_PARSE_NOENT | XML_PARSE_DTDATTR
1254 | (preserve_whitespace ? 0 : XML_PARSE_NOBLANKS));
1256 xml_ereport(ERROR, ERRCODE_INVALID_XML_DOCUMENT,
1257 "invalid XML document");
1263 xmlChar *version = NULL;
1264 int standalone = -1;
1266 doc = xmlNewDoc(NULL);
1268 res_code = parse_xml_decl(utf8string, &count, &version, NULL, &standalone);
1270 xml_ereport_by_code(ERROR, ERRCODE_INVALID_XML_CONTENT,
1271 "invalid XML content: invalid XML declaration", res_code);
1273 res_code = xmlParseBalancedChunkMemory(doc, NULL, NULL, 0, utf8string + count, NULL);
1275 xml_ereport(ERROR, ERRCODE_INVALID_XML_CONTENT,
1276 "invalid XML content");
1278 doc->version = xmlStrdup(version);
1279 doc->encoding = xmlStrdup((xmlChar *) "UTF-8");
1280 doc->standalone = standalone;
1284 xmlFreeParserCtxt(ctxt);
1293 xmlFreeParserCtxt(ctxt);
1305 * xmlChar<->text convertions
1308 xml_text2xmlChar(text *in)
1310 int32 len = VARSIZE(in) - VARHDRSZ;
1313 res = palloc(len + 1);
1314 memcpy(res, VARDATA(in), len);
1322 * Wrappers for memory management functions
1325 xml_palloc(size_t size)
1327 return palloc(size);
1332 xml_repalloc(void *ptr, size_t size)
1334 return repalloc(ptr, size);
1339 xml_pfree(void *ptr)
1346 xml_pstrdup(const char *string)
1348 return pstrdup(string);
1353 * Wrapper for "ereport" function for XML-related errors. The "msg"
1354 * is the SQL-level message; some can be adopted from the SQL/XML
1355 * standard. This function adds libxml's native error messages, if
1359 xml_ereport(int level, int sqlcode, const char *msg)
1363 if (xml_err_buf->len > 0)
1365 detail = pstrdup(xml_err_buf->data);
1366 resetStringInfo(xml_err_buf);
1371 /* libxml error messages end in '\n'; get rid of it */
1376 len = strlen(detail);
1377 if (len > 0 && detail[len-1] == '\n')
1378 detail[len-1] = '\0';
1383 errdetail("%s", detail)));
1389 errmsg("%s", msg)));
1395 * Error handler for libxml error messages
1398 xml_errorHandler(void *ctxt, const char *msg,...)
1400 /* Append the formatted text to xml_err_buf */
1406 /* Try to format the data. */
1407 va_start(args, msg);
1408 success = appendStringInfoVA(xml_err_buf, msg, args);
1414 /* Double the buffer size and try again. */
1415 enlargeStringInfo(xml_err_buf, xml_err_buf->maxlen);
1421 * Wrapper for "ereport" function for XML-related errors. The "msg"
1422 * is the SQL-level message; some can be adopted from the SQL/XML
1423 * standard. This function uses "code" to create a textual detail
1424 * message. At the moment, we only need to cover those codes that we
1425 * may raise in this file.
1428 xml_ereport_by_code(int level, int sqlcode,
1429 const char *msg, int code)
1435 case XML_ERR_INVALID_CHAR:
1436 det = "Invalid character value";
1438 case XML_ERR_SPACE_REQUIRED:
1439 det = "Space required";
1441 case XML_ERR_STANDALONE_VALUE:
1442 det = "standalone accepts only 'yes' or 'no'";
1444 case XML_ERR_VERSION_MISSING:
1445 det = "Malformed declaration expecting version";
1447 case XML_ERR_MISSING_ENCODING:
1448 det = "Missing encoding in text declaration";
1450 case XML_ERR_XMLDECL_NOT_FINISHED:
1451 det = "Parsing XML declaration: '?>' expected";
1454 det = "Unrecognized libxml error code: %d";
1461 errdetail(det, code)));
1466 * Convert one char in the current server encoding to a Unicode codepoint.
1469 sqlchar_to_unicode(char *s)
1472 pg_wchar ret[2]; /* need space for trailing zero */
1474 utf8string = (char *) pg_do_encoding_conversion((unsigned char *) s,
1476 GetDatabaseEncoding(),
1479 pg_encoding_mb2wchar_with_len(PG_UTF8, utf8string, ret, pg_mblen(s));
1486 is_valid_xml_namefirst(pg_wchar c)
1488 /* (Letter | '_' | ':') */
1489 return (xmlIsBaseCharQ(c) || xmlIsIdeographicQ(c)
1490 || c == '_' || c == ':');
1495 is_valid_xml_namechar(pg_wchar c)
1497 /* Letter | Digit | '.' | '-' | '_' | ':' | CombiningChar | Extender */
1498 return (xmlIsBaseCharQ(c) || xmlIsIdeographicQ(c)
1500 || c == '.' || c == '-' || c == '_' || c == ':'
1501 || xmlIsCombiningQ(c)
1502 || xmlIsExtenderQ(c));
1504 #endif /* USE_LIBXML */
1508 * Map SQL identifier to XML name; see SQL/XML:2003 section 9.1.
1511 map_sql_identifier_to_xml_name(char *ident, bool fully_escaped,
1519 * SQL/XML doesn't make use of this case anywhere, so it's
1520 * probably a mistake.
1522 Assert(fully_escaped || !escape_period);
1524 initStringInfo(&buf);
1526 for (p = ident; *p; p += pg_mblen(p))
1528 if (*p == ':' && (p == ident || fully_escaped))
1529 appendStringInfo(&buf, "_x003A_");
1530 else if (*p == '_' && *(p+1) == 'x')
1531 appendStringInfo(&buf, "_x005F_");
1532 else if (fully_escaped && p == ident &&
1533 pg_strncasecmp(p, "xml", 3) == 0)
1536 appendStringInfo(&buf, "_x0078_");
1538 appendStringInfo(&buf, "_x0058_");
1540 else if (escape_period && *p == '.')
1541 appendStringInfo(&buf, "_x002E_");
1544 pg_wchar u = sqlchar_to_unicode(p);
1547 ? !is_valid_xml_namefirst(u)
1548 : !is_valid_xml_namechar(u))
1549 appendStringInfo(&buf, "_x%04X_", (unsigned int) u);
1551 appendBinaryStringInfo(&buf, p, pg_mblen(p));
1556 #else /* not USE_LIBXML */
1559 #endif /* not USE_LIBXML */
1564 * Map a Unicode codepoint into the current server encoding.
1567 unicode_to_sqlchar(pg_wchar c)
1569 static unsigned char utf8string[5]; /* need trailing zero */
1575 else if (c <= 0x7FF)
1577 utf8string[0] = 0xC0 | ((c >> 6) & 0x1F);
1578 utf8string[1] = 0x80 | (c & 0x3F);
1580 else if (c <= 0xFFFF)
1582 utf8string[0] = 0xE0 | ((c >> 12) & 0x0F);
1583 utf8string[1] = 0x80 | ((c >> 6) & 0x3F);
1584 utf8string[2] = 0x80 | (c & 0x3F);
1588 utf8string[0] = 0xF0 | ((c >> 18) & 0x07);
1589 utf8string[1] = 0x80 | ((c >> 12) & 0x3F);
1590 utf8string[2] = 0x80 | ((c >> 6) & 0x3F);
1591 utf8string[3] = 0x80 | (c & 0x3F);
1594 return (char *) pg_do_encoding_conversion(utf8string,
1595 pg_mblen((char *) utf8string),
1597 GetDatabaseEncoding());
1602 * Map XML name to SQL identifier; see SQL/XML:2003 section 9.17.
1605 map_xml_name_to_sql_identifier(char *name)
1610 initStringInfo(&buf);
1612 for (p = name; *p; p += pg_mblen(p))
1614 if (*p == '_' && *(p+1) == 'x'
1615 && isxdigit((unsigned char) *(p+2))
1616 && isxdigit((unsigned char) *(p+3))
1617 && isxdigit((unsigned char) *(p+4))
1618 && isxdigit((unsigned char) *(p+5))
1623 sscanf(p + 2, "%X", &u);
1624 appendStringInfoString(&buf, unicode_to_sqlchar(u));
1628 appendBinaryStringInfo(&buf, p, pg_mblen(p));
1635 * Map SQL value to XML value; see SQL/XML:2003 section 9.16.
1638 map_sql_value_to_xml_value(Datum value, Oid type)
1642 initStringInfo(&buf);
1644 if (type_is_array(type))
1656 array = DatumGetArrayTypeP(value);
1657 elmtype = ARR_ELEMTYPE(array);
1658 get_typlenbyvalalign(elmtype, &elmlen, &elmbyval, &elmalign);
1660 deconstruct_array(array, elmtype,
1661 elmlen, elmbyval, elmalign,
1662 &elem_values, &elem_nulls,
1665 for (i = 0; i < num_elems; i++)
1669 appendStringInfoString(&buf, "<element>");
1670 appendStringInfoString(&buf,
1671 map_sql_value_to_xml_value(elem_values[i],
1673 appendStringInfoString(&buf, "</element>");
1686 * Special XSD formatting for some data types
1691 if (DatumGetBool(value))
1700 char buf[MAXDATELEN + 1];
1702 date = DatumGetDateADT(value);
1703 j2date(date + POSTGRES_EPOCH_JDATE,
1704 &(tm.tm_year), &(tm.tm_mon), &(tm.tm_mday));
1705 EncodeDateOnly(&tm, USE_XSD_DATES, buf);
1707 return pstrdup(buf);
1712 Timestamp timestamp;
1716 char buf[MAXDATELEN + 1];
1718 timestamp = DatumGetTimestamp(value);
1720 /* XSD doesn't support infinite values */
1721 if (TIMESTAMP_NOT_FINITE(timestamp))
1723 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
1724 errmsg("timestamp out of range")));
1725 else if (timestamp2tm(timestamp, NULL, &tm, &fsec, NULL, NULL) == 0)
1726 EncodeDateTime(&tm, fsec, NULL, &tzn, USE_XSD_DATES, buf);
1729 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
1730 errmsg("timestamp out of range")));
1732 return pstrdup(buf);
1735 case TIMESTAMPTZOID:
1737 TimestampTz timestamp;
1742 char buf[MAXDATELEN + 1];
1744 timestamp = DatumGetTimestamp(value);
1746 /* XSD doesn't support infinite values */
1747 if (TIMESTAMP_NOT_FINITE(timestamp))
1749 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
1750 errmsg("timestamp out of range")));
1751 else if (timestamp2tm(timestamp, &tz, &tm, &fsec, &tzn, NULL) == 0)
1752 EncodeDateTime(&tm, fsec, &tz, &tzn, USE_XSD_DATES, buf);
1755 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
1756 errmsg("timestamp out of range")));
1758 return pstrdup(buf);
1762 getTypeOutputInfo(type, &typeOut, &isvarlena);
1763 str = OidOutputFunctionCall(typeOut, value);
1769 if (type == BYTEAOID)
1772 xmlTextWriterPtr writer;
1777 buf = xmlBufferCreate();
1778 writer = xmlNewTextWriterMemory(buf, 0);
1780 if (xmlbinary == XMLBINARY_BASE64)
1781 xmlTextWriterWriteBase64(writer, VARDATA(value), 0, VARSIZE(value) - VARHDRSZ);
1783 xmlTextWriterWriteBinHex(writer, VARDATA(value), 0, VARSIZE(value) - VARHDRSZ);
1785 xmlFreeTextWriter(writer);
1786 result = pstrdup((const char *) xmlBufferContent(buf));
1790 #endif /* USE_LIBXML */
1792 for (p = str; *p; p += pg_mblen(p))
1797 appendStringInfo(&buf, "&");
1800 appendStringInfo(&buf, "<");
1803 appendStringInfo(&buf, ">");
1806 appendStringInfo(&buf, "
");
1809 appendBinaryStringInfo(&buf, p, pg_mblen(p));
1820 _SPI_strdup(const char *s)
1822 char *ret = SPI_palloc(strlen(s) + 1);
1829 * SQL to XML mapping functions
1831 * What follows below is intentionally organized so that you can read
1832 * along in the SQL/XML:2003 standard. The functions are mostly split
1833 * up and ordered they way the clauses lay out in the standards
1834 * document, and the identifiers are also aligned with the standard
1835 * text. (SQL/XML:2006 appears to be ordered differently,
1838 * There are many things going on there:
1840 * There are two kinds of mappings: Mapping SQL data (table contents)
1841 * to XML documents, and mapping SQL structure (the "schema") to XML
1842 * Schema. And there are functions that do both at the same time.
1844 * Then you can map a database, a schema, or a table, each in both
1845 * ways. This breaks down recursively: Mapping a database invokes
1846 * mapping schemas, which invokes mapping tables, which invokes
1847 * mapping rows, which invokes mapping columns, although you can't
1848 * call the last two from the outside. Because of this, there are a
1849 * number of xyz_internal() functions which are to be called both from
1850 * the function manager wrapper and from some upper layer in a
1853 * See the documentation about what the common function arguments
1854 * nulls, tableforest, and targetns mean.
1856 * Some style guidelines for XML output: Use double quotes for quoting
1857 * XML attributes. Indent XML elements by two spaces, but remember
1858 * that a lot of code is called recursively at different levels, so
1859 * it's better not to indent rather than create output that indents
1860 * and outdents weirdly. Add newlines to make the output look nice.
1865 * Visibility of objects for XML mappings; see SQL/XML:2003 section
1870 * Given a query, which must return type oid as first column, produce
1871 * a list of Oids with the query results.
1874 query_to_oid_list(const char *query)
1879 SPI_execute(query, true, 0);
1881 for (i = 0; i < SPI_processed; i++)
1886 oid = SPI_getbinval(SPI_tuptable->vals[i],
1887 SPI_tuptable->tupdesc,
1891 list = lappend_oid(list, DatumGetObjectId(oid));
1899 schema_get_xml_visible_tables(Oid nspid)
1901 StringInfoData query;
1903 initStringInfo(&query);
1904 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);
1906 return query_to_oid_list(query.data);
1911 * Including the system schemas is probably not useful for a database
1914 #define XML_VISIBLE_SCHEMAS_EXCLUDE "(nspname ~ '^pg_' OR nspname = 'information_schema')"
1916 #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
1920 database_get_xml_visible_schemas(void)
1922 return query_to_oid_list(XML_VISIBLE_SCHEMAS " ORDER BY nspname;");
1927 database_get_xml_visible_tables(void)
1929 /* At the moment there is no order required here. */
1930 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 ");");
1935 * Map SQL table to XML and/or XML Schema document; see SQL/XML:2003
1940 table_to_xml_internal(Oid relid,
1941 const char *xmlschema, bool nulls, bool tableforest,
1942 const char *targetns, bool top_level)
1944 StringInfoData query;
1946 initStringInfo(&query);
1947 appendStringInfo(&query, "SELECT * FROM %s",
1948 DatumGetCString(DirectFunctionCall1(regclassout,
1949 ObjectIdGetDatum(relid))));
1950 return query_to_xml_internal(query.data, get_rel_name(relid),
1951 xmlschema, nulls, tableforest,
1952 targetns, top_level);
1957 table_to_xml(PG_FUNCTION_ARGS)
1959 Oid relid = PG_GETARG_OID(0);
1960 bool nulls = PG_GETARG_BOOL(1);
1961 bool tableforest = PG_GETARG_BOOL(2);
1962 const char *targetns = _textout(PG_GETARG_TEXT_P(3));
1964 PG_RETURN_XML_P(stringinfo_to_xmltype(table_to_xml_internal(relid, NULL,
1971 query_to_xml(PG_FUNCTION_ARGS)
1973 char *query = _textout(PG_GETARG_TEXT_P(0));
1974 bool nulls = PG_GETARG_BOOL(1);
1975 bool tableforest = PG_GETARG_BOOL(2);
1976 const char *targetns = _textout(PG_GETARG_TEXT_P(3));
1978 PG_RETURN_XML_P(stringinfo_to_xmltype(query_to_xml_internal(query, NULL,
1979 NULL, nulls, tableforest,
1985 cursor_to_xml(PG_FUNCTION_ARGS)
1987 char *name = _textout(PG_GETARG_TEXT_P(0));
1988 int32 count = PG_GETARG_INT32(1);
1989 bool nulls = PG_GETARG_BOOL(2);
1990 bool tableforest = PG_GETARG_BOOL(3);
1991 const char *targetns = _textout(PG_GETARG_TEXT_P(4));
1993 StringInfoData result;
1997 initStringInfo(&result);
2000 portal = SPI_cursor_find(name);
2003 (errcode(ERRCODE_UNDEFINED_CURSOR),
2004 errmsg("cursor \"%s\" does not exist", name)));
2006 SPI_cursor_fetch(portal, true, count);
2007 for (i = 0; i < SPI_processed; i++)
2008 SPI_sql_row_to_xmlelement(i, &result, NULL, nulls,
2009 tableforest, targetns, true);
2013 PG_RETURN_XML_P(stringinfo_to_xmltype(&result));
2018 * Write the start tag of the root element of a data mapping.
2020 * top_level means that this is the very top level of the eventual
2021 * output. For example, when the user calls table_to_xml, then a call
2022 * with a table name to this function is the top level. When the user
2023 * calls database_to_xml, then a call with a schema name to this
2024 * function is not the top level. If top_level is false, then the XML
2025 * namespace declarations are omitted, because they supposedly already
2026 * appeared earlier in the output. Repeating them is not wrong, but
2030 xmldata_root_element_start(StringInfo result, const char *eltname,
2031 const char *xmlschema, const char *targetns,
2034 /* This isn't really wrong but currently makes no sense. */
2035 Assert(top_level || !xmlschema);
2037 appendStringInfo(result, "<%s", eltname);
2040 appendStringInfoString(result, " xmlns:xsi=\"" NAMESPACE_XSI "\"");
2041 if (strlen(targetns) > 0)
2042 appendStringInfo(result, " xmlns=\"%s\"", targetns);
2046 /* FIXME: better targets */
2047 if (strlen(targetns) > 0)
2048 appendStringInfo(result, " xsi:schemaLocation=\"%s #\"", targetns);
2050 appendStringInfo(result, " xsi:noNamespaceSchemaLocation=\"#\"");
2052 appendStringInfo(result, ">\n\n");
2057 xmldata_root_element_end(StringInfo result, const char *eltname)
2059 appendStringInfo(result, "</%s>\n", eltname);
2064 query_to_xml_internal(const char *query, char *tablename,
2065 const char *xmlschema, bool nulls, bool tableforest,
2066 const char *targetns, bool top_level)
2073 xmltn = map_sql_identifier_to_xml_name(tablename, true, false);
2077 result = makeStringInfo();
2080 if (SPI_execute(query, true, 0) != SPI_OK_SELECT)
2082 (errcode(ERRCODE_DATA_EXCEPTION),
2083 errmsg("invalid query")));
2086 xmldata_root_element_start(result, xmltn, xmlschema,
2087 targetns, top_level);
2090 appendStringInfo(result, "%s\n\n", xmlschema);
2092 for(i = 0; i < SPI_processed; i++)
2093 SPI_sql_row_to_xmlelement(i, result, tablename, nulls,
2094 tableforest, targetns, top_level);
2097 xmldata_root_element_end(result, xmltn);
2106 table_to_xmlschema(PG_FUNCTION_ARGS)
2108 Oid relid = PG_GETARG_OID(0);
2109 bool nulls = PG_GETARG_BOOL(1);
2110 bool tableforest = PG_GETARG_BOOL(2);
2111 const char *targetns = _textout(PG_GETARG_TEXT_P(3));
2115 rel = heap_open(relid, AccessShareLock);
2116 result = map_sql_table_to_xmlschema(rel->rd_att, relid, nulls,
2117 tableforest, targetns);
2118 heap_close(rel, NoLock);
2120 PG_RETURN_XML_P(cstring_to_xmltype(result));
2125 query_to_xmlschema(PG_FUNCTION_ARGS)
2127 char *query = _textout(PG_GETARG_TEXT_P(0));
2128 bool nulls = PG_GETARG_BOOL(1);
2129 bool tableforest = PG_GETARG_BOOL(2);
2130 const char *targetns = _textout(PG_GETARG_TEXT_P(3));
2136 plan = SPI_prepare(query, 0, NULL);
2137 portal = SPI_cursor_open(NULL, plan, NULL, NULL, true);
2138 result = _SPI_strdup(map_sql_table_to_xmlschema(portal->tupDesc,
2140 tableforest, targetns));
2141 SPI_cursor_close(portal);
2144 PG_RETURN_XML_P(cstring_to_xmltype(result));
2149 cursor_to_xmlschema(PG_FUNCTION_ARGS)
2151 char *name = _textout(PG_GETARG_TEXT_P(0));
2152 bool nulls = PG_GETARG_BOOL(1);
2153 bool tableforest = PG_GETARG_BOOL(2);
2154 const char *targetns = _textout(PG_GETARG_TEXT_P(3));
2155 const char *xmlschema;
2159 portal = SPI_cursor_find(name);
2162 (errcode(ERRCODE_UNDEFINED_CURSOR),
2163 errmsg("cursor \"%s\" does not exist", name)));
2165 xmlschema = _SPI_strdup(map_sql_table_to_xmlschema(portal->tupDesc,
2167 tableforest, targetns));
2170 PG_RETURN_XML_P(cstring_to_xmltype(xmlschema));
2175 table_to_xml_and_xmlschema(PG_FUNCTION_ARGS)
2177 Oid relid = PG_GETARG_OID(0);
2178 bool nulls = PG_GETARG_BOOL(1);
2179 bool tableforest = PG_GETARG_BOOL(2);
2180 const char *targetns = _textout(PG_GETARG_TEXT_P(3));
2182 const char *xmlschema;
2184 rel = heap_open(relid, AccessShareLock);
2185 xmlschema = map_sql_table_to_xmlschema(rel->rd_att, relid, nulls,
2186 tableforest, targetns);
2187 heap_close(rel, NoLock);
2189 PG_RETURN_XML_P(stringinfo_to_xmltype(table_to_xml_internal(relid,
2190 xmlschema, nulls, tableforest,
2196 query_to_xml_and_xmlschema(PG_FUNCTION_ARGS)
2198 char *query = _textout(PG_GETARG_TEXT_P(0));
2199 bool nulls = PG_GETARG_BOOL(1);
2200 bool tableforest = PG_GETARG_BOOL(2);
2201 const char *targetns = _textout(PG_GETARG_TEXT_P(3));
2203 const char *xmlschema;
2208 plan = SPI_prepare(query, 0, NULL);
2209 portal = SPI_cursor_open(NULL, plan, NULL, NULL, true);
2210 xmlschema = _SPI_strdup(map_sql_table_to_xmlschema(portal->tupDesc,
2211 InvalidOid, nulls, tableforest, targetns));
2212 SPI_cursor_close(portal);
2215 PG_RETURN_XML_P(stringinfo_to_xmltype(query_to_xml_internal(query, NULL,
2216 xmlschema, nulls, tableforest,
2222 * Map SQL schema to XML and/or XML Schema document; see SQL/XML:2003
2227 schema_to_xml_internal(Oid nspid, const char *xmlschema, bool nulls,
2228 bool tableforest, const char *targetns, bool top_level)
2235 xmlsn = map_sql_identifier_to_xml_name(get_namespace_name(nspid),
2237 result = makeStringInfo();
2239 xmldata_root_element_start(result, xmlsn, xmlschema, targetns, top_level);
2242 appendStringInfo(result, "%s\n\n", xmlschema);
2246 relid_list = schema_get_xml_visible_tables(nspid);
2250 foreach(cell, relid_list)
2252 Oid relid = lfirst_oid(cell);
2255 subres = table_to_xml_internal(relid, NULL, nulls, tableforest,
2258 appendStringInfoString(result, subres->data);
2259 appendStringInfoChar(result, '\n');
2265 xmldata_root_element_end(result, xmlsn);
2272 schema_to_xml(PG_FUNCTION_ARGS)
2274 Name name = PG_GETARG_NAME(0);
2275 bool nulls = PG_GETARG_BOOL(1);
2276 bool tableforest = PG_GETARG_BOOL(2);
2277 const char *targetns = _textout(PG_GETARG_TEXT_P(3));
2282 schemaname = NameStr(*name);
2283 nspid = LookupExplicitNamespace(schemaname);
2285 PG_RETURN_XML_P(stringinfo_to_xmltype(schema_to_xml_internal(nspid, NULL,
2286 nulls, tableforest, targetns, true)));
2291 * Write the start element of the root element of an XML Schema mapping.
2294 xsd_schema_element_start(StringInfo result, const char *targetns)
2296 appendStringInfoString(result,
2298 " xmlns:xsd=\"" NAMESPACE_XSD "\"");
2299 if (strlen(targetns) > 0)
2300 appendStringInfo(result,
2302 " targetNamespace=\"%s\"\n"
2303 " elementFormDefault=\"qualified\"",
2305 appendStringInfoString(result,
2311 xsd_schema_element_end(StringInfo result)
2313 appendStringInfoString(result, "</xsd:schema>");
2318 schema_to_xmlschema_internal(const char *schemaname, bool nulls,
2319 bool tableforest, const char *targetns)
2327 result = makeStringInfo();
2329 nspid = LookupExplicitNamespace(schemaname);
2331 xsd_schema_element_start(result, targetns);
2335 relid_list = schema_get_xml_visible_tables(nspid);
2338 foreach (cell, relid_list)
2342 rel = heap_open(lfirst_oid(cell), AccessShareLock);
2343 tupdesc_list = lappend(tupdesc_list, CreateTupleDescCopy(rel->rd_att));
2344 heap_close(rel, NoLock);
2347 appendStringInfoString(result,
2348 map_sql_typecoll_to_xmlschema_types(tupdesc_list));
2350 appendStringInfoString(result,
2351 map_sql_schema_to_xmlschema_types(nspid, relid_list,
2352 nulls, tableforest, targetns));
2354 xsd_schema_element_end(result);
2363 schema_to_xmlschema(PG_FUNCTION_ARGS)
2365 Name name = PG_GETARG_NAME(0);
2366 bool nulls = PG_GETARG_BOOL(1);
2367 bool tableforest = PG_GETARG_BOOL(2);
2368 const char *targetns = _textout(PG_GETARG_TEXT_P(3));
2370 PG_RETURN_XML_P(stringinfo_to_xmltype(schema_to_xmlschema_internal(NameStr(*name),
2371 nulls, tableforest, targetns)));
2376 schema_to_xml_and_xmlschema(PG_FUNCTION_ARGS)
2378 Name name = PG_GETARG_NAME(0);
2379 bool nulls = PG_GETARG_BOOL(1);
2380 bool tableforest = PG_GETARG_BOOL(2);
2381 const char *targetns = _textout(PG_GETARG_TEXT_P(3));
2384 StringInfo xmlschema;
2386 schemaname = NameStr(*name);
2387 nspid = LookupExplicitNamespace(schemaname);
2389 xmlschema = schema_to_xmlschema_internal(schemaname, nulls,
2390 tableforest, targetns);
2392 PG_RETURN_XML_P(stringinfo_to_xmltype(schema_to_xml_internal(nspid,
2393 xmlschema->data, nulls,
2394 tableforest, targetns, true)));
2399 * Map SQL database to XML and/or XML Schema document; see SQL/XML:2003
2404 database_to_xml_internal(const char *xmlschema, bool nulls,
2405 bool tableforest, const char *targetns)
2412 xmlcn = map_sql_identifier_to_xml_name(get_database_name(MyDatabaseId),
2414 result = makeStringInfo();
2416 xmldata_root_element_start(result, xmlcn, xmlschema, targetns, true);
2419 appendStringInfo(result, "%s\n\n", xmlschema);
2423 nspid_list = database_get_xml_visible_schemas();
2427 foreach(cell, nspid_list)
2429 Oid nspid = lfirst_oid(cell);
2432 subres = schema_to_xml_internal(nspid, NULL, nulls,
2433 tableforest, targetns, false);
2435 appendStringInfoString(result, subres->data);
2436 appendStringInfoChar(result, '\n');
2442 xmldata_root_element_end(result, xmlcn);
2449 database_to_xml(PG_FUNCTION_ARGS)
2451 bool nulls = PG_GETARG_BOOL(0);
2452 bool tableforest = PG_GETARG_BOOL(1);
2453 const char *targetns = _textout(PG_GETARG_TEXT_P(2));
2455 PG_RETURN_XML_P(stringinfo_to_xmltype(database_to_xml_internal(NULL, nulls,
2456 tableforest, targetns)));
2461 database_to_xmlschema_internal(bool nulls, bool tableforest,
2462 const char *targetns)
2470 result = makeStringInfo();
2472 xsd_schema_element_start(result, targetns);
2476 relid_list = database_get_xml_visible_tables();
2477 nspid_list = database_get_xml_visible_schemas();
2480 foreach (cell, relid_list)
2484 rel = heap_open(lfirst_oid(cell), AccessShareLock);
2485 tupdesc_list = lappend(tupdesc_list, CreateTupleDescCopy(rel->rd_att));
2486 heap_close(rel, NoLock);
2489 appendStringInfoString(result,
2490 map_sql_typecoll_to_xmlschema_types(tupdesc_list));
2492 appendStringInfoString(result,
2493 map_sql_catalog_to_xmlschema_types(nspid_list, nulls, tableforest, targetns));
2495 xsd_schema_element_end(result);
2504 database_to_xmlschema(PG_FUNCTION_ARGS)
2506 bool nulls = PG_GETARG_BOOL(0);
2507 bool tableforest = PG_GETARG_BOOL(1);
2508 const char *targetns = _textout(PG_GETARG_TEXT_P(2));
2510 PG_RETURN_XML_P(stringinfo_to_xmltype(database_to_xmlschema_internal(nulls,
2511 tableforest, targetns)));
2516 database_to_xml_and_xmlschema(PG_FUNCTION_ARGS)
2518 bool nulls = PG_GETARG_BOOL(0);
2519 bool tableforest = PG_GETARG_BOOL(1);
2520 const char *targetns = _textout(PG_GETARG_TEXT_P(2));
2521 StringInfo xmlschema;
2523 xmlschema = database_to_xmlschema_internal(nulls, tableforest, targetns);
2525 PG_RETURN_XML_P(stringinfo_to_xmltype(database_to_xml_internal(xmlschema->data,
2526 nulls, tableforest, targetns)));
2531 * Map a multi-part SQL name to an XML name; see SQL/XML:2003 section
2535 map_multipart_sql_identifier_to_xml_name(char *a, char *b, char *c, char *d)
2537 StringInfoData result;
2539 initStringInfo(&result);
2542 appendStringInfo(&result, "%s",
2543 map_sql_identifier_to_xml_name(a, true, true));
2545 appendStringInfo(&result, ".%s",
2546 map_sql_identifier_to_xml_name(b, true, true));
2548 appendStringInfo(&result, ".%s",
2549 map_sql_identifier_to_xml_name(c, true, true));
2551 appendStringInfo(&result, ".%s",
2552 map_sql_identifier_to_xml_name(d, true, true));
2559 * Map an SQL table to an XML Schema document; see SQL/XML:2003
2562 * Map an SQL table to XML Schema data types; see SQL/XML:2003 section
2566 map_sql_table_to_xmlschema(TupleDesc tupdesc, Oid relid, bool nulls,
2567 bool tableforest, const char *targetns)
2571 char *tabletypename;
2573 StringInfoData result;
2575 initStringInfo(&result);
2577 if (OidIsValid(relid))
2580 Form_pg_class reltuple;
2582 tuple = SearchSysCache(RELOID,
2583 ObjectIdGetDatum(relid),
2585 if (!HeapTupleIsValid(tuple))
2586 elog(ERROR, "cache lookup failed for relation %u", relid);
2587 reltuple = (Form_pg_class) GETSTRUCT(tuple);
2589 xmltn = map_sql_identifier_to_xml_name(NameStr(reltuple->relname),
2592 tabletypename = map_multipart_sql_identifier_to_xml_name("TableType",
2593 get_database_name(MyDatabaseId),
2594 get_namespace_name(reltuple->relnamespace),
2595 NameStr(reltuple->relname));
2597 rowtypename = map_multipart_sql_identifier_to_xml_name("RowType",
2598 get_database_name(MyDatabaseId),
2599 get_namespace_name(reltuple->relnamespace),
2600 NameStr(reltuple->relname));
2602 ReleaseSysCache(tuple);
2611 tabletypename = "TableType";
2612 rowtypename = "RowType";
2615 xsd_schema_element_start(&result, targetns);
2617 appendStringInfoString(&result,
2618 map_sql_typecoll_to_xmlschema_types(list_make1(tupdesc)));
2620 appendStringInfo(&result,
2621 "<xsd:complexType name=\"%s\">\n"
2622 " <xsd:sequence>\n",
2625 for (i = 0; i < tupdesc->natts; i++)
2626 appendStringInfo(&result,
2627 " <xsd:element name=\"%s\" type=\"%s\"%s></xsd:element>\n",
2628 map_sql_identifier_to_xml_name(NameStr(tupdesc->attrs[i]->attname),
2630 map_sql_type_to_xml_name(tupdesc->attrs[i]->atttypid, -1),
2631 nulls ? " nillable=\"true\"" : " minOccurs=\"0\"");
2633 appendStringInfoString(&result,
2634 " </xsd:sequence>\n"
2635 "</xsd:complexType>\n\n");
2639 appendStringInfo(&result,
2640 "<xsd:complexType name=\"%s\">\n"
2642 " <xsd:element name=\"row\" type=\"%s\" minOccurs=\"0\" maxOccurs=\"unbounded\"/>\n"
2643 " </xsd:sequence>\n"
2644 "</xsd:complexType>\n\n",
2645 tabletypename, rowtypename);
2647 appendStringInfo(&result,
2648 "<xsd:element name=\"%s\" type=\"%s\"/>\n\n",
2649 xmltn, tabletypename);
2652 appendStringInfo(&result,
2653 "<xsd:element name=\"%s\" type=\"%s\"/>\n\n",
2654 xmltn, rowtypename);
2656 xsd_schema_element_end(&result);
2663 * Map an SQL schema to XML Schema data types; see SQL/XML section
2667 map_sql_schema_to_xmlschema_types(Oid nspid, List *relid_list, bool nulls,
2668 bool tableforest, const char *targetns)
2673 char *schematypename;
2674 StringInfoData result;
2677 dbname = get_database_name(MyDatabaseId);
2678 nspname = get_namespace_name(nspid);
2680 initStringInfo(&result);
2682 xmlsn = map_sql_identifier_to_xml_name(nspname, true, false);
2684 schematypename = map_multipart_sql_identifier_to_xml_name("SchemaType",
2689 appendStringInfo(&result,
2690 "<xsd:complexType name=\"%s\">\n", schematypename);
2692 appendStringInfoString(&result,
2695 appendStringInfoString(&result,
2696 " <xsd:sequence>\n");
2698 foreach (cell, relid_list)
2700 Oid relid = lfirst_oid(cell);
2701 char *relname = get_rel_name(relid);
2702 char *xmltn = map_sql_identifier_to_xml_name(relname, true, false);
2703 char *tabletypename = map_multipart_sql_identifier_to_xml_name(tableforest ? "RowType" : "TableType",
2709 appendStringInfo(&result,
2710 " <xsd:element name=\"%s\" type=\"%s\"/>\n",
2711 xmltn, tabletypename);
2713 appendStringInfo(&result,
2714 " <xsd:element name=\"%s\" type=\"%s\" minOccurs=\"0\" maxOccurs=\"unbounded\"/>\n",
2715 xmltn, tabletypename);
2719 appendStringInfoString(&result,
2722 appendStringInfoString(&result,
2723 " </xsd:sequence>\n");
2724 appendStringInfoString(&result,
2725 "</xsd:complexType>\n\n");
2727 appendStringInfo(&result,
2728 "<xsd:element name=\"%s\" type=\"%s\"/>\n\n",
2729 xmlsn, schematypename);
2736 * Map an SQL catalog to XML Schema data types; see SQL/XML section
2740 map_sql_catalog_to_xmlschema_types(List *nspid_list, bool nulls,
2741 bool tableforest, const char *targetns)
2745 char *catalogtypename;
2746 StringInfoData result;
2749 dbname = get_database_name(MyDatabaseId);
2751 initStringInfo(&result);
2753 xmlcn = map_sql_identifier_to_xml_name(dbname, true, false);
2755 catalogtypename = map_multipart_sql_identifier_to_xml_name("CatalogType",
2760 appendStringInfo(&result,
2761 "<xsd:complexType name=\"%s\">\n", catalogtypename);
2762 appendStringInfoString(&result,
2765 foreach (cell, nspid_list)
2767 Oid nspid = lfirst_oid(cell);
2768 char *nspname = get_namespace_name(nspid);
2769 char *xmlsn = map_sql_identifier_to_xml_name(nspname, true, false);
2770 char *schematypename = map_multipart_sql_identifier_to_xml_name("SchemaType",
2775 appendStringInfo(&result,
2776 " <xsd:element name=\"%s\" type=\"%s\"/>\n",
2777 xmlsn, schematypename);
2780 appendStringInfoString(&result,
2782 appendStringInfoString(&result,
2783 "</xsd:complexType>\n\n");
2785 appendStringInfo(&result,
2786 "<xsd:element name=\"%s\" type=\"%s\"/>\n\n",
2787 xmlcn, catalogtypename);
2794 * Map an SQL data type to an XML name; see SQL/XML:2003 section 9.9.
2797 map_sql_type_to_xml_name(Oid typeoid, int typmod)
2799 StringInfoData result;
2801 initStringInfo(&result);
2807 appendStringInfo(&result, "CHAR");
2809 appendStringInfo(&result, "CHAR_%d", typmod - VARHDRSZ);
2813 appendStringInfo(&result, "VARCHAR");
2815 appendStringInfo(&result, "VARCHAR_%d", typmod - VARHDRSZ);
2819 appendStringInfo(&result, "NUMERIC");
2821 appendStringInfo(&result, "NUMERIC_%d_%d",
2822 ((typmod - VARHDRSZ) >> 16) & 0xffff,
2823 (typmod - VARHDRSZ) & 0xffff);
2826 appendStringInfo(&result, "INTEGER");
2829 appendStringInfo(&result, "SMALLINT");
2832 appendStringInfo(&result, "BIGINT");
2835 appendStringInfo(&result, "REAL");
2838 appendStringInfo(&result, "DOUBLE");
2841 appendStringInfo(&result, "BOOLEAN");
2845 appendStringInfo(&result, "TIME");
2847 appendStringInfo(&result, "TIME_%d", typmod);
2851 appendStringInfo(&result, "TIME_WTZ");
2853 appendStringInfo(&result, "TIME_WTZ_%d", typmod);
2857 appendStringInfo(&result, "TIMESTAMP");
2859 appendStringInfo(&result, "TIMESTAMP_%d", typmod);
2861 case TIMESTAMPTZOID:
2863 appendStringInfo(&result, "TIMESTAMP_WTZ");
2865 appendStringInfo(&result, "TIMESTAMP_WTZ_%d", typmod);
2868 appendStringInfo(&result, "DATE");
2871 appendStringInfo(&result, "XML");
2876 Form_pg_type typtuple;
2878 tuple = SearchSysCache(TYPEOID,
2879 ObjectIdGetDatum(typeoid),
2881 if (!HeapTupleIsValid(tuple))
2882 elog(ERROR, "cache lookup failed for type %u", typeoid);
2883 typtuple = (Form_pg_type) GETSTRUCT(tuple);
2885 appendStringInfoString(&result,
2886 map_multipart_sql_identifier_to_xml_name((typtuple->typtype == TYPTYPE_DOMAIN) ? "Domain" : "UDT",
2887 get_database_name(MyDatabaseId),
2888 get_namespace_name(typtuple->typnamespace),
2889 NameStr(typtuple->typname)));
2891 ReleaseSysCache(tuple);
2900 * Map a collection of SQL data types to XML Schema data types; see
2901 * SQL/XML:2002 section 9.10.
2904 map_sql_typecoll_to_xmlschema_types(List *tupdesc_list)
2906 List *uniquetypes = NIL;
2908 StringInfoData result;
2911 /* extract all column types used in the set of TupleDescs */
2912 foreach(cell0, tupdesc_list)
2914 TupleDesc tupdesc = (TupleDesc) lfirst(cell0);
2916 for (i = 0; i < tupdesc->natts; i++)
2918 if (tupdesc->attrs[i]->attisdropped)
2920 uniquetypes = list_append_unique_oid(uniquetypes,
2921 tupdesc->attrs[i]->atttypid);
2925 /* add base types of domains */
2926 foreach(cell0, uniquetypes)
2928 Oid typid = lfirst_oid(cell0);
2929 Oid basetypid = getBaseType(typid);
2931 if (basetypid != typid)
2932 uniquetypes = list_append_unique_oid(uniquetypes, basetypid);
2935 /* Convert to textual form */
2936 initStringInfo(&result);
2938 foreach(cell0, uniquetypes)
2940 appendStringInfo(&result, "%s\n",
2941 map_sql_type_to_xmlschema_type(lfirst_oid(cell0),
2950 * Map an SQL data type to a named XML Schema data type; see SQL/XML
2951 * sections 9.11 and 9.15.
2953 * (The distinction between 9.11 and 9.15 is basically that 9.15 adds
2954 * a name attribute, which this function does. The name-less version
2955 * 9.11 doesn't appear to be required anywhere.)
2958 map_sql_type_to_xmlschema_type(Oid typeoid, int typmod)
2960 StringInfoData result;
2961 const char *typename = map_sql_type_to_xml_name(typeoid, typmod);
2963 initStringInfo(&result);
2965 if (typeoid == XMLOID)
2967 appendStringInfo(&result,
2968 "<xsd:complexType mixed=\"true\">\n"
2970 " <xsd:any name=\"element\" minOccurs=\"0\" maxOccurs=\"unbounded\" processContents=\"skip\"/>\n"
2971 " </xsd:sequence>\n"
2972 "</xsd:complexType>\n");
2976 appendStringInfo(&result,
2977 "<xsd:simpleType name=\"%s\">\n", typename);
2985 appendStringInfo(&result,
2986 " <xsd:restriction base=\"xsd:string\">\n"
2987 " <xsd:maxLength value=\"%d\"/>\n"
2988 " </xsd:restriction>\n",
2993 appendStringInfo(&result,
2994 " <xsd:restriction base=\"xsd:%s\">\n"
2995 " </xsd:restriction>\n",
2996 xmlbinary == XMLBINARY_BASE64 ? "base64Binary" : "hexBinary");
3000 appendStringInfo(&result,
3001 " <xsd:restriction base=\"xsd:decimal\">\n"
3002 " <xsd:totalDigits value=\"%d\"/>\n"
3003 " <xsd:fractionDigits value=\"%d\"/>\n"
3004 " </xsd:restriction>\n",
3005 ((typmod - VARHDRSZ) >> 16) & 0xffff,
3006 (typmod - VARHDRSZ) & 0xffff);
3010 appendStringInfo(&result,
3011 " <xsd:restriction base=\"xsd:short\">\n"
3012 " <xsd:maxInclusive value=\"%d\"/>\n"
3013 " <xsd:minInclusive value=\"%d\"/>\n"
3014 " </xsd:restriction>\n",
3015 SHRT_MAX, SHRT_MIN);
3019 appendStringInfo(&result,
3020 " <xsd:restriction base='xsd:int'>\n"
3021 " <xsd:maxInclusive value=\"%d\"/>\n"
3022 " <xsd:minInclusive value=\"%d\"/>\n"
3023 " </xsd:restriction>\n",
3028 appendStringInfo(&result,
3029 " <xsd:restriction base=\"xsd:long\">\n"
3030 " <xsd:maxInclusive value=\"" INT64_FORMAT "\"/>\n"
3031 " <xsd:minInclusive value=\"" INT64_FORMAT "\"/>\n"
3032 " </xsd:restriction>\n",
3033 (((uint64) 1) << (sizeof(int64) * 8 - 1)) - 1,
3034 (((uint64) 1) << (sizeof(int64) * 8 - 1)));
3038 appendStringInfo(&result,
3039 " <xsd:restriction base=\"xsd:float\"></xsd:restriction>\n");
3043 appendStringInfo(&result,
3044 " <xsd:restriction base=\"xsd:double\"></xsd:restriction>\n");
3048 appendStringInfo(&result,
3049 " <xsd:restriction base=\"xsd:boolean\"></xsd:restriction>\n");
3055 const char *tz = (typeoid == TIMETZOID ? "(+|-)\\p{Nd}{2}:\\p{Nd}{2}" : "");
3058 appendStringInfo(&result,
3059 " <xsd:restriction base=\"xsd:time\">\n"
3060 " <xsd:pattern value=\"\\p{Nd}{2}:\\p{Nd}{2}:\\p{Nd}{2}(.\\p{Nd}+)?%s\"/>\n"
3061 " </xsd:restriction>\n", tz);
3062 else if (typmod == 0)
3063 appendStringInfo(&result,
3064 " <xsd:restriction base=\"xsd:time\">\n"
3065 " <xsd:pattern value=\"\\p{Nd}{2}:\\p{Nd}{2}:\\p{Nd}{2}%s\"/>\n"
3066 " </xsd:restriction>\n", tz);
3068 appendStringInfo(&result,
3069 " <xsd:restriction base=\"xsd:time\">\n"
3070 " <xsd:pattern value=\"\\p{Nd}{2}:\\p{Nd}{2}:\\p{Nd}{2}.\\p{Nd}{%d}%s\"/>\n"
3071 " </xsd:restriction>\n", typmod - VARHDRSZ, tz);
3076 case TIMESTAMPTZOID:
3078 const char *tz = (typeoid == TIMESTAMPTZOID ? "(+|-)\\p{Nd}{2}:\\p{Nd}{2}" : "");
3081 appendStringInfo(&result,
3082 " <xsd:restriction base=\"xsd:dateTime\">\n"
3083 " <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"
3084 " </xsd:restriction>\n", tz);
3085 else if (typmod == 0)
3086 appendStringInfo(&result,
3087 " <xsd:restriction base=\"xsd:dateTime\">\n"
3088 " <xsd:pattern value=\"\\p{Nd}{4}-\\p{Nd}{2}-\\p{Nd}{2}T\\p{Nd}{2}:\\p{Nd}{2}:\\p{Nd}{2}%s\"/>\n"
3089 " </xsd:restriction>\n", tz);
3091 appendStringInfo(&result,
3092 " <xsd:restriction base=\"xsd:dateTime\">\n"
3093 " <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"
3094 " </xsd:restriction>\n", typmod - VARHDRSZ, tz);
3099 appendStringInfo(&result,
3100 " <xsd:restriction base=\"xsd:date\">\n"
3101 " <xsd:pattern value=\"\\p{Nd}{4}-\\p{Nd}{2}-\\p{Nd}{2}\"/>\n"
3102 " </xsd:restriction>\n");
3106 if (get_typtype(typeoid) == TYPTYPE_DOMAIN)
3109 int32 base_typmod = -1;
3111 base_typeoid = getBaseTypeAndTypmod(typeoid, &base_typmod);
3113 appendStringInfo(&result,
3114 " <xsd:restriction base=\"%s\"/>\n",
3115 map_sql_type_to_xml_name(base_typeoid, base_typmod));
3119 appendStringInfo(&result,
3120 "</xsd:simpleType>\n");
3128 * Map an SQL row to an XML element, taking the row from the active
3129 * SPI cursor. See also SQL/XML:2003 section 9.12.
3132 SPI_sql_row_to_xmlelement(int rownum, StringInfo result, char *tablename,
3133 bool nulls, bool tableforest,
3134 const char *targetns, bool top_level)
3140 xmltn = map_sql_identifier_to_xml_name(tablename, true, false);
3150 xmldata_root_element_start(result, xmltn, NULL, targetns, top_level);
3152 appendStringInfoString(result, "<row>\n");
3154 for(i = 1; i <= SPI_tuptable->tupdesc->natts; i++)
3160 colname = map_sql_identifier_to_xml_name(SPI_fname(SPI_tuptable->tupdesc, i),
3162 colval = SPI_getbinval(SPI_tuptable->vals[rownum],
3163 SPI_tuptable->tupdesc,
3169 appendStringInfo(result, " <%s xsi:nil='true'/>\n", colname);
3172 appendStringInfo(result, " <%s>%s</%s>\n",
3174 map_sql_value_to_xml_value(colval,
3175 SPI_gettypeid(SPI_tuptable->tupdesc, i)),
3181 xmldata_root_element_end(result, xmltn);
3182 appendStringInfoChar(result, '\n');
3185 appendStringInfoString(result, "</row>\n\n");
3190 * XPath related functions
3195 * Convert XML node to text (dump subtree in case of element,
3196 * return value otherwise)
3199 xml_xmlnodetoxmltype(xmlNodePtr cur)
3206 if (cur->type == XML_ELEMENT_NODE)
3208 buf = xmlBufferCreate();
3209 xmlNodeDump(buf, NULL, cur, 0, 1);
3210 result = xmlBuffer_to_xmltype(buf);
3215 str = xmlXPathCastNodeToString(cur);
3216 len = strlen((char *) str);
3217 result = (text *) palloc(len + VARHDRSZ);
3218 SET_VARSIZE(result, len + VARHDRSZ);
3219 memcpy(VARDATA(result), str, len);
3228 * Evaluate XPath expression and return array of XML values.
3230 * As we have no support of XQuery sequences yet, this function seems
3231 * to be the most useful one (array of XML functions plays a role of
3232 * some kind of substitution for XQuery sequences).
3234 * Workaround here: we parse XML data in different way to allow XPath for
3235 * fragments (see "XPath for fragment" TODO comment inside).
3238 xpath(PG_FUNCTION_ARGS)
3241 text *xpath_expr_text = PG_GETARG_TEXT_P(0);
3242 xmltype *data = PG_GETARG_XML_P(1);
3243 ArrayType *namespaces = PG_GETARG_ARRAYTYPE_P(2);
3244 ArrayBuildState *astate = NULL;
3245 xmlParserCtxtPtr ctxt = NULL;
3246 xmlDocPtr doc = NULL;
3247 xmlXPathContextPtr xpathctx = NULL;
3248 xmlXPathCompExprPtr xpathcomp = NULL;
3249 xmlXPathObjectPtr xpathobj = NULL;
3254 xmlChar *xpath_expr;
3258 Datum *ns_names_uris;
3259 bool *ns_names_uris_nulls;
3263 * Namespace mappings are passed as text[]. If an empty array is
3264 * passed (ndim = 0, "0-dimensional"), then there are no namespace
3265 * mappings. Else, a 2-dimensional array with length of the
3266 * second axis being equal to 2 should be passed, i.e., every
3267 * subarray contains 2 elements, the first element defining the
3268 * name, the second one the URI. Example: ARRAY[ARRAY['myns',
3269 * 'http://example.com'], ARRAY['myns2', 'http://example2.com']].
3271 ndim = ARR_NDIM(namespaces);
3276 dims = ARR_DIMS(namespaces);
3278 if (ndim != 2 || dims[1] != 2)
3280 (errcode(ERRCODE_DATA_EXCEPTION),
3281 errmsg("invalid array for XML namespace mapping"),
3282 errdetail("The array must be two-dimensional with length of the second axis equal to 2.")));
3284 Assert(ARR_ELEMTYPE(namespaces) == TEXTOID);
3286 deconstruct_array(namespaces, TEXTOID, -1, false, 'i',
3287 &ns_names_uris, &ns_names_uris_nulls,
3290 Assert((ns_count % 2) == 0); /* checked above */
3291 ns_count /= 2; /* count pairs only */
3295 ns_names_uris = NULL;
3296 ns_names_uris_nulls = NULL;
3300 datastr = VARDATA(data);
3301 len = VARSIZE(data) - VARHDRSZ;
3302 xpath_len = VARSIZE(xpath_expr_text) - VARHDRSZ;
3305 (errcode(ERRCODE_DATA_EXCEPTION),
3306 errmsg("empty XPath expression")));
3309 * To handle both documents and fragments, regardless of the fact
3310 * whether the XML datum has a single root (XML well-formedness),
3311 * we wrap the XML datum in a dummy element (<x>...</x>) and
3312 * extend the XPath expression accordingly. To do it, throw away
3313 * the XML prolog, if any.
3316 xmlStrncmp((xmlChar *) datastr, (xmlChar *) "<?xml", 5) == 0)
3320 !(datastr[i - 1] == '?' && datastr[i] == '>'))
3324 xml_ereport(ERROR, ERRCODE_INTERNAL_ERROR,
3325 "could not parse XML data");
3328 string = xmlStrncatNew((xmlChar *) "<x>",
3329 (xmlChar *) datastr + i, len - i);
3332 string = xmlStrncatNew((xmlChar *) "<x>",
3333 (xmlChar *) datastr, len);
3335 string = xmlStrncat(string, (xmlChar *) "</x>", 5);
3337 xpath_expr = xmlStrncatNew((xmlChar *) "/x",
3338 (xmlChar *) VARDATA(xpath_expr_text), xpath_len);
3343 /* We use a PG_TRY block to ensure libxml parser is cleaned up on error */
3348 * redundant XML parsing (two parsings for the same value
3349 * during one command execution are possible)
3351 ctxt = xmlNewParserCtxt();
3353 xml_ereport(ERROR, ERRCODE_INTERNAL_ERROR,
3354 "could not allocate parser context");
3355 doc = xmlCtxtReadMemory(ctxt, (char *) string, len, NULL, NULL, 0);
3357 xml_ereport(ERROR, ERRCODE_INVALID_XML_DOCUMENT,
3358 "could not parse XML data");
3359 xpathctx = xmlXPathNewContext(doc);
3360 if (xpathctx == NULL)
3361 xml_ereport(ERROR, ERRCODE_INTERNAL_ERROR,
3362 "could not allocate XPath context");
3363 xpathctx->node = xmlDocGetRootElement(doc);
3364 if (xpathctx->node == NULL)
3365 xml_ereport(ERROR, ERRCODE_INTERNAL_ERROR,
3366 "could not find root XML element");
3368 /* register namespaces, if any */
3371 for (i = 0; i < ns_count; i++)
3376 if (ns_names_uris_nulls[i * 2] ||
3377 ns_names_uris_nulls[i * 2 + 1])
3379 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3380 errmsg("neither namespace name nor URI may be null")));
3381 ns_name = _textout(ns_names_uris[i * 2]);
3382 ns_uri = _textout(ns_names_uris[i * 2 + 1]);
3383 if (xmlXPathRegisterNs(xpathctx,
3384 (xmlChar *) ns_name,
3385 (xmlChar *) ns_uri) != 0)
3386 ereport(ERROR, /* is this an internal error??? */
3387 (errmsg("could not register XML namespace with name \"%s\" and URI \"%s\"",
3392 xpathcomp = xmlXPathCompile(xpath_expr);
3393 if (xpathcomp == NULL) /* TODO: show proper XPath error details */
3394 xml_ereport(ERROR, ERRCODE_INTERNAL_ERROR,
3395 "invalid XPath expression");
3397 xpathobj = xmlXPathCompiledEval(xpathcomp, xpathctx);
3398 if (xpathobj == NULL) /* TODO: reason? */
3400 (errmsg("could not create XPath object")));
3402 xmlXPathFreeCompExpr(xpathcomp);
3405 /* return empty array in cases when nothing is found */
3406 if (xpathobj->nodesetval == NULL)
3409 res_nitems = xpathobj->nodesetval->nodeNr;
3412 for (i = 0; i < xpathobj->nodesetval->nodeNr; i++)
3415 bool elemisnull = false;
3416 elem = PointerGetDatum(xml_xmlnodetoxmltype(xpathobj->nodesetval->nodeTab[i]));
3417 astate = accumArrayResult(astate, elem,
3419 CurrentMemoryContext);
3422 xmlXPathFreeObject(xpathobj);
3424 xmlXPathFreeContext(xpathctx);
3428 xmlFreeParserCtxt(ctxt);
3435 xmlXPathFreeCompExpr(xpathcomp);
3437 xmlXPathFreeObject(xpathobj);
3439 xmlXPathFreeContext(xpathctx);
3443 xmlFreeParserCtxt(ctxt);
3450 if (res_nitems == 0)
3451 PG_RETURN_ARRAYTYPE_P(construct_empty_array(XMLOID));
3453 PG_RETURN_ARRAYTYPE_P(makeArrayResult(astate, CurrentMemoryContext));