]> granicus.if.org Git - postgresql/blob - src/backend/utils/adt/xml.c
Some code review for xml.c:
[postgresql] / src / backend / utils / adt / xml.c
1 /*-------------------------------------------------------------------------
2  *
3  * xml.c
4  *        XML data type support.
5  *
6  *
7  * Portions Copyright (c) 1996-2007, PostgreSQL Global Development Group
8  * Portions Copyright (c) 1994, Regents of the University of California
9  *
10  * $PostgreSQL: pgsql/src/backend/utils/adt/xml.c,v 1.51 2007/11/06 03:06:28 tgl Exp $
11  *
12  *-------------------------------------------------------------------------
13  */
14
15 /*
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
23  * else does.
24  */
25
26 /*
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
38  * here.
39  */
40
41 #include "postgres.h"
42
43 #ifdef USE_LIBXML
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 */
53
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"
59 #include "fmgr.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"
74
75
76 /* GUC variables */
77 XmlBinaryType xmlbinary;
78 XmlOptionType xmloption;
79
80 #ifdef USE_LIBXML
81
82 static StringInfo xml_err_buf = NULL;
83
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);
101
102 #endif /* USE_LIBXML */
103
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);
121
122 #define NO_XML_SUPPORT() \
123         ereport(ERROR, \
124                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), \
125                          errmsg("unsupported XML feature"), \
126                          errdetail("This functionality requires libxml support."), \
127                          errhint("You need to re-compile PostgreSQL using --with-libxml.")))
128
129
130 #define _textin(str) DirectFunctionCall1(textin, CStringGetDatum(str))
131 #define _textout(x) DatumGetCString(DirectFunctionCall1(textout, PointerGetDatum(x)))
132
133
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"
138
139
140 #ifdef USE_LIBXML
141
142 static int
143 xmlChar_to_encoding(xmlChar *encoding_name)
144 {
145         int             encoding = pg_char_to_encoding((char *) encoding_name);
146
147         if (encoding < 0)
148                 ereport(ERROR,
149                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
150                                  errmsg("invalid encoding name \"%s\"",
151                                                 (char *) encoding_name)));
152         return encoding;
153 }
154
155 #endif
156
157
158 Datum
159 xml_in(PG_FUNCTION_ARGS)
160 {
161 #ifdef USE_LIBXML
162         char            *s = PG_GETARG_CSTRING(0);
163         size_t          len;
164         xmltype         *vardata;
165         xmlDocPtr        doc;
166
167         len = strlen(s);
168         vardata = palloc(len + VARHDRSZ);
169         SET_VARSIZE(vardata, len + VARHDRSZ);
170         memcpy(VARDATA(vardata), s, len);
171
172         /*
173          * Parse the data to check if it is well-formed XML data.  Assume
174          * that ERROR occurred if parsing failed.
175          */
176         doc = xml_parse(vardata, xmloption, true, NULL);
177         xmlFreeDoc(doc);
178
179         PG_RETURN_XML_P(vardata);
180 #else
181         NO_XML_SUPPORT();
182         return 0;
183 #endif
184 }
185
186
187 #define PG_XML_DEFAULT_VERSION "1.0"
188
189
190 static char *
191 xml_out_internal(xmltype *x, pg_enc target_encoding)
192 {
193         char            *str;
194         size_t          len;
195 #ifdef USE_LIBXML
196         xmlChar         *version;
197         xmlChar         *encoding;
198         int                     standalone;
199         int                     res_code;
200 #endif
201
202         len = VARSIZE(x) - VARHDRSZ;
203         str = palloc(len + 1);
204         memcpy(str, VARDATA(x), len);
205         str[len] = '\0';
206
207 #ifdef USE_LIBXML
208         if ((res_code = parse_xml_decl((xmlChar *) str,
209                                                                    &len, &version, &encoding, &standalone)) == 0)
210         {
211                 StringInfoData buf;
212
213                 initStringInfo(&buf);
214
215                 if (!print_xml_decl(&buf, version, target_encoding, standalone))
216                 {
217                         /*
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.
221                          */
222                         if (*(str + len) == '\n')
223                                 len += 1;
224                 }
225                 appendStringInfoString(&buf, str + len);
226
227                 return buf.data;
228         }
229
230         xml_ereport_by_code(WARNING, ERRCODE_INTERNAL_ERROR,
231                                                 "could not parse XML declaration in stored value",
232                                                 res_code);
233 #endif
234         return str;
235 }
236
237
238 Datum
239 xml_out(PG_FUNCTION_ARGS)
240 {
241         xmltype    *x = PG_GETARG_XML_P(0);
242
243         /*
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.
248          */
249         PG_RETURN_CSTRING(xml_out_internal(x, 0));
250 }
251
252
253 Datum
254 xml_recv(PG_FUNCTION_ARGS)
255 {
256 #ifdef USE_LIBXML
257         StringInfo      buf = (StringInfo) PG_GETARG_POINTER(0);
258         xmltype    *result;
259         char       *str;
260         char       *newstr;
261         int                     nbytes;
262         xmlDocPtr       doc;
263         xmlChar    *encoding = NULL;
264
265         /*
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.
269          */
270         nbytes = buf->len - buf->cursor;
271         str = (char *) pq_getmsgbytes(buf, nbytes);
272
273         /*
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.
277          */
278         result = palloc(nbytes + 1 + VARHDRSZ);
279         SET_VARSIZE(result, nbytes + VARHDRSZ);
280         memcpy(VARDATA(result), str, nbytes);
281         str = VARDATA(result);
282         str[nbytes] = '\0';
283
284         parse_xml_decl((xmlChar *) str, NULL, NULL, &encoding, NULL);
285
286         /*
287          * Parse the data to check if it is well-formed XML data.  Assume
288          * that xml_parse will throw ERROR if not.
289          */
290         doc = xml_parse(result, xmloption, true, encoding);
291         xmlFreeDoc(doc);
292
293         /* Now that we know what we're dealing with, convert to server encoding */
294         newstr = (char *) pg_do_encoding_conversion((unsigned char *) str,
295                                                                                                 nbytes,
296                                                                                                 encoding ?
297                                                                                                 xmlChar_to_encoding(encoding) :
298                                                                                                 PG_UTF8,
299                                                                                                 GetDatabaseEncoding());
300
301         if (newstr != str)
302         {
303                 pfree(result);
304
305                 nbytes = strlen(newstr);
306
307                 result = palloc(nbytes + VARHDRSZ);
308                 SET_VARSIZE(result, nbytes + VARHDRSZ);
309                 memcpy(VARDATA(result), newstr, nbytes);
310
311                 pfree(newstr);
312         }
313
314         PG_RETURN_XML_P(result);
315 #else
316         NO_XML_SUPPORT();
317         return 0;
318 #endif
319 }
320
321
322 Datum
323 xml_send(PG_FUNCTION_ARGS)
324 {
325         xmltype    *x = PG_GETARG_XML_P(0);
326         char       *outval;
327         StringInfoData buf;
328         
329         /*
330          * xml_out_internal doesn't convert the encoding, it just prints
331          * the right declaration. pq_sendtext will do the conversion.
332          */
333         outval = xml_out_internal(x, pg_get_client_encoding());
334
335         pq_begintypsend(&buf);
336         pq_sendtext(&buf, outval, strlen(outval));
337         pfree(outval);
338         PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
339 }
340
341
342 #ifdef USE_LIBXML
343 static void
344 appendStringInfoText(StringInfo str, const text *t)
345 {
346         appendBinaryStringInfo(str, VARDATA(t), VARSIZE(t) - VARHDRSZ);
347 }
348 #endif
349
350
351 static xmltype *
352 stringinfo_to_xmltype(StringInfo buf)
353 {
354         int32 len;
355         xmltype *result;
356
357         len = buf->len + VARHDRSZ;
358         result = palloc(len);
359         SET_VARSIZE(result, len);
360         memcpy(VARDATA(result), buf->data, buf->len);
361
362         return result;
363 }
364
365
366 static xmltype *
367 cstring_to_xmltype(const char *string)
368 {
369         int32           len;
370         xmltype    *result;
371
372         len = strlen(string) + VARHDRSZ;
373         result = palloc(len);
374         SET_VARSIZE(result, len);
375         memcpy(VARDATA(result), string, len - VARHDRSZ);
376
377         return result;
378 }
379
380
381 #ifdef USE_LIBXML
382 static xmltype *
383 xmlBuffer_to_xmltype(xmlBufferPtr buf)
384 {
385         int32           len;
386         xmltype    *result;
387
388         len = xmlBufferLength(buf) + VARHDRSZ;
389         result = palloc(len);
390         SET_VARSIZE(result, len);
391         memcpy(VARDATA(result), xmlBufferContent(buf), len - VARHDRSZ);
392
393         return result;
394 }
395 #endif
396
397
398 Datum
399 xmlcomment(PG_FUNCTION_ARGS)
400 {
401 #ifdef USE_LIBXML
402         text *arg = PG_GETARG_TEXT_P(0);
403         char *argdata = VARDATA(arg);
404         int len =  VARSIZE(arg) - VARHDRSZ;
405         StringInfoData buf;
406         int i;
407
408         /* check for "--" in string or "-" at the end */
409         for (i = 1; i < len; i++)
410         {
411                 if (argdata[i] == '-' && argdata[i - 1] == '-')
412                         ereport(ERROR,
413                                         (errcode(ERRCODE_INVALID_XML_COMMENT),
414                                          errmsg("invalid XML comment")));
415         }
416         if (len > 0 && argdata[len - 1] == '-')
417                 ereport(ERROR,
418                                 (errcode(ERRCODE_INVALID_XML_COMMENT),
419                                  errmsg("invalid XML comment")));
420
421         initStringInfo(&buf);
422         appendStringInfo(&buf, "<!--");
423         appendStringInfoText(&buf, arg);
424         appendStringInfo(&buf, "-->");
425
426         PG_RETURN_XML_P(stringinfo_to_xmltype(&buf));
427 #else
428         NO_XML_SUPPORT();
429         return 0;
430 #endif
431 }
432
433
434
435 /*
436  * TODO: xmlconcat needs to merge the notations and unparsed entities
437  * of the argument values.  Not very important in practice, though.
438  */
439 xmltype *
440 xmlconcat(List *args)
441 {
442 #ifdef USE_LIBXML
443         int                     global_standalone = 1;
444         xmlChar    *global_version = NULL;
445         bool            global_version_no_value = false;
446         StringInfoData buf;
447         ListCell   *v;
448
449         initStringInfo(&buf);
450         foreach(v, args)
451         {
452                 xmltype    *x = DatumGetXmlP(PointerGetDatum(lfirst(v)));
453                 size_t          len;
454                 xmlChar    *version;
455                 int                     standalone;
456                 char       *str;
457
458                 len = VARSIZE(x) - VARHDRSZ;
459                 str = palloc(len + 1);
460                 memcpy(str, VARDATA(x), len);
461                 str[len] = '\0';
462
463                 parse_xml_decl((xmlChar *) str, &len, &version, NULL, &standalone);
464
465                 if (standalone == 0 && global_standalone == 1)
466                         global_standalone = 0;
467                 if (standalone < 0)
468                         global_standalone = -1;
469
470                 if (!version)
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;
476
477                 appendStringInfoString(&buf, str + len);
478                 pfree(str);
479         }
480
481         if (!global_version_no_value || global_standalone >= 0)
482         {
483                 StringInfoData buf2;
484
485                 initStringInfo(&buf2);
486
487                 print_xml_decl(&buf2,
488                                            (!global_version_no_value) ? global_version : NULL,
489                                            0,
490                                            global_standalone);
491
492                 appendStringInfoString(&buf2, buf.data);
493                 buf = buf2;
494         }
495
496         return stringinfo_to_xmltype(&buf);
497 #else
498         NO_XML_SUPPORT();
499         return NULL;
500 #endif
501 }
502
503
504 /*
505  * XMLAGG support
506  */
507 Datum
508 xmlconcat2(PG_FUNCTION_ARGS)
509 {
510         if (PG_ARGISNULL(0))
511         {
512                 if (PG_ARGISNULL(1))
513                         PG_RETURN_NULL();
514                 else
515                         PG_RETURN_XML_P(PG_GETARG_XML_P(1));
516         }
517         else if (PG_ARGISNULL(1))
518                 PG_RETURN_XML_P(PG_GETARG_XML_P(0));
519         else
520                 PG_RETURN_XML_P(xmlconcat(list_make2(PG_GETARG_XML_P(0),
521                                                                                          PG_GETARG_XML_P(1))));
522 }
523
524
525 Datum
526 texttoxml(PG_FUNCTION_ARGS)
527 {
528         text       *data = PG_GETARG_TEXT_P(0);
529
530         PG_RETURN_XML_P(xmlparse(data, xmloption, true));
531 }
532
533
534 Datum
535 xmltotext(PG_FUNCTION_ARGS)
536 {
537         xmltype    *data = PG_GETARG_XML_P(0);
538
539         PG_RETURN_TEXT_P(xmltotext_with_xmloption(data, xmloption));
540 }
541
542
543 text *
544 xmltotext_with_xmloption(xmltype *data, XmlOptionType xmloption_arg)
545 {
546         if (xmloption_arg == XMLOPTION_DOCUMENT && !xml_is_document(data))
547                 ereport(ERROR,
548                                 (errcode(ERRCODE_NOT_AN_XML_DOCUMENT),
549                                  errmsg("not an XML document")));
550
551         /* It's actually binary compatible, save for the above check. */
552         return (text *) data;
553 }
554
555
556 xmltype *
557 xmlelement(XmlExprState *xmlExpr, ExprContext *econtext)
558 {
559 #ifdef USE_LIBXML
560         XmlExpr    *xexpr = (XmlExpr *) xmlExpr->xprstate.expr;
561         xmltype    *result;
562         List       *named_arg_strings;
563         List       *arg_strings;
564         int                     i;
565         ListCell   *arg;
566         ListCell   *narg;
567         xmlBufferPtr buf;
568         xmlTextWriterPtr writer;
569
570         /*
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.
575          */
576         named_arg_strings = NIL;
577         i = 0;
578         foreach(arg, xmlExpr->named_args)
579         {
580                 ExprState       *e = (ExprState *) lfirst(arg);
581                 Datum           value;
582                 bool            isnull;
583                 char       *str;
584
585                 value = ExecEvalExpr(e, econtext, &isnull, NULL);
586                 if (isnull)
587                         str = NULL;
588                 else
589                         str = OutputFunctionCall(&xmlExpr->named_outfuncs[i], value);
590                 named_arg_strings = lappend(named_arg_strings, str);
591                 i++;
592         }
593
594         arg_strings = NIL;
595         foreach(arg, xmlExpr->args)
596         {
597                 ExprState       *e = (ExprState *) lfirst(arg);
598                 Datum           value;
599                 bool            isnull;
600                 char       *str;
601
602                 value = ExecEvalExpr(e, econtext, &isnull, NULL);
603                 /* here we can just forget NULL elements immediately */
604                 if (!isnull)
605                 {
606                         str = map_sql_value_to_xml_value(value,
607                                                                                          exprType((Node *) e->expr));
608                         arg_strings = lappend(arg_strings, str);
609                 }
610         }
611
612         /* now safe to run libxml */
613         xml_init();
614
615         buf = xmlBufferCreate();
616         writer = xmlNewTextWriterMemory(buf, 0);
617
618         xmlTextWriterStartElement(writer, (xmlChar *) xexpr->name);
619
620         forboth(arg, named_arg_strings, narg, xexpr->arg_names)
621         {
622                 char    *str = (char *) lfirst(arg);
623                 char    *argname = strVal(lfirst(narg));
624
625                 if (str)
626                 {
627                         xmlTextWriterWriteAttribute(writer,
628                                                                                 (xmlChar *) argname,
629                                                                                 (xmlChar *) str);
630                         pfree(str);
631                 }
632         }
633
634         foreach(arg, arg_strings)
635         {
636                 char    *str = (char *) lfirst(arg);
637
638                 xmlTextWriterWriteRaw(writer, (xmlChar *) str);
639         }
640
641         xmlTextWriterEndElement(writer);
642         xmlFreeTextWriter(writer);
643
644         result = xmlBuffer_to_xmltype(buf);
645         xmlBufferFree(buf);
646
647         return result;
648 #else
649         NO_XML_SUPPORT();
650         return NULL;
651 #endif
652 }
653
654
655 xmltype *
656 xmlparse(text *data, XmlOptionType xmloption_arg, bool preserve_whitespace)
657 {
658 #ifdef USE_LIBXML
659         xmlDocPtr       doc;
660
661         doc = xml_parse(data, xmloption_arg, preserve_whitespace, NULL);
662         xmlFreeDoc(doc);
663
664         return (xmltype *) data;
665 #else
666         NO_XML_SUPPORT();
667         return NULL;
668 #endif
669 }
670
671
672 xmltype *
673 xmlpi(char *target, text *arg, bool arg_is_null, bool *result_is_null)
674 {
675 #ifdef USE_LIBXML
676         xmltype *result;
677         StringInfoData buf;
678
679         if (pg_strncasecmp(target, "xml", 3) == 0)
680                 ereport(ERROR,
681                                 (errcode(ERRCODE_SYNTAX_ERROR), /* really */
682                                  errmsg("invalid XML processing instruction"),
683                                  errdetail("XML processing instruction target name cannot start with \"xml\".")));
684
685         /*
686          * Following the SQL standard, the null check comes after the
687          * syntax check above.
688          */
689         *result_is_null = arg_is_null;
690         if (*result_is_null)
691                 return NULL;            
692
693         initStringInfo(&buf);
694
695         appendStringInfo(&buf, "<?%s", target);
696
697         if (arg != NULL)
698         {
699                 char *string;
700
701                 string = _textout(arg);
702                 if (strstr(string, "?>") != NULL)
703                 ereport(ERROR,
704                                 (errcode(ERRCODE_INVALID_XML_PROCESSING_INSTRUCTION),
705                                  errmsg("invalid XML processing instruction"),
706                                  errdetail("XML processing instruction cannot contain \"?>\".")));
707
708                 appendStringInfoChar(&buf, ' ');
709                 appendStringInfoString(&buf, string + strspn(string, " "));
710                 pfree(string);
711         }
712         appendStringInfoString(&buf, "?>");
713
714         result = stringinfo_to_xmltype(&buf);
715         pfree(buf.data);
716         return result;
717 #else
718         NO_XML_SUPPORT();
719         return NULL;
720 #endif
721 }
722
723
724 xmltype *
725 xmlroot(xmltype *data, text *version, int standalone)
726 {
727 #ifdef USE_LIBXML
728         char       *str;
729         size_t          len;
730         xmlChar    *orig_version;
731         int                     orig_standalone;
732         StringInfoData buf;
733
734         len = VARSIZE(data) - VARHDRSZ;
735         str = palloc(len + 1);
736         memcpy(str, VARDATA(data), len);
737         str[len] = '\0';
738
739         parse_xml_decl((xmlChar *) str, &len, &orig_version, NULL, &orig_standalone);
740
741         if (version)
742                 orig_version = xml_text2xmlChar(version);
743         else
744                 orig_version = NULL;
745
746         switch (standalone)
747         {
748                 case XML_STANDALONE_YES:
749                         orig_standalone = 1;
750                         break;
751                 case XML_STANDALONE_NO:
752                         orig_standalone = 0;
753                         break;
754                 case XML_STANDALONE_NO_VALUE:
755                         orig_standalone = -1;
756                         break;
757                 case XML_STANDALONE_OMITTED:
758                         /* leave original value */
759                         break;
760         }
761
762         initStringInfo(&buf);
763         print_xml_decl(&buf, orig_version, 0, orig_standalone);
764         appendStringInfoString(&buf, str + len);
765
766         return stringinfo_to_xmltype(&buf);
767 #else
768         NO_XML_SUPPORT();
769         return NULL;
770 #endif
771 }
772
773
774 /*
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)
779  */
780 Datum
781 xmlvalidate(PG_FUNCTION_ARGS)
782 {
783 #ifdef USE_LIBXML
784         text                            *data = PG_GETARG_TEXT_P(0);
785         text                            *dtdOrUri = PG_GETARG_TEXT_P(1);
786         bool                            result = false;
787         xmlParserCtxtPtr        ctxt = NULL;
788         xmlDocPtr                       doc = NULL;
789         xmlDtdPtr                       dtd = NULL;
790
791         xml_init();
792
793         /* We use a PG_TRY block to ensure libxml parser is cleaned up on error */
794         PG_TRY();
795         {
796                 xmlInitParser();
797                 ctxt = xmlNewParserCtxt();
798                 if (ctxt == NULL)
799                         xml_ereport(ERROR, ERRCODE_INTERNAL_ERROR,
800                                                 "could not allocate parser context");
801
802                 doc = xmlCtxtReadMemory(ctxt, (char *) VARDATA(data),
803                                                                 VARSIZE(data) - VARHDRSZ,
804                                                                 NULL, NULL, 0);
805                 if (doc == NULL)
806                         xml_ereport(ERROR, ERRCODE_INVALID_XML_DOCUMENT,
807                                                 "could not parse XML data");
808
809 #if 0
810                 uri = xmlCreateURI();
811                 elog(NOTICE, "dtd - %s", dtdOrUri);
812                 dtd = palloc(sizeof(xmlDtdPtr));
813                 uri = xmlParseURI(dtdOrUri);
814                 if (uri == NULL)
815                         xml_ereport(ERROR, ERRCODE_INTERNAL_ERROR,
816                                                 "not implemented yet... (TODO)");
817                 else
818 #endif
819                         dtd = xmlParseDTD(NULL, xml_text2xmlChar(dtdOrUri));
820
821                 if (dtd == NULL)
822                         xml_ereport(ERROR, ERRCODE_INVALID_XML_DOCUMENT,
823                                                 "could not load DTD");
824
825                 if (xmlValidateDtd(xmlNewValidCtxt(), doc, dtd) == 1)
826                         result = true;
827
828                 if (!result)
829                         xml_ereport(NOTICE, ERRCODE_INVALID_XML_DOCUMENT,
830                                                 "validation against DTD failed");
831
832 #if 0
833                 if (uri)
834                         xmlFreeURI(uri);
835                 uri = NULL;
836 #endif
837                 if (dtd)
838                         xmlFreeDtd(dtd);
839                 dtd = NULL;
840                 if (doc)
841                         xmlFreeDoc(doc);
842                 doc = NULL;
843                 if (ctxt)
844                         xmlFreeParserCtxt(ctxt);
845                 ctxt = NULL;
846                 xmlCleanupParser();
847         }
848         PG_CATCH();
849         {
850 #if 0
851                 if (uri)
852                         xmlFreeURI(uri);
853 #endif
854                 if (dtd)
855                         xmlFreeDtd(dtd);
856                 if (doc)
857                         xmlFreeDoc(doc);
858                 if (ctxt)
859                         xmlFreeParserCtxt(ctxt);
860                 xmlCleanupParser();
861
862                 PG_RE_THROW();
863         }
864         PG_END_TRY();
865
866         PG_RETURN_BOOL(result);
867 #else /* not USE_LIBXML */
868         NO_XML_SUPPORT();
869         return 0;
870 #endif /* not USE_LIBXML */
871 }
872
873
874 bool
875 xml_is_document(xmltype *arg)
876 {
877 #ifdef USE_LIBXML
878         bool            result;
879         xmlDocPtr       doc = NULL;
880         MemoryContext ccxt = CurrentMemoryContext;
881
882         PG_TRY();
883         {
884                 doc = xml_parse((text *) arg, XMLOPTION_DOCUMENT, true, NULL);
885                 result = true;
886         }
887         PG_CATCH();
888         {
889                 ErrorData *errdata;
890                 MemoryContext ecxt;
891
892                 ecxt = MemoryContextSwitchTo(ccxt);
893                 errdata = CopyErrorData();
894                 if (errdata->sqlerrcode == ERRCODE_INVALID_XML_DOCUMENT)
895                 {
896                         FlushErrorState();
897                         result = false;
898                 }
899                 else
900                 {
901                         MemoryContextSwitchTo(ecxt);
902                         PG_RE_THROW();
903                 }
904         }
905         PG_END_TRY();
906
907         if (doc)
908                 xmlFreeDoc(doc);
909
910         return result;
911 #else /* not USE_LIBXML */
912         NO_XML_SUPPORT();
913         return false;
914 #endif /* not USE_LIBXML */
915 }
916
917
918 #ifdef USE_LIBXML
919
920 /*
921  * Set up for use of libxml --- this should be called by each function that
922  * is about to use libxml facilities.
923  *
924  * TODO: xmlChar is utf8-char, make proper tuning (initdb with enc!=utf8 and
925  * check)
926  */
927 static void
928 xml_init(void)
929 {
930         static bool first_time = true;
931
932         if (first_time)
933         {
934                 /* Stuff we need do only once per session */
935                 MemoryContext oldcontext;
936
937                 /*
938                  * Currently, we have no pure UTF-8 support for internals -- check
939                  * if we can work.
940                  */
941                 if (sizeof(char) != sizeof(xmlChar))
942                         ereport(ERROR,
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))));
946
947                 /* create error buffer in permanent context */
948                 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
949                 xml_err_buf = makeStringInfo();
950                 MemoryContextSwitchTo(oldcontext);
951
952                 /* Now that xml_err_buf exists, safe to call xml_errorHandler */
953                 xmlSetGenericErrorFunc(NULL, xml_errorHandler);
954
955                 /* Set up memory allocation our way, too */
956                 xmlMemSetup(xml_pfree, xml_palloc, xml_repalloc, xml_pstrdup);
957
958                 /* Check library compatibility */
959                 LIBXML_TEST_VERSION;
960
961                 first_time = false;
962         }
963         else
964         {
965                 /* Reset pre-existing buffer to empty */
966                 Assert(xml_err_buf != NULL);
967                 resetStringInfo(xml_err_buf);
968
969                 /*
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.
975                  */
976                 xmlSetGenericErrorFunc(NULL, xml_errorHandler);
977                 xmlMemSetup(xml_pfree, xml_palloc, xml_repalloc, xml_pstrdup);
978         }
979 }
980
981
982 /*
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
988  * to complete this.
989  */
990
991 #define CHECK_XML_SPACE(p) \
992         do { \
993                 if (!xmlIsBlank_ch(*(p))) \
994                         return XML_ERR_SPACE_REQUIRED; \
995         } while (0)
996
997 #define SKIP_XML_SPACE(p) \
998         while (xmlIsBlank_ch(*(p))) (p)++
999
1000 static int
1001 parse_xml_decl(const xmlChar *str,size_t *lenp,
1002                            xmlChar **version, xmlChar **encoding, int *standalone)
1003 {
1004         const xmlChar *p;
1005         const xmlChar *save_p;
1006         size_t          len;
1007
1008         xml_init();
1009
1010         if (version)
1011                 *version = NULL;
1012         if (encoding)
1013                 *encoding = NULL;
1014         if (standalone)
1015                 *standalone = -1;
1016
1017         p = str;
1018
1019         if (xmlStrncmp(p, (xmlChar *)"<?xml", 5) != 0)
1020                 goto finished;
1021
1022         p += 5;
1023
1024         /* version */
1025         CHECK_XML_SPACE(p);
1026         SKIP_XML_SPACE(p);
1027         if (xmlStrncmp(p, (xmlChar *)"version", 7) != 0)
1028                 return XML_ERR_VERSION_MISSING;
1029         p += 7;
1030         SKIP_XML_SPACE(p);
1031         if (*p != '=')
1032                 return XML_ERR_VERSION_MISSING;
1033         p += 1;
1034         SKIP_XML_SPACE(p);
1035
1036         if (*p == '\'' || *p == '"')
1037         {
1038                 const xmlChar *q;
1039
1040                 q = xmlStrchr(p + 1, *p);
1041                 if (!q)
1042                         return XML_ERR_VERSION_MISSING;
1043
1044                 if (version)
1045                         *version = xmlStrndup(p + 1, q - p - 1);
1046                 p = q + 1;
1047         }
1048         else
1049                 return XML_ERR_VERSION_MISSING;
1050
1051         /* encoding */
1052         save_p = p;
1053         SKIP_XML_SPACE(p);
1054         if (xmlStrncmp(p, (xmlChar *)"encoding", 8) == 0)
1055         {
1056                 CHECK_XML_SPACE(save_p);
1057                 p += 8;
1058                 SKIP_XML_SPACE(p);
1059                 if (*p != '=')
1060                         return XML_ERR_MISSING_ENCODING;
1061                 p += 1;
1062                 SKIP_XML_SPACE(p);
1063
1064                 if (*p == '\'' || *p == '"')
1065                 {
1066                         const xmlChar *q;
1067
1068                         q = xmlStrchr(p + 1, *p);
1069                         if (!q)
1070                                 return XML_ERR_MISSING_ENCODING;
1071
1072                         if (encoding)
1073                         *encoding = xmlStrndup(p + 1, q - p - 1);
1074                         p = q + 1;
1075                 }
1076                 else
1077                         return XML_ERR_MISSING_ENCODING;
1078         }
1079         else
1080         {
1081                 p = save_p;
1082         }
1083
1084         /* standalone */
1085         save_p = p;
1086         SKIP_XML_SPACE(p);
1087         if (xmlStrncmp(p, (xmlChar *)"standalone", 10) == 0)
1088         {
1089                 CHECK_XML_SPACE(save_p);
1090                 p += 10;
1091                 SKIP_XML_SPACE(p);
1092                 if (*p != '=')
1093                         return XML_ERR_STANDALONE_VALUE;
1094                 p += 1;
1095                 SKIP_XML_SPACE(p);
1096                 if (xmlStrncmp(p, (xmlChar *)"'yes'", 5) == 0 || xmlStrncmp(p, (xmlChar *)"\"yes\"", 5) == 0)
1097                 {
1098                         *standalone = 1;
1099                         p += 5;
1100                 }
1101                 else if (xmlStrncmp(p, (xmlChar *)"'no'", 4) == 0 || xmlStrncmp(p, (xmlChar *)"\"no\"", 4) == 0)
1102                 {
1103                         *standalone = 0;
1104                         p += 4;
1105                 }
1106                 else
1107                         return XML_ERR_STANDALONE_VALUE;
1108         }
1109         else
1110         {
1111                 p = save_p;
1112         }
1113
1114         SKIP_XML_SPACE(p);
1115         if (xmlStrncmp(p, (xmlChar *)"?>", 2) != 0)
1116                 return XML_ERR_XMLDECL_NOT_FINISHED;
1117         p += 2;
1118
1119 finished:
1120         len = p - str;
1121
1122         for (p = str; p < str + len; p++)
1123                 if (*p > 127)
1124                         return XML_ERR_INVALID_CHAR;
1125
1126         if (lenp)
1127                 *lenp = len;
1128
1129         return XML_ERR_OK;
1130 }
1131
1132
1133 /*
1134  * Write an XML declaration.  On output, we adjust the XML declaration
1135  * as follows.  (These rules are the moral equivalent of the clause
1136  * "Serialization of an XML value" in the SQL standard.)
1137  *
1138  * We try to avoid generating an XML declaration if possible.  This is
1139  * so that you don't get trivial things like xml '<foo/>' resulting in
1140  * '<?xml version="1.0"?><foo/>', which would surely be annoying.  We
1141  * must provide a declaration if the standalone property is specified
1142  * or if we include an encoding declaration.  If we have a
1143  * declaration, we must specify a version (XML requires this).
1144  * Otherwise we only make a declaration if the version is not "1.0",
1145  * which is the default version specified in SQL:2003.
1146  */
1147 static bool
1148 print_xml_decl(StringInfo buf, const xmlChar *version,
1149                            pg_enc encoding, int standalone)
1150 {
1151         xml_init();
1152
1153         if ((version && strcmp((char *) version, PG_XML_DEFAULT_VERSION) != 0)
1154                 || (encoding && encoding != PG_UTF8)
1155                 || standalone != -1)
1156         {
1157                 appendStringInfoString(buf, "<?xml");
1158
1159                 if (version)
1160                         appendStringInfo(buf, " version=\"%s\"", version);
1161                 else
1162                         appendStringInfo(buf, " version=\"%s\"", PG_XML_DEFAULT_VERSION);
1163
1164                 if (encoding && encoding != PG_UTF8)
1165                 {
1166                         /*
1167                          * XXX might be useful to convert this to IANA names
1168                          * (ISO-8859-1 instead of LATIN1 etc.); needs field experience
1169                          */
1170                         appendStringInfo(buf, " encoding=\"%s\"",
1171                                                          pg_encoding_to_char(encoding));
1172                 }
1173
1174                 if (standalone == 1)
1175                         appendStringInfoString(buf, " standalone=\"yes\"");
1176                 else if (standalone == 0)
1177                         appendStringInfoString(buf, " standalone=\"no\"");
1178                 appendStringInfoString(buf, "?>");
1179
1180                 return true;
1181         }
1182         else
1183                 return false;
1184 }
1185
1186
1187 /*
1188  * Convert a C string to XML internal representation
1189  *
1190  * TODO maybe, libxml2's xmlreader is better? (do not construct DOM,
1191  * yet do not use SAX - see xml_reader.c)
1192  */
1193 static xmlDocPtr
1194 xml_parse(text *data, XmlOptionType xmloption_arg, bool preserve_whitespace,
1195                   xmlChar *encoding)
1196 {
1197         int32                           len;
1198         xmlChar                         *string;
1199         xmlChar                         *utf8string;
1200         xmlParserCtxtPtr        ctxt = NULL;
1201         xmlDocPtr                       doc = NULL;
1202
1203         len = VARSIZE(data) - VARHDRSZ; /* will be useful later */
1204         string = xml_text2xmlChar(data);
1205
1206         utf8string = pg_do_encoding_conversion(string,
1207                                                                                    len,
1208                                                                                    encoding ?
1209                                                                                    xmlChar_to_encoding(encoding) :
1210                                                                                    GetDatabaseEncoding(),
1211                                                                                    PG_UTF8);
1212
1213         xml_init();
1214
1215         /* We use a PG_TRY block to ensure libxml parser is cleaned up on error */
1216         PG_TRY();
1217         {
1218                 xmlInitParser();
1219                 ctxt = xmlNewParserCtxt();
1220                 if (ctxt == NULL)
1221                         xml_ereport(ERROR, ERRCODE_INTERNAL_ERROR,
1222                                                 "could not allocate parser context");
1223
1224                 if (xmloption_arg == XMLOPTION_DOCUMENT)
1225                 {
1226                         /*
1227                          * Note, that here we try to apply DTD defaults
1228                          * (XML_PARSE_DTDATTR) according to SQL/XML:10.16.7.d:
1229                          * 'Default valies defined by internal DTD are applied'.
1230                          * As for external DTDs, we try to support them too, (see
1231                          * SQL/XML:10.16.7.e)
1232                          */
1233                         doc = xmlCtxtReadDoc(ctxt, utf8string,
1234                                                                  NULL,
1235                                                                  "UTF-8",
1236                                                                  XML_PARSE_NOENT | XML_PARSE_DTDATTR
1237                                                                  | (preserve_whitespace ? 0 : XML_PARSE_NOBLANKS));
1238                         if (doc == NULL)
1239                                 xml_ereport(ERROR, ERRCODE_INVALID_XML_DOCUMENT,
1240                                                         "invalid XML document");
1241                 }
1242                 else
1243                 {
1244                         int                     res_code;
1245                         size_t count;
1246                         xmlChar    *version = NULL;
1247                         int standalone = -1;
1248
1249                         doc = xmlNewDoc(NULL);
1250
1251                         res_code = parse_xml_decl(utf8string, &count, &version, NULL, &standalone);
1252                         if (res_code != 0)
1253                                 xml_ereport_by_code(ERROR, ERRCODE_INVALID_XML_CONTENT,
1254                                                                         "invalid XML content: invalid XML declaration", res_code);
1255
1256                         res_code = xmlParseBalancedChunkMemory(doc, NULL, NULL, 0, utf8string + count, NULL);
1257                         if (res_code != 0)
1258                                 xml_ereport(ERROR, ERRCODE_INVALID_XML_CONTENT,
1259                                                         "invalid XML content");
1260
1261                         doc->version = xmlStrdup(version);
1262                         doc->encoding = xmlStrdup((xmlChar *) "UTF-8");
1263                         doc->standalone = standalone;
1264                 }
1265
1266                 if (ctxt)
1267                         xmlFreeParserCtxt(ctxt);
1268                 ctxt = NULL;
1269                 xmlCleanupParser();
1270         }
1271         PG_CATCH();
1272         {
1273                 if (doc)
1274                         xmlFreeDoc(doc);
1275                 if (ctxt)
1276                         xmlFreeParserCtxt(ctxt);
1277                 xmlCleanupParser();
1278
1279                 PG_RE_THROW();
1280         }
1281         PG_END_TRY();
1282
1283         return doc;
1284 }
1285
1286
1287 /*
1288  * xmlChar<->text convertions
1289  */
1290 static xmlChar *
1291 xml_text2xmlChar(text *in)
1292 {
1293         int32           len = VARSIZE(in) - VARHDRSZ;
1294         xmlChar         *res;
1295
1296         res = palloc(len + 1);
1297         memcpy(res, VARDATA(in), len);
1298         res[len] = '\0';
1299
1300         return(res);
1301 }
1302
1303
1304 /*
1305  * Wrappers for memory management functions
1306  */
1307 static void *
1308 xml_palloc(size_t size)
1309 {
1310         return palloc(size);
1311 }
1312
1313
1314 static void *
1315 xml_repalloc(void *ptr, size_t size)
1316 {
1317         return repalloc(ptr, size);
1318 }
1319
1320
1321 static void
1322 xml_pfree(void *ptr)
1323 {
1324         pfree(ptr);
1325 }
1326
1327
1328 static char *
1329 xml_pstrdup(const char *string)
1330 {
1331         return pstrdup(string);
1332 }
1333
1334
1335 /*
1336  * Wrapper for "ereport" function for XML-related errors.  The "msg"
1337  * is the SQL-level message; some can be adopted from the SQL/XML
1338  * standard.  This function adds libxml's native error messages, if
1339  * any, as detail.
1340  */
1341 static void
1342 xml_ereport(int level, int sqlcode, const char *msg)
1343 {
1344         char *detail;
1345
1346         if (xml_err_buf->len > 0)
1347         {
1348                 detail = pstrdup(xml_err_buf->data);
1349                 resetStringInfo(xml_err_buf);
1350         }
1351         else
1352                 detail = NULL;
1353
1354         /* libxml error messages end in '\n'; get rid of it */
1355         if (detail)
1356         {
1357                 size_t len;
1358
1359                 len = strlen(detail);
1360                 if (len > 0 && detail[len-1] == '\n')
1361                         detail[len-1] = '\0';
1362
1363                 ereport(level,
1364                                 (errcode(sqlcode),
1365                                  errmsg("%s", msg),
1366                                  errdetail("%s", detail)));
1367         }
1368         else
1369         {
1370                 ereport(level,
1371                                 (errcode(sqlcode),
1372                                  errmsg("%s", msg)));
1373         }
1374 }
1375
1376
1377 /*
1378  * Error handler for libxml error messages
1379  */
1380 static void
1381 xml_errorHandler(void *ctxt, const char *msg,...)
1382 {
1383         /* Append the formatted text to xml_err_buf */
1384         for (;;)
1385         {
1386                 va_list         args;
1387                 bool            success;
1388
1389                 /* Try to format the data. */
1390                 va_start(args, msg);
1391                 success = appendStringInfoVA(xml_err_buf, msg, args);
1392                 va_end(args);
1393
1394                 if (success)
1395                         break;
1396
1397                 /* Double the buffer size and try again. */
1398                 enlargeStringInfo(xml_err_buf, xml_err_buf->maxlen);
1399         }
1400 }
1401
1402
1403 /*
1404  * Wrapper for "ereport" function for XML-related errors.  The "msg"
1405  * is the SQL-level message; some can be adopted from the SQL/XML
1406  * standard.  This function uses "code" to create a textual detail
1407  * message.  At the moment, we only need to cover those codes that we
1408  * may raise in this file.
1409  */
1410 static void
1411 xml_ereport_by_code(int level, int sqlcode,
1412                                         const char *msg, int code)
1413 {
1414     const char *det;
1415
1416     switch (code)
1417         {
1418                 case XML_ERR_INVALID_CHAR:
1419                         det = "Invalid character value";
1420                         break;
1421                 case XML_ERR_SPACE_REQUIRED:
1422                         det = "Space required";
1423                         break;
1424                 case XML_ERR_STANDALONE_VALUE:
1425                         det = "standalone accepts only 'yes' or 'no'";
1426                         break;
1427                 case XML_ERR_VERSION_MISSING:
1428                         det = "Malformed declaration expecting version";
1429                         break;
1430                 case XML_ERR_MISSING_ENCODING:
1431                         det = "Missing encoding in text declaration";
1432                         break;
1433                 case XML_ERR_XMLDECL_NOT_FINISHED:
1434                         det = "Parsing XML declaration: '?>' expected";
1435                         break;
1436         default:
1437             det = "Unrecognized libxml error code: %d";
1438                         break;
1439         }
1440
1441         ereport(level,
1442                         (errcode(sqlcode),
1443                          errmsg("%s", msg),
1444                          errdetail(det, code)));
1445 }
1446
1447
1448 /*
1449  * Convert one char in the current server encoding to a Unicode codepoint.
1450  */
1451 static pg_wchar
1452 sqlchar_to_unicode(char *s)
1453 {
1454         char *utf8string;
1455         pg_wchar ret[2];                        /* need space for trailing zero */
1456
1457         utf8string = (char *) pg_do_encoding_conversion((unsigned char *) s,
1458                                                                                                         pg_mblen(s),
1459                                                                                                         GetDatabaseEncoding(),
1460                                                                                                         PG_UTF8);
1461
1462         pg_encoding_mb2wchar_with_len(PG_UTF8, utf8string, ret, pg_mblen(s));
1463
1464         return ret[0];
1465 }
1466
1467
1468 static bool
1469 is_valid_xml_namefirst(pg_wchar c)
1470 {
1471         /* (Letter | '_' | ':') */
1472         return (xmlIsBaseCharQ(c) || xmlIsIdeographicQ(c)
1473                         || c == '_' || c == ':');
1474 }
1475
1476
1477 static bool
1478 is_valid_xml_namechar(pg_wchar c)
1479 {
1480         /* Letter | Digit | '.' | '-' | '_' | ':' | CombiningChar | Extender */
1481         return (xmlIsBaseCharQ(c) || xmlIsIdeographicQ(c)
1482                         || xmlIsDigitQ(c)
1483                         || c == '.' || c == '-' || c == '_' || c == ':'
1484                         || xmlIsCombiningQ(c)
1485                         || xmlIsExtenderQ(c));
1486 }
1487 #endif /* USE_LIBXML */
1488
1489
1490 /*
1491  * Map SQL identifier to XML name; see SQL/XML:2003 section 9.1.
1492  */
1493 char *
1494 map_sql_identifier_to_xml_name(char *ident, bool fully_escaped,
1495                                                            bool escape_period)
1496 {
1497 #ifdef USE_LIBXML
1498         StringInfoData buf;
1499         char *p;
1500
1501         /*
1502          * SQL/XML doesn't make use of this case anywhere, so it's
1503          * probably a mistake.
1504          */
1505         Assert(fully_escaped || !escape_period);
1506
1507         initStringInfo(&buf);
1508
1509         for (p = ident; *p; p += pg_mblen(p))
1510         {
1511                 if (*p == ':' && (p == ident || fully_escaped))
1512                         appendStringInfo(&buf, "_x003A_");
1513                 else if (*p == '_' && *(p+1) == 'x')
1514                         appendStringInfo(&buf, "_x005F_");
1515                 else if (fully_escaped && p == ident &&
1516                                  pg_strncasecmp(p, "xml", 3) == 0)
1517                 {
1518                         if (*p == 'x')
1519                                 appendStringInfo(&buf, "_x0078_");
1520                         else
1521                                 appendStringInfo(&buf, "_x0058_");
1522                 }
1523                 else if (escape_period && *p == '.')
1524                         appendStringInfo(&buf, "_x002E_");
1525                 else
1526                 {
1527                         pg_wchar u = sqlchar_to_unicode(p);
1528
1529                         if ((p == ident)
1530                                 ? !is_valid_xml_namefirst(u)
1531                                 : !is_valid_xml_namechar(u))
1532                                 appendStringInfo(&buf, "_x%04X_", (unsigned int) u);
1533                         else
1534                                 appendBinaryStringInfo(&buf, p, pg_mblen(p));
1535                 }
1536         }
1537
1538         return buf.data;
1539 #else /* not USE_LIBXML */
1540         NO_XML_SUPPORT();
1541         return NULL;
1542 #endif /* not USE_LIBXML */
1543 }
1544
1545
1546 /*
1547  * Map a Unicode codepoint into the current server encoding.
1548  */
1549 static char *
1550 unicode_to_sqlchar(pg_wchar c)
1551 {
1552         static unsigned char utf8string[5];     /* need trailing zero */
1553
1554         if (c <= 0x7F)
1555         {
1556                 utf8string[0] = c;
1557         }
1558         else if (c <= 0x7FF)
1559         {
1560                 utf8string[0] = 0xC0 | ((c >> 6) & 0x1F);
1561                 utf8string[1] = 0x80 | (c & 0x3F);
1562         }
1563         else if (c <= 0xFFFF)
1564         {
1565                 utf8string[0] = 0xE0 | ((c >> 12) & 0x0F);
1566                 utf8string[1] = 0x80 | ((c >> 6) & 0x3F);
1567                 utf8string[2] = 0x80 | (c & 0x3F);
1568         }
1569         else
1570         {
1571                 utf8string[0] = 0xF0 | ((c >> 18) & 0x07);
1572                 utf8string[1] = 0x80 | ((c >> 12) & 0x3F);
1573                 utf8string[2] = 0x80 | ((c >> 6) & 0x3F);
1574                 utf8string[3] = 0x80 | (c & 0x3F);
1575         }
1576
1577         return (char *) pg_do_encoding_conversion(utf8string,
1578                                                                                           pg_mblen((char *) utf8string),
1579                                                                                           PG_UTF8,
1580                                                                                           GetDatabaseEncoding());
1581 }
1582
1583
1584 /*
1585  * Map XML name to SQL identifier; see SQL/XML:2003 section 9.17.
1586  */
1587 char *
1588 map_xml_name_to_sql_identifier(char *name)
1589 {
1590         StringInfoData buf;
1591         char *p;
1592
1593         initStringInfo(&buf);
1594
1595         for (p = name; *p; p += pg_mblen(p))
1596         {
1597                 if (*p == '_' && *(p+1) == 'x'
1598                         && isxdigit((unsigned char) *(p+2))
1599                         && isxdigit((unsigned char) *(p+3))
1600                         && isxdigit((unsigned char) *(p+4))
1601                         && isxdigit((unsigned char) *(p+5))
1602                         && *(p+6) == '_')
1603                 {
1604                         unsigned int u;
1605
1606                         sscanf(p + 2, "%X", &u);
1607                         appendStringInfoString(&buf, unicode_to_sqlchar(u));
1608                         p += 6;
1609                 }
1610                 else
1611                         appendBinaryStringInfo(&buf, p, pg_mblen(p));
1612         }
1613
1614         return buf.data;
1615 }
1616
1617 /*
1618  * Map SQL value to XML value; see SQL/XML:2003 section 9.16.
1619  */
1620 char *
1621 map_sql_value_to_xml_value(Datum value, Oid type)
1622 {
1623         StringInfoData buf;
1624
1625         initStringInfo(&buf);
1626
1627         if (type_is_array(type))
1628         {
1629                 ArrayType *array;
1630                 Oid elmtype;
1631                 int16 elmlen;
1632                 bool elmbyval;
1633                 char elmalign;
1634                 int                     num_elems;
1635                 Datum      *elem_values;
1636                 bool       *elem_nulls;
1637                 int i;
1638
1639                 array = DatumGetArrayTypeP(value);
1640                 elmtype = ARR_ELEMTYPE(array);
1641                 get_typlenbyvalalign(elmtype, &elmlen, &elmbyval, &elmalign);
1642
1643                 deconstruct_array(array, elmtype,
1644                                                   elmlen, elmbyval, elmalign,
1645                                                   &elem_values, &elem_nulls,
1646                                                   &num_elems);
1647
1648                 for (i = 0; i < num_elems; i++)
1649                 {
1650                         if (elem_nulls[i])
1651                                 continue;
1652                         appendStringInfoString(&buf, "<element>");
1653                         appendStringInfoString(&buf,
1654                                                                    map_sql_value_to_xml_value(elem_values[i],
1655                                                                                                                           elmtype));
1656                         appendStringInfoString(&buf, "</element>");
1657                 }
1658
1659                 pfree(elem_values);
1660                 pfree(elem_nulls);
1661         }
1662         else
1663         {
1664                 Oid typeOut;
1665                 bool isvarlena;
1666                 char *p, *str;
1667
1668                 /*
1669                  * Special XSD formatting for some data types
1670                  */
1671                 switch (type)
1672                 {
1673                         case BOOLOID:
1674                                 if (DatumGetBool(value))
1675                                         return "true";
1676                                 else
1677                                         return "false";
1678
1679                         case DATEOID:
1680                         {
1681                                 DateADT         date;
1682                                 struct pg_tm tm;
1683                                 char            buf[MAXDATELEN + 1];
1684
1685                                 date = DatumGetDateADT(value);
1686                                 j2date(date + POSTGRES_EPOCH_JDATE,
1687                                            &(tm.tm_year), &(tm.tm_mon), &(tm.tm_mday));
1688                                 EncodeDateOnly(&tm, USE_XSD_DATES, buf);
1689
1690                                 return pstrdup(buf);
1691                         }
1692
1693                         case TIMESTAMPOID:
1694                         {
1695                                 Timestamp       timestamp;
1696                                 struct pg_tm tm;
1697                                 fsec_t          fsec;
1698                                 char       *tzn = NULL;
1699                                 char            buf[MAXDATELEN + 1];
1700
1701                                 timestamp = DatumGetTimestamp(value);
1702
1703                                 /* XSD doesn't support infinite values */
1704                                 if (TIMESTAMP_NOT_FINITE(timestamp))
1705                                         ereport(ERROR,
1706                                                         (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
1707                                                          errmsg("timestamp out of range")));
1708                                 else if (timestamp2tm(timestamp, NULL, &tm, &fsec, NULL, NULL) == 0)
1709                                         EncodeDateTime(&tm, fsec, NULL, &tzn, USE_XSD_DATES, buf);
1710                                 else
1711                                         ereport(ERROR,
1712                                                         (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
1713                                                          errmsg("timestamp out of range")));
1714
1715                                 return pstrdup(buf);
1716                         }
1717
1718                         case TIMESTAMPTZOID:
1719                         {
1720                                 TimestampTz     timestamp;
1721                                 struct pg_tm tm;
1722                                 int                     tz;
1723                                 fsec_t          fsec;
1724                                 char       *tzn = NULL;
1725                                 char            buf[MAXDATELEN + 1];
1726
1727                                 timestamp = DatumGetTimestamp(value);
1728
1729                                 /* XSD doesn't support infinite values */
1730                                 if (TIMESTAMP_NOT_FINITE(timestamp))
1731                                         ereport(ERROR,
1732                                                         (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
1733                                                          errmsg("timestamp out of range")));
1734                                 else if (timestamp2tm(timestamp, &tz, &tm, &fsec, &tzn, NULL) == 0)
1735                                         EncodeDateTime(&tm, fsec, &tz, &tzn, USE_XSD_DATES, buf);
1736                                 else
1737                                         ereport(ERROR,
1738                                                         (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
1739                                                          errmsg("timestamp out of range")));
1740
1741                                 return pstrdup(buf);
1742                         }
1743                 }
1744
1745                 getTypeOutputInfo(type, &typeOut, &isvarlena);
1746                 str = OidOutputFunctionCall(typeOut, value);
1747
1748                 if (type == XMLOID)
1749                         return str;
1750
1751 #ifdef USE_LIBXML
1752                 if (type == BYTEAOID)
1753                 {
1754                         xmlBufferPtr buf;
1755                         xmlTextWriterPtr writer;
1756                         char *result;
1757
1758                         xml_init();
1759
1760                         buf = xmlBufferCreate();
1761                         writer = xmlNewTextWriterMemory(buf, 0);
1762
1763                         if (xmlbinary == XMLBINARY_BASE64)
1764                                 xmlTextWriterWriteBase64(writer, VARDATA(value), 0, VARSIZE(value) - VARHDRSZ);
1765                         else
1766                                 xmlTextWriterWriteBinHex(writer, VARDATA(value), 0, VARSIZE(value) - VARHDRSZ);
1767
1768                         xmlFreeTextWriter(writer);
1769                         result = pstrdup((const char *) xmlBufferContent(buf));
1770                         xmlBufferFree(buf);
1771                         return result;
1772                 }
1773 #endif /* USE_LIBXML */
1774
1775                 for (p = str; *p; p += pg_mblen(p))
1776                 {
1777                         switch (*p)
1778                         {
1779                                 case '&':
1780                                         appendStringInfo(&buf, "&amp;");
1781                                         break;
1782                                 case '<':
1783                                         appendStringInfo(&buf, "&lt;");
1784                                         break;
1785                                 case '>':
1786                                         appendStringInfo(&buf, "&gt;");
1787                                         break;
1788                                 case '\r':
1789                                         appendStringInfo(&buf, "&#x0d;");
1790                                         break;
1791                                 default:
1792                                         appendBinaryStringInfo(&buf, p, pg_mblen(p));
1793                                         break;
1794                         }
1795                 }
1796         }
1797
1798         return buf.data;
1799 }
1800
1801
1802 static char *
1803 _SPI_strdup(const char *s)
1804 {
1805         char *ret = SPI_palloc(strlen(s) + 1);
1806         strcpy(ret, s);
1807         return ret;
1808 }
1809
1810
1811 /*
1812  * SQL to XML mapping functions
1813  *
1814  * What follows below is intentionally organized so that you can read
1815  * along in the SQL/XML:2003 standard.  The functions are mostly split
1816  * up and ordered they way the clauses lay out in the standards
1817  * document, and the identifiers are also aligned with the standard
1818  * text.  (SQL/XML:2006 appears to be ordered differently,
1819  * unfortunately.)
1820  *
1821  * There are many things going on there:
1822  *
1823  * There are two kinds of mappings: Mapping SQL data (table contents)
1824  * to XML documents, and mapping SQL structure (the "schema") to XML
1825  * Schema.  And there are functions that do both at the same time.
1826  *
1827  * Then you can map a database, a schema, or a table, each in both
1828  * ways.  This breaks down recursively: Mapping a database invokes
1829  * mapping schemas, which invokes mapping tables, which invokes
1830  * mapping rows, which invokes mapping columns, although you can't
1831  * call the last two from the outside.  Because of this, there are a
1832  * number of xyz_internal() functions which are to be called both from
1833  * the function manager wrapper and from some upper layer in a
1834  * recursive call.
1835  *
1836  * See the documentation about what the common function arguments
1837  * nulls, tableforest, and targetns mean.
1838  *
1839  * Some style guidelines for XML output: Use double quotes for quoting
1840  * XML attributes.  Indent XML elements by two spaces, but remember
1841  * that a lot of code is called recursively at different levels, so
1842  * it's better not to indent rather than create output that indents
1843  * and outdents weirdly.  Add newlines to make the output look nice.
1844  */
1845
1846
1847 /*
1848  * Visibility of objects for XML mappings; see SQL/XML:2003 section
1849  * 4.8.5.
1850  */
1851
1852 /*
1853  * Given a query, which must return type oid as first column, produce
1854  * a list of Oids with the query results.
1855  */
1856 static List *
1857 query_to_oid_list(const char *query)
1858 {
1859         int                     i;
1860         List       *list = NIL;
1861
1862         SPI_execute(query, true, 0);
1863
1864         for (i = 0; i < SPI_processed; i++)
1865         {
1866                 Datum oid;
1867                 bool isnull;
1868
1869                 oid = SPI_getbinval(SPI_tuptable->vals[i],
1870                                                         SPI_tuptable->tupdesc,
1871                                                         1,
1872                                                         &isnull);
1873                 if (!isnull)
1874                         list = lappend_oid(list, DatumGetObjectId(oid));
1875         }
1876
1877         return list;
1878 }
1879
1880
1881 static List *
1882 schema_get_xml_visible_tables(Oid nspid)
1883 {
1884         StringInfoData query;
1885
1886         initStringInfo(&query);
1887         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);
1888
1889         return query_to_oid_list(query.data);
1890 }
1891
1892
1893 /* 
1894  * Including the system schemas is probably not useful for a database
1895  * mapping.
1896  */
1897 #define XML_VISIBLE_SCHEMAS_EXCLUDE "(nspname ~ '^pg_' OR nspname = 'information_schema')"
1898
1899 #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
1900
1901
1902 static List *
1903 database_get_xml_visible_schemas(void)
1904 {
1905         return query_to_oid_list(XML_VISIBLE_SCHEMAS " ORDER BY nspname;");
1906 }
1907
1908
1909 static List *
1910 database_get_xml_visible_tables(void)
1911 {
1912         /* At the moment there is no order required here. */
1913         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 ");");
1914 }
1915
1916
1917 /*
1918  * Map SQL table to XML and/or XML Schema document; see SQL/XML:2003
1919  * section 9.3.
1920  */
1921
1922 static StringInfo
1923 table_to_xml_internal(Oid relid,
1924                                           const char *xmlschema, bool nulls, bool tableforest,
1925                                           const char *targetns, bool top_level)
1926 {
1927         StringInfoData query;
1928
1929         initStringInfo(&query);
1930         appendStringInfo(&query, "SELECT * FROM %s",
1931                                          DatumGetCString(DirectFunctionCall1(regclassout,
1932                                                                                                 ObjectIdGetDatum(relid))));
1933         return query_to_xml_internal(query.data, get_rel_name(relid),
1934                                                                  xmlschema, nulls, tableforest,
1935                                                                  targetns, top_level);
1936 }
1937
1938
1939 Datum
1940 table_to_xml(PG_FUNCTION_ARGS)
1941 {
1942         Oid                     relid = PG_GETARG_OID(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));
1946
1947         PG_RETURN_XML_P(stringinfo_to_xmltype(table_to_xml_internal(relid, NULL,
1948                                                                                                                 nulls, tableforest,
1949                                                                                                                 targetns, true)));
1950 }
1951
1952
1953 Datum
1954 query_to_xml(PG_FUNCTION_ARGS)
1955 {
1956         char       *query = _textout(PG_GETARG_TEXT_P(0));
1957         bool            nulls = PG_GETARG_BOOL(1);
1958         bool            tableforest = PG_GETARG_BOOL(2);
1959         const char *targetns = _textout(PG_GETARG_TEXT_P(3));
1960
1961         PG_RETURN_XML_P(stringinfo_to_xmltype(query_to_xml_internal(query, NULL,
1962                                                                                                         NULL, nulls, tableforest,
1963                                                                                                         targetns, true)));
1964 }
1965
1966
1967 Datum
1968 cursor_to_xml(PG_FUNCTION_ARGS)
1969 {
1970         char       *name = _textout(PG_GETARG_TEXT_P(0));
1971         int32           count = PG_GETARG_INT32(1);
1972         bool            nulls = PG_GETARG_BOOL(2);
1973         bool            tableforest = PG_GETARG_BOOL(3);
1974         const char *targetns = _textout(PG_GETARG_TEXT_P(4));
1975
1976         StringInfoData result;
1977         Portal          portal;
1978         int                     i;
1979
1980         initStringInfo(&result);
1981
1982         SPI_connect();
1983         portal = SPI_cursor_find(name);
1984         if (portal == NULL)
1985                 ereport(ERROR,
1986                                 (errcode(ERRCODE_UNDEFINED_CURSOR),
1987                                  errmsg("cursor \"%s\" does not exist", name)));
1988
1989         SPI_cursor_fetch(portal, true, count);
1990         for (i = 0; i < SPI_processed; i++)
1991                 SPI_sql_row_to_xmlelement(i, &result, NULL, nulls,
1992                                                                   tableforest, targetns, true);
1993
1994         SPI_finish();
1995
1996         PG_RETURN_XML_P(stringinfo_to_xmltype(&result));
1997 }
1998
1999
2000 /*
2001  * Write the start tag of the root element of a data mapping.
2002  *
2003  * top_level means that this is the very top level of the eventual
2004  * output.  For example, when the user calls table_to_xml, then a call
2005  * with a table name to this function is the top level.  When the user
2006  * calls database_to_xml, then a call with a schema name to this
2007  * function is not the top level.  If top_level is false, then the XML
2008  * namespace declarations are omitted, because they supposedly already
2009  * appeared earlier in the output.  Repeating them is not wrong, but
2010  * it looks ugly.
2011  */
2012 static void
2013 xmldata_root_element_start(StringInfo result, const char *eltname,
2014                                                    const char *xmlschema, const char *targetns,
2015                                                    bool top_level)
2016 {
2017         /* This isn't really wrong but currently makes no sense. */
2018         Assert(top_level || !xmlschema);
2019
2020         appendStringInfo(result, "<%s", eltname);
2021         if (top_level)
2022         {
2023                 appendStringInfoString(result, " xmlns:xsi=\"" NAMESPACE_XSI "\"");
2024                 if (strlen(targetns) > 0)
2025                         appendStringInfo(result, " xmlns=\"%s\"", targetns);
2026         }
2027         if (xmlschema)
2028         {
2029                 /* FIXME: better targets */
2030                 if (strlen(targetns) > 0)
2031                         appendStringInfo(result, " xsi:schemaLocation=\"%s #\"", targetns);
2032                 else
2033                         appendStringInfo(result, " xsi:noNamespaceSchemaLocation=\"#\"");
2034         }
2035         appendStringInfo(result, ">\n\n");
2036 }
2037
2038
2039 static void
2040 xmldata_root_element_end(StringInfo result, const char *eltname)
2041 {
2042         appendStringInfo(result, "</%s>\n", eltname);
2043 }
2044
2045
2046 static StringInfo
2047 query_to_xml_internal(const char *query, char *tablename,
2048                                           const char *xmlschema, bool nulls, bool tableforest,
2049                                           const char *targetns, bool top_level)
2050 {
2051         StringInfo      result;
2052         char       *xmltn;
2053         int                     i;
2054
2055         if (tablename)
2056                 xmltn = map_sql_identifier_to_xml_name(tablename, true, false);
2057         else
2058                 xmltn = "table";
2059
2060         result = makeStringInfo();
2061
2062         SPI_connect();
2063         if (SPI_execute(query, true, 0) != SPI_OK_SELECT)
2064                 ereport(ERROR,
2065                                 (errcode(ERRCODE_DATA_EXCEPTION),
2066                                  errmsg("invalid query")));
2067
2068         if (!tableforest)
2069                 xmldata_root_element_start(result, xmltn, xmlschema,
2070                                                                    targetns, top_level);
2071
2072         if (xmlschema)
2073                 appendStringInfo(result, "%s\n\n", xmlschema);
2074
2075         for(i = 0; i < SPI_processed; i++)
2076                 SPI_sql_row_to_xmlelement(i, result, tablename, nulls,
2077                                                                   tableforest, targetns, top_level);
2078
2079         if (!tableforest)
2080                 xmldata_root_element_end(result, xmltn);
2081
2082         SPI_finish();
2083
2084         return result;
2085 }
2086
2087
2088 Datum
2089 table_to_xmlschema(PG_FUNCTION_ARGS)
2090 {
2091         Oid                     relid = PG_GETARG_OID(0);
2092         bool            nulls = PG_GETARG_BOOL(1);
2093         bool            tableforest = PG_GETARG_BOOL(2);
2094         const char *targetns = _textout(PG_GETARG_TEXT_P(3));
2095         const char *result;
2096         Relation rel;
2097
2098         rel = heap_open(relid, AccessShareLock);
2099         result = map_sql_table_to_xmlschema(rel->rd_att, relid, nulls,
2100                                                                                 tableforest, targetns);
2101         heap_close(rel, NoLock);
2102
2103         PG_RETURN_XML_P(cstring_to_xmltype(result));
2104 }
2105
2106
2107 Datum
2108 query_to_xmlschema(PG_FUNCTION_ARGS)
2109 {
2110         char       *query = _textout(PG_GETARG_TEXT_P(0));
2111         bool            nulls = PG_GETARG_BOOL(1);
2112         bool            tableforest = PG_GETARG_BOOL(2);
2113         const char *targetns = _textout(PG_GETARG_TEXT_P(3));
2114         const char *result;
2115         SPIPlanPtr      plan;
2116         Portal          portal;
2117
2118         SPI_connect();
2119         plan = SPI_prepare(query, 0, NULL);
2120         portal = SPI_cursor_open(NULL, plan, NULL, NULL, true);
2121         result = _SPI_strdup(map_sql_table_to_xmlschema(portal->tupDesc,
2122                                                                                                         InvalidOid, nulls,
2123                                                                                                         tableforest, targetns));
2124         SPI_cursor_close(portal);
2125         SPI_finish();
2126
2127         PG_RETURN_XML_P(cstring_to_xmltype(result));
2128 }
2129
2130
2131 Datum
2132 cursor_to_xmlschema(PG_FUNCTION_ARGS)
2133 {
2134         char       *name = _textout(PG_GETARG_TEXT_P(0));
2135         bool            nulls = PG_GETARG_BOOL(1);
2136         bool            tableforest = PG_GETARG_BOOL(2);
2137         const char *targetns = _textout(PG_GETARG_TEXT_P(3));
2138         const char *xmlschema;
2139         Portal          portal;
2140
2141         SPI_connect();
2142         portal = SPI_cursor_find(name);
2143         if (portal == NULL)
2144                 ereport(ERROR,
2145                                 (errcode(ERRCODE_UNDEFINED_CURSOR),
2146                                  errmsg("cursor \"%s\" does not exist", name)));
2147
2148         xmlschema = _SPI_strdup(map_sql_table_to_xmlschema(portal->tupDesc,
2149                                                                                                            InvalidOid, nulls,
2150                                                                                                            tableforest, targetns));
2151         SPI_finish();
2152
2153         PG_RETURN_XML_P(cstring_to_xmltype(xmlschema));
2154 }
2155
2156
2157 Datum
2158 table_to_xml_and_xmlschema(PG_FUNCTION_ARGS)
2159 {
2160         Oid                     relid = PG_GETARG_OID(0);
2161         bool            nulls = PG_GETARG_BOOL(1);
2162         bool            tableforest = PG_GETARG_BOOL(2);
2163         const char *targetns = _textout(PG_GETARG_TEXT_P(3));
2164         Relation        rel;
2165         const char *xmlschema;
2166
2167         rel = heap_open(relid, AccessShareLock);
2168         xmlschema = map_sql_table_to_xmlschema(rel->rd_att, relid, nulls,
2169                                                                                    tableforest, targetns);
2170         heap_close(rel, NoLock);
2171
2172         PG_RETURN_XML_P(stringinfo_to_xmltype(table_to_xml_internal(relid,
2173                                                                                         xmlschema, nulls, tableforest,
2174                                                                                         targetns, true)));
2175 }
2176
2177
2178 Datum
2179 query_to_xml_and_xmlschema(PG_FUNCTION_ARGS)
2180 {
2181         char       *query = _textout(PG_GETARG_TEXT_P(0));
2182         bool            nulls = PG_GETARG_BOOL(1);
2183         bool            tableforest = PG_GETARG_BOOL(2);
2184         const char *targetns = _textout(PG_GETARG_TEXT_P(3));
2185
2186         const char *xmlschema;
2187         SPIPlanPtr      plan;
2188         Portal          portal;
2189
2190         SPI_connect();
2191         plan = SPI_prepare(query, 0, NULL);
2192         portal = SPI_cursor_open(NULL, plan, NULL, NULL, true);
2193         xmlschema = _SPI_strdup(map_sql_table_to_xmlschema(portal->tupDesc,
2194                                                                    InvalidOid, nulls, tableforest, targetns));
2195         SPI_cursor_close(portal);
2196         SPI_finish();
2197
2198         PG_RETURN_XML_P(stringinfo_to_xmltype(query_to_xml_internal(query, NULL,
2199                                                                         xmlschema, nulls, tableforest,
2200                                                                         targetns, true)));
2201 }
2202
2203
2204 /*
2205  * Map SQL schema to XML and/or XML Schema document; see SQL/XML:2003
2206  * section 9.4.
2207  */
2208
2209 static StringInfo
2210 schema_to_xml_internal(Oid nspid, const char *xmlschema, bool nulls,
2211                                            bool tableforest, const char *targetns, bool top_level)
2212 {
2213         StringInfo      result;
2214         char       *xmlsn;
2215         List       *relid_list;
2216         ListCell   *cell;
2217
2218         xmlsn = map_sql_identifier_to_xml_name(get_namespace_name(nspid),
2219                                                                                    true, false);
2220         result = makeStringInfo();
2221
2222         xmldata_root_element_start(result, xmlsn, xmlschema, targetns, top_level);
2223
2224         if (xmlschema)
2225                 appendStringInfo(result, "%s\n\n", xmlschema);
2226
2227         SPI_connect();
2228
2229         relid_list = schema_get_xml_visible_tables(nspid);
2230
2231         SPI_push();
2232
2233         foreach(cell, relid_list)
2234         {
2235                 Oid relid = lfirst_oid(cell);
2236                 StringInfo subres;
2237
2238                 subres = table_to_xml_internal(relid, NULL, nulls, tableforest,
2239                                                                            targetns, false);
2240
2241                 appendStringInfoString(result, subres->data);
2242                 appendStringInfoChar(result, '\n');
2243         }
2244
2245         SPI_pop();
2246         SPI_finish();
2247
2248         xmldata_root_element_end(result, xmlsn);
2249
2250         return result;
2251 }
2252
2253
2254 Datum
2255 schema_to_xml(PG_FUNCTION_ARGS)
2256 {
2257         Name            name = PG_GETARG_NAME(0);
2258         bool            nulls = PG_GETARG_BOOL(1);
2259         bool            tableforest = PG_GETARG_BOOL(2);
2260         const char *targetns = _textout(PG_GETARG_TEXT_P(3));
2261
2262         char       *schemaname;
2263         Oid                     nspid;
2264
2265         schemaname = NameStr(*name);
2266         nspid = LookupExplicitNamespace(schemaname);
2267
2268         PG_RETURN_XML_P(stringinfo_to_xmltype(schema_to_xml_internal(nspid, NULL,
2269                                                                                  nulls, tableforest, targetns, true)));
2270 }
2271
2272
2273 /*
2274  * Write the start element of the root element of an XML Schema mapping.
2275  */
2276 static void
2277 xsd_schema_element_start(StringInfo result, const char *targetns)
2278 {
2279         appendStringInfoString(result,
2280                                                    "<xsd:schema\n"
2281                                                    "    xmlns:xsd=\"" NAMESPACE_XSD "\"");
2282         if (strlen(targetns) > 0)
2283                 appendStringInfo(result,
2284                                                  "\n"
2285                                                  "    targetNamespace=\"%s\"\n"
2286                                                  "    elementFormDefault=\"qualified\"",
2287                                                  targetns);
2288         appendStringInfoString(result,
2289                                                    ">\n\n");
2290 }
2291
2292
2293 static void
2294 xsd_schema_element_end(StringInfo result)
2295 {
2296         appendStringInfoString(result, "</xsd:schema>");
2297 }
2298
2299
2300 static StringInfo
2301 schema_to_xmlschema_internal(const char *schemaname, bool nulls,
2302                                                          bool tableforest, const char *targetns)
2303 {
2304         Oid                     nspid;
2305         List       *relid_list;
2306         List       *tupdesc_list;
2307         ListCell   *cell;
2308         StringInfo      result;
2309
2310         result = makeStringInfo();
2311
2312         nspid = LookupExplicitNamespace(schemaname);
2313
2314         xsd_schema_element_start(result, targetns);
2315
2316         SPI_connect();
2317
2318         relid_list = schema_get_xml_visible_tables(nspid);
2319
2320         tupdesc_list = NIL;
2321         foreach (cell, relid_list)
2322         {
2323                 Relation rel;
2324
2325                 rel = heap_open(lfirst_oid(cell), AccessShareLock);
2326                 tupdesc_list = lappend(tupdesc_list, CreateTupleDescCopy(rel->rd_att));
2327                 heap_close(rel, NoLock);
2328         }
2329
2330         appendStringInfoString(result,
2331                                                    map_sql_typecoll_to_xmlschema_types(tupdesc_list));
2332
2333         appendStringInfoString(result,
2334                                                    map_sql_schema_to_xmlschema_types(nspid, relid_list,
2335                                                                                                                          nulls, tableforest, targetns));
2336
2337         xsd_schema_element_end(result);
2338
2339         SPI_finish();
2340
2341         return result;
2342 }
2343
2344
2345 Datum
2346 schema_to_xmlschema(PG_FUNCTION_ARGS)
2347 {
2348         Name            name = PG_GETARG_NAME(0);
2349         bool            nulls = PG_GETARG_BOOL(1);
2350         bool            tableforest = PG_GETARG_BOOL(2);
2351         const char *targetns = _textout(PG_GETARG_TEXT_P(3));
2352
2353         PG_RETURN_XML_P(stringinfo_to_xmltype(schema_to_xmlschema_internal(NameStr(*name),
2354                                                                                            nulls, tableforest, targetns)));
2355 }
2356
2357
2358 Datum
2359 schema_to_xml_and_xmlschema(PG_FUNCTION_ARGS)
2360 {
2361         Name            name = PG_GETARG_NAME(0);
2362         bool            nulls = PG_GETARG_BOOL(1);
2363         bool            tableforest = PG_GETARG_BOOL(2);
2364         const char *targetns = _textout(PG_GETARG_TEXT_P(3));
2365         char       *schemaname;
2366         Oid                     nspid;
2367         StringInfo      xmlschema;
2368
2369         schemaname = NameStr(*name);
2370         nspid = LookupExplicitNamespace(schemaname);
2371
2372         xmlschema = schema_to_xmlschema_internal(schemaname, nulls,
2373                                                                                          tableforest, targetns);
2374
2375         PG_RETURN_XML_P(stringinfo_to_xmltype(schema_to_xml_internal(nspid,
2376                                                                                          xmlschema->data, nulls,
2377                                                                                          tableforest, targetns, true)));
2378 }
2379
2380
2381 /*
2382  * Map SQL database to XML and/or XML Schema document; see SQL/XML:2003
2383  * section 9.5.
2384  */
2385
2386 static StringInfo
2387 database_to_xml_internal(const char *xmlschema, bool nulls,
2388                                                  bool tableforest, const char *targetns)
2389 {
2390         StringInfo      result;
2391         List       *nspid_list;
2392         ListCell   *cell;
2393         char       *xmlcn;
2394
2395         xmlcn = map_sql_identifier_to_xml_name(get_database_name(MyDatabaseId),
2396                                                                                    true, false);
2397         result = makeStringInfo();
2398
2399         xmldata_root_element_start(result, xmlcn, xmlschema, targetns, true);
2400
2401         if (xmlschema)
2402                 appendStringInfo(result, "%s\n\n", xmlschema);
2403
2404         SPI_connect();
2405
2406         nspid_list = database_get_xml_visible_schemas();
2407
2408         SPI_push();
2409
2410         foreach(cell, nspid_list)
2411         {
2412                 Oid nspid = lfirst_oid(cell);
2413                 StringInfo subres;
2414
2415                 subres = schema_to_xml_internal(nspid, NULL, nulls,
2416                                                                                 tableforest, targetns, false);
2417
2418                 appendStringInfoString(result, subres->data);
2419                 appendStringInfoChar(result, '\n');
2420         }
2421
2422         SPI_pop();
2423         SPI_finish();
2424
2425         xmldata_root_element_end(result, xmlcn);
2426
2427         return result;
2428 }
2429
2430
2431 Datum
2432 database_to_xml(PG_FUNCTION_ARGS)
2433 {
2434         bool            nulls = PG_GETARG_BOOL(0);
2435         bool            tableforest = PG_GETARG_BOOL(1);
2436         const char *targetns = _textout(PG_GETARG_TEXT_P(2));
2437
2438         PG_RETURN_XML_P(stringinfo_to_xmltype(database_to_xml_internal(NULL, nulls,
2439                                                                                                    tableforest, targetns)));
2440 }
2441
2442
2443 static StringInfo
2444 database_to_xmlschema_internal(bool nulls, bool tableforest,
2445                                                            const char *targetns)
2446 {
2447         List       *relid_list;
2448         List       *nspid_list;
2449         List       *tupdesc_list;
2450         ListCell   *cell;
2451         StringInfo      result;
2452
2453         result = makeStringInfo();
2454
2455         xsd_schema_element_start(result, targetns);
2456
2457         SPI_connect();
2458
2459         relid_list = database_get_xml_visible_tables();
2460         nspid_list = database_get_xml_visible_schemas();
2461
2462         tupdesc_list = NIL;
2463         foreach (cell, relid_list)
2464         {
2465                 Relation rel;
2466
2467                 rel = heap_open(lfirst_oid(cell), AccessShareLock);
2468                 tupdesc_list = lappend(tupdesc_list, CreateTupleDescCopy(rel->rd_att));
2469                 heap_close(rel, NoLock);
2470         }
2471
2472         appendStringInfoString(result,
2473                                                    map_sql_typecoll_to_xmlschema_types(tupdesc_list));
2474
2475         appendStringInfoString(result,
2476                                                    map_sql_catalog_to_xmlschema_types(nspid_list, nulls, tableforest, targetns));
2477
2478         xsd_schema_element_end(result);
2479
2480         SPI_finish();
2481
2482         return result;
2483 }
2484
2485
2486 Datum
2487 database_to_xmlschema(PG_FUNCTION_ARGS)
2488 {
2489         bool            nulls = PG_GETARG_BOOL(0);
2490         bool            tableforest = PG_GETARG_BOOL(1);
2491         const char *targetns = _textout(PG_GETARG_TEXT_P(2));
2492
2493         PG_RETURN_XML_P(stringinfo_to_xmltype(database_to_xmlschema_internal(nulls,
2494                                                                                                          tableforest, targetns)));
2495 }
2496
2497
2498 Datum
2499 database_to_xml_and_xmlschema(PG_FUNCTION_ARGS)
2500 {
2501         bool            nulls = PG_GETARG_BOOL(0);
2502         bool            tableforest = PG_GETARG_BOOL(1);
2503         const char *targetns = _textout(PG_GETARG_TEXT_P(2));
2504         StringInfo      xmlschema;
2505
2506         xmlschema = database_to_xmlschema_internal(nulls, tableforest, targetns);
2507
2508         PG_RETURN_XML_P(stringinfo_to_xmltype(database_to_xml_internal(xmlschema->data,
2509                                                                                            nulls, tableforest, targetns)));
2510 }
2511
2512
2513 /*
2514  * Map a multi-part SQL name to an XML name; see SQL/XML:2003 section
2515  * 9.2.
2516  */
2517 static char *
2518 map_multipart_sql_identifier_to_xml_name(char *a, char *b, char *c, char *d)
2519 {
2520         StringInfoData result;
2521
2522         initStringInfo(&result);
2523
2524         if (a)
2525                 appendStringInfo(&result, "%s",
2526                                                  map_sql_identifier_to_xml_name(a, true, true));
2527         if (b)
2528                 appendStringInfo(&result, ".%s",
2529                                                  map_sql_identifier_to_xml_name(b, true, true));
2530         if (c)
2531                 appendStringInfo(&result, ".%s",
2532                                                  map_sql_identifier_to_xml_name(c, true, true));
2533         if (d)
2534                 appendStringInfo(&result, ".%s",
2535                                                  map_sql_identifier_to_xml_name(d, true, true));
2536
2537         return result.data;
2538 }
2539
2540
2541 /*
2542  * Map an SQL table to an XML Schema document; see SQL/XML:2003
2543  * section 9.3.
2544  *
2545  * Map an SQL table to XML Schema data types; see SQL/XML:2003 section
2546  * 9.6.
2547  */
2548 static const char *
2549 map_sql_table_to_xmlschema(TupleDesc tupdesc, Oid relid, bool nulls,
2550                                                    bool tableforest, const char *targetns)
2551 {
2552         int                     i;
2553         char       *xmltn;
2554         char       *tabletypename;
2555         char       *rowtypename;
2556         StringInfoData result;
2557
2558         initStringInfo(&result);
2559
2560         if (OidIsValid(relid))
2561         {
2562                 HeapTuple tuple;
2563                 Form_pg_class reltuple;
2564
2565                 tuple = SearchSysCache(RELOID,
2566                                                            ObjectIdGetDatum(relid),
2567                                                            0, 0, 0);
2568                 if (!HeapTupleIsValid(tuple))
2569                         elog(ERROR, "cache lookup failed for relation %u", relid);
2570                 reltuple = (Form_pg_class) GETSTRUCT(tuple);
2571
2572                 xmltn = map_sql_identifier_to_xml_name(NameStr(reltuple->relname),
2573                                                                                            true, false);
2574
2575                 tabletypename = map_multipart_sql_identifier_to_xml_name("TableType",
2576                                                                                                                                  get_database_name(MyDatabaseId),
2577                                                                                                                                  get_namespace_name(reltuple->relnamespace),
2578                                                                                                                                  NameStr(reltuple->relname));
2579
2580                 rowtypename = map_multipart_sql_identifier_to_xml_name("RowType",
2581                                                                                                                            get_database_name(MyDatabaseId),
2582                                                                                                                            get_namespace_name(reltuple->relnamespace),
2583                                                                                                                            NameStr(reltuple->relname));
2584
2585                 ReleaseSysCache(tuple);
2586         }
2587         else
2588         {
2589                 if (tableforest)
2590                         xmltn = "row";
2591                 else
2592                         xmltn = "table";
2593
2594                 tabletypename = "TableType";
2595                 rowtypename = "RowType";
2596         }
2597
2598         xsd_schema_element_start(&result, targetns);
2599
2600         appendStringInfoString(&result,
2601                                                    map_sql_typecoll_to_xmlschema_types(list_make1(tupdesc)));
2602
2603         appendStringInfo(&result,
2604                                          "<xsd:complexType name=\"%s\">\n"
2605                                          "  <xsd:sequence>\n",
2606                                          rowtypename);
2607
2608         for (i = 0; i < tupdesc->natts; i++)
2609                 appendStringInfo(&result,
2610                                                  "    <xsd:element name=\"%s\" type=\"%s\"%s></xsd:element>\n",
2611                                                  map_sql_identifier_to_xml_name(NameStr(tupdesc->attrs[i]->attname),
2612                                                                                                                 true, false),
2613                                                  map_sql_type_to_xml_name(tupdesc->attrs[i]->atttypid, -1),
2614                                                  nulls ? " nillable=\"true\"" : " minOccurs=\"0\"");
2615
2616         appendStringInfoString(&result,
2617                                                    "  </xsd:sequence>\n"
2618                                                    "</xsd:complexType>\n\n");
2619
2620         if (!tableforest)
2621         {
2622                 appendStringInfo(&result,
2623                                                  "<xsd:complexType name=\"%s\">\n"
2624                                                  "  <xsd:sequence>\n"
2625                                                  "    <xsd:element name=\"row\" type=\"%s\" minOccurs=\"0\" maxOccurs=\"unbounded\"/>\n"
2626                                                  "  </xsd:sequence>\n"
2627                                                  "</xsd:complexType>\n\n",
2628                                                  tabletypename, rowtypename);
2629
2630                 appendStringInfo(&result,
2631                                                  "<xsd:element name=\"%s\" type=\"%s\"/>\n\n",
2632                                                  xmltn, tabletypename);
2633         }
2634         else
2635                 appendStringInfo(&result,
2636                                                  "<xsd:element name=\"%s\" type=\"%s\"/>\n\n",
2637                                                  xmltn, rowtypename);
2638
2639         xsd_schema_element_end(&result);
2640
2641         return result.data;
2642 }
2643
2644
2645 /*
2646  * Map an SQL schema to XML Schema data types; see SQL/XML section
2647  * 9.7.
2648  */
2649 static const char *
2650 map_sql_schema_to_xmlschema_types(Oid nspid, List *relid_list, bool nulls,
2651                                                                   bool tableforest, const char *targetns)
2652 {
2653         char       *dbname;
2654         char       *nspname;
2655         char       *xmlsn;
2656         char       *schematypename;
2657         StringInfoData result;
2658         ListCell   *cell;
2659
2660         dbname = get_database_name(MyDatabaseId);
2661         nspname = get_namespace_name(nspid);
2662
2663         initStringInfo(&result);
2664
2665         xmlsn = map_sql_identifier_to_xml_name(nspname, true, false);
2666
2667         schematypename = map_multipart_sql_identifier_to_xml_name("SchemaType",
2668                                                                                                                           dbname,
2669                                                                                                                           nspname,
2670                                                                                                                           NULL);
2671
2672         appendStringInfo(&result,
2673                                          "<xsd:complexType name=\"%s\">\n", schematypename);
2674         if (!tableforest)
2675                 appendStringInfoString(&result,
2676                                                            "  <xsd:all>\n");
2677         else
2678                 appendStringInfoString(&result,
2679                                                            "  <xsd:sequence>\n");
2680
2681         foreach (cell, relid_list)
2682         {
2683                 Oid relid = lfirst_oid(cell);
2684                 char *relname = get_rel_name(relid);
2685                 char *xmltn = map_sql_identifier_to_xml_name(relname, true, false);
2686                 char *tabletypename = map_multipart_sql_identifier_to_xml_name(tableforest ? "RowType" : "TableType",
2687                                                                                                                                            dbname,
2688                                                                                                                                            nspname,
2689                                                                                                                                            relname);
2690
2691                 if (!tableforest)
2692                         appendStringInfo(&result,
2693                                                          "    <xsd:element name=\"%s\" type=\"%s\" />\n",
2694                                                          xmltn, tabletypename);
2695                 else
2696                         appendStringInfo(&result,
2697                                                          "    <xsd:element name=\"%s\" type=\"%s\" minOccurs=\"0\" maxOccurs=\"unbounded\" />\n",
2698                                                          xmltn, tabletypename);
2699         }
2700
2701         if (!tableforest)
2702                 appendStringInfoString(&result,
2703                                                            "  </xsd:all>\n");
2704         else
2705                 appendStringInfoString(&result,
2706                                                            "  </xsd:sequence>\n");
2707         appendStringInfoString(&result,
2708                                                    "</xsd:complexType>\n\n");
2709
2710         appendStringInfo(&result,
2711                                          "<xsd:element name=\"%s\" type=\"%s\"/>\n\n",
2712                                          xmlsn, schematypename);
2713
2714         return result.data;
2715 }
2716
2717
2718 /*
2719  * Map an SQL catalog to XML Schema data types; see SQL/XML section
2720  * 9.8.
2721  */
2722 static const char *
2723 map_sql_catalog_to_xmlschema_types(List *nspid_list, bool nulls,
2724                                                                    bool tableforest, const char *targetns)
2725 {
2726         char       *dbname;
2727         char       *xmlcn;
2728         char       *catalogtypename;
2729         StringInfoData result;
2730         ListCell   *cell;
2731
2732         dbname = get_database_name(MyDatabaseId);
2733
2734         initStringInfo(&result);
2735
2736         xmlcn = map_sql_identifier_to_xml_name(dbname, true, false);
2737
2738         catalogtypename = map_multipart_sql_identifier_to_xml_name("CatalogType",
2739                                                                                                                            dbname,
2740                                                                                                                            NULL,
2741                                                                                                                            NULL);
2742
2743         appendStringInfo(&result,
2744                                          "<xsd:complexType name=\"%s\">\n", catalogtypename);
2745         appendStringInfoString(&result,
2746                                                    "  <xsd:all>\n");
2747
2748         foreach (cell, nspid_list)
2749         {
2750                 Oid nspid = lfirst_oid(cell);
2751                 char       *nspname = get_namespace_name(nspid);
2752                 char *xmlsn = map_sql_identifier_to_xml_name(nspname, true, false);
2753                 char *schematypename = map_multipart_sql_identifier_to_xml_name("SchemaType",
2754                                                                                                                                                 dbname,
2755                                                                                                                                                 nspname,
2756                                                                                                                                                 NULL);
2757
2758                 appendStringInfo(&result,
2759                                                  "    <xsd:element name=\"%s\" type=\"%s\" />\n",
2760                                                  xmlsn, schematypename);
2761         }
2762
2763         appendStringInfoString(&result,
2764                                                    "  </xsd:all>\n");
2765         appendStringInfoString(&result,
2766                                                    "</xsd:complexType>\n\n");
2767
2768         appendStringInfo(&result,
2769                                          "<xsd:element name=\"%s\" type=\"%s\"/>\n\n",
2770                                          xmlcn, catalogtypename);
2771
2772         return result.data;
2773 }
2774
2775
2776 /*
2777  * Map an SQL data type to an XML name; see SQL/XML:2003 section 9.9.
2778  */
2779 static const char *
2780 map_sql_type_to_xml_name(Oid typeoid, int typmod)
2781 {
2782         StringInfoData result;
2783
2784         initStringInfo(&result);
2785
2786         switch(typeoid)
2787         {
2788                 case BPCHAROID:
2789                         if (typmod == -1)
2790                                 appendStringInfo(&result, "CHAR");
2791                         else
2792                                 appendStringInfo(&result, "CHAR_%d", typmod - VARHDRSZ);
2793                         break;
2794                 case VARCHAROID:
2795                         if (typmod == -1)
2796                                 appendStringInfo(&result, "VARCHAR");
2797                         else
2798                                 appendStringInfo(&result, "VARCHAR_%d", typmod - VARHDRSZ);
2799                         break;
2800                 case NUMERICOID:
2801                         if (typmod == -1)
2802                                 appendStringInfo(&result, "NUMERIC");
2803                         else
2804                                 appendStringInfo(&result, "NUMERIC_%d_%d",
2805                                                                  ((typmod - VARHDRSZ) >> 16) & 0xffff,
2806                                                                  (typmod - VARHDRSZ) & 0xffff);
2807                         break;
2808                 case INT4OID:
2809                         appendStringInfo(&result, "INTEGER");
2810                         break;
2811                 case INT2OID:
2812                         appendStringInfo(&result, "SMALLINT");
2813                         break;
2814                 case INT8OID:
2815                         appendStringInfo(&result, "BIGINT");
2816                         break;
2817                 case FLOAT4OID:
2818                         appendStringInfo(&result, "REAL");
2819                         break;
2820                 case FLOAT8OID:
2821                         appendStringInfo(&result, "DOUBLE");
2822                         break;
2823                 case BOOLOID:
2824                         appendStringInfo(&result, "BOOLEAN");
2825                         break;
2826                 case TIMEOID:
2827                         if (typmod == -1)
2828                                 appendStringInfo(&result, "TIME");
2829                         else
2830                                 appendStringInfo(&result, "TIME_%d", typmod);
2831                         break;
2832                 case TIMETZOID:
2833                         if (typmod == -1)
2834                                 appendStringInfo(&result, "TIME_WTZ");
2835                         else
2836                                 appendStringInfo(&result, "TIME_WTZ_%d", typmod);
2837                         break;
2838                 case TIMESTAMPOID:
2839                         if (typmod == -1)
2840                                 appendStringInfo(&result, "TIMESTAMP");
2841                         else
2842                                 appendStringInfo(&result, "TIMESTAMP_%d", typmod);
2843                         break;
2844                 case TIMESTAMPTZOID:
2845                         if (typmod == -1)
2846                                 appendStringInfo(&result, "TIMESTAMP_WTZ");
2847                         else
2848                                 appendStringInfo(&result, "TIMESTAMP_WTZ_%d", typmod);
2849                         break;
2850                 case DATEOID:
2851                         appendStringInfo(&result, "DATE");
2852                         break;
2853                 case XMLOID:
2854                         appendStringInfo(&result, "XML");
2855                         break;
2856                 default:
2857                 {
2858                         HeapTuple tuple;
2859                         Form_pg_type typtuple;
2860
2861                         tuple = SearchSysCache(TYPEOID,
2862                                                                    ObjectIdGetDatum(typeoid),
2863                                                                    0, 0, 0);
2864                         if (!HeapTupleIsValid(tuple))
2865                                 elog(ERROR, "cache lookup failed for type %u", typeoid);
2866                         typtuple = (Form_pg_type) GETSTRUCT(tuple);
2867
2868                         appendStringInfoString(&result,
2869                                                                    map_multipart_sql_identifier_to_xml_name((typtuple->typtype == TYPTYPE_DOMAIN) ? "Domain" : "UDT",
2870                                                                                                                                                         get_database_name(MyDatabaseId),
2871                                                                                                                                                         get_namespace_name(typtuple->typnamespace),
2872                                                                                                                                                         NameStr(typtuple->typname)));
2873
2874                         ReleaseSysCache(tuple);
2875                 }
2876         }
2877
2878         return result.data;
2879 }
2880
2881
2882 /*
2883  * Map a collection of SQL data types to XML Schema data types; see
2884  * SQL/XML:2002 section 9.10.
2885  */
2886 static const char *
2887 map_sql_typecoll_to_xmlschema_types(List *tupdesc_list)
2888 {
2889         List       *uniquetypes = NIL;
2890         int                     i;
2891         StringInfoData result;
2892         ListCell   *cell0;
2893
2894         /* extract all column types used in the set of TupleDescs */
2895         foreach(cell0, tupdesc_list)
2896         {
2897                 TupleDesc tupdesc = (TupleDesc) lfirst(cell0);
2898
2899                 for (i = 0; i < tupdesc->natts; i++)
2900                 {
2901                         if (tupdesc->attrs[i]->attisdropped)
2902                                 continue;
2903                         uniquetypes = list_append_unique_oid(uniquetypes,
2904                                                                                                  tupdesc->attrs[i]->atttypid);
2905                 }
2906         }
2907
2908         /* add base types of domains */
2909         foreach(cell0, uniquetypes)
2910         {
2911                 Oid typid = lfirst_oid(cell0);
2912                 Oid basetypid = getBaseType(typid);
2913
2914                 if (basetypid != typid)
2915                         uniquetypes = list_append_unique_oid(uniquetypes, basetypid);
2916         }
2917
2918         /* Convert to textual form */
2919         initStringInfo(&result);
2920
2921         foreach(cell0, uniquetypes)
2922         {
2923                 appendStringInfo(&result, "%s\n",
2924                                                  map_sql_type_to_xmlschema_type(lfirst_oid(cell0),
2925                                                                                                                 -1));
2926         }
2927
2928         return result.data;
2929 }
2930
2931
2932 /*
2933  * Map an SQL data type to a named XML Schema data type; see SQL/XML
2934  * sections 9.11 and 9.15.
2935  *
2936  * (The distinction between 9.11 and 9.15 is basically that 9.15 adds
2937  * a name attribute, which this function does.  The name-less version
2938  * 9.11 doesn't appear to be required anywhere.)
2939  */
2940 static const char *
2941 map_sql_type_to_xmlschema_type(Oid typeoid, int typmod)
2942 {
2943         StringInfoData result;
2944         const char *typename = map_sql_type_to_xml_name(typeoid, typmod);
2945
2946         initStringInfo(&result);
2947
2948         if (typeoid == XMLOID)
2949         {
2950                 appendStringInfo(&result,
2951                                                  "<xsd:complexType mixed=\"true\">\n"
2952                                                  "  <xsd:sequence>\n"
2953                                                  "    <xsd:any name=\"element\" minOccurs=\"0\" maxOccurs=\"unbounded\" processContents=\"skip\"/>\n"
2954                                                  "  </xsd:sequence>\n"
2955                                                  "</xsd:complexType>\n");
2956         }
2957         else
2958         {
2959                 appendStringInfo(&result,
2960                                                  "<xsd:simpleType name=\"%s\">\n", typename);
2961
2962                 switch(typeoid)
2963                 {
2964                         case BPCHAROID:
2965                         case VARCHAROID:
2966                         case TEXTOID:
2967                                 if (typmod != -1)
2968                                         appendStringInfo(&result,
2969                                                                          "  <xsd:restriction base=\"xsd:string\">\n"
2970                                                                          "    <xsd:maxLength value=\"%d\"/>\n"
2971                                                                          "  </xsd:restriction>\n",
2972                                                                          typmod - VARHDRSZ);
2973                                 break;
2974
2975                         case BYTEAOID:
2976                                 appendStringInfo(&result,
2977                                                                  "  <xsd:restriction base=\"xsd:%s\">\n"
2978                                                                  "  </xsd:restriction>\n",
2979                                                                  xmlbinary == XMLBINARY_BASE64 ? "base64Binary" : "hexBinary");
2980
2981                         case NUMERICOID:
2982                                 if (typmod != -1)
2983                                         appendStringInfo(&result,
2984                                                                          "  <xsd:restriction base=\"xsd:decimal\">\n"
2985                                                                          "    <xsd:totalDigits value=\"%d\"/>\n"
2986                                                                          "    <xsd:fractionDigits value=\"%d\"/>\n"
2987                                                                          "  </xsd:restriction>\n",
2988                                                                          ((typmod - VARHDRSZ) >> 16) & 0xffff,
2989                                                                          (typmod - VARHDRSZ) & 0xffff);
2990                                 break;
2991
2992                         case INT2OID:
2993                                 appendStringInfo(&result,
2994                                                                  "  <xsd:restriction base=\"xsd:short\">\n"
2995                                                                  "    <xsd:maxInclusive value=\"%d\"/>\n"
2996                                                                  "    <xsd:minInclusive value=\"%d\"/>\n"
2997                                                                  "  </xsd:restriction>\n",
2998                                                                  SHRT_MAX, SHRT_MIN);
2999                                 break;
3000
3001                         case INT4OID:
3002                                 appendStringInfo(&result,
3003                                                                  "  <xsd:restriction base='xsd:int'>\n"
3004                                                                  "    <xsd:maxInclusive value=\"%d\"/>\n"
3005                                                                  "    <xsd:minInclusive value=\"%d\"/>\n"
3006                                                                  "  </xsd:restriction>\n",
3007                                                                  INT_MAX, INT_MIN);
3008                                 break;
3009
3010                         case INT8OID:
3011                                 appendStringInfo(&result,
3012                                                                  "  <xsd:restriction base=\"xsd:long\">\n"
3013                                                                  "    <xsd:maxInclusive value=\"" INT64_FORMAT "\"/>\n"
3014                                                                  "    <xsd:minInclusive value=\"" INT64_FORMAT "\"/>\n"
3015                                                                  "  </xsd:restriction>\n",
3016                                                                  (((uint64) 1) << (sizeof(int64) * 8 - 1)) - 1,
3017                                                                  (((uint64) 1) << (sizeof(int64) * 8 - 1)));
3018                                 break;
3019
3020                         case FLOAT4OID:
3021                                 appendStringInfo(&result,
3022                                                                  "  <xsd:restriction base=\"xsd:float\"></xsd:restriction>\n");
3023                                 break;
3024
3025                         case FLOAT8OID:
3026                                 appendStringInfo(&result,
3027                                                                  "  <xsd:restriction base=\"xsd:double\"></xsd:restriction>\n");
3028                                 break;
3029
3030                         case BOOLOID:
3031                                 appendStringInfo(&result,
3032                                                                  "  <xsd:restriction base=\"xsd:boolean\"></xsd:restriction>\n");
3033                                 break;
3034
3035                         case TIMEOID:
3036                         case TIMETZOID:
3037                         {
3038                                 const char *tz = (typeoid == TIMETZOID ? "(+|-)\\p{Nd}{2}:\\p{Nd}{2}" : "");
3039
3040                                 if (typmod == -1)
3041                                         appendStringInfo(&result,
3042                                                                          "  <xsd:restriction base=\"xsd:time\">\n"
3043                                                                          "    <xsd:pattern value=\"\\p{Nd}{2}:\\p{Nd}{2}:\\p{Nd}{2}(.\\p{Nd}+)?%s\"/>\n"
3044                                                                          "  </xsd:restriction>\n", tz);
3045                                 else if (typmod == 0)
3046                                         appendStringInfo(&result,
3047                                                                          "  <xsd:restriction base=\"xsd:time\">\n"
3048                                                                          "    <xsd:pattern value=\"\\p{Nd}{2}:\\p{Nd}{2}:\\p{Nd}{2}%s\"/>\n"
3049                                                                          "  </xsd:restriction>\n", tz);
3050                                 else
3051                                         appendStringInfo(&result,
3052                                                                          "  <xsd:restriction base=\"xsd:time\">\n"
3053                                                                          "    <xsd:pattern value=\"\\p{Nd}{2}:\\p{Nd}{2}:\\p{Nd}{2}.\\p{Nd}{%d}%s\"/>\n"
3054                                                                          "  </xsd:restriction>\n", typmod - VARHDRSZ, tz);
3055                                 break;
3056                         }
3057
3058                         case TIMESTAMPOID:
3059                         case TIMESTAMPTZOID:
3060                         {
3061                                 const char *tz = (typeoid == TIMESTAMPTZOID ? "(+|-)\\p{Nd}{2}:\\p{Nd}{2}" : "");
3062
3063                                 if (typmod == -1)
3064                                         appendStringInfo(&result,
3065                                                                          "  <xsd:restriction base=\"xsd:dateTime\">\n"
3066                                                                          "    <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"
3067                                                                          "  </xsd:restriction>\n", tz);
3068                                 else if (typmod == 0)
3069                                         appendStringInfo(&result,
3070                                                                          "  <xsd:restriction base=\"xsd:dateTime\">\n"
3071                                                                          "    <xsd:pattern value=\"\\p{Nd}{4}-\\p{Nd}{2}-\\p{Nd}{2}T\\p{Nd}{2}:\\p{Nd}{2}:\\p{Nd}{2}%s\"/>\n"
3072                                                                          "  </xsd:restriction>\n", tz);
3073                                 else
3074                                         appendStringInfo(&result,
3075                                                                          "  <xsd:restriction base=\"xsd:dateTime\">\n"
3076                                                                          "    <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"
3077                                                                          "  </xsd:restriction>\n", typmod - VARHDRSZ, tz);
3078                                 break;
3079                         }
3080
3081                         case DATEOID:
3082                                 appendStringInfo(&result,
3083                                                                  "  <xsd:restriction base=\"xsd:date\">\n"
3084                                                                  "    <xsd:pattern value=\"\\p{Nd}{4}-\\p{Nd}{2}-\\p{Nd}{2}\"/>\n"
3085                                                                  "  </xsd:restriction>\n");
3086                                 break;
3087
3088                         default:
3089                                 if (get_typtype(typeoid) == TYPTYPE_DOMAIN)
3090                                 {
3091                                         Oid base_typeoid;
3092                                         int32 base_typmod = -1;
3093
3094                                         base_typeoid = getBaseTypeAndTypmod(typeoid, &base_typmod);
3095
3096                                         appendStringInfo(&result,
3097                                                                          "  <xsd:restriction base=\"%s\">\n",
3098                                                                          map_sql_type_to_xml_name(base_typeoid, base_typmod));
3099                                 }
3100                                 break;
3101                 }
3102                 appendStringInfo(&result,
3103                                                  "</xsd:simpleType>\n");
3104         }
3105
3106         return result.data;
3107 }
3108
3109
3110 /*
3111  * Map an SQL row to an XML element, taking the row from the active
3112  * SPI cursor.  See also SQL/XML:2003 section 9.12.
3113  */
3114 static void
3115 SPI_sql_row_to_xmlelement(int rownum, StringInfo result, char *tablename,
3116                                                   bool nulls, bool tableforest,
3117                                                   const char *targetns, bool top_level)
3118 {
3119         int                     i;
3120         char       *xmltn;
3121
3122         if (tablename)
3123                 xmltn = map_sql_identifier_to_xml_name(tablename, true, false);
3124         else
3125         {
3126                 if (tableforest)
3127                         xmltn = "row";
3128                 else
3129                         xmltn = "table";
3130         }
3131
3132         if (tableforest)
3133                 xmldata_root_element_start(result, xmltn, NULL, targetns, top_level);
3134         else
3135                 appendStringInfoString(result, "<row>\n");
3136
3137         for(i = 1; i <= SPI_tuptable->tupdesc->natts; i++)
3138         {
3139                 char *colname;
3140                 Datum colval;
3141                 bool isnull;
3142
3143                 colname = map_sql_identifier_to_xml_name(SPI_fname(SPI_tuptable->tupdesc, i),
3144                                                                                                  true, false);
3145                 colval = SPI_getbinval(SPI_tuptable->vals[rownum],
3146                                                            SPI_tuptable->tupdesc,
3147                                                            i,
3148                                                            &isnull);
3149                 if (isnull)
3150                 {
3151                         if (nulls)
3152                                 appendStringInfo(result, "  <%s xsi:nil='true'/>\n", colname);
3153                 }
3154                 else
3155                         appendStringInfo(result, "  <%s>%s</%s>\n",
3156                                                          colname,
3157                                                          map_sql_value_to_xml_value(colval,
3158                                                                                                                 SPI_gettypeid(SPI_tuptable->tupdesc, i)),
3159                                                          colname);
3160         }
3161
3162         if (tableforest)
3163         {
3164                 xmldata_root_element_end(result, xmltn);
3165                 appendStringInfoChar(result, '\n');
3166         }
3167         else
3168                 appendStringInfoString(result, "</row>\n\n");
3169 }
3170
3171
3172 /*
3173  * XPath related functions
3174  */
3175
3176 #ifdef USE_LIBXML
3177 /* 
3178  * Convert XML node to text (dump subtree in case of element,
3179  * return value otherwise)
3180  */
3181 static text *
3182 xml_xmlnodetoxmltype(xmlNodePtr cur)
3183 {
3184         xmlChar                         *str;
3185         xmltype                         *result;
3186         size_t                          len;
3187         xmlBufferPtr            buf;
3188         
3189         if (cur->type == XML_ELEMENT_NODE)
3190         {
3191                 buf = xmlBufferCreate();
3192                 xmlNodeDump(buf, NULL, cur, 0, 1);
3193                 result = xmlBuffer_to_xmltype(buf);
3194                 xmlBufferFree(buf);
3195         }
3196         else
3197         {
3198                 str = xmlXPathCastNodeToString(cur);
3199                 len = strlen((char *) str);
3200                 result = (text *) palloc(len + VARHDRSZ);
3201                 SET_VARSIZE(result, len + VARHDRSZ);
3202                 memcpy(VARDATA(result), str, len);
3203         }
3204         
3205         return result;
3206 }
3207 #endif
3208
3209
3210 /*
3211  * Evaluate XPath expression and return array of XML values.
3212  *
3213  * As we have no support of XQuery sequences yet, this function seems
3214  * to be the most useful one (array of XML functions plays a role of
3215  * some kind of substitution for XQuery sequences).
3216  *
3217  * Workaround here: we parse XML data in different way to allow XPath for
3218  * fragments (see "XPath for fragment" TODO comment inside).
3219  */
3220 Datum
3221 xpath(PG_FUNCTION_ARGS)
3222 {
3223 #ifdef USE_LIBXML
3224         text       *xpath_expr_text = PG_GETARG_TEXT_P(0);
3225         xmltype    *data = PG_GETARG_XML_P(1);
3226         ArrayType  *namespaces = PG_GETARG_ARRAYTYPE_P(2);
3227         ArrayBuildState    *astate = NULL;
3228         xmlParserCtxtPtr        ctxt = NULL;
3229         xmlDocPtr                       doc = NULL;
3230         xmlXPathContextPtr      xpathctx = NULL;
3231         xmlXPathCompExprPtr     xpathcomp = NULL;
3232         xmlXPathObjectPtr       xpathobj = NULL;
3233         char       *datastr;
3234         int32           len;
3235         int32           xpath_len;
3236         xmlChar    *string;
3237         xmlChar    *xpath_expr;
3238         int                     i;
3239         int                     res_nitems;
3240         int                     ndim;
3241         Datum      *ns_names_uris;
3242         bool       *ns_names_uris_nulls;
3243         int                     ns_count;
3244
3245         /*
3246          * Namespace mappings are passed as text[].  If an empty array is
3247          * passed (ndim = 0, "0-dimensional"), then there are no namespace
3248          * mappings.  Else, a 2-dimensional array with length of the
3249          * second axis being equal to 2 should be passed, i.e., every
3250          * subarray contains 2 elements, the first element defining the
3251          * name, the second one the URI.  Example: ARRAY[ARRAY['myns',
3252          * 'http://example.com'], ARRAY['myns2', 'http://example2.com']].
3253          */
3254         ndim = ARR_NDIM(namespaces);
3255         if (ndim != 0)
3256         {
3257                 int                *dims;
3258
3259                 dims = ARR_DIMS(namespaces);
3260
3261                 if (ndim != 2 || dims[1] != 2)
3262                         ereport(ERROR,
3263                                         (errcode(ERRCODE_DATA_EXCEPTION),
3264                                          errmsg("invalid array for XML namespace mapping"),
3265                                          errdetail("The array must be two-dimensional with length of the second axis equal to 2.")));
3266
3267                 Assert(ARR_ELEMTYPE(namespaces) == TEXTOID);
3268
3269                 deconstruct_array(namespaces, TEXTOID, -1, false, 'i',
3270                                                   &ns_names_uris, &ns_names_uris_nulls,
3271                                                   &ns_count);
3272
3273                 Assert((ns_count % 2) == 0); /* checked above */
3274                 ns_count /= 2;                  /* count pairs only */
3275         }
3276         else
3277         {
3278                 ns_names_uris = NULL;
3279                 ns_names_uris_nulls = NULL;
3280                 ns_count = 0;
3281         }
3282
3283         datastr = VARDATA(data);
3284         len = VARSIZE(data) - VARHDRSZ;
3285         xpath_len = VARSIZE(xpath_expr_text) - VARHDRSZ;
3286         if (xpath_len == 0)
3287                 ereport(ERROR,
3288                                 (errcode(ERRCODE_DATA_EXCEPTION),
3289                                  errmsg("empty XPath expression")));
3290
3291         /*
3292          * To handle both documents and fragments, regardless of the fact
3293          * whether the XML datum has a single root (XML well-formedness),
3294          * we wrap the XML datum in a dummy element (<x>...</x>) and
3295          * extend the XPath expression accordingly.  To do it, throw away
3296          * the XML prolog, if any.
3297          */
3298         if (len >= 5 &&
3299                 xmlStrncmp((xmlChar *) datastr, (xmlChar *) "<?xml", 5) == 0)
3300         {
3301                 i = 5;
3302                 while (i < len &&
3303                            !(datastr[i - 1] == '?' && datastr[i] == '>'))
3304                         i++;
3305
3306                 if (i == len)
3307                         xml_ereport(ERROR, ERRCODE_INTERNAL_ERROR,
3308                                                 "could not parse XML data");
3309
3310                 ++i;
3311                 string = xmlStrncatNew((xmlChar *) "<x>",
3312                                                            (xmlChar *) datastr + i, len - i);
3313         }
3314         else
3315                 string = xmlStrncatNew((xmlChar *) "<x>",
3316                                                            (xmlChar *) datastr, len);
3317
3318         string = xmlStrncat(string, (xmlChar *) "</x>", 5);
3319         len += 7;
3320         xpath_expr = xmlStrncatNew((xmlChar *) "/x",
3321                                                            (xmlChar *) VARDATA(xpath_expr_text), xpath_len);
3322         xpath_len += 2;
3323
3324         xml_init();
3325
3326         /* We use a PG_TRY block to ensure libxml parser is cleaned up on error */
3327         PG_TRY();
3328         {
3329                 xmlInitParser();
3330                 /*
3331                  * redundant XML parsing (two parsings for the same value
3332                  * during one command execution are possible)
3333                  */
3334                 ctxt = xmlNewParserCtxt();
3335                 if (ctxt == NULL)
3336                         xml_ereport(ERROR, ERRCODE_INTERNAL_ERROR,
3337                                                 "could not allocate parser context");
3338                 doc = xmlCtxtReadMemory(ctxt, (char *) string, len, NULL, NULL, 0);
3339                 if (doc == NULL)
3340                         xml_ereport(ERROR, ERRCODE_INVALID_XML_DOCUMENT,
3341                                                 "could not parse XML data");
3342                 xpathctx = xmlXPathNewContext(doc);
3343                 if (xpathctx == NULL)
3344                         xml_ereport(ERROR, ERRCODE_INTERNAL_ERROR,
3345                                                 "could not allocate XPath context");
3346                 xpathctx->node = xmlDocGetRootElement(doc);
3347                 if (xpathctx->node == NULL)
3348                         xml_ereport(ERROR, ERRCODE_INTERNAL_ERROR,
3349                                                 "could not find root XML element");
3350
3351                 /* register namespaces, if any */
3352                 if (ns_count > 0)
3353                 {
3354                         for (i = 0; i < ns_count; i++)
3355                         {
3356                                 char *ns_name;
3357                                 char *ns_uri;
3358
3359                                 if (ns_names_uris_nulls[i * 2] ||
3360                                         ns_names_uris_nulls[i * 2 + 1])
3361                                         ereport(ERROR,
3362                                                         (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3363                                                          errmsg("neither namespace name nor URI may be null")));
3364                                 ns_name = _textout(ns_names_uris[i * 2]);
3365                                 ns_uri = _textout(ns_names_uris[i * 2 + 1]);
3366                                 if (xmlXPathRegisterNs(xpathctx,
3367                                                                            (xmlChar *) ns_name,
3368                                                                            (xmlChar *) ns_uri) != 0)
3369                                         ereport(ERROR, /* is this an internal error??? */
3370                                                         (errmsg("could not register XML namespace with name \"%s\" and URI \"%s\"",
3371                                                                         ns_name, ns_uri)));
3372                         }
3373                 }
3374
3375                 xpathcomp = xmlXPathCompile(xpath_expr);
3376                 if (xpathcomp == NULL)  /* TODO: show proper XPath error details */
3377                         xml_ereport(ERROR, ERRCODE_INTERNAL_ERROR,
3378                                                 "invalid XPath expression");
3379
3380                 xpathobj = xmlXPathCompiledEval(xpathcomp, xpathctx);
3381                 if (xpathobj == NULL)   /* TODO: reason? */
3382                         ereport(ERROR,
3383                                         (errmsg("could not create XPath object")));
3384
3385                 xmlXPathFreeCompExpr(xpathcomp);
3386                 xpathcomp = NULL;
3387
3388                 /* return empty array in cases when nothing is found */
3389                 if (xpathobj->nodesetval == NULL)
3390                         res_nitems = 0;
3391                 else
3392                         res_nitems = xpathobj->nodesetval->nodeNr;
3393
3394                 if (res_nitems)
3395                         for (i = 0; i < xpathobj->nodesetval->nodeNr; i++)
3396                         {
3397                                 Datum           elem;
3398                                 bool            elemisnull = false;
3399                                 elem = PointerGetDatum(xml_xmlnodetoxmltype(xpathobj->nodesetval->nodeTab[i]));
3400                                 astate = accumArrayResult(astate, elem,
3401                                                                                   elemisnull, XMLOID,
3402                                                                                   CurrentMemoryContext);
3403                         }
3404
3405                 xmlXPathFreeObject(xpathobj);
3406                 xpathobj = NULL;
3407                 xmlXPathFreeContext(xpathctx);
3408                 xpathctx = NULL;
3409                 xmlFreeDoc(doc);
3410                 doc = NULL;
3411                 xmlFreeParserCtxt(ctxt);
3412                 ctxt = NULL;
3413                 xmlCleanupParser();
3414         }
3415         PG_CATCH();
3416         {
3417                 if (xpathcomp)
3418                         xmlXPathFreeCompExpr(xpathcomp);
3419                 if (xpathobj)
3420                         xmlXPathFreeObject(xpathobj);
3421                 if (xpathctx)
3422                         xmlXPathFreeContext(xpathctx);
3423                 if (doc)
3424                         xmlFreeDoc(doc);
3425                 if (ctxt)
3426                         xmlFreeParserCtxt(ctxt);
3427                 xmlCleanupParser();
3428
3429                 PG_RE_THROW();
3430         }
3431         PG_END_TRY();
3432
3433         if (res_nitems == 0)
3434                 PG_RETURN_ARRAYTYPE_P(construct_empty_array(XMLOID));
3435         else
3436                 PG_RETURN_ARRAYTYPE_P(makeArrayResult(astate, CurrentMemoryContext));
3437 #else
3438         NO_XML_SUPPORT();
3439         return 0;
3440 #endif
3441 }