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.39 2007/04/02 03:49:39 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"
78 static StringInfo xml_err_buf = NULL;
80 static void xml_init(void);
81 static void *xml_palloc(size_t size);
82 static void *xml_repalloc(void *ptr, size_t size);
83 static void xml_pfree(void *ptr);
84 static char *xml_pstrdup(const char *string);
85 static void xml_ereport(int level, int sqlcode,
87 static void xml_errorHandler(void *ctxt, const char *msg, ...);
88 static void xml_ereport_by_code(int level, int sqlcode,
89 const char *msg, int errcode);
90 static xmlChar *xml_text2xmlChar(text *in);
91 static int parse_xml_decl(const xmlChar *str, size_t *lenp, xmlChar **version, xmlChar **encoding, int *standalone);
92 static bool print_xml_decl(StringInfo buf, const xmlChar *version, pg_enc encoding, int standalone);
93 static xmlDocPtr xml_parse(text *data, XmlOptionType xmloption_arg, bool preserve_whitespace, xmlChar *encoding);
94 static text *xml_xmlnodetoxmltype(xmlNodePtr cur);
96 #endif /* USE_LIBXML */
98 static StringInfo query_to_xml_internal(const char *query, char *tablename, const char *xmlschema, bool nulls, bool tableforest, const char *targetns, bool top_level);
99 static const char * map_sql_table_to_xmlschema(TupleDesc tupdesc, Oid relid, bool nulls, bool tableforest, const char *targetns);
100 static const char * map_sql_schema_to_xmlschema_types(Oid nspid, List *relid_list, bool nulls, bool tableforest, const char *targetns);
101 static const char * map_sql_catalog_to_xmlschema_types(List *nspid_list, bool nulls, bool tableforest, const char *targetns);
102 static const char * map_sql_type_to_xml_name(Oid typeoid, int typmod);
103 static const char * map_sql_typecoll_to_xmlschema_types(List *tupdesc_list);
104 static const char * map_sql_type_to_xmlschema_type(Oid typeoid, int typmod);
105 static void SPI_sql_row_to_xmlelement(int rownum, StringInfo result, char *tablename, bool nulls, bool tableforest, const char *targetns, bool top_level);
108 XmlBinaryType xmlbinary;
109 XmlOptionType xmloption;
112 #define NO_XML_SUPPORT() \
114 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), \
115 errmsg("no XML support in this installation")))
118 #define _textin(str) DirectFunctionCall1(textin, CStringGetDatum(str))
119 #define _textout(x) DatumGetCString(DirectFunctionCall1(textout, PointerGetDatum(x)))
122 /* from SQL/XML:2003 section 4.7 */
123 #define NAMESPACE_XSD "http://www.w3.org/2001/XMLSchema"
124 #define NAMESPACE_XSI "http://www.w3.org/2001/XMLSchema-instance"
125 #define NAMESPACE_SQLXML "http://standards.iso.org/iso/9075/2003/sqlxml"
129 xml_in(PG_FUNCTION_ARGS)
132 char *s = PG_GETARG_CSTRING(0);
138 vardata = palloc(len + VARHDRSZ);
139 SET_VARSIZE(vardata, len + VARHDRSZ);
140 memcpy(VARDATA(vardata), s, len);
143 * Parse the data to check if it is well-formed XML data. Assume
144 * that ERROR occurred if parsing failed.
146 doc = xml_parse(vardata, xmloption, true, NULL);
149 PG_RETURN_XML_P(vardata);
157 #define PG_XML_DEFAULT_VERSION "1.0"
161 xml_out_internal(xmltype *x, pg_enc target_encoding)
172 len = VARSIZE(x) - VARHDRSZ;
173 str = palloc(len + 1);
174 memcpy(str, VARDATA(x), len);
178 if ((res_code = parse_xml_decl((xmlChar *) str, &len, &version, &encoding, &standalone)) == 0)
182 initStringInfo(&buf);
184 if (!print_xml_decl(&buf, version, target_encoding, standalone))
187 * If we are not going to produce an XML declaration, eat
188 * a single newline in the original string to prevent
189 * empty first lines in the output.
191 if (*(str + len) == '\n')
194 appendStringInfoString(&buf, str + len);
199 xml_ereport_by_code(WARNING, ERRCODE_INTERNAL_ERROR,
200 "could not parse XML declaration in stored value", res_code);
207 xml_out(PG_FUNCTION_ARGS)
209 xmltype *x = PG_GETARG_XML_P(0);
212 * xml_out removes the encoding property in all cases. This is
213 * because we cannot control from here whether the datum will be
214 * converted to a different client encoding, so we'd do more harm
215 * than good by including it.
217 PG_RETURN_CSTRING(xml_out_internal(x, 0));
222 xml_recv(PG_FUNCTION_ARGS)
225 StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
231 xmlChar *encoding = NULL;
233 str = pq_getmsgtext(buf, buf->len - buf->cursor, &nbytes);
235 result = palloc(nbytes + VARHDRSZ);
236 SET_VARSIZE(result, nbytes + VARHDRSZ);
237 memcpy(VARDATA(result), str, nbytes);
239 parse_xml_decl((xmlChar *) str, NULL, NULL, &encoding, NULL);
242 * Parse the data to check if it is well-formed XML data. Assume
243 * that ERROR occurred if parsing failed.
245 doc = xml_parse(result, xmloption, true, encoding);
248 newstr = (char *) pg_do_encoding_conversion((unsigned char *) str,
250 encoding ? pg_char_to_encoding((char *) encoding) : PG_UTF8,
251 GetDatabaseEncoding());
259 nbytes = strlen(newstr);
261 result = palloc(nbytes + VARHDRSZ);
262 SET_VARSIZE(result, nbytes + VARHDRSZ);
263 memcpy(VARDATA(result), newstr, nbytes);
266 PG_RETURN_XML_P(result);
275 xml_send(PG_FUNCTION_ARGS)
277 xmltype *x = PG_GETARG_XML_P(0);
278 char *outval = xml_out_internal(x, pg_get_client_encoding());
281 pq_begintypsend(&buf);
282 pq_sendstring(&buf, outval);
283 PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
289 appendStringInfoText(StringInfo str, const text *t)
291 appendBinaryStringInfo(str, VARDATA(t), VARSIZE(t) - VARHDRSZ);
297 stringinfo_to_xmltype(StringInfo buf)
302 len = buf->len + VARHDRSZ;
303 result = palloc(len);
304 SET_VARSIZE(result, len);
305 memcpy(VARDATA(result), buf->data, buf->len);
312 cstring_to_xmltype(const char *string)
317 len = strlen(string) + VARHDRSZ;
318 result = palloc(len);
319 SET_VARSIZE(result, len);
320 memcpy(VARDATA(result), string, len - VARHDRSZ);
328 xmlBuffer_to_xmltype(xmlBufferPtr buf)
333 len = xmlBufferLength(buf) + VARHDRSZ;
334 result = palloc(len);
335 SET_VARSIZE(result, len);
336 memcpy(VARDATA(result), xmlBufferContent(buf), len - VARHDRSZ);
344 xmlcomment(PG_FUNCTION_ARGS)
347 text *arg = PG_GETARG_TEXT_P(0);
348 int len = VARSIZE(arg) - VARHDRSZ;
352 /* check for "--" in string or "-" at the end */
353 for (i = 1; i < len; i++)
354 if ((VARDATA(arg)[i] == '-' && VARDATA(arg)[i - 1] == '-')
355 || (VARDATA(arg)[i] == '-' && i == len - 1))
357 (errcode(ERRCODE_INVALID_XML_COMMENT),
358 errmsg("invalid XML comment")));
360 initStringInfo(&buf);
361 appendStringInfo(&buf, "<!--");
362 appendStringInfoText(&buf, arg);
363 appendStringInfo(&buf, "-->");
365 PG_RETURN_XML_P(stringinfo_to_xmltype(&buf));
375 * TODO: xmlconcat needs to merge the notations and unparsed entities
376 * of the argument values. Not very important in practice, though.
379 xmlconcat(List *args)
385 int global_standalone = 1;
386 xmlChar *global_version = NULL;
387 bool global_version_no_value = false;
389 initStringInfo(&buf);
395 xmltype *x = DatumGetXmlP(PointerGetDatum(lfirst(v)));
398 len = VARSIZE(x) - VARHDRSZ;
399 str = palloc(len + 1);
400 memcpy(str, VARDATA(x), len);
403 parse_xml_decl((xmlChar *) str, &len, &version, NULL, &standalone);
405 if (standalone == 0 && global_standalone == 1)
406 global_standalone = 0;
408 global_standalone = -1;
411 global_version_no_value = true;
412 else if (!global_version)
413 global_version = xmlStrdup(version);
414 else if (xmlStrcmp(version, global_version) != 0)
415 global_version_no_value = true;
417 appendStringInfoString(&buf, str + len);
421 if (!global_version_no_value || global_standalone >= 0)
425 initStringInfo(&buf2);
427 print_xml_decl(&buf2,
428 (!global_version_no_value && global_version) ? global_version : NULL,
432 appendStringInfoString(&buf2, buf.data);
436 return stringinfo_to_xmltype(&buf);
448 xmlconcat2(PG_FUNCTION_ARGS)
455 PG_RETURN_XML_P(PG_GETARG_XML_P(1));
457 else if (PG_ARGISNULL(1))
458 PG_RETURN_XML_P(PG_GETARG_XML_P(0));
460 PG_RETURN_XML_P(xmlconcat(list_make2(PG_GETARG_XML_P(0), PG_GETARG_XML_P(1))));
465 texttoxml(PG_FUNCTION_ARGS)
467 text *data = PG_GETARG_TEXT_P(0);
469 PG_RETURN_XML_P(xmlparse(data, xmloption, true));
474 xmltotext(PG_FUNCTION_ARGS)
476 xmltype *data = PG_GETARG_XML_P(0);
478 PG_RETURN_TEXT_P(xmltotext_with_xmloption(data, xmloption));
483 xmltotext_with_xmloption(xmltype *data, XmlOptionType xmloption_arg)
485 if (xmloption_arg == XMLOPTION_DOCUMENT && !xml_is_document(data))
487 (errcode(ERRCODE_NOT_AN_XML_DOCUMENT),
488 errmsg("not an XML document")));
490 /* It's actually binary compatible, save for the above check. */
491 return (text *) data;
496 xmlelement(XmlExprState *xmlExpr, ExprContext *econtext)
499 XmlExpr *xexpr = (XmlExpr *) xmlExpr->xprstate.expr;
509 xmlTextWriterPtr writer;
511 buf = xmlBufferCreate();
512 writer = xmlNewTextWriterMemory(buf, 0);
514 xmlTextWriterStartElement(writer, (xmlChar *) xexpr->name);
517 forboth(arg, xmlExpr->named_args, narg, xexpr->arg_names)
519 ExprState *e = (ExprState *) lfirst(arg);
520 char *argname = strVal(lfirst(narg));
522 value = ExecEvalExpr(e, econtext, &isnull, NULL);
525 str = OutputFunctionCall(&xmlExpr->named_outfuncs[i], value);
526 xmlTextWriterWriteAttribute(writer, (xmlChar *) argname, (xmlChar *) str);
532 foreach(arg, xmlExpr->args)
534 ExprState *e = (ExprState *) lfirst(arg);
536 value = ExecEvalExpr(e, econtext, &isnull, NULL);
538 xmlTextWriterWriteRaw(writer, (xmlChar *) map_sql_value_to_xml_value(value, exprType((Node *) e->expr)));
541 xmlTextWriterEndElement(writer);
542 xmlFreeTextWriter(writer);
544 result = xmlBuffer_to_xmltype(buf);
555 xmlparse(text *data, XmlOptionType xmloption_arg, bool preserve_whitespace)
560 doc = xml_parse(data, xmloption_arg, preserve_whitespace, NULL);
563 return (xmltype *) data;
572 xmlpi(char *target, text *arg, bool arg_is_null, bool *result_is_null)
578 if (pg_strncasecmp(target, "xml", 3) == 0)
580 (errcode(ERRCODE_SYNTAX_ERROR), /* really */
581 errmsg("invalid XML processing instruction"),
582 errdetail("XML processing instruction target name cannot start with \"xml\".")));
585 * Following the SQL standard, the null check comes after the
586 * syntax check above.
588 *result_is_null = arg_is_null;
592 initStringInfo(&buf);
594 appendStringInfo(&buf, "<?%s", target);
600 string = DatumGetCString(DirectFunctionCall1(textout,
601 PointerGetDatum(arg)));
602 if (strstr(string, "?>") != NULL)
604 (errcode(ERRCODE_INVALID_XML_PROCESSING_INSTRUCTION),
605 errmsg("invalid XML processing instruction"),
606 errdetail("XML processing instruction cannot contain \"?>\".")));
608 appendStringInfoChar(&buf, ' ');
609 appendStringInfoString(&buf, string + strspn(string, " "));
612 appendStringInfoString(&buf, "?>");
614 result = stringinfo_to_xmltype(&buf);
625 xmlroot(xmltype *data, text *version, int standalone)
630 xmlChar *orig_version;
634 len = VARSIZE(data) - VARHDRSZ;
635 str = palloc(len + 1);
636 memcpy(str, VARDATA(data), len);
639 parse_xml_decl((xmlChar *) str, &len, &orig_version, NULL, &orig_standalone);
642 orig_version = xml_text2xmlChar(version);
648 case XML_STANDALONE_YES:
651 case XML_STANDALONE_NO:
654 case XML_STANDALONE_NO_VALUE:
655 orig_standalone = -1;
657 case XML_STANDALONE_OMITTED:
658 /* leave original value */
662 initStringInfo(&buf);
663 print_xml_decl(&buf, orig_version, 0, orig_standalone);
664 appendStringInfoString(&buf, str + len);
666 return stringinfo_to_xmltype(&buf);
675 * Validate document (given as string) against DTD (given as external link)
676 * TODO !!! use text instead of cstring for second arg
677 * TODO allow passing DTD as a string value (not only as an URI)
678 * TODO redesign (see comment with '!!!' below)
681 xmlvalidate(PG_FUNCTION_ARGS)
684 text *data = PG_GETARG_TEXT_P(0);
685 text *dtdOrUri = PG_GETARG_TEXT_P(1);
687 xmlParserCtxtPtr ctxt = NULL;
688 xmlDocPtr doc = NULL;
689 xmlDtdPtr dtd = NULL;
693 /* We use a PG_TRY block to ensure libxml is cleaned up on error */
696 ctxt = xmlNewParserCtxt();
698 xml_ereport(ERROR, ERRCODE_INTERNAL_ERROR,
699 "could not allocate parser context");
701 doc = xmlCtxtReadMemory(ctxt, (char *) VARDATA(data),
702 VARSIZE(data) - VARHDRSZ,
705 xml_ereport(ERROR, ERRCODE_INVALID_XML_DOCUMENT,
706 "could not parse XML data");
709 uri = xmlCreateURI();
710 elog(NOTICE, "dtd - %s", dtdOrUri);
711 dtd = palloc(sizeof(xmlDtdPtr));
712 uri = xmlParseURI(dtdOrUri);
714 xml_ereport(ERROR, ERRCODE_INTERNAL_ERROR,
715 "not implemented yet... (TODO)");
718 dtd = xmlParseDTD(NULL, xml_text2xmlChar(dtdOrUri));
721 xml_ereport(ERROR, ERRCODE_INVALID_XML_DOCUMENT,
722 "could not load DTD");
724 if (xmlValidateDtd(xmlNewValidCtxt(), doc, dtd) == 1)
728 xml_ereport(NOTICE, ERRCODE_INVALID_XML_DOCUMENT,
729 "validation against DTD failed");
740 xmlFreeParserCtxt(ctxt);
754 xmlFreeParserCtxt(ctxt);
761 PG_RETURN_BOOL(result);
762 #else /* not USE_LIBXML */
765 #endif /* not USE_LIBXML */
770 xml_is_document(xmltype *arg)
774 xmlDocPtr doc = NULL;
775 MemoryContext ccxt = CurrentMemoryContext;
779 doc = xml_parse((text *) arg, XMLOPTION_DOCUMENT, true, NULL);
787 ecxt = MemoryContextSwitchTo(ccxt);
788 errdata = CopyErrorData();
789 if (errdata->sqlerrcode == ERRCODE_INVALID_XML_DOCUMENT)
796 MemoryContextSwitchTo(ecxt);
806 #else /* not USE_LIBXML */
809 #endif /* not USE_LIBXML */
816 * Container for some init stuff (not good design!)
817 * TODO xmlChar is utf8-char, make proper tuning (initdb with enc!=utf8 and check)
823 * Currently, we have no pure UTF-8 support for internals -- check
826 if (sizeof (char) != sizeof (xmlChar))
828 (errmsg("could not initialize XML library"),
829 errdetail("libxml2 has incompatible char type: sizeof(char)=%u, sizeof(xmlChar)=%u.",
830 (int) sizeof(char), (int) sizeof(xmlChar))));
832 if (xml_err_buf == NULL)
834 /* First time through: create error buffer in permanent context */
835 MemoryContext oldcontext;
837 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
838 xml_err_buf = makeStringInfo();
839 MemoryContextSwitchTo(oldcontext);
843 /* Reset pre-existing buffer to empty */
844 resetStringInfo(xml_err_buf);
846 /* Now that xml_err_buf exists, safe to call xml_errorHandler */
847 xmlSetGenericErrorFunc(NULL, xml_errorHandler);
849 xmlMemSetup(xml_pfree, xml_palloc, xml_repalloc, xml_pstrdup);
857 * SQL/XML allows storing "XML documents" or "XML content". "XML
858 * documents" are specified by the XML specification and are parsed
859 * easily by libxml. "XML content" is specified by SQL/XML as the
860 * production "XMLDecl? content". But libxml can only parse the
861 * "content" part, so we have to parse the XML declaration ourselves
865 #define CHECK_XML_SPACE(p) if (!xmlIsBlank_ch(*(p))) return XML_ERR_SPACE_REQUIRED
866 #define SKIP_XML_SPACE(p) while (xmlIsBlank_ch(*(p))) (p)++
869 parse_xml_decl(const xmlChar *str, size_t *lenp, xmlChar **version, xmlChar **encoding, int *standalone)
872 const xmlChar *save_p;
884 if (xmlStrncmp(p, (xmlChar *)"<?xml", 5) != 0)
892 if (xmlStrncmp(p, (xmlChar *)"version", 7) != 0)
893 return XML_ERR_VERSION_MISSING;
897 return XML_ERR_VERSION_MISSING;
901 if (*p == '\'' || *p == '"')
905 q = xmlStrchr(p + 1, *p);
907 return XML_ERR_VERSION_MISSING;
910 *version = xmlStrndup(p + 1, q - p - 1);
914 return XML_ERR_VERSION_MISSING;
919 if (xmlStrncmp(p, (xmlChar *)"encoding", 8) == 0)
921 CHECK_XML_SPACE(save_p);
925 return XML_ERR_MISSING_ENCODING;
929 if (*p == '\'' || *p == '"')
933 q = xmlStrchr(p + 1, *p);
935 return XML_ERR_MISSING_ENCODING;
938 *encoding = xmlStrndup(p + 1, q - p - 1);
942 return XML_ERR_MISSING_ENCODING;
952 if (xmlStrncmp(p, (xmlChar *)"standalone", 10) == 0)
954 CHECK_XML_SPACE(save_p);
958 return XML_ERR_STANDALONE_VALUE;
961 if (xmlStrncmp(p, (xmlChar *)"'yes'", 5) == 0 || xmlStrncmp(p, (xmlChar *)"\"yes\"", 5) == 0)
966 else if (xmlStrncmp(p, (xmlChar *)"'no'", 4) == 0 || xmlStrncmp(p, (xmlChar *)"\"no\"", 4) == 0)
972 return XML_ERR_STANDALONE_VALUE;
980 if (xmlStrncmp(p, (xmlChar *)"?>", 2) != 0)
981 return XML_ERR_XMLDECL_NOT_FINISHED;
987 for (p = str; p < str + len; p++)
989 return XML_ERR_INVALID_CHAR;
999 * Write an XML declaration. On output, we adjust the XML declaration
1000 * as follows. (These rules are the moral equivalent of the clause
1001 * "Serialization of an XML value" in the SQL standard.)
1003 * We try to avoid generating an XML declaration if possible. This is
1004 * so that you don't get trivial things like xml '<foo/>' resulting in
1005 * '<?xml version="1.0"?><foo/>', which would surely be annoying. We
1006 * must provide a declaration if the standalone property is specified
1007 * or if we include an encoding declaration. If we have a
1008 * declaration, we must specify a version (XML requires this).
1009 * Otherwise we only make a declaration if the version is not "1.0",
1010 * which is the default version specified in SQL:2003.
1013 print_xml_decl(StringInfo buf, const xmlChar *version, pg_enc encoding, int standalone)
1015 if ((version && strcmp((char *) version, PG_XML_DEFAULT_VERSION) != 0)
1016 || (encoding && encoding != PG_UTF8)
1017 || standalone != -1)
1019 appendStringInfoString(buf, "<?xml");
1022 appendStringInfo(buf, " version=\"%s\"", version);
1024 appendStringInfo(buf, " version=\"%s\"", PG_XML_DEFAULT_VERSION);
1026 if (encoding && encoding != PG_UTF8)
1027 /* XXX might be useful to convert this to IANA names
1028 * (ISO-8859-1 instead of LATIN1 etc.); needs field
1030 appendStringInfo(buf, " encoding=\"%s\"", pg_encoding_to_char(encoding));
1032 if (standalone == 1)
1033 appendStringInfoString(buf, " standalone=\"yes\"");
1034 else if (standalone == 0)
1035 appendStringInfoString(buf, " standalone=\"no\"");
1036 appendStringInfoString(buf, "?>");
1046 * Convert a C string to XML internal representation
1048 * TODO maybe, libxml2's xmlreader is better? (do not construct DOM, yet do not use SAX - see xml_reader.c)
1051 xml_parse(text *data, XmlOptionType xmloption_arg, bool preserve_whitespace, xmlChar *encoding)
1055 xmlChar *utf8string;
1056 xmlParserCtxtPtr ctxt = NULL;
1057 xmlDocPtr doc = NULL;
1059 len = VARSIZE(data) - VARHDRSZ; /* will be useful later */
1060 string = xml_text2xmlChar(data);
1062 utf8string = pg_do_encoding_conversion(string,
1065 ? pg_char_to_encoding((char *) encoding)
1066 : GetDatabaseEncoding(),
1071 /* We use a PG_TRY block to ensure libxml is cleaned up on error */
1074 ctxt = xmlNewParserCtxt();
1076 xml_ereport(ERROR, ERRCODE_INTERNAL_ERROR,
1077 "could not allocate parser context");
1079 if (xmloption_arg == XMLOPTION_DOCUMENT)
1082 * Note, that here we try to apply DTD defaults
1083 * (XML_PARSE_DTDATTR) according to SQL/XML:10.16.7.d:
1084 * 'Default valies defined by internal DTD are applied'.
1085 * As for external DTDs, we try to support them too, (see
1086 * SQL/XML:10.16.7.e)
1088 doc = xmlCtxtReadDoc(ctxt, utf8string,
1091 XML_PARSE_NOENT | XML_PARSE_DTDATTR
1092 | (preserve_whitespace ? 0 : XML_PARSE_NOBLANKS));
1094 xml_ereport(ERROR, ERRCODE_INVALID_XML_DOCUMENT,
1095 "invalid XML document");
1101 xmlChar *version = NULL;
1102 int standalone = -1;
1104 doc = xmlNewDoc(NULL);
1106 res_code = parse_xml_decl(utf8string, &count, &version, NULL, &standalone);
1108 xml_ereport_by_code(ERROR, ERRCODE_INVALID_XML_CONTENT,
1109 "invalid XML content: invalid XML declaration", res_code);
1111 res_code = xmlParseBalancedChunkMemory(doc, NULL, NULL, 0, utf8string + count, NULL);
1113 xml_ereport(ERROR, ERRCODE_INVALID_XML_CONTENT,
1114 "invalid XML content");
1116 doc->version = xmlStrdup(version);
1117 doc->encoding = xmlStrdup((xmlChar *) "UTF-8");
1118 doc->standalone = standalone;
1122 xmlFreeParserCtxt(ctxt);
1131 xmlFreeParserCtxt(ctxt);
1143 * xmlChar<->text convertions
1146 xml_text2xmlChar(text *in)
1148 int32 len = VARSIZE(in) - VARHDRSZ;
1151 res = palloc(len + 1);
1152 memcpy(res, VARDATA(in), len);
1160 * Wrappers for memory management functions
1163 xml_palloc(size_t size)
1165 return palloc(size);
1170 xml_repalloc(void *ptr, size_t size)
1172 return repalloc(ptr, size);
1177 xml_pfree(void *ptr)
1184 xml_pstrdup(const char *string)
1186 return pstrdup(string);
1191 * Wrapper for "ereport" function for XML-related errors. The "msg"
1192 * is the SQL-level message; some can be adopted from the SQL/XML
1193 * standard. This function adds libxml's native error messages, if
1197 xml_ereport(int level, int sqlcode,
1202 if (xml_err_buf->len > 0)
1204 detail = pstrdup(xml_err_buf->data);
1205 resetStringInfo(xml_err_buf);
1210 /* libxml error messages end in '\n'; get rid of it */
1215 len = strlen(detail);
1216 if (len > 0 && detail[len-1] == '\n')
1217 detail[len-1] = '\0';
1222 errdetail("%s", detail)));
1228 errmsg("%s", msg)));
1234 * Error handler for libxml error messages
1237 xml_errorHandler(void *ctxt, const char *msg,...)
1239 /* Append the formatted text to xml_err_buf */
1245 /* Try to format the data. */
1246 va_start(args, msg);
1247 success = appendStringInfoVA(xml_err_buf, msg, args);
1253 /* Double the buffer size and try again. */
1254 enlargeStringInfo(xml_err_buf, xml_err_buf->maxlen);
1260 * Wrapper for "ereport" function for XML-related errors. The "msg"
1261 * is the SQL-level message; some can be adopted from the SQL/XML
1262 * standard. This function uses "code" to create a textual detail
1263 * message. At the moment, we only need to cover those codes that we
1264 * may raise in this file.
1267 xml_ereport_by_code(int level, int sqlcode,
1268 const char *msg, int code)
1274 case XML_ERR_INVALID_CHAR:
1275 det = "Invalid character value";
1277 case XML_ERR_SPACE_REQUIRED:
1278 det = "Space required";
1280 case XML_ERR_STANDALONE_VALUE:
1281 det = "standalone accepts only 'yes' or 'no'";
1283 case XML_ERR_VERSION_MISSING:
1284 det = "Malformed declaration expecting version";
1286 case XML_ERR_MISSING_ENCODING:
1287 det = "Missing encoding in text declaration";
1289 case XML_ERR_XMLDECL_NOT_FINISHED:
1290 det = "Parsing XML declaration: '?>' expected";
1293 det = "Unrecognized libxml error code: %d";
1300 errdetail(det, code)));
1305 * Convert one char in the current server encoding to a Unicode codepoint.
1308 sqlchar_to_unicode(char *s)
1311 pg_wchar ret[2]; /* need space for trailing zero */
1313 utf8string = (char *) pg_do_encoding_conversion((unsigned char *) s,
1315 GetDatabaseEncoding(),
1318 pg_encoding_mb2wchar_with_len(PG_UTF8, utf8string, ret, pg_mblen(s));
1325 is_valid_xml_namefirst(pg_wchar c)
1327 /* (Letter | '_' | ':') */
1328 return (xmlIsBaseCharQ(c) || xmlIsIdeographicQ(c)
1329 || c == '_' || c == ':');
1334 is_valid_xml_namechar(pg_wchar c)
1336 /* Letter | Digit | '.' | '-' | '_' | ':' | CombiningChar | Extender */
1337 return (xmlIsBaseCharQ(c) || xmlIsIdeographicQ(c)
1339 || c == '.' || c == '-' || c == '_' || c == ':'
1340 || xmlIsCombiningQ(c)
1341 || xmlIsExtenderQ(c));
1343 #endif /* USE_LIBXML */
1347 * Map SQL identifier to XML name; see SQL/XML:2003 section 9.1.
1350 map_sql_identifier_to_xml_name(char *ident, bool fully_escaped, bool escape_period)
1357 * SQL/XML doesn't make use of this case anywhere, so it's
1358 * probably a mistake.
1360 Assert(fully_escaped || !escape_period);
1362 initStringInfo(&buf);
1364 for (p = ident; *p; p += pg_mblen(p))
1366 if (*p == ':' && (p == ident || fully_escaped))
1367 appendStringInfo(&buf, "_x003A_");
1368 else if (*p == '_' && *(p+1) == 'x')
1369 appendStringInfo(&buf, "_x005F_");
1370 else if (fully_escaped && p == ident &&
1371 pg_strncasecmp(p, "xml", 3) == 0)
1374 appendStringInfo(&buf, "_x0078_");
1376 appendStringInfo(&buf, "_x0058_");
1378 else if (escape_period && *p == '.')
1379 appendStringInfo(&buf, "_x002E_");
1382 pg_wchar u = sqlchar_to_unicode(p);
1385 ? !is_valid_xml_namefirst(u)
1386 : !is_valid_xml_namechar(u))
1387 appendStringInfo(&buf, "_x%04X_", (unsigned int) u);
1389 appendBinaryStringInfo(&buf, p, pg_mblen(p));
1394 #else /* not USE_LIBXML */
1397 #endif /* not USE_LIBXML */
1402 * Map a Unicode codepoint into the current server encoding.
1405 unicode_to_sqlchar(pg_wchar c)
1407 static unsigned char utf8string[5]; /* need trailing zero */
1413 else if (c <= 0x7FF)
1415 utf8string[0] = 0xC0 | ((c >> 6) & 0x1F);
1416 utf8string[1] = 0x80 | (c & 0x3F);
1418 else if (c <= 0xFFFF)
1420 utf8string[0] = 0xE0 | ((c >> 12) & 0x0F);
1421 utf8string[1] = 0x80 | ((c >> 6) & 0x3F);
1422 utf8string[2] = 0x80 | (c & 0x3F);
1426 utf8string[0] = 0xF0 | ((c >> 18) & 0x07);
1427 utf8string[1] = 0x80 | ((c >> 12) & 0x3F);
1428 utf8string[2] = 0x80 | ((c >> 6) & 0x3F);
1429 utf8string[3] = 0x80 | (c & 0x3F);
1432 return (char *) pg_do_encoding_conversion(utf8string,
1433 pg_mblen((char *) utf8string),
1435 GetDatabaseEncoding());
1440 * Map XML name to SQL identifier; see SQL/XML:2003 section 9.17.
1443 map_xml_name_to_sql_identifier(char *name)
1448 initStringInfo(&buf);
1450 for (p = name; *p; p += pg_mblen(p))
1452 if (*p == '_' && *(p+1) == 'x'
1453 && isxdigit((unsigned char) *(p+2))
1454 && isxdigit((unsigned char) *(p+3))
1455 && isxdigit((unsigned char) *(p+4))
1456 && isxdigit((unsigned char) *(p+5))
1461 sscanf(p + 2, "%X", &u);
1462 appendStringInfoString(&buf, unicode_to_sqlchar(u));
1466 appendBinaryStringInfo(&buf, p, pg_mblen(p));
1473 * Map SQL value to XML value; see SQL/XML:2003 section 9.16.
1476 map_sql_value_to_xml_value(Datum value, Oid type)
1480 initStringInfo(&buf);
1482 if (is_array_type(type))
1491 array = DatumGetArrayTypeP(value);
1493 /* TODO: need some code-fu here to remove this limitation */
1494 if (ARR_NDIM(array) != 1)
1496 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1497 errmsg("only supported for one-dimensional array")));
1499 elmtype = ARR_ELEMTYPE(array);
1500 get_typlenbyvalalign(elmtype, &elmlen, &elmbyval, &elmalign);
1502 for (i = ARR_LBOUND(array)[0];
1503 i < ARR_LBOUND(array)[0] + ARR_DIMS(array)[0];
1509 subval = array_ref(array, 1, &i, -1, elmlen, elmbyval, elmalign, &isnull);
1510 appendStringInfoString(&buf, "<element>");
1511 appendStringInfoString(&buf, map_sql_value_to_xml_value(subval, elmtype));
1512 appendStringInfoString(&buf, "</element>");
1522 * Special XSD formatting for some data types
1527 if (DatumGetBool(value))
1536 char buf[MAXDATELEN + 1];
1538 date = DatumGetDateADT(value);
1539 j2date(date + POSTGRES_EPOCH_JDATE,
1540 &(tm.tm_year), &(tm.tm_mon), &(tm.tm_mday));
1541 EncodeDateOnly(&tm, USE_XSD_DATES, buf);
1543 return pstrdup(buf);
1548 Timestamp timestamp;
1552 char buf[MAXDATELEN + 1];
1554 timestamp = DatumGetTimestamp(value);
1556 /* XSD doesn't support infinite values */
1557 if (TIMESTAMP_NOT_FINITE(timestamp))
1559 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
1560 errmsg("timestamp out of range")));
1561 else if (timestamp2tm(timestamp, NULL, &tm, &fsec, NULL, NULL) == 0)
1562 EncodeDateTime(&tm, fsec, NULL, &tzn, USE_XSD_DATES, buf);
1565 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
1566 errmsg("timestamp out of range")));
1568 return pstrdup(buf);
1571 case TIMESTAMPTZOID:
1573 TimestampTz timestamp;
1578 char buf[MAXDATELEN + 1];
1580 timestamp = DatumGetTimestamp(value);
1582 /* XSD doesn't support infinite values */
1583 if (TIMESTAMP_NOT_FINITE(timestamp))
1585 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
1586 errmsg("timestamp out of range")));
1587 else if (timestamp2tm(timestamp, &tz, &tm, &fsec, &tzn, NULL) == 0)
1588 EncodeDateTime(&tm, fsec, &tz, &tzn, USE_XSD_DATES, buf);
1591 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
1592 errmsg("timestamp out of range")));
1594 return pstrdup(buf);
1598 getTypeOutputInfo(type, &typeOut, &isvarlena);
1599 str = OidOutputFunctionCall(typeOut, value);
1605 if (type == BYTEAOID)
1608 xmlTextWriterPtr writer;
1611 buf = xmlBufferCreate();
1612 writer = xmlNewTextWriterMemory(buf, 0);
1614 if (xmlbinary == XMLBINARY_BASE64)
1615 xmlTextWriterWriteBase64(writer, VARDATA(value), 0, VARSIZE(value) - VARHDRSZ);
1617 xmlTextWriterWriteBinHex(writer, VARDATA(value), 0, VARSIZE(value) - VARHDRSZ);
1619 xmlFreeTextWriter(writer);
1620 result = pstrdup((const char *) xmlBufferContent(buf));
1624 #endif /* USE_LIBXML */
1626 for (p = str; *p; p += pg_mblen(p))
1631 appendStringInfo(&buf, "&");
1634 appendStringInfo(&buf, "<");
1637 appendStringInfo(&buf, ">");
1640 appendStringInfo(&buf, "
");
1643 appendBinaryStringInfo(&buf, p, pg_mblen(p));
1654 _SPI_strdup(const char *s)
1656 char *ret = SPI_palloc(strlen(s) + 1);
1663 * SQL to XML mapping functions
1665 * What follows below is intentionally organized so that you can read
1666 * along in the SQL/XML:2003 standard. The functions are mostly split
1667 * up and ordered they way the clauses lay out in the standards
1668 * document, and the identifiers are also aligned with the standard
1669 * text. (SQL/XML:2006 appears to be ordered differently,
1672 * There are many things going on there:
1674 * There are two kinds of mappings: Mapping SQL data (table contents)
1675 * to XML documents, and mapping SQL structure (the "schema") to XML
1676 * Schema. And there are functions that do both at the same time.
1678 * Then you can map a database, a schema, or a table, each in both
1679 * ways. This breaks down recursively: Mapping a database invokes
1680 * mapping schemas, which invokes mapping tables, which invokes
1681 * mapping rows, which invokes mapping columns, although you can't
1682 * call the last two from the outside. Because of this, there are a
1683 * number of xyz_internal() functions which are to be called both from
1684 * the function manager wrapper and from some upper layer in a
1687 * See the documentation about what the common function arguments
1688 * nulls, tableforest, and targetns mean.
1690 * Some style guidelines for XML output: Use double quotes for quoting
1691 * XML attributes. Indent XML elements by two spaces, but remember
1692 * that a lot of code is called recursively at different levels, so
1693 * it's better not to indent rather than create output that indents
1694 * and outdents weirdly. Add newlines to make the output look nice.
1699 * Visibility of objects for XML mappings; see SQL/XML:2003 section
1704 * Given a query, which must return type oid as first column, produce
1705 * a list of Oids with the query results.
1708 query_to_oid_list(const char *query)
1713 SPI_execute(query, true, 0);
1715 for (i = 0; i < SPI_processed; i++)
1720 oid = DatumGetObjectId(SPI_getbinval(SPI_tuptable->vals[i], SPI_tuptable->tupdesc, 1, &isnull));
1723 list = lappend_oid(list, oid);
1731 schema_get_xml_visible_tables(Oid nspid)
1733 StringInfoData query;
1735 initStringInfo(&query);
1736 appendStringInfo(&query, "SELECT oid FROM pg_class WHERE relnamespace = %u AND relkind IN ('r', 'v') AND has_table_privilege (oid, 'SELECT') ORDER BY relname;", nspid);
1738 return query_to_oid_list(query.data);
1743 * Including the system schemas is probably not useful for a database
1746 #define XML_VISIBLE_SCHEMAS_EXCLUDE "nspname LIKE 'pg_%' ESCAPE '' OR nspname = 'information_schema'"
1748 #define XML_VISIBLE_SCHEMAS "SELECT oid FROM pg_namespace WHERE has_schema_privilege (oid, 'USAGE') AND NOT (" XML_VISIBLE_SCHEMAS_EXCLUDE ")"
1752 database_get_xml_visible_schemas(void)
1754 return query_to_oid_list(XML_VISIBLE_SCHEMAS " ORDER BY nspname;");
1759 database_get_xml_visible_tables(void)
1761 /* At the moment there is no order required here. */
1762 return query_to_oid_list("SELECT oid FROM pg_class WHERE relkind IN ('r', 'v') AND has_table_privilege (pg_class.oid, 'SELECT') AND relnamespace IN (" XML_VISIBLE_SCHEMAS ");");
1767 * Map SQL table to XML and/or XML Schema document; see SQL/XML:2003
1772 table_to_xml_internal(Oid relid, bool nulls, bool tableforest, const char *targetns, bool top_level)
1774 StringInfoData query;
1776 initStringInfo(&query);
1777 appendStringInfo(&query, "SELECT * FROM %s", DatumGetCString(DirectFunctionCall1(regclassout, ObjectIdGetDatum(relid))));
1778 return query_to_xml_internal(query.data, get_rel_name(relid), NULL, nulls, tableforest, targetns, top_level);
1783 table_to_xml(PG_FUNCTION_ARGS)
1785 Oid relid = PG_GETARG_OID(0);
1786 bool nulls = PG_GETARG_BOOL(1);
1787 bool tableforest = PG_GETARG_BOOL(2);
1788 const char *targetns = _textout(PG_GETARG_TEXT_P(3));
1790 PG_RETURN_XML_P(stringinfo_to_xmltype(table_to_xml_internal(relid, nulls, tableforest, targetns, true)));
1795 query_to_xml(PG_FUNCTION_ARGS)
1797 char *query = _textout(PG_GETARG_TEXT_P(0));
1798 bool nulls = PG_GETARG_BOOL(1);
1799 bool tableforest = PG_GETARG_BOOL(2);
1800 const char *targetns = _textout(PG_GETARG_TEXT_P(3));
1802 PG_RETURN_XML_P(stringinfo_to_xmltype(query_to_xml_internal(query, NULL, NULL, nulls, tableforest, targetns, true)));
1807 cursor_to_xml(PG_FUNCTION_ARGS)
1809 char *name = _textout(PG_GETARG_TEXT_P(0));
1810 int32 count = PG_GETARG_INT32(1);
1811 bool nulls = PG_GETARG_BOOL(2);
1812 bool tableforest = PG_GETARG_BOOL(3);
1813 const char *targetns = _textout(PG_GETARG_TEXT_P(4));
1815 StringInfoData result;
1819 initStringInfo(&result);
1822 portal = SPI_cursor_find(name);
1825 (errcode(ERRCODE_UNDEFINED_CURSOR),
1826 errmsg("cursor \"%s\" does not exist", name)));
1828 SPI_cursor_fetch(portal, true, count);
1829 for (i = 0; i < SPI_processed; i++)
1830 SPI_sql_row_to_xmlelement(i, &result, NULL, nulls, tableforest, targetns, true);
1834 PG_RETURN_XML_P(stringinfo_to_xmltype(&result));
1839 * Write the start tag of the root element of a data mapping.
1841 * top_level means that this is the very top level of the eventual
1842 * output. For example, when the user calls table_to_xml, then a call
1843 * with a table name to this function is the top level. When the user
1844 * calls database_to_xml, then a call with a schema name to this
1845 * function is not the top level. If top_level is false, then the XML
1846 * namespace declarations are omitted, because they supposedly already
1847 * appeared earlier in the output. Repeating them is not wrong, but
1851 xmldata_root_element_start(StringInfo result, const char *eltname, const char *xmlschema, const char *targetns, bool top_level)
1853 /* This isn't really wrong but currently makes no sense. */
1854 Assert(top_level || !xmlschema);
1856 appendStringInfo(result, "<%s", eltname);
1859 appendStringInfoString(result, " xmlns:xsi=\"" NAMESPACE_XSI "\"");
1860 if (strlen(targetns) > 0)
1861 appendStringInfo(result, " xmlns=\"%s\"", targetns);
1865 /* FIXME: better targets */
1866 if (strlen(targetns) > 0)
1867 appendStringInfo(result, " xsi:schemaLocation=\"%s #\"", targetns);
1869 appendStringInfo(result, " xsi:noNamespaceSchemaLocation=\"#\"");
1871 appendStringInfo(result, ">\n\n");
1876 xmldata_root_element_end(StringInfo result, const char *eltname)
1878 appendStringInfo(result, "</%s>\n", eltname);
1883 query_to_xml_internal(const char *query, char *tablename, const char *xmlschema, bool nulls, bool tableforest, const char *targetns, bool top_level)
1890 xmltn = map_sql_identifier_to_xml_name(tablename, true, false);
1894 result = makeStringInfo();
1897 if (SPI_execute(query, true, 0) != SPI_OK_SELECT)
1899 (errcode(ERRCODE_DATA_EXCEPTION),
1900 errmsg("invalid query")));
1903 xmldata_root_element_start(result, xmltn, xmlschema, targetns, top_level);
1906 appendStringInfo(result, "%s\n\n", xmlschema);
1908 for(i = 0; i < SPI_processed; i++)
1909 SPI_sql_row_to_xmlelement(i, result, tablename, nulls, tableforest, targetns, top_level);
1912 xmldata_root_element_end(result, xmltn);
1921 table_to_xmlschema(PG_FUNCTION_ARGS)
1923 Oid relid = PG_GETARG_OID(0);
1924 bool nulls = PG_GETARG_BOOL(1);
1925 bool tableforest = PG_GETARG_BOOL(2);
1926 const char *targetns = _textout(PG_GETARG_TEXT_P(3));
1931 rel = heap_open(relid, AccessShareLock);
1932 result = map_sql_table_to_xmlschema(rel->rd_att, relid, nulls, tableforest, targetns);
1933 heap_close(rel, NoLock);
1935 PG_RETURN_XML_P(cstring_to_xmltype(result));
1940 query_to_xmlschema(PG_FUNCTION_ARGS)
1942 char *query = _textout(PG_GETARG_TEXT_P(0));
1943 bool nulls = PG_GETARG_BOOL(1);
1944 bool tableforest = PG_GETARG_BOOL(2);
1945 const char *targetns = _textout(PG_GETARG_TEXT_P(3));
1952 plan = SPI_prepare(query, 0, NULL);
1953 portal = SPI_cursor_open(NULL, plan, NULL, NULL, true);
1954 result = _SPI_strdup(map_sql_table_to_xmlschema(portal->tupDesc, InvalidOid, nulls, tableforest, targetns));
1955 SPI_cursor_close(portal);
1958 PG_RETURN_XML_P(cstring_to_xmltype(result));
1963 cursor_to_xmlschema(PG_FUNCTION_ARGS)
1965 char *name = _textout(PG_GETARG_TEXT_P(0));
1966 bool nulls = PG_GETARG_BOOL(1);
1967 bool tableforest = PG_GETARG_BOOL(2);
1968 const char *targetns = _textout(PG_GETARG_TEXT_P(3));
1970 const char *xmlschema;
1974 portal = SPI_cursor_find(name);
1977 (errcode(ERRCODE_UNDEFINED_CURSOR),
1978 errmsg("cursor \"%s\" does not exist", name)));
1980 xmlschema = _SPI_strdup(map_sql_table_to_xmlschema(portal->tupDesc, InvalidOid, nulls, tableforest, targetns));
1983 PG_RETURN_XML_P(cstring_to_xmltype(xmlschema));
1988 table_to_xml_and_xmlschema(PG_FUNCTION_ARGS)
1990 Oid relid = PG_GETARG_OID(0);
1991 bool nulls = PG_GETARG_BOOL(1);
1992 bool tableforest = PG_GETARG_BOOL(2);
1993 const char *targetns = _textout(PG_GETARG_TEXT_P(3));
1995 StringInfoData query;
1997 const char *xmlschema;
1999 rel = heap_open(relid, AccessShareLock);
2000 xmlschema = map_sql_table_to_xmlschema(rel->rd_att, relid, nulls, tableforest, targetns);
2001 heap_close(rel, NoLock);
2003 initStringInfo(&query);
2004 appendStringInfo(&query, "SELECT * FROM %s", DatumGetCString(DirectFunctionCall1(regclassout, ObjectIdGetDatum(relid))));
2006 PG_RETURN_XML_P(stringinfo_to_xmltype(query_to_xml_internal(query.data, get_rel_name(relid), xmlschema, nulls, tableforest, targetns, true)));
2011 query_to_xml_and_xmlschema(PG_FUNCTION_ARGS)
2013 char *query = _textout(PG_GETARG_TEXT_P(0));
2014 bool nulls = PG_GETARG_BOOL(1);
2015 bool tableforest = PG_GETARG_BOOL(2);
2016 const char *targetns = _textout(PG_GETARG_TEXT_P(3));
2018 const char *xmlschema;
2023 plan = SPI_prepare(query, 0, NULL);
2024 portal = SPI_cursor_open(NULL, plan, NULL, NULL, true);
2025 xmlschema = _SPI_strdup(map_sql_table_to_xmlschema(portal->tupDesc, InvalidOid, nulls, tableforest, targetns));
2026 SPI_cursor_close(portal);
2029 PG_RETURN_XML_P(stringinfo_to_xmltype(query_to_xml_internal(query, NULL, xmlschema, nulls, tableforest, targetns, true)));
2034 * Map SQL schema to XML and/or XML Schema document; see SQL/XML:2003
2039 schema_to_xml_internal(Oid nspid, const char *xmlschema, bool nulls, bool tableforest, const char *targetns, bool top_level)
2046 xmlsn = map_sql_identifier_to_xml_name(get_namespace_name(nspid), true, false);
2047 result = makeStringInfo();
2049 xmldata_root_element_start(result, xmlsn, xmlschema, targetns, top_level);
2052 appendStringInfo(result, "%s\n\n", xmlschema);
2056 relid_list = schema_get_xml_visible_tables(nspid);
2060 foreach(cell, relid_list)
2062 Oid relid = lfirst_oid(cell);
2065 subres = table_to_xml_internal(relid, nulls, tableforest, targetns, false);
2067 appendStringInfoString(result, subres->data);
2068 appendStringInfoChar(result, '\n');
2074 xmldata_root_element_end(result, xmlsn);
2081 schema_to_xml(PG_FUNCTION_ARGS)
2083 Name name = PG_GETARG_NAME(0);
2084 bool nulls = PG_GETARG_BOOL(1);
2085 bool tableforest = PG_GETARG_BOOL(2);
2086 const char *targetns = _textout(PG_GETARG_TEXT_P(3));
2091 schemaname = NameStr(*name);
2092 nspid = LookupExplicitNamespace(schemaname);
2094 PG_RETURN_XML_P(stringinfo_to_xmltype(schema_to_xml_internal(nspid, NULL, nulls, tableforest, targetns, true)));
2099 * Write the start element of the root element of an XML Schema mapping.
2102 xsd_schema_element_start(StringInfo result, const char *targetns)
2104 appendStringInfoString(result,
2106 " xmlns:xsd=\"" NAMESPACE_XSD "\"");
2107 if (strlen(targetns) > 0)
2108 appendStringInfo(result,
2110 " targetNamespace=\"%s\"\n"
2111 " elementFormDefault=\"qualified\"",
2113 appendStringInfoString(result,
2119 xsd_schema_element_end(StringInfo result)
2121 appendStringInfoString(result,
2127 schema_to_xmlschema_internal(const char *schemaname, bool nulls, bool tableforest, const char *targetns)
2135 result = makeStringInfo();
2137 nspid = LookupExplicitNamespace(schemaname);
2139 xsd_schema_element_start(result, targetns);
2143 relid_list = schema_get_xml_visible_tables(nspid);
2146 foreach (cell, relid_list)
2150 rel = heap_open(lfirst_oid(cell), AccessShareLock);
2151 tupdesc_list = lappend(tupdesc_list, rel->rd_att);
2152 heap_close(rel, NoLock);
2155 appendStringInfoString(result,
2156 map_sql_typecoll_to_xmlschema_types(tupdesc_list));
2158 appendStringInfoString(result,
2159 map_sql_schema_to_xmlschema_types(nspid, relid_list, nulls, tableforest, targetns));
2161 xsd_schema_element_end(result);
2170 schema_to_xmlschema(PG_FUNCTION_ARGS)
2172 Name name = PG_GETARG_NAME(0);
2173 bool nulls = PG_GETARG_BOOL(1);
2174 bool tableforest = PG_GETARG_BOOL(2);
2175 const char *targetns = _textout(PG_GETARG_TEXT_P(3));
2177 PG_RETURN_XML_P(stringinfo_to_xmltype(schema_to_xmlschema_internal(NameStr(*name), nulls, tableforest, targetns)));
2182 schema_to_xml_and_xmlschema(PG_FUNCTION_ARGS)
2184 Name name = PG_GETARG_NAME(0);
2185 bool nulls = PG_GETARG_BOOL(1);
2186 bool tableforest = PG_GETARG_BOOL(2);
2187 const char *targetns = _textout(PG_GETARG_TEXT_P(3));
2191 StringInfo xmlschema;
2193 schemaname = NameStr(*name);
2194 nspid = LookupExplicitNamespace(schemaname);
2196 xmlschema = schema_to_xmlschema_internal(schemaname, nulls, tableforest, targetns);
2198 PG_RETURN_XML_P(stringinfo_to_xmltype(schema_to_xml_internal(nspid, xmlschema->data, nulls, tableforest, targetns, true)));
2203 * Map SQL database to XML and/or XML Schema document; see SQL/XML:2003
2208 database_to_xml_internal(const char *xmlschema, bool nulls, bool tableforest, const char *targetns)
2215 xmlcn = map_sql_identifier_to_xml_name(get_database_name(MyDatabaseId), true, false);
2216 result = makeStringInfo();
2218 xmldata_root_element_start(result, xmlcn, xmlschema, targetns, true);
2221 appendStringInfo(result, "%s\n\n", xmlschema);
2225 nspid_list = database_get_xml_visible_schemas();
2229 foreach(cell, nspid_list)
2231 Oid nspid = lfirst_oid(cell);
2234 subres = schema_to_xml_internal(nspid, NULL, nulls, tableforest, targetns, false);
2236 appendStringInfoString(result, subres->data);
2237 appendStringInfoChar(result, '\n');
2243 xmldata_root_element_end(result, xmlcn);
2250 database_to_xml(PG_FUNCTION_ARGS)
2252 bool nulls = PG_GETARG_BOOL(0);
2253 bool tableforest = PG_GETARG_BOOL(1);
2254 const char *targetns = _textout(PG_GETARG_TEXT_P(2));
2256 PG_RETURN_XML_P(stringinfo_to_xmltype(database_to_xml_internal(NULL, nulls, tableforest, targetns)));
2261 database_to_xmlschema_internal(bool nulls, bool tableforest, const char *targetns)
2269 result = makeStringInfo();
2271 xsd_schema_element_start(result, targetns);
2275 relid_list = database_get_xml_visible_tables();
2276 nspid_list = database_get_xml_visible_schemas();
2279 foreach (cell, relid_list)
2283 rel = heap_open(lfirst_oid(cell), AccessShareLock);
2284 tupdesc_list = lappend(tupdesc_list, rel->rd_att);
2285 heap_close(rel, NoLock);
2288 appendStringInfoString(result,
2289 map_sql_typecoll_to_xmlschema_types(tupdesc_list));
2291 appendStringInfoString(result,
2292 map_sql_catalog_to_xmlschema_types(nspid_list, nulls, tableforest, targetns));
2294 xsd_schema_element_end(result);
2303 database_to_xmlschema(PG_FUNCTION_ARGS)
2305 bool nulls = PG_GETARG_BOOL(0);
2306 bool tableforest = PG_GETARG_BOOL(1);
2307 const char *targetns = _textout(PG_GETARG_TEXT_P(2));
2309 PG_RETURN_XML_P(stringinfo_to_xmltype(database_to_xmlschema_internal(nulls, tableforest, targetns)));
2314 database_to_xml_and_xmlschema(PG_FUNCTION_ARGS)
2316 bool nulls = PG_GETARG_BOOL(0);
2317 bool tableforest = PG_GETARG_BOOL(1);
2318 const char *targetns = _textout(PG_GETARG_TEXT_P(2));
2320 StringInfo xmlschema;
2322 xmlschema = database_to_xmlschema_internal(nulls, tableforest, targetns);
2324 PG_RETURN_XML_P(stringinfo_to_xmltype(database_to_xml_internal(xmlschema->data, nulls, tableforest, targetns)));
2329 * Map a multi-part SQL name to an XML name; see SQL/XML:2003 section
2333 map_multipart_sql_identifier_to_xml_name(char *a, char *b, char *c, char *d)
2335 StringInfoData result;
2337 initStringInfo(&result);
2340 appendStringInfo(&result, "%s", map_sql_identifier_to_xml_name(a, true, true));
2342 appendStringInfo(&result, ".%s", map_sql_identifier_to_xml_name(b, true, true));
2344 appendStringInfo(&result, ".%s", map_sql_identifier_to_xml_name(c, true, true));
2346 appendStringInfo(&result, ".%s", map_sql_identifier_to_xml_name(d, true, true));
2353 * Map an SQL table to an XML Schema document; see SQL/XML:2003
2356 * Map an SQL table to XML Schema data types; see SQL/XML:2003 section
2360 map_sql_table_to_xmlschema(TupleDesc tupdesc, Oid relid, bool nulls, bool tableforest, const char *targetns)
2364 char *tabletypename;
2366 StringInfoData result;
2368 initStringInfo(&result);
2372 HeapTuple tuple = SearchSysCache(RELOID, ObjectIdGetDatum(relid), 0, 0, 0);
2373 Form_pg_class reltuple = (Form_pg_class) GETSTRUCT(tuple);
2375 xmltn = map_sql_identifier_to_xml_name(NameStr(reltuple->relname), true, false);
2377 tabletypename = map_multipart_sql_identifier_to_xml_name("TableType",
2378 get_database_name(MyDatabaseId),
2379 get_namespace_name(reltuple->relnamespace),
2380 NameStr(reltuple->relname));
2382 rowtypename = map_multipart_sql_identifier_to_xml_name("RowType",
2383 get_database_name(MyDatabaseId),
2384 get_namespace_name(reltuple->relnamespace),
2385 NameStr(reltuple->relname));
2387 ReleaseSysCache(tuple);
2396 tabletypename = "TableType";
2397 rowtypename = "RowType";
2400 xsd_schema_element_start(&result, targetns);
2402 appendStringInfoString(&result,
2403 map_sql_typecoll_to_xmlschema_types(list_make1(tupdesc)));
2405 appendStringInfo(&result,
2406 "<xsd:complexType name=\"%s\">\n"
2407 " <xsd:sequence>\n",
2410 for (i = 0; i < tupdesc->natts; i++)
2411 appendStringInfo(&result,
2412 " <xsd:element name=\"%s\" type=\"%s\"%s></xsd:element>\n",
2413 map_sql_identifier_to_xml_name(NameStr(tupdesc->attrs[i]->attname), true, false),
2414 map_sql_type_to_xml_name(tupdesc->attrs[i]->atttypid, -1),
2415 nulls ? " nillable=\"true\"" : " minOccurs=\"0\"");
2417 appendStringInfoString(&result,
2418 " </xsd:sequence>\n"
2419 "</xsd:complexType>\n\n");
2423 appendStringInfo(&result,
2424 "<xsd:complexType name=\"%s\">\n"
2426 " <xsd:element name=\"row\" type=\"%s\" minOccurs=\"0\" maxOccurs=\"unbounded\"/>\n"
2427 " </xsd:sequence>\n"
2428 "</xsd:complexType>\n\n",
2429 tabletypename, rowtypename);
2431 appendStringInfo(&result,
2432 "<xsd:element name=\"%s\" type=\"%s\"/>\n\n",
2433 xmltn, tabletypename);
2436 appendStringInfo(&result,
2437 "<xsd:element name=\"%s\" type=\"%s\"/>\n\n",
2438 xmltn, rowtypename);
2440 xsd_schema_element_end(&result);
2447 * Map an SQL schema to XML Schema data types; see SQL/XML section
2451 map_sql_schema_to_xmlschema_types(Oid nspid, List *relid_list, bool nulls, bool tableforest, const char *targetns)
2454 char *schematypename;
2455 StringInfoData result;
2458 initStringInfo(&result);
2460 xmlsn = map_sql_identifier_to_xml_name(get_namespace_name(nspid), true, false);
2462 schematypename = map_multipart_sql_identifier_to_xml_name("SchemaType",
2463 get_database_name(MyDatabaseId),
2464 get_namespace_name(nspid),
2467 appendStringInfo(&result,
2468 "<xsd:complexType name=\"%s\">\n", schematypename);
2470 appendStringInfoString(&result,
2473 appendStringInfoString(&result,
2474 " <xsd:sequence>\n");
2476 foreach (cell, relid_list)
2478 Oid relid = lfirst_oid(cell);
2479 char *xmltn = map_sql_identifier_to_xml_name(get_rel_name(relid), true, false);
2480 char *tabletypename = map_multipart_sql_identifier_to_xml_name(tableforest ? "RowType" : "TableType",
2481 get_database_name(MyDatabaseId),
2482 get_namespace_name(nspid),
2483 get_rel_name(relid));
2486 appendStringInfo(&result,
2487 " <xsd:element name=\"%s\" type=\"%s\" />\n",
2488 xmltn, tabletypename);
2490 appendStringInfo(&result,
2491 " <xsd:element name=\"%s\" type=\"%s\" minOccurs=\"0\" maxOccurs=\"unbounded\" />\n",
2492 xmltn, tabletypename);
2496 appendStringInfoString(&result,
2499 appendStringInfoString(&result,
2500 " </xsd:sequence>\n");
2501 appendStringInfoString(&result,
2502 "</xsd:complexType>\n\n");
2504 appendStringInfo(&result,
2505 "<xsd:element name=\"%s\" type=\"%s\"/>\n\n",
2506 xmlsn, schematypename);
2513 * Map an SQL catalog to XML Schema data types; see SQL/XML section
2517 map_sql_catalog_to_xmlschema_types(List *nspid_list, bool nulls, bool tableforest, const char *targetns)
2520 char *catalogtypename;
2521 StringInfoData result;
2524 initStringInfo(&result);
2526 xmlcn = map_sql_identifier_to_xml_name(get_database_name(MyDatabaseId), true, false);
2528 catalogtypename = map_multipart_sql_identifier_to_xml_name("CatalogType",
2529 get_database_name(MyDatabaseId),
2533 appendStringInfo(&result,
2534 "<xsd:complexType name=\"%s\">\n", catalogtypename);
2535 appendStringInfoString(&result,
2538 foreach (cell, nspid_list)
2540 Oid nspid = lfirst_oid(cell);
2541 char *xmlsn = map_sql_identifier_to_xml_name(get_namespace_name(nspid), true, false);
2542 char *schematypename = map_multipart_sql_identifier_to_xml_name("SchemaType",
2543 get_database_name(MyDatabaseId),
2544 get_namespace_name(nspid),
2547 appendStringInfo(&result,
2548 " <xsd:element name=\"%s\" type=\"%s\" />\n",
2549 xmlsn, schematypename);
2552 appendStringInfoString(&result,
2554 appendStringInfoString(&result,
2555 "</xsd:complexType>\n\n");
2557 appendStringInfo(&result,
2558 "<xsd:element name=\"%s\" type=\"%s\"/>\n\n",
2559 xmlcn, catalogtypename);
2566 * Map an SQL data type to an XML name; see SQL/XML:2003 section 9.9.
2569 map_sql_type_to_xml_name(Oid typeoid, int typmod)
2571 StringInfoData result;
2573 initStringInfo(&result);
2579 appendStringInfo(&result, "CHAR");
2581 appendStringInfo(&result, "CHAR_%d", typmod - VARHDRSZ);
2585 appendStringInfo(&result, "VARCHAR");
2587 appendStringInfo(&result, "VARCHAR_%d", typmod - VARHDRSZ);
2591 appendStringInfo(&result, "NUMERIC");
2593 appendStringInfo(&result, "NUMERIC_%d_%d",
2594 ((typmod - VARHDRSZ) >> 16) & 0xffff,
2595 (typmod - VARHDRSZ) & 0xffff);
2598 appendStringInfo(&result, "INTEGER");
2601 appendStringInfo(&result, "SMALLINT");
2604 appendStringInfo(&result, "BIGINT");
2607 appendStringInfo(&result, "REAL");
2610 appendStringInfo(&result, "DOUBLE");
2613 appendStringInfo(&result, "BOOLEAN");
2617 appendStringInfo(&result, "TIME");
2619 appendStringInfo(&result, "TIME_%d", typmod);
2623 appendStringInfo(&result, "TIME_WTZ");
2625 appendStringInfo(&result, "TIME_WTZ_%d", typmod);
2629 appendStringInfo(&result, "TIMESTAMP");
2631 appendStringInfo(&result, "TIMESTAMP_%d", typmod);
2633 case TIMESTAMPTZOID:
2635 appendStringInfo(&result, "TIMESTAMP_WTZ");
2637 appendStringInfo(&result, "TIMESTAMP_WTZ_%d", typmod);
2640 appendStringInfo(&result, "DATE");
2643 appendStringInfo(&result, "XML");
2647 HeapTuple tuple = SearchSysCache(TYPEOID, ObjectIdGetDatum(typeoid), 0, 0, 0);
2648 Form_pg_type typtuple = (Form_pg_type) GETSTRUCT(tuple);
2650 appendStringInfoString(&result,
2651 map_multipart_sql_identifier_to_xml_name((typtuple->typtype == TYPTYPE_DOMAIN) ? "Domain" : "UDT",
2652 get_database_name(MyDatabaseId),
2653 get_namespace_name(typtuple->typnamespace),
2654 NameStr(typtuple->typname)));
2656 ReleaseSysCache(tuple);
2665 * Map a collection of SQL data types to XML Schema data types; see
2666 * SQL/XML:2002 section 9.10.
2669 map_sql_typecoll_to_xmlschema_types(List *tupdesc_list)
2671 List *uniquetypes = NIL;
2673 StringInfoData result;
2674 ListCell *cell0, *cell1, *cell2;
2676 foreach (cell0, tupdesc_list)
2678 TupleDesc tupdesc = lfirst(cell0);
2680 for (i = 1; i <= tupdesc->natts; i++)
2682 bool already_done = false;
2683 Oid type = SPI_gettypeid(tupdesc, i);
2684 foreach (cell1, uniquetypes)
2685 if (type == lfirst_oid(cell1))
2687 already_done = true;
2693 uniquetypes = lappend_oid(uniquetypes, type);
2697 /* add base types of domains */
2698 foreach (cell1, uniquetypes)
2700 bool already_done = false;
2701 Oid type = getBaseType(lfirst_oid(cell1));
2702 foreach (cell2, uniquetypes)
2703 if (type == lfirst_oid(cell2))
2705 already_done = true;
2711 uniquetypes = lappend_oid(uniquetypes, type);
2714 initStringInfo(&result);
2716 foreach (cell1, uniquetypes)
2717 appendStringInfo(&result, "%s\n", map_sql_type_to_xmlschema_type(lfirst_oid(cell1), -1));
2724 * Map an SQL data type to a named XML Schema data type; see SQL/XML
2725 * sections 9.11 and 9.15.
2727 * (The distinction between 9.11 and 9.15 is basically that 9.15 adds
2728 * a name attribute, which this function does. The name-less version
2729 * 9.11 doesn't appear to be required anywhere.)
2732 map_sql_type_to_xmlschema_type(Oid typeoid, int typmod)
2734 StringInfoData result;
2735 const char *typename = map_sql_type_to_xml_name(typeoid, typmod);
2737 initStringInfo(&result);
2739 if (typeoid == XMLOID)
2741 appendStringInfo(&result,
2742 "<xsd:complexType mixed=\"true\">\n"
2744 " <xsd:any name=\"element\" minOccurs=\"0\" maxOccurs=\"unbounded\" processContents=\"skip\"/>\n"
2745 " </xsd:sequence>\n"
2746 "</xsd:complexType>\n");
2750 appendStringInfo(&result,
2751 "<xsd:simpleType name=\"%s\">\n", typename);
2759 appendStringInfo(&result,
2760 " <xsd:restriction base=\"xsd:string\">\n"
2761 " <xsd:maxLength value=\"%d\"/>\n"
2762 " </xsd:restriction>\n",
2767 appendStringInfo(&result,
2768 " <xsd:restriction base=\"xsd:%s\">\n"
2769 " </xsd:restriction>\n",
2770 xmlbinary == XMLBINARY_BASE64 ? "base64Binary" : "hexBinary");
2774 appendStringInfo(&result,
2775 " <xsd:restriction base=\"xsd:decimal\">\n"
2776 " <xsd:totalDigits value=\"%d\"/>\n"
2777 " <xsd:fractionDigits value=\"%d\"/>\n"
2778 " </xsd:restriction>\n",
2779 ((typmod - VARHDRSZ) >> 16) & 0xffff,
2780 (typmod - VARHDRSZ) & 0xffff);
2784 appendStringInfo(&result,
2785 " <xsd:restriction base=\"xsd:short\">\n"
2786 " <xsd:maxInclusive value=\"%d\"/>\n"
2787 " <xsd:minInclusive value=\"%d\"/>\n"
2788 " </xsd:restriction>\n",
2789 SHRT_MAX, SHRT_MIN);
2793 appendStringInfo(&result,
2794 " <xsd:restriction base='xsd:int'>\n"
2795 " <xsd:maxInclusive value=\"%d\"/>\n"
2796 " <xsd:minInclusive value=\"%d\"/>\n"
2797 " </xsd:restriction>\n",
2802 appendStringInfo(&result,
2803 " <xsd:restriction base=\"xsd:long\">\n"
2804 " <xsd:maxInclusive value=\"" INT64_FORMAT "\"/>\n"
2805 " <xsd:minInclusive value=\"" INT64_FORMAT "\"/>\n"
2806 " </xsd:restriction>\n",
2807 -((INT64CONST(1) << (sizeof(int64) * 8 - 1)) + 1),
2808 (INT64CONST(1) << (sizeof(int64) * 8 - 1)));
2812 appendStringInfo(&result,
2813 " <xsd:restriction base=\"xsd:float\"></xsd:restriction>\n");
2817 appendStringInfo(&result,
2818 " <xsd:restriction base=\"xsd:double\"></xsd:restriction>\n");
2822 appendStringInfo(&result,
2823 " <xsd:restriction base=\"xsd:boolean\"></xsd:restriction>\n");
2829 const char *tz = (typeoid == TIMETZOID ? "(+|-)\\p{Nd}{2}:\\p{Nd}{2}" : "");
2832 appendStringInfo(&result,
2833 " <xsd:restriction base=\"xsd:time\">\n"
2834 " <xsd:pattern value=\"\\p{Nd}{2}:\\p{Nd}{2}:\\p{Nd}{2}(.\\p{Nd}+)?%s\"/>\n"
2835 " </xsd:restriction>\n", tz);
2836 else if (typmod == 0)
2837 appendStringInfo(&result,
2838 " <xsd:restriction base=\"xsd:time\">\n"
2839 " <xsd:pattern value=\"\\p{Nd}{2}:\\p{Nd}{2}:\\p{Nd}{2}%s\"/>\n"
2840 " </xsd:restriction>\n", tz);
2842 appendStringInfo(&result,
2843 " <xsd:restriction base=\"xsd:time\">\n"
2844 " <xsd:pattern value=\"\\p{Nd}{2}:\\p{Nd}{2}:\\p{Nd}{2}.\\p{Nd}{%d}%s\"/>\n"
2845 " </xsd:restriction>\n", typmod - VARHDRSZ, tz);
2850 case TIMESTAMPTZOID:
2852 const char *tz = (typeoid == TIMESTAMPTZOID ? "(+|-)\\p{Nd}{2}:\\p{Nd}{2}" : "");
2855 appendStringInfo(&result,
2856 " <xsd:restriction base=\"xsd:dateTime\">\n"
2857 " <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"
2858 " </xsd:restriction>\n", tz);
2859 else if (typmod == 0)
2860 appendStringInfo(&result,
2861 " <xsd:restriction base=\"xsd:dateTime\">\n"
2862 " <xsd:pattern value=\"\\p{Nd}{4}-\\p{Nd}{2}-\\p{Nd}{2}T\\p{Nd}{2}:\\p{Nd}{2}:\\p{Nd}{2}%s\"/>\n"
2863 " </xsd:restriction>\n", tz);
2865 appendStringInfo(&result,
2866 " <xsd:restriction base=\"xsd:dateTime\">\n"
2867 " <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"
2868 " </xsd:restriction>\n", typmod - VARHDRSZ, tz);
2873 appendStringInfo(&result,
2874 " <xsd:restriction base=\"xsd:date\">\n"
2875 " <xsd:pattern value=\"\\p{Nd}{4}-\\p{Nd}{2}-\\p{Nd}{2}\"/>\n"
2876 " </xsd:restriction>\n");
2880 if (get_typtype(typeoid) == TYPTYPE_DOMAIN)
2883 int32 base_typmod = -1;
2885 base_typeoid = getBaseTypeAndTypmod(typeoid, &base_typmod);
2887 appendStringInfo(&result,
2888 " <xsd:restriction base=\"%s\">\n",
2889 map_sql_type_to_xml_name(base_typeoid, base_typmod));
2892 appendStringInfo(&result,
2893 "</xsd:simpleType>\n");
2901 * Map an SQL row to an XML element, taking the row from the active
2902 * SPI cursor. See also SQL/XML:2003 section 9.12.
2905 SPI_sql_row_to_xmlelement(int rownum, StringInfo result, char *tablename, bool nulls, bool tableforest, const char *targetns, bool top_level)
2911 xmltn = map_sql_identifier_to_xml_name(tablename, true, false);
2921 xmldata_root_element_start(result, xmltn, NULL, targetns, top_level);
2923 appendStringInfoString(result, "<row>\n");
2925 for(i = 1; i <= SPI_tuptable->tupdesc->natts; i++)
2931 colname = map_sql_identifier_to_xml_name(SPI_fname(SPI_tuptable->tupdesc, i), true, false);
2932 colval = SPI_getbinval(SPI_tuptable->vals[rownum], SPI_tuptable->tupdesc, i, &isnull);
2937 appendStringInfo(result, " <%s xsi:nil='true'/>\n", colname);
2941 appendStringInfo(result, " <%s>%s</%s>\n",
2942 colname, map_sql_value_to_xml_value(colval, SPI_gettypeid(SPI_tuptable->tupdesc, i)),
2948 xmldata_root_element_end(result, xmltn);
2949 appendStringInfoChar(result, '\n');
2952 appendStringInfoString(result, "</row>\n\n");
2957 * XPath related functions
2962 * Convert XML node to text (dump subtree in case of element, return value otherwise)
2965 xml_xmlnodetoxmltype(xmlNodePtr cur)
2972 if (cur->type == XML_ELEMENT_NODE)
2974 buf = xmlBufferCreate();
2975 xmlNodeDump(buf, NULL, cur, 0, 1);
2976 result = xmlBuffer_to_xmltype(buf);
2981 str = xmlXPathCastNodeToString(cur);
2982 len = strlen((char *) str);
2983 result = (text *) palloc(len + VARHDRSZ);
2984 SET_VARSIZE(result, len + VARHDRSZ);
2985 memcpy(VARDATA(result), str, len);
2993 * Evaluate XPath expression and return array of XML values.
2994 * As we have no support of XQuery sequences yet, this functions seems
2995 * to be the most useful one (array of XML functions plays a role of
2996 * some kind of substritution for XQuery sequences).
2998 * Workaround here: we parse XML data in different way to allow XPath for
2999 * fragments (see "XPath for fragment" TODO comment inside).
3002 xmlpath(PG_FUNCTION_ARGS)
3005 ArrayBuildState *astate = NULL;
3006 xmlParserCtxtPtr ctxt = NULL;
3007 xmlDocPtr doc = NULL;
3008 xmlXPathContextPtr xpathctx = NULL;
3009 xmlXPathCompExprPtr xpathcomp = NULL;
3010 xmlXPathObjectPtr xpathobj = NULL;
3011 int32 len, xpath_len;
3012 xmlChar *string, *xpath_expr;
3013 bool res_is_null = FALSE;
3016 text *xpath_expr_text;
3017 ArrayType *namespaces;
3018 int *dims, ndims, ns_count = 0, bitmask = 1;
3021 char **ns_names = NULL, **ns_uris = NULL;
3026 /* the function is not strict, we must check first two args */
3027 if (PG_ARGISNULL(0) || PG_ARGISNULL(1))
3030 xpath_expr_text = PG_GETARG_TEXT_P(0);
3031 data = PG_GETARG_XML_P(1);
3033 /* Namespace mappings passed as text[].
3034 * Assume that 2-dimensional array has been passed,
3035 * the 1st subarray is array of names, the 2nd -- array of URIs,
3036 * example: ARRAY[ARRAY['myns', 'myns2'], ARRAY['http://example.com', 'http://example2.com']].
3038 if (!PG_ARGISNULL(2))
3040 namespaces = PG_GETARG_ARRAYTYPE_P(2);
3041 ndims = ARR_NDIM(namespaces);
3042 dims = ARR_DIMS(namespaces);
3046 ereport(ERROR, (errmsg("invalid array passed for namespace mappings"),
3047 errdetail("Only 2-dimensional array may be used for namespace mappings.")));
3049 Assert(ARR_ELEMTYPE(namespaces) == TEXTOID);
3051 ns_count = ArrayGetNItems(ndims, dims) / 2;
3052 get_typlenbyvalalign(ARR_ELEMTYPE(namespaces),
3053 &typlen, &typbyval, &typalign);
3054 ns_names = (char **) palloc(ns_count * sizeof(char *));
3055 ns_uris = (char **) palloc(ns_count * sizeof(char *));
3056 ptr = ARR_DATA_PTR(namespaces);
3057 bitmap = ARR_NULLBITMAP(namespaces);
3060 for (i = 0; i < ns_count * 2; i++)
3062 if (bitmap && (*bitmap & bitmask) == 0)
3063 ereport(ERROR, (errmsg("neither namespace nor URI may be NULL"))); /* TODO: better message */
3067 ns_names[i] = DatumGetCString(DirectFunctionCall1(textout,
3068 PointerGetDatum(ptr)));
3070 ns_uris[i - ns_count] = DatumGetCString(DirectFunctionCall1(textout,
3071 PointerGetDatum(ptr)));
3072 ptr = att_addlength(ptr, typlen, PointerGetDatum(ptr));
3073 ptr = (char *) att_align(ptr, typalign);
3076 /* advance bitmap pointer if any */
3080 if (bitmask == 0x100)
3089 len = VARSIZE(data) - VARHDRSZ;
3090 xpath_len = VARSIZE(xpath_expr_text) - VARHDRSZ;
3092 ereport(ERROR, (errmsg("empty XPath expression")));
3094 if (xmlStrncmp((xmlChar *) VARDATA(data), (xmlChar *) "<?xml", 5) == 0)
3096 string = palloc(len + 1);
3097 memcpy(string, VARDATA(data), len);
3099 xpath_expr = palloc(xpath_len + 1);
3100 memcpy(xpath_expr, VARDATA(xpath_expr_text), xpath_len);
3101 xpath_expr[xpath_len] = '\0';
3105 /* use "<x>...</x>" as dummy root element to enable XPath for fragments */
3106 /* TODO: (XPath for fragment) find better solution to work with XML fragment! */
3107 string = xmlStrncatNew((xmlChar *) "<x>", (xmlChar *) VARDATA(data), len);
3108 string = xmlStrncat(string, (xmlChar *) "</x>", 5);
3110 xpath_expr = xmlStrncatNew((xmlChar *) "/x", (xmlChar *) VARDATA(xpath_expr_text), xpath_len);
3118 /* redundant XML parsing (two parsings for the same value in the same session are possible) */
3119 ctxt = xmlNewParserCtxt();
3121 xml_ereport(ERROR, ERRCODE_INTERNAL_ERROR,
3122 "could not allocate parser context");
3123 doc = xmlCtxtReadMemory(ctxt, (char *) string, len, NULL, NULL, 0);
3125 xml_ereport(ERROR, ERRCODE_INVALID_XML_DOCUMENT,
3126 "could not parse XML data");
3127 xpathctx = xmlXPathNewContext(doc);
3128 if (xpathctx == NULL)
3129 xml_ereport(ERROR, ERRCODE_INTERNAL_ERROR,
3130 "could not allocate XPath context");
3131 xpathctx->node = xmlDocGetRootElement(doc);
3132 if (xpathctx->node == NULL)
3133 xml_ereport(ERROR, ERRCODE_INTERNAL_ERROR,
3134 "could not find root XML element");
3136 /* register namespaces, if any */
3137 if ((ns_count > 0) && ns_names && ns_uris)
3138 for (i = 0; i < ns_count; i++)
3139 if (0 != xmlXPathRegisterNs(xpathctx, (xmlChar *) ns_names[i], (xmlChar *) ns_uris[i]))
3141 (errmsg("could not register XML namespace with prefix=\"%s\" and href=\"%s\"", ns_names[i], ns_uris[i])));
3143 xpathcomp = xmlXPathCompile(xpath_expr);
3144 if (xpathcomp == NULL)
3145 xml_ereport(ERROR, ERRCODE_INTERNAL_ERROR,
3146 "invalid XPath expression"); /* TODO: show proper XPath error details */
3148 xpathobj = xmlXPathCompiledEval(xpathcomp, xpathctx);
3149 xmlXPathFreeCompExpr(xpathcomp);
3150 if (xpathobj == NULL)
3151 ereport(ERROR, (errmsg("could not create XPath object")));
3153 if (xpathobj->nodesetval == NULL)
3156 if (!res_is_null && xpathobj->nodesetval->nodeNr == 0)
3157 /* TODO maybe empty array should be here, not NULL? (if so -- fix segfault) */
3158 /*PG_RETURN_ARRAYTYPE_P(makeArrayResult(astate, CurrentMemoryContext));*/
3162 for (i = 0; i < xpathobj->nodesetval->nodeNr; i++)
3165 bool elemisnull = false;
3166 elem = PointerGetDatum(xml_xmlnodetoxmltype(xpathobj->nodesetval->nodeTab[i]));
3167 astate = accumArrayResult(astate, elem,
3169 CurrentMemoryContext);
3172 xmlXPathFreeObject(xpathobj);
3173 xmlXPathFreeContext(xpathctx);
3174 xmlFreeParserCtxt(ctxt);
3181 xmlXPathFreeCompExpr(xpathcomp);
3183 xmlXPathFreeObject(xpathobj);
3185 xmlXPathFreeContext(xpathctx);
3189 xmlFreeParserCtxt(ctxt);
3202 PG_RETURN_ARRAYTYPE_P(makeArrayResult(astate, CurrentMemoryContext));