]> granicus.if.org Git - postgresql/blob - src/backend/utils/adt/xml.c
Allow XML processing instructions starting with "xml" while prohibiting
[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.54 2007/11/09 15:52:51 petere 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 the server to be built with libxml support."), \
127                          errhint("You need to rebuild 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_strcasecmp(target, "xml") == 0)
680                 ereport(ERROR,
681                                 (errcode(ERRCODE_SYNTAX_ERROR), /* really */
682                                  errmsg("invalid XML processing instruction"),
683                                  errdetail("XML processing instruction target name cannot be \"%s\".", target)));
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 /* Letter | Digit | '.' | '-' | '_' | ':' | CombiningChar | Extender */
1001 #define pg_xmlIsNameChar(c) \
1002         (xmlIsBaseChar_ch(c) || xmlIsIdeographicQ(c) \
1003                         || xmlIsDigit_ch(c) \
1004                         || c == '.' || c == '-' || c == '_' || c == ':' \
1005                         || xmlIsCombiningQ(c) \
1006                         || xmlIsExtender_ch(c))
1007
1008 static int
1009 parse_xml_decl(const xmlChar *str,size_t *lenp,
1010                            xmlChar **version, xmlChar **encoding, int *standalone)
1011 {
1012         const xmlChar *p;
1013         const xmlChar *save_p;
1014         size_t          len;
1015         int                     utf8len;
1016
1017         xml_init();
1018
1019         if (version)
1020                 *version = NULL;
1021         if (encoding)
1022                 *encoding = NULL;
1023         if (standalone)
1024                 *standalone = -1;
1025
1026         p = str;
1027
1028         if (xmlStrncmp(p, (xmlChar *)"<?xml", 5) != 0)
1029                 goto finished;
1030
1031         /* This means it's a PI like <?xml-stylesheet ...?>. */
1032         if (pg_xmlIsNameChar(xmlGetUTF8Char(&p[5], &utf8len)))
1033                 goto finished;
1034
1035         p += 5;
1036
1037         /* version */
1038         CHECK_XML_SPACE(p);
1039         SKIP_XML_SPACE(p);
1040         if (xmlStrncmp(p, (xmlChar *)"version", 7) != 0)
1041                 return XML_ERR_VERSION_MISSING;
1042         p += 7;
1043         SKIP_XML_SPACE(p);
1044         if (*p != '=')
1045                 return XML_ERR_VERSION_MISSING;
1046         p += 1;
1047         SKIP_XML_SPACE(p);
1048
1049         if (*p == '\'' || *p == '"')
1050         {
1051                 const xmlChar *q;
1052
1053                 q = xmlStrchr(p + 1, *p);
1054                 if (!q)
1055                         return XML_ERR_VERSION_MISSING;
1056
1057                 if (version)
1058                         *version = xmlStrndup(p + 1, q - p - 1);
1059                 p = q + 1;
1060         }
1061         else
1062                 return XML_ERR_VERSION_MISSING;
1063
1064         /* encoding */
1065         save_p = p;
1066         SKIP_XML_SPACE(p);
1067         if (xmlStrncmp(p, (xmlChar *)"encoding", 8) == 0)
1068         {
1069                 CHECK_XML_SPACE(save_p);
1070                 p += 8;
1071                 SKIP_XML_SPACE(p);
1072                 if (*p != '=')
1073                         return XML_ERR_MISSING_ENCODING;
1074                 p += 1;
1075                 SKIP_XML_SPACE(p);
1076
1077                 if (*p == '\'' || *p == '"')
1078                 {
1079                         const xmlChar *q;
1080
1081                         q = xmlStrchr(p + 1, *p);
1082                         if (!q)
1083                                 return XML_ERR_MISSING_ENCODING;
1084
1085                         if (encoding)
1086                         *encoding = xmlStrndup(p + 1, q - p - 1);
1087                         p = q + 1;
1088                 }
1089                 else
1090                         return XML_ERR_MISSING_ENCODING;
1091         }
1092         else
1093         {
1094                 p = save_p;
1095         }
1096
1097         /* standalone */
1098         save_p = p;
1099         SKIP_XML_SPACE(p);
1100         if (xmlStrncmp(p, (xmlChar *)"standalone", 10) == 0)
1101         {
1102                 CHECK_XML_SPACE(save_p);
1103                 p += 10;
1104                 SKIP_XML_SPACE(p);
1105                 if (*p != '=')
1106                         return XML_ERR_STANDALONE_VALUE;
1107                 p += 1;
1108                 SKIP_XML_SPACE(p);
1109                 if (xmlStrncmp(p, (xmlChar *)"'yes'", 5) == 0 || xmlStrncmp(p, (xmlChar *)"\"yes\"", 5) == 0)
1110                 {
1111                         *standalone = 1;
1112                         p += 5;
1113                 }
1114                 else if (xmlStrncmp(p, (xmlChar *)"'no'", 4) == 0 || xmlStrncmp(p, (xmlChar *)"\"no\"", 4) == 0)
1115                 {
1116                         *standalone = 0;
1117                         p += 4;
1118                 }
1119                 else
1120                         return XML_ERR_STANDALONE_VALUE;
1121         }
1122         else
1123         {
1124                 p = save_p;
1125         }
1126
1127         SKIP_XML_SPACE(p);
1128         if (xmlStrncmp(p, (xmlChar *)"?>", 2) != 0)
1129                 return XML_ERR_XMLDECL_NOT_FINISHED;
1130         p += 2;
1131
1132 finished:
1133         len = p - str;
1134
1135         for (p = str; p < str + len; p++)
1136                 if (*p > 127)
1137                         return XML_ERR_INVALID_CHAR;
1138
1139         if (lenp)
1140                 *lenp = len;
1141
1142         return XML_ERR_OK;
1143 }
1144
1145
1146 /*
1147  * Write an XML declaration.  On output, we adjust the XML declaration
1148  * as follows.  (These rules are the moral equivalent of the clause
1149  * "Serialization of an XML value" in the SQL standard.)
1150  *
1151  * We try to avoid generating an XML declaration if possible.  This is
1152  * so that you don't get trivial things like xml '<foo/>' resulting in
1153  * '<?xml version="1.0"?><foo/>', which would surely be annoying.  We
1154  * must provide a declaration if the standalone property is specified
1155  * or if we include an encoding declaration.  If we have a
1156  * declaration, we must specify a version (XML requires this).
1157  * Otherwise we only make a declaration if the version is not "1.0",
1158  * which is the default version specified in SQL:2003.
1159  */
1160 static bool
1161 print_xml_decl(StringInfo buf, const xmlChar *version,
1162                            pg_enc encoding, int standalone)
1163 {
1164         xml_init();
1165
1166         if ((version && strcmp((char *) version, PG_XML_DEFAULT_VERSION) != 0)
1167                 || (encoding && encoding != PG_UTF8)
1168                 || standalone != -1)
1169         {
1170                 appendStringInfoString(buf, "<?xml");
1171
1172                 if (version)
1173                         appendStringInfo(buf, " version=\"%s\"", version);
1174                 else
1175                         appendStringInfo(buf, " version=\"%s\"", PG_XML_DEFAULT_VERSION);
1176
1177                 if (encoding && encoding != PG_UTF8)
1178                 {
1179                         /*
1180                          * XXX might be useful to convert this to IANA names
1181                          * (ISO-8859-1 instead of LATIN1 etc.); needs field experience
1182                          */
1183                         appendStringInfo(buf, " encoding=\"%s\"",
1184                                                          pg_encoding_to_char(encoding));
1185                 }
1186
1187                 if (standalone == 1)
1188                         appendStringInfoString(buf, " standalone=\"yes\"");
1189                 else if (standalone == 0)
1190                         appendStringInfoString(buf, " standalone=\"no\"");
1191                 appendStringInfoString(buf, "?>");
1192
1193                 return true;
1194         }
1195         else
1196                 return false;
1197 }
1198
1199
1200 /*
1201  * Convert a C string to XML internal representation
1202  *
1203  * TODO maybe, libxml2's xmlreader is better? (do not construct DOM,
1204  * yet do not use SAX - see xml_reader.c)
1205  */
1206 static xmlDocPtr
1207 xml_parse(text *data, XmlOptionType xmloption_arg, bool preserve_whitespace,
1208                   xmlChar *encoding)
1209 {
1210         int32                           len;
1211         xmlChar                         *string;
1212         xmlChar                         *utf8string;
1213         xmlParserCtxtPtr        ctxt = NULL;
1214         xmlDocPtr                       doc = NULL;
1215
1216         len = VARSIZE(data) - VARHDRSZ; /* will be useful later */
1217         string = xml_text2xmlChar(data);
1218
1219         utf8string = pg_do_encoding_conversion(string,
1220                                                                                    len,
1221                                                                                    encoding ?
1222                                                                                    xmlChar_to_encoding(encoding) :
1223                                                                                    GetDatabaseEncoding(),
1224                                                                                    PG_UTF8);
1225
1226         xml_init();
1227
1228         /* We use a PG_TRY block to ensure libxml parser is cleaned up on error */
1229         PG_TRY();
1230         {
1231                 xmlInitParser();
1232                 ctxt = xmlNewParserCtxt();
1233                 if (ctxt == NULL)
1234                         xml_ereport(ERROR, ERRCODE_INTERNAL_ERROR,
1235                                                 "could not allocate parser context");
1236
1237                 if (xmloption_arg == XMLOPTION_DOCUMENT)
1238                 {
1239                         /*
1240                          * Note, that here we try to apply DTD defaults
1241                          * (XML_PARSE_DTDATTR) according to SQL/XML:10.16.7.d:
1242                          * 'Default valies defined by internal DTD are applied'.
1243                          * As for external DTDs, we try to support them too, (see
1244                          * SQL/XML:10.16.7.e)
1245                          */
1246                         doc = xmlCtxtReadDoc(ctxt, utf8string,
1247                                                                  NULL,
1248                                                                  "UTF-8",
1249                                                                  XML_PARSE_NOENT | XML_PARSE_DTDATTR
1250                                                                  | (preserve_whitespace ? 0 : XML_PARSE_NOBLANKS));
1251                         if (doc == NULL)
1252                                 xml_ereport(ERROR, ERRCODE_INVALID_XML_DOCUMENT,
1253                                                         "invalid XML document");
1254                 }
1255                 else
1256                 {
1257                         int                     res_code;
1258                         size_t count;
1259                         xmlChar    *version = NULL;
1260                         int standalone = -1;
1261
1262                         doc = xmlNewDoc(NULL);
1263
1264                         res_code = parse_xml_decl(utf8string, &count, &version, NULL, &standalone);
1265                         if (res_code != 0)
1266                                 xml_ereport_by_code(ERROR, ERRCODE_INVALID_XML_CONTENT,
1267                                                                         "invalid XML content: invalid XML declaration", res_code);
1268
1269                         res_code = xmlParseBalancedChunkMemory(doc, NULL, NULL, 0, utf8string + count, NULL);
1270                         if (res_code != 0)
1271                                 xml_ereport(ERROR, ERRCODE_INVALID_XML_CONTENT,
1272                                                         "invalid XML content");
1273
1274                         doc->version = xmlStrdup(version);
1275                         doc->encoding = xmlStrdup((xmlChar *) "UTF-8");
1276                         doc->standalone = standalone;
1277                 }
1278
1279                 if (ctxt)
1280                         xmlFreeParserCtxt(ctxt);
1281                 ctxt = NULL;
1282                 xmlCleanupParser();
1283         }
1284         PG_CATCH();
1285         {
1286                 if (doc)
1287                         xmlFreeDoc(doc);
1288                 if (ctxt)
1289                         xmlFreeParserCtxt(ctxt);
1290                 xmlCleanupParser();
1291
1292                 PG_RE_THROW();
1293         }
1294         PG_END_TRY();
1295
1296         return doc;
1297 }
1298
1299
1300 /*
1301  * xmlChar<->text convertions
1302  */
1303 static xmlChar *
1304 xml_text2xmlChar(text *in)
1305 {
1306         int32           len = VARSIZE(in) - VARHDRSZ;
1307         xmlChar         *res;
1308
1309         res = palloc(len + 1);
1310         memcpy(res, VARDATA(in), len);
1311         res[len] = '\0';
1312
1313         return(res);
1314 }
1315
1316
1317 /*
1318  * Wrappers for memory management functions
1319  */
1320 static void *
1321 xml_palloc(size_t size)
1322 {
1323         return palloc(size);
1324 }
1325
1326
1327 static void *
1328 xml_repalloc(void *ptr, size_t size)
1329 {
1330         return repalloc(ptr, size);
1331 }
1332
1333
1334 static void
1335 xml_pfree(void *ptr)
1336 {
1337         pfree(ptr);
1338 }
1339
1340
1341 static char *
1342 xml_pstrdup(const char *string)
1343 {
1344         return pstrdup(string);
1345 }
1346
1347
1348 /*
1349  * Wrapper for "ereport" function for XML-related errors.  The "msg"
1350  * is the SQL-level message; some can be adopted from the SQL/XML
1351  * standard.  This function adds libxml's native error messages, if
1352  * any, as detail.
1353  */
1354 static void
1355 xml_ereport(int level, int sqlcode, const char *msg)
1356 {
1357         char *detail;
1358
1359         if (xml_err_buf->len > 0)
1360         {
1361                 detail = pstrdup(xml_err_buf->data);
1362                 resetStringInfo(xml_err_buf);
1363         }
1364         else
1365                 detail = NULL;
1366
1367         /* libxml error messages end in '\n'; get rid of it */
1368         if (detail)
1369         {
1370                 size_t len;
1371
1372                 len = strlen(detail);
1373                 if (len > 0 && detail[len-1] == '\n')
1374                         detail[len-1] = '\0';
1375
1376                 ereport(level,
1377                                 (errcode(sqlcode),
1378                                  errmsg("%s", msg),
1379                                  errdetail("%s", detail)));
1380         }
1381         else
1382         {
1383                 ereport(level,
1384                                 (errcode(sqlcode),
1385                                  errmsg("%s", msg)));
1386         }
1387 }
1388
1389
1390 /*
1391  * Error handler for libxml error messages
1392  */
1393 static void
1394 xml_errorHandler(void *ctxt, const char *msg,...)
1395 {
1396         /* Append the formatted text to xml_err_buf */
1397         for (;;)
1398         {
1399                 va_list         args;
1400                 bool            success;
1401
1402                 /* Try to format the data. */
1403                 va_start(args, msg);
1404                 success = appendStringInfoVA(xml_err_buf, msg, args);
1405                 va_end(args);
1406
1407                 if (success)
1408                         break;
1409
1410                 /* Double the buffer size and try again. */
1411                 enlargeStringInfo(xml_err_buf, xml_err_buf->maxlen);
1412         }
1413 }
1414
1415
1416 /*
1417  * Wrapper for "ereport" function for XML-related errors.  The "msg"
1418  * is the SQL-level message; some can be adopted from the SQL/XML
1419  * standard.  This function uses "code" to create a textual detail
1420  * message.  At the moment, we only need to cover those codes that we
1421  * may raise in this file.
1422  */
1423 static void
1424 xml_ereport_by_code(int level, int sqlcode,
1425                                         const char *msg, int code)
1426 {
1427     const char *det;
1428
1429     switch (code)
1430         {
1431                 case XML_ERR_INVALID_CHAR:
1432                         det = "Invalid character value";
1433                         break;
1434                 case XML_ERR_SPACE_REQUIRED:
1435                         det = "Space required";
1436                         break;
1437                 case XML_ERR_STANDALONE_VALUE:
1438                         det = "standalone accepts only 'yes' or 'no'";
1439                         break;
1440                 case XML_ERR_VERSION_MISSING:
1441                         det = "Malformed declaration expecting version";
1442                         break;
1443                 case XML_ERR_MISSING_ENCODING:
1444                         det = "Missing encoding in text declaration";
1445                         break;
1446                 case XML_ERR_XMLDECL_NOT_FINISHED:
1447                         det = "Parsing XML declaration: '?>' expected";
1448                         break;
1449         default:
1450             det = "Unrecognized libxml error code: %d";
1451                         break;
1452         }
1453
1454         ereport(level,
1455                         (errcode(sqlcode),
1456                          errmsg("%s", msg),
1457                          errdetail(det, code)));
1458 }
1459
1460
1461 /*
1462  * Convert one char in the current server encoding to a Unicode codepoint.
1463  */
1464 static pg_wchar
1465 sqlchar_to_unicode(char *s)
1466 {
1467         char *utf8string;
1468         pg_wchar ret[2];                        /* need space for trailing zero */
1469
1470         utf8string = (char *) pg_do_encoding_conversion((unsigned char *) s,
1471                                                                                                         pg_mblen(s),
1472                                                                                                         GetDatabaseEncoding(),
1473                                                                                                         PG_UTF8);
1474
1475         pg_encoding_mb2wchar_with_len(PG_UTF8, utf8string, ret, pg_mblen(s));
1476
1477         return ret[0];
1478 }
1479
1480
1481 static bool
1482 is_valid_xml_namefirst(pg_wchar c)
1483 {
1484         /* (Letter | '_' | ':') */
1485         return (xmlIsBaseCharQ(c) || xmlIsIdeographicQ(c)
1486                         || c == '_' || c == ':');
1487 }
1488
1489
1490 static bool
1491 is_valid_xml_namechar(pg_wchar c)
1492 {
1493         /* Letter | Digit | '.' | '-' | '_' | ':' | CombiningChar | Extender */
1494         return (xmlIsBaseCharQ(c) || xmlIsIdeographicQ(c)
1495                         || xmlIsDigitQ(c)
1496                         || c == '.' || c == '-' || c == '_' || c == ':'
1497                         || xmlIsCombiningQ(c)
1498                         || xmlIsExtenderQ(c));
1499 }
1500 #endif /* USE_LIBXML */
1501
1502
1503 /*
1504  * Map SQL identifier to XML name; see SQL/XML:2003 section 9.1.
1505  */
1506 char *
1507 map_sql_identifier_to_xml_name(char *ident, bool fully_escaped,
1508                                                            bool escape_period)
1509 {
1510 #ifdef USE_LIBXML
1511         StringInfoData buf;
1512         char *p;
1513
1514         /*
1515          * SQL/XML doesn't make use of this case anywhere, so it's
1516          * probably a mistake.
1517          */
1518         Assert(fully_escaped || !escape_period);
1519
1520         initStringInfo(&buf);
1521
1522         for (p = ident; *p; p += pg_mblen(p))
1523         {
1524                 if (*p == ':' && (p == ident || fully_escaped))
1525                         appendStringInfo(&buf, "_x003A_");
1526                 else if (*p == '_' && *(p+1) == 'x')
1527                         appendStringInfo(&buf, "_x005F_");
1528                 else if (fully_escaped && p == ident &&
1529                                  pg_strncasecmp(p, "xml", 3) == 0)
1530                 {
1531                         if (*p == 'x')
1532                                 appendStringInfo(&buf, "_x0078_");
1533                         else
1534                                 appendStringInfo(&buf, "_x0058_");
1535                 }
1536                 else if (escape_period && *p == '.')
1537                         appendStringInfo(&buf, "_x002E_");
1538                 else
1539                 {
1540                         pg_wchar u = sqlchar_to_unicode(p);
1541
1542                         if ((p == ident)
1543                                 ? !is_valid_xml_namefirst(u)
1544                                 : !is_valid_xml_namechar(u))
1545                                 appendStringInfo(&buf, "_x%04X_", (unsigned int) u);
1546                         else
1547                                 appendBinaryStringInfo(&buf, p, pg_mblen(p));
1548                 }
1549         }
1550
1551         return buf.data;
1552 #else /* not USE_LIBXML */
1553         NO_XML_SUPPORT();
1554         return NULL;
1555 #endif /* not USE_LIBXML */
1556 }
1557
1558
1559 /*
1560  * Map a Unicode codepoint into the current server encoding.
1561  */
1562 static char *
1563 unicode_to_sqlchar(pg_wchar c)
1564 {
1565         static unsigned char utf8string[5];     /* need trailing zero */
1566
1567         if (c <= 0x7F)
1568         {
1569                 utf8string[0] = c;
1570         }
1571         else if (c <= 0x7FF)
1572         {
1573                 utf8string[0] = 0xC0 | ((c >> 6) & 0x1F);
1574                 utf8string[1] = 0x80 | (c & 0x3F);
1575         }
1576         else if (c <= 0xFFFF)
1577         {
1578                 utf8string[0] = 0xE0 | ((c >> 12) & 0x0F);
1579                 utf8string[1] = 0x80 | ((c >> 6) & 0x3F);
1580                 utf8string[2] = 0x80 | (c & 0x3F);
1581         }
1582         else
1583         {
1584                 utf8string[0] = 0xF0 | ((c >> 18) & 0x07);
1585                 utf8string[1] = 0x80 | ((c >> 12) & 0x3F);
1586                 utf8string[2] = 0x80 | ((c >> 6) & 0x3F);
1587                 utf8string[3] = 0x80 | (c & 0x3F);
1588         }
1589
1590         return (char *) pg_do_encoding_conversion(utf8string,
1591                                                                                           pg_mblen((char *) utf8string),
1592                                                                                           PG_UTF8,
1593                                                                                           GetDatabaseEncoding());
1594 }
1595
1596
1597 /*
1598  * Map XML name to SQL identifier; see SQL/XML:2003 section 9.17.
1599  */
1600 char *
1601 map_xml_name_to_sql_identifier(char *name)
1602 {
1603         StringInfoData buf;
1604         char *p;
1605
1606         initStringInfo(&buf);
1607
1608         for (p = name; *p; p += pg_mblen(p))
1609         {
1610                 if (*p == '_' && *(p+1) == 'x'
1611                         && isxdigit((unsigned char) *(p+2))
1612                         && isxdigit((unsigned char) *(p+3))
1613                         && isxdigit((unsigned char) *(p+4))
1614                         && isxdigit((unsigned char) *(p+5))
1615                         && *(p+6) == '_')
1616                 {
1617                         unsigned int u;
1618
1619                         sscanf(p + 2, "%X", &u);
1620                         appendStringInfoString(&buf, unicode_to_sqlchar(u));
1621                         p += 6;
1622                 }
1623                 else
1624                         appendBinaryStringInfo(&buf, p, pg_mblen(p));
1625         }
1626
1627         return buf.data;
1628 }
1629
1630 /*
1631  * Map SQL value to XML value; see SQL/XML:2003 section 9.16.
1632  */
1633 char *
1634 map_sql_value_to_xml_value(Datum value, Oid type)
1635 {
1636         StringInfoData buf;
1637
1638         initStringInfo(&buf);
1639
1640         if (type_is_array(type))
1641         {
1642                 ArrayType *array;
1643                 Oid elmtype;
1644                 int16 elmlen;
1645                 bool elmbyval;
1646                 char elmalign;
1647                 int                     num_elems;
1648                 Datum      *elem_values;
1649                 bool       *elem_nulls;
1650                 int i;
1651
1652                 array = DatumGetArrayTypeP(value);
1653                 elmtype = ARR_ELEMTYPE(array);
1654                 get_typlenbyvalalign(elmtype, &elmlen, &elmbyval, &elmalign);
1655
1656                 deconstruct_array(array, elmtype,
1657                                                   elmlen, elmbyval, elmalign,
1658                                                   &elem_values, &elem_nulls,
1659                                                   &num_elems);
1660
1661                 for (i = 0; i < num_elems; i++)
1662                 {
1663                         if (elem_nulls[i])
1664                                 continue;
1665                         appendStringInfoString(&buf, "<element>");
1666                         appendStringInfoString(&buf,
1667                                                                    map_sql_value_to_xml_value(elem_values[i],
1668                                                                                                                           elmtype));
1669                         appendStringInfoString(&buf, "</element>");
1670                 }
1671
1672                 pfree(elem_values);
1673                 pfree(elem_nulls);
1674         }
1675         else
1676         {
1677                 Oid typeOut;
1678                 bool isvarlena;
1679                 char *p, *str;
1680
1681                 /*
1682                  * Special XSD formatting for some data types
1683                  */
1684                 switch (type)
1685                 {
1686                         case BOOLOID:
1687                                 if (DatumGetBool(value))
1688                                         return "true";
1689                                 else
1690                                         return "false";
1691
1692                         case DATEOID:
1693                         {
1694                                 DateADT         date;
1695                                 struct pg_tm tm;
1696                                 char            buf[MAXDATELEN + 1];
1697
1698                                 date = DatumGetDateADT(value);
1699                                 j2date(date + POSTGRES_EPOCH_JDATE,
1700                                            &(tm.tm_year), &(tm.tm_mon), &(tm.tm_mday));
1701                                 EncodeDateOnly(&tm, USE_XSD_DATES, buf);
1702
1703                                 return pstrdup(buf);
1704                         }
1705
1706                         case TIMESTAMPOID:
1707                         {
1708                                 Timestamp       timestamp;
1709                                 struct pg_tm tm;
1710                                 fsec_t          fsec;
1711                                 char       *tzn = NULL;
1712                                 char            buf[MAXDATELEN + 1];
1713
1714                                 timestamp = DatumGetTimestamp(value);
1715
1716                                 /* XSD doesn't support infinite values */
1717                                 if (TIMESTAMP_NOT_FINITE(timestamp))
1718                                         ereport(ERROR,
1719                                                         (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
1720                                                          errmsg("timestamp out of range")));
1721                                 else if (timestamp2tm(timestamp, NULL, &tm, &fsec, NULL, NULL) == 0)
1722                                         EncodeDateTime(&tm, fsec, NULL, &tzn, USE_XSD_DATES, buf);
1723                                 else
1724                                         ereport(ERROR,
1725                                                         (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
1726                                                          errmsg("timestamp out of range")));
1727
1728                                 return pstrdup(buf);
1729                         }
1730
1731                         case TIMESTAMPTZOID:
1732                         {
1733                                 TimestampTz     timestamp;
1734                                 struct pg_tm tm;
1735                                 int                     tz;
1736                                 fsec_t          fsec;
1737                                 char       *tzn = NULL;
1738                                 char            buf[MAXDATELEN + 1];
1739
1740                                 timestamp = DatumGetTimestamp(value);
1741
1742                                 /* XSD doesn't support infinite values */
1743                                 if (TIMESTAMP_NOT_FINITE(timestamp))
1744                                         ereport(ERROR,
1745                                                         (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
1746                                                          errmsg("timestamp out of range")));
1747                                 else if (timestamp2tm(timestamp, &tz, &tm, &fsec, &tzn, NULL) == 0)
1748                                         EncodeDateTime(&tm, fsec, &tz, &tzn, USE_XSD_DATES, buf);
1749                                 else
1750                                         ereport(ERROR,
1751                                                         (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
1752                                                          errmsg("timestamp out of range")));
1753
1754                                 return pstrdup(buf);
1755                         }
1756                 }
1757
1758                 getTypeOutputInfo(type, &typeOut, &isvarlena);
1759                 str = OidOutputFunctionCall(typeOut, value);
1760
1761                 if (type == XMLOID)
1762                         return str;
1763
1764 #ifdef USE_LIBXML
1765                 if (type == BYTEAOID)
1766                 {
1767                         xmlBufferPtr buf;
1768                         xmlTextWriterPtr writer;
1769                         char *result;
1770
1771                         xml_init();
1772
1773                         buf = xmlBufferCreate();
1774                         writer = xmlNewTextWriterMemory(buf, 0);
1775
1776                         if (xmlbinary == XMLBINARY_BASE64)
1777                                 xmlTextWriterWriteBase64(writer, VARDATA(value), 0, VARSIZE(value) - VARHDRSZ);
1778                         else
1779                                 xmlTextWriterWriteBinHex(writer, VARDATA(value), 0, VARSIZE(value) - VARHDRSZ);
1780
1781                         xmlFreeTextWriter(writer);
1782                         result = pstrdup((const char *) xmlBufferContent(buf));
1783                         xmlBufferFree(buf);
1784                         return result;
1785                 }
1786 #endif /* USE_LIBXML */
1787
1788                 for (p = str; *p; p += pg_mblen(p))
1789                 {
1790                         switch (*p)
1791                         {
1792                                 case '&':
1793                                         appendStringInfo(&buf, "&amp;");
1794                                         break;
1795                                 case '<':
1796                                         appendStringInfo(&buf, "&lt;");
1797                                         break;
1798                                 case '>':
1799                                         appendStringInfo(&buf, "&gt;");
1800                                         break;
1801                                 case '\r':
1802                                         appendStringInfo(&buf, "&#x0d;");
1803                                         break;
1804                                 default:
1805                                         appendBinaryStringInfo(&buf, p, pg_mblen(p));
1806                                         break;
1807                         }
1808                 }
1809         }
1810
1811         return buf.data;
1812 }
1813
1814
1815 static char *
1816 _SPI_strdup(const char *s)
1817 {
1818         char *ret = SPI_palloc(strlen(s) + 1);
1819         strcpy(ret, s);
1820         return ret;
1821 }
1822
1823
1824 /*
1825  * SQL to XML mapping functions
1826  *
1827  * What follows below is intentionally organized so that you can read
1828  * along in the SQL/XML:2003 standard.  The functions are mostly split
1829  * up and ordered they way the clauses lay out in the standards
1830  * document, and the identifiers are also aligned with the standard
1831  * text.  (SQL/XML:2006 appears to be ordered differently,
1832  * unfortunately.)
1833  *
1834  * There are many things going on there:
1835  *
1836  * There are two kinds of mappings: Mapping SQL data (table contents)
1837  * to XML documents, and mapping SQL structure (the "schema") to XML
1838  * Schema.  And there are functions that do both at the same time.
1839  *
1840  * Then you can map a database, a schema, or a table, each in both
1841  * ways.  This breaks down recursively: Mapping a database invokes
1842  * mapping schemas, which invokes mapping tables, which invokes
1843  * mapping rows, which invokes mapping columns, although you can't
1844  * call the last two from the outside.  Because of this, there are a
1845  * number of xyz_internal() functions which are to be called both from
1846  * the function manager wrapper and from some upper layer in a
1847  * recursive call.
1848  *
1849  * See the documentation about what the common function arguments
1850  * nulls, tableforest, and targetns mean.
1851  *
1852  * Some style guidelines for XML output: Use double quotes for quoting
1853  * XML attributes.  Indent XML elements by two spaces, but remember
1854  * that a lot of code is called recursively at different levels, so
1855  * it's better not to indent rather than create output that indents
1856  * and outdents weirdly.  Add newlines to make the output look nice.
1857  */
1858
1859
1860 /*
1861  * Visibility of objects for XML mappings; see SQL/XML:2003 section
1862  * 4.8.5.
1863  */
1864
1865 /*
1866  * Given a query, which must return type oid as first column, produce
1867  * a list of Oids with the query results.
1868  */
1869 static List *
1870 query_to_oid_list(const char *query)
1871 {
1872         int                     i;
1873         List       *list = NIL;
1874
1875         SPI_execute(query, true, 0);
1876
1877         for (i = 0; i < SPI_processed; i++)
1878         {
1879                 Datum oid;
1880                 bool isnull;
1881
1882                 oid = SPI_getbinval(SPI_tuptable->vals[i],
1883                                                         SPI_tuptable->tupdesc,
1884                                                         1,
1885                                                         &isnull);
1886                 if (!isnull)
1887                         list = lappend_oid(list, DatumGetObjectId(oid));
1888         }
1889
1890         return list;
1891 }
1892
1893
1894 static List *
1895 schema_get_xml_visible_tables(Oid nspid)
1896 {
1897         StringInfoData query;
1898
1899         initStringInfo(&query);
1900         appendStringInfo(&query, "SELECT oid FROM pg_catalog.pg_class WHERE relnamespace = %u AND relkind IN ('r', 'v') AND pg_catalog.has_table_privilege (oid, 'SELECT') ORDER BY relname;", nspid);
1901
1902         return query_to_oid_list(query.data);
1903 }
1904
1905
1906 /* 
1907  * Including the system schemas is probably not useful for a database
1908  * mapping.
1909  */
1910 #define XML_VISIBLE_SCHEMAS_EXCLUDE "(nspname ~ '^pg_' OR nspname = 'information_schema')"
1911
1912 #define XML_VISIBLE_SCHEMAS "SELECT oid FROM pg_catalog.pg_namespace WHERE pg_catalog.has_schema_privilege (oid, 'USAGE') AND NOT " XML_VISIBLE_SCHEMAS_EXCLUDE
1913
1914
1915 static List *
1916 database_get_xml_visible_schemas(void)
1917 {
1918         return query_to_oid_list(XML_VISIBLE_SCHEMAS " ORDER BY nspname;");
1919 }
1920
1921
1922 static List *
1923 database_get_xml_visible_tables(void)
1924 {
1925         /* At the moment there is no order required here. */
1926         return query_to_oid_list("SELECT oid FROM pg_catalog.pg_class WHERE relkind IN ('r', 'v') AND pg_catalog.has_table_privilege (pg_class.oid, 'SELECT') AND relnamespace IN (" XML_VISIBLE_SCHEMAS ");");
1927 }
1928
1929
1930 /*
1931  * Map SQL table to XML and/or XML Schema document; see SQL/XML:2003
1932  * section 9.3.
1933  */
1934
1935 static StringInfo
1936 table_to_xml_internal(Oid relid,
1937                                           const char *xmlschema, bool nulls, bool tableforest,
1938                                           const char *targetns, bool top_level)
1939 {
1940         StringInfoData query;
1941
1942         initStringInfo(&query);
1943         appendStringInfo(&query, "SELECT * FROM %s",
1944                                          DatumGetCString(DirectFunctionCall1(regclassout,
1945                                                                                                 ObjectIdGetDatum(relid))));
1946         return query_to_xml_internal(query.data, get_rel_name(relid),
1947                                                                  xmlschema, nulls, tableforest,
1948                                                                  targetns, top_level);
1949 }
1950
1951
1952 Datum
1953 table_to_xml(PG_FUNCTION_ARGS)
1954 {
1955         Oid                     relid = PG_GETARG_OID(0);
1956         bool            nulls = PG_GETARG_BOOL(1);
1957         bool            tableforest = PG_GETARG_BOOL(2);
1958         const char *targetns = _textout(PG_GETARG_TEXT_P(3));
1959
1960         PG_RETURN_XML_P(stringinfo_to_xmltype(table_to_xml_internal(relid, NULL,
1961                                                                                                                 nulls, tableforest,
1962                                                                                                                 targetns, true)));
1963 }
1964
1965
1966 Datum
1967 query_to_xml(PG_FUNCTION_ARGS)
1968 {
1969         char       *query = _textout(PG_GETARG_TEXT_P(0));
1970         bool            nulls = PG_GETARG_BOOL(1);
1971         bool            tableforest = PG_GETARG_BOOL(2);
1972         const char *targetns = _textout(PG_GETARG_TEXT_P(3));
1973
1974         PG_RETURN_XML_P(stringinfo_to_xmltype(query_to_xml_internal(query, NULL,
1975                                                                                                         NULL, nulls, tableforest,
1976                                                                                                         targetns, true)));
1977 }
1978
1979
1980 Datum
1981 cursor_to_xml(PG_FUNCTION_ARGS)
1982 {
1983         char       *name = _textout(PG_GETARG_TEXT_P(0));
1984         int32           count = PG_GETARG_INT32(1);
1985         bool            nulls = PG_GETARG_BOOL(2);
1986         bool            tableforest = PG_GETARG_BOOL(3);
1987         const char *targetns = _textout(PG_GETARG_TEXT_P(4));
1988
1989         StringInfoData result;
1990         Portal          portal;
1991         int                     i;
1992
1993         initStringInfo(&result);
1994
1995         SPI_connect();
1996         portal = SPI_cursor_find(name);
1997         if (portal == NULL)
1998                 ereport(ERROR,
1999                                 (errcode(ERRCODE_UNDEFINED_CURSOR),
2000                                  errmsg("cursor \"%s\" does not exist", name)));
2001
2002         SPI_cursor_fetch(portal, true, count);
2003         for (i = 0; i < SPI_processed; i++)
2004                 SPI_sql_row_to_xmlelement(i, &result, NULL, nulls,
2005                                                                   tableforest, targetns, true);
2006
2007         SPI_finish();
2008
2009         PG_RETURN_XML_P(stringinfo_to_xmltype(&result));
2010 }
2011
2012
2013 /*
2014  * Write the start tag of the root element of a data mapping.
2015  *
2016  * top_level means that this is the very top level of the eventual
2017  * output.  For example, when the user calls table_to_xml, then a call
2018  * with a table name to this function is the top level.  When the user
2019  * calls database_to_xml, then a call with a schema name to this
2020  * function is not the top level.  If top_level is false, then the XML
2021  * namespace declarations are omitted, because they supposedly already
2022  * appeared earlier in the output.  Repeating them is not wrong, but
2023  * it looks ugly.
2024  */
2025 static void
2026 xmldata_root_element_start(StringInfo result, const char *eltname,
2027                                                    const char *xmlschema, const char *targetns,
2028                                                    bool top_level)
2029 {
2030         /* This isn't really wrong but currently makes no sense. */
2031         Assert(top_level || !xmlschema);
2032
2033         appendStringInfo(result, "<%s", eltname);
2034         if (top_level)
2035         {
2036                 appendStringInfoString(result, " xmlns:xsi=\"" NAMESPACE_XSI "\"");
2037                 if (strlen(targetns) > 0)
2038                         appendStringInfo(result, " xmlns=\"%s\"", targetns);
2039         }
2040         if (xmlschema)
2041         {
2042                 /* FIXME: better targets */
2043                 if (strlen(targetns) > 0)
2044                         appendStringInfo(result, " xsi:schemaLocation=\"%s #\"", targetns);
2045                 else
2046                         appendStringInfo(result, " xsi:noNamespaceSchemaLocation=\"#\"");
2047         }
2048         appendStringInfo(result, ">\n\n");
2049 }
2050
2051
2052 static void
2053 xmldata_root_element_end(StringInfo result, const char *eltname)
2054 {
2055         appendStringInfo(result, "</%s>\n", eltname);
2056 }
2057
2058
2059 static StringInfo
2060 query_to_xml_internal(const char *query, char *tablename,
2061                                           const char *xmlschema, bool nulls, bool tableforest,
2062                                           const char *targetns, bool top_level)
2063 {
2064         StringInfo      result;
2065         char       *xmltn;
2066         int                     i;
2067
2068         if (tablename)
2069                 xmltn = map_sql_identifier_to_xml_name(tablename, true, false);
2070         else
2071                 xmltn = "table";
2072
2073         result = makeStringInfo();
2074
2075         SPI_connect();
2076         if (SPI_execute(query, true, 0) != SPI_OK_SELECT)
2077                 ereport(ERROR,
2078                                 (errcode(ERRCODE_DATA_EXCEPTION),
2079                                  errmsg("invalid query")));
2080
2081         if (!tableforest)
2082                 xmldata_root_element_start(result, xmltn, xmlschema,
2083                                                                    targetns, top_level);
2084
2085         if (xmlschema)
2086                 appendStringInfo(result, "%s\n\n", xmlschema);
2087
2088         for(i = 0; i < SPI_processed; i++)
2089                 SPI_sql_row_to_xmlelement(i, result, tablename, nulls,
2090                                                                   tableforest, targetns, top_level);
2091
2092         if (!tableforest)
2093                 xmldata_root_element_end(result, xmltn);
2094
2095         SPI_finish();
2096
2097         return result;
2098 }
2099
2100
2101 Datum
2102 table_to_xmlschema(PG_FUNCTION_ARGS)
2103 {
2104         Oid                     relid = PG_GETARG_OID(0);
2105         bool            nulls = PG_GETARG_BOOL(1);
2106         bool            tableforest = PG_GETARG_BOOL(2);
2107         const char *targetns = _textout(PG_GETARG_TEXT_P(3));
2108         const char *result;
2109         Relation rel;
2110
2111         rel = heap_open(relid, AccessShareLock);
2112         result = map_sql_table_to_xmlschema(rel->rd_att, relid, nulls,
2113                                                                                 tableforest, targetns);
2114         heap_close(rel, NoLock);
2115
2116         PG_RETURN_XML_P(cstring_to_xmltype(result));
2117 }
2118
2119
2120 Datum
2121 query_to_xmlschema(PG_FUNCTION_ARGS)
2122 {
2123         char       *query = _textout(PG_GETARG_TEXT_P(0));
2124         bool            nulls = PG_GETARG_BOOL(1);
2125         bool            tableforest = PG_GETARG_BOOL(2);
2126         const char *targetns = _textout(PG_GETARG_TEXT_P(3));
2127         const char *result;
2128         SPIPlanPtr      plan;
2129         Portal          portal;
2130
2131         SPI_connect();
2132         plan = SPI_prepare(query, 0, NULL);
2133         portal = SPI_cursor_open(NULL, plan, NULL, NULL, true);
2134         result = _SPI_strdup(map_sql_table_to_xmlschema(portal->tupDesc,
2135                                                                                                         InvalidOid, nulls,
2136                                                                                                         tableforest, targetns));
2137         SPI_cursor_close(portal);
2138         SPI_finish();
2139
2140         PG_RETURN_XML_P(cstring_to_xmltype(result));
2141 }
2142
2143
2144 Datum
2145 cursor_to_xmlschema(PG_FUNCTION_ARGS)
2146 {
2147         char       *name = _textout(PG_GETARG_TEXT_P(0));
2148         bool            nulls = PG_GETARG_BOOL(1);
2149         bool            tableforest = PG_GETARG_BOOL(2);
2150         const char *targetns = _textout(PG_GETARG_TEXT_P(3));
2151         const char *xmlschema;
2152         Portal          portal;
2153
2154         SPI_connect();
2155         portal = SPI_cursor_find(name);
2156         if (portal == NULL)
2157                 ereport(ERROR,
2158                                 (errcode(ERRCODE_UNDEFINED_CURSOR),
2159                                  errmsg("cursor \"%s\" does not exist", name)));
2160
2161         xmlschema = _SPI_strdup(map_sql_table_to_xmlschema(portal->tupDesc,
2162                                                                                                            InvalidOid, nulls,
2163                                                                                                            tableforest, targetns));
2164         SPI_finish();
2165
2166         PG_RETURN_XML_P(cstring_to_xmltype(xmlschema));
2167 }
2168
2169
2170 Datum
2171 table_to_xml_and_xmlschema(PG_FUNCTION_ARGS)
2172 {
2173         Oid                     relid = PG_GETARG_OID(0);
2174         bool            nulls = PG_GETARG_BOOL(1);
2175         bool            tableforest = PG_GETARG_BOOL(2);
2176         const char *targetns = _textout(PG_GETARG_TEXT_P(3));
2177         Relation        rel;
2178         const char *xmlschema;
2179
2180         rel = heap_open(relid, AccessShareLock);
2181         xmlschema = map_sql_table_to_xmlschema(rel->rd_att, relid, nulls,
2182                                                                                    tableforest, targetns);
2183         heap_close(rel, NoLock);
2184
2185         PG_RETURN_XML_P(stringinfo_to_xmltype(table_to_xml_internal(relid,
2186                                                                                         xmlschema, nulls, tableforest,
2187                                                                                         targetns, true)));
2188 }
2189
2190
2191 Datum
2192 query_to_xml_and_xmlschema(PG_FUNCTION_ARGS)
2193 {
2194         char       *query = _textout(PG_GETARG_TEXT_P(0));
2195         bool            nulls = PG_GETARG_BOOL(1);
2196         bool            tableforest = PG_GETARG_BOOL(2);
2197         const char *targetns = _textout(PG_GETARG_TEXT_P(3));
2198
2199         const char *xmlschema;
2200         SPIPlanPtr      plan;
2201         Portal          portal;
2202
2203         SPI_connect();
2204         plan = SPI_prepare(query, 0, NULL);
2205         portal = SPI_cursor_open(NULL, plan, NULL, NULL, true);
2206         xmlschema = _SPI_strdup(map_sql_table_to_xmlschema(portal->tupDesc,
2207                                                                    InvalidOid, nulls, tableforest, targetns));
2208         SPI_cursor_close(portal);
2209         SPI_finish();
2210
2211         PG_RETURN_XML_P(stringinfo_to_xmltype(query_to_xml_internal(query, NULL,
2212                                                                         xmlschema, nulls, tableforest,
2213                                                                         targetns, true)));
2214 }
2215
2216
2217 /*
2218  * Map SQL schema to XML and/or XML Schema document; see SQL/XML:2003
2219  * section 9.4.
2220  */
2221
2222 static StringInfo
2223 schema_to_xml_internal(Oid nspid, const char *xmlschema, bool nulls,
2224                                            bool tableforest, const char *targetns, bool top_level)
2225 {
2226         StringInfo      result;
2227         char       *xmlsn;
2228         List       *relid_list;
2229         ListCell   *cell;
2230
2231         xmlsn = map_sql_identifier_to_xml_name(get_namespace_name(nspid),
2232                                                                                    true, false);
2233         result = makeStringInfo();
2234
2235         xmldata_root_element_start(result, xmlsn, xmlschema, targetns, top_level);
2236
2237         if (xmlschema)
2238                 appendStringInfo(result, "%s\n\n", xmlschema);
2239
2240         SPI_connect();
2241
2242         relid_list = schema_get_xml_visible_tables(nspid);
2243
2244         SPI_push();
2245
2246         foreach(cell, relid_list)
2247         {
2248                 Oid relid = lfirst_oid(cell);
2249                 StringInfo subres;
2250
2251                 subres = table_to_xml_internal(relid, NULL, nulls, tableforest,
2252                                                                            targetns, false);
2253
2254                 appendStringInfoString(result, subres->data);
2255                 appendStringInfoChar(result, '\n');
2256         }
2257
2258         SPI_pop();
2259         SPI_finish();
2260
2261         xmldata_root_element_end(result, xmlsn);
2262
2263         return result;
2264 }
2265
2266
2267 Datum
2268 schema_to_xml(PG_FUNCTION_ARGS)
2269 {
2270         Name            name = PG_GETARG_NAME(0);
2271         bool            nulls = PG_GETARG_BOOL(1);
2272         bool            tableforest = PG_GETARG_BOOL(2);
2273         const char *targetns = _textout(PG_GETARG_TEXT_P(3));
2274
2275         char       *schemaname;
2276         Oid                     nspid;
2277
2278         schemaname = NameStr(*name);
2279         nspid = LookupExplicitNamespace(schemaname);
2280
2281         PG_RETURN_XML_P(stringinfo_to_xmltype(schema_to_xml_internal(nspid, NULL,
2282                                                                                  nulls, tableforest, targetns, true)));
2283 }
2284
2285
2286 /*
2287  * Write the start element of the root element of an XML Schema mapping.
2288  */
2289 static void
2290 xsd_schema_element_start(StringInfo result, const char *targetns)
2291 {
2292         appendStringInfoString(result,
2293                                                    "<xsd:schema\n"
2294                                                    "    xmlns:xsd=\"" NAMESPACE_XSD "\"");
2295         if (strlen(targetns) > 0)
2296                 appendStringInfo(result,
2297                                                  "\n"
2298                                                  "    targetNamespace=\"%s\"\n"
2299                                                  "    elementFormDefault=\"qualified\"",
2300                                                  targetns);
2301         appendStringInfoString(result,
2302                                                    ">\n\n");
2303 }
2304
2305
2306 static void
2307 xsd_schema_element_end(StringInfo result)
2308 {
2309         appendStringInfoString(result, "</xsd:schema>");
2310 }
2311
2312
2313 static StringInfo
2314 schema_to_xmlschema_internal(const char *schemaname, bool nulls,
2315                                                          bool tableforest, const char *targetns)
2316 {
2317         Oid                     nspid;
2318         List       *relid_list;
2319         List       *tupdesc_list;
2320         ListCell   *cell;
2321         StringInfo      result;
2322
2323         result = makeStringInfo();
2324
2325         nspid = LookupExplicitNamespace(schemaname);
2326
2327         xsd_schema_element_start(result, targetns);
2328
2329         SPI_connect();
2330
2331         relid_list = schema_get_xml_visible_tables(nspid);
2332
2333         tupdesc_list = NIL;
2334         foreach (cell, relid_list)
2335         {
2336                 Relation rel;
2337
2338                 rel = heap_open(lfirst_oid(cell), AccessShareLock);
2339                 tupdesc_list = lappend(tupdesc_list, CreateTupleDescCopy(rel->rd_att));
2340                 heap_close(rel, NoLock);
2341         }
2342
2343         appendStringInfoString(result,
2344                                                    map_sql_typecoll_to_xmlschema_types(tupdesc_list));
2345
2346         appendStringInfoString(result,
2347                                                    map_sql_schema_to_xmlschema_types(nspid, relid_list,
2348                                                                                                                          nulls, tableforest, targetns));
2349
2350         xsd_schema_element_end(result);
2351
2352         SPI_finish();
2353
2354         return result;
2355 }
2356
2357
2358 Datum
2359 schema_to_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
2366         PG_RETURN_XML_P(stringinfo_to_xmltype(schema_to_xmlschema_internal(NameStr(*name),
2367                                                                                            nulls, tableforest, targetns)));
2368 }
2369
2370
2371 Datum
2372 schema_to_xml_and_xmlschema(PG_FUNCTION_ARGS)
2373 {
2374         Name            name = PG_GETARG_NAME(0);
2375         bool            nulls = PG_GETARG_BOOL(1);
2376         bool            tableforest = PG_GETARG_BOOL(2);
2377         const char *targetns = _textout(PG_GETARG_TEXT_P(3));
2378         char       *schemaname;
2379         Oid                     nspid;
2380         StringInfo      xmlschema;
2381
2382         schemaname = NameStr(*name);
2383         nspid = LookupExplicitNamespace(schemaname);
2384
2385         xmlschema = schema_to_xmlschema_internal(schemaname, nulls,
2386                                                                                          tableforest, targetns);
2387
2388         PG_RETURN_XML_P(stringinfo_to_xmltype(schema_to_xml_internal(nspid,
2389                                                                                          xmlschema->data, nulls,
2390                                                                                          tableforest, targetns, true)));
2391 }
2392
2393
2394 /*
2395  * Map SQL database to XML and/or XML Schema document; see SQL/XML:2003
2396  * section 9.5.
2397  */
2398
2399 static StringInfo
2400 database_to_xml_internal(const char *xmlschema, bool nulls,
2401                                                  bool tableforest, const char *targetns)
2402 {
2403         StringInfo      result;
2404         List       *nspid_list;
2405         ListCell   *cell;
2406         char       *xmlcn;
2407
2408         xmlcn = map_sql_identifier_to_xml_name(get_database_name(MyDatabaseId),
2409                                                                                    true, false);
2410         result = makeStringInfo();
2411
2412         xmldata_root_element_start(result, xmlcn, xmlschema, targetns, true);
2413
2414         if (xmlschema)
2415                 appendStringInfo(result, "%s\n\n", xmlschema);
2416
2417         SPI_connect();
2418
2419         nspid_list = database_get_xml_visible_schemas();
2420
2421         SPI_push();
2422
2423         foreach(cell, nspid_list)
2424         {
2425                 Oid nspid = lfirst_oid(cell);
2426                 StringInfo subres;
2427
2428                 subres = schema_to_xml_internal(nspid, NULL, nulls,
2429                                                                                 tableforest, targetns, false);
2430
2431                 appendStringInfoString(result, subres->data);
2432                 appendStringInfoChar(result, '\n');
2433         }
2434
2435         SPI_pop();
2436         SPI_finish();
2437
2438         xmldata_root_element_end(result, xmlcn);
2439
2440         return result;
2441 }
2442
2443
2444 Datum
2445 database_to_xml(PG_FUNCTION_ARGS)
2446 {
2447         bool            nulls = PG_GETARG_BOOL(0);
2448         bool            tableforest = PG_GETARG_BOOL(1);
2449         const char *targetns = _textout(PG_GETARG_TEXT_P(2));
2450
2451         PG_RETURN_XML_P(stringinfo_to_xmltype(database_to_xml_internal(NULL, nulls,
2452                                                                                                    tableforest, targetns)));
2453 }
2454
2455
2456 static StringInfo
2457 database_to_xmlschema_internal(bool nulls, bool tableforest,
2458                                                            const char *targetns)
2459 {
2460         List       *relid_list;
2461         List       *nspid_list;
2462         List       *tupdesc_list;
2463         ListCell   *cell;
2464         StringInfo      result;
2465
2466         result = makeStringInfo();
2467
2468         xsd_schema_element_start(result, targetns);
2469
2470         SPI_connect();
2471
2472         relid_list = database_get_xml_visible_tables();
2473         nspid_list = database_get_xml_visible_schemas();
2474
2475         tupdesc_list = NIL;
2476         foreach (cell, relid_list)
2477         {
2478                 Relation rel;
2479
2480                 rel = heap_open(lfirst_oid(cell), AccessShareLock);
2481                 tupdesc_list = lappend(tupdesc_list, CreateTupleDescCopy(rel->rd_att));
2482                 heap_close(rel, NoLock);
2483         }
2484
2485         appendStringInfoString(result,
2486                                                    map_sql_typecoll_to_xmlschema_types(tupdesc_list));
2487
2488         appendStringInfoString(result,
2489                                                    map_sql_catalog_to_xmlschema_types(nspid_list, nulls, tableforest, targetns));
2490
2491         xsd_schema_element_end(result);
2492
2493         SPI_finish();
2494
2495         return result;
2496 }
2497
2498
2499 Datum
2500 database_to_xmlschema(PG_FUNCTION_ARGS)
2501 {
2502         bool            nulls = PG_GETARG_BOOL(0);
2503         bool            tableforest = PG_GETARG_BOOL(1);
2504         const char *targetns = _textout(PG_GETARG_TEXT_P(2));
2505
2506         PG_RETURN_XML_P(stringinfo_to_xmltype(database_to_xmlschema_internal(nulls,
2507                                                                                                          tableforest, targetns)));
2508 }
2509
2510
2511 Datum
2512 database_to_xml_and_xmlschema(PG_FUNCTION_ARGS)
2513 {
2514         bool            nulls = PG_GETARG_BOOL(0);
2515         bool            tableforest = PG_GETARG_BOOL(1);
2516         const char *targetns = _textout(PG_GETARG_TEXT_P(2));
2517         StringInfo      xmlschema;
2518
2519         xmlschema = database_to_xmlschema_internal(nulls, tableforest, targetns);
2520
2521         PG_RETURN_XML_P(stringinfo_to_xmltype(database_to_xml_internal(xmlschema->data,
2522                                                                                            nulls, tableforest, targetns)));
2523 }
2524
2525
2526 /*
2527  * Map a multi-part SQL name to an XML name; see SQL/XML:2003 section
2528  * 9.2.
2529  */
2530 static char *
2531 map_multipart_sql_identifier_to_xml_name(char *a, char *b, char *c, char *d)
2532 {
2533         StringInfoData result;
2534
2535         initStringInfo(&result);
2536
2537         if (a)
2538                 appendStringInfo(&result, "%s",
2539                                                  map_sql_identifier_to_xml_name(a, true, true));
2540         if (b)
2541                 appendStringInfo(&result, ".%s",
2542                                                  map_sql_identifier_to_xml_name(b, true, true));
2543         if (c)
2544                 appendStringInfo(&result, ".%s",
2545                                                  map_sql_identifier_to_xml_name(c, true, true));
2546         if (d)
2547                 appendStringInfo(&result, ".%s",
2548                                                  map_sql_identifier_to_xml_name(d, true, true));
2549
2550         return result.data;
2551 }
2552
2553
2554 /*
2555  * Map an SQL table to an XML Schema document; see SQL/XML:2003
2556  * section 9.3.
2557  *
2558  * Map an SQL table to XML Schema data types; see SQL/XML:2003 section
2559  * 9.6.
2560  */
2561 static const char *
2562 map_sql_table_to_xmlschema(TupleDesc tupdesc, Oid relid, bool nulls,
2563                                                    bool tableforest, const char *targetns)
2564 {
2565         int                     i;
2566         char       *xmltn;
2567         char       *tabletypename;
2568         char       *rowtypename;
2569         StringInfoData result;
2570
2571         initStringInfo(&result);
2572
2573         if (OidIsValid(relid))
2574         {
2575                 HeapTuple tuple;
2576                 Form_pg_class reltuple;
2577
2578                 tuple = SearchSysCache(RELOID,
2579                                                            ObjectIdGetDatum(relid),
2580                                                            0, 0, 0);
2581                 if (!HeapTupleIsValid(tuple))
2582                         elog(ERROR, "cache lookup failed for relation %u", relid);
2583                 reltuple = (Form_pg_class) GETSTRUCT(tuple);
2584
2585                 xmltn = map_sql_identifier_to_xml_name(NameStr(reltuple->relname),
2586                                                                                            true, false);
2587
2588                 tabletypename = map_multipart_sql_identifier_to_xml_name("TableType",
2589                                                                                                                                  get_database_name(MyDatabaseId),
2590                                                                                                                                  get_namespace_name(reltuple->relnamespace),
2591                                                                                                                                  NameStr(reltuple->relname));
2592
2593                 rowtypename = map_multipart_sql_identifier_to_xml_name("RowType",
2594                                                                                                                            get_database_name(MyDatabaseId),
2595                                                                                                                            get_namespace_name(reltuple->relnamespace),
2596                                                                                                                            NameStr(reltuple->relname));
2597
2598                 ReleaseSysCache(tuple);
2599         }
2600         else
2601         {
2602                 if (tableforest)
2603                         xmltn = "row";
2604                 else
2605                         xmltn = "table";
2606
2607                 tabletypename = "TableType";
2608                 rowtypename = "RowType";
2609         }
2610
2611         xsd_schema_element_start(&result, targetns);
2612
2613         appendStringInfoString(&result,
2614                                                    map_sql_typecoll_to_xmlschema_types(list_make1(tupdesc)));
2615
2616         appendStringInfo(&result,
2617                                          "<xsd:complexType name=\"%s\">\n"
2618                                          "  <xsd:sequence>\n",
2619                                          rowtypename);
2620
2621         for (i = 0; i < tupdesc->natts; i++)
2622                 appendStringInfo(&result,
2623                                                  "    <xsd:element name=\"%s\" type=\"%s\"%s></xsd:element>\n",
2624                                                  map_sql_identifier_to_xml_name(NameStr(tupdesc->attrs[i]->attname),
2625                                                                                                                 true, false),
2626                                                  map_sql_type_to_xml_name(tupdesc->attrs[i]->atttypid, -1),
2627                                                  nulls ? " nillable=\"true\"" : " minOccurs=\"0\"");
2628
2629         appendStringInfoString(&result,
2630                                                    "  </xsd:sequence>\n"
2631                                                    "</xsd:complexType>\n\n");
2632
2633         if (!tableforest)
2634         {
2635                 appendStringInfo(&result,
2636                                                  "<xsd:complexType name=\"%s\">\n"
2637                                                  "  <xsd:sequence>\n"
2638                                                  "    <xsd:element name=\"row\" type=\"%s\" minOccurs=\"0\" maxOccurs=\"unbounded\"/>\n"
2639                                                  "  </xsd:sequence>\n"
2640                                                  "</xsd:complexType>\n\n",
2641                                                  tabletypename, rowtypename);
2642
2643                 appendStringInfo(&result,
2644                                                  "<xsd:element name=\"%s\" type=\"%s\"/>\n\n",
2645                                                  xmltn, tabletypename);
2646         }
2647         else
2648                 appendStringInfo(&result,
2649                                                  "<xsd:element name=\"%s\" type=\"%s\"/>\n\n",
2650                                                  xmltn, rowtypename);
2651
2652         xsd_schema_element_end(&result);
2653
2654         return result.data;
2655 }
2656
2657
2658 /*
2659  * Map an SQL schema to XML Schema data types; see SQL/XML section
2660  * 9.7.
2661  */
2662 static const char *
2663 map_sql_schema_to_xmlschema_types(Oid nspid, List *relid_list, bool nulls,
2664                                                                   bool tableforest, const char *targetns)
2665 {
2666         char       *dbname;
2667         char       *nspname;
2668         char       *xmlsn;
2669         char       *schematypename;
2670         StringInfoData result;
2671         ListCell   *cell;
2672
2673         dbname = get_database_name(MyDatabaseId);
2674         nspname = get_namespace_name(nspid);
2675
2676         initStringInfo(&result);
2677
2678         xmlsn = map_sql_identifier_to_xml_name(nspname, true, false);
2679
2680         schematypename = map_multipart_sql_identifier_to_xml_name("SchemaType",
2681                                                                                                                           dbname,
2682                                                                                                                           nspname,
2683                                                                                                                           NULL);
2684
2685         appendStringInfo(&result,
2686                                          "<xsd:complexType name=\"%s\">\n", schematypename);
2687         if (!tableforest)
2688                 appendStringInfoString(&result,
2689                                                            "  <xsd:all>\n");
2690         else
2691                 appendStringInfoString(&result,
2692                                                            "  <xsd:sequence>\n");
2693
2694         foreach (cell, relid_list)
2695         {
2696                 Oid relid = lfirst_oid(cell);
2697                 char *relname = get_rel_name(relid);
2698                 char *xmltn = map_sql_identifier_to_xml_name(relname, true, false);
2699                 char *tabletypename = map_multipart_sql_identifier_to_xml_name(tableforest ? "RowType" : "TableType",
2700                                                                                                                                            dbname,
2701                                                                                                                                            nspname,
2702                                                                                                                                            relname);
2703
2704                 if (!tableforest)
2705                         appendStringInfo(&result,
2706                                                          "    <xsd:element name=\"%s\" type=\"%s\" />\n",
2707                                                          xmltn, tabletypename);
2708                 else
2709                         appendStringInfo(&result,
2710                                                          "    <xsd:element name=\"%s\" type=\"%s\" minOccurs=\"0\" maxOccurs=\"unbounded\" />\n",
2711                                                          xmltn, tabletypename);
2712         }
2713
2714         if (!tableforest)
2715                 appendStringInfoString(&result,
2716                                                            "  </xsd:all>\n");
2717         else
2718                 appendStringInfoString(&result,
2719                                                            "  </xsd:sequence>\n");
2720         appendStringInfoString(&result,
2721                                                    "</xsd:complexType>\n\n");
2722
2723         appendStringInfo(&result,
2724                                          "<xsd:element name=\"%s\" type=\"%s\"/>\n\n",
2725                                          xmlsn, schematypename);
2726
2727         return result.data;
2728 }
2729
2730
2731 /*
2732  * Map an SQL catalog to XML Schema data types; see SQL/XML section
2733  * 9.8.
2734  */
2735 static const char *
2736 map_sql_catalog_to_xmlschema_types(List *nspid_list, bool nulls,
2737                                                                    bool tableforest, const char *targetns)
2738 {
2739         char       *dbname;
2740         char       *xmlcn;
2741         char       *catalogtypename;
2742         StringInfoData result;
2743         ListCell   *cell;
2744
2745         dbname = get_database_name(MyDatabaseId);
2746
2747         initStringInfo(&result);
2748
2749         xmlcn = map_sql_identifier_to_xml_name(dbname, true, false);
2750
2751         catalogtypename = map_multipart_sql_identifier_to_xml_name("CatalogType",
2752                                                                                                                            dbname,
2753                                                                                                                            NULL,
2754                                                                                                                            NULL);
2755
2756         appendStringInfo(&result,
2757                                          "<xsd:complexType name=\"%s\">\n", catalogtypename);
2758         appendStringInfoString(&result,
2759                                                    "  <xsd:all>\n");
2760
2761         foreach (cell, nspid_list)
2762         {
2763                 Oid nspid = lfirst_oid(cell);
2764                 char       *nspname = get_namespace_name(nspid);
2765                 char *xmlsn = map_sql_identifier_to_xml_name(nspname, true, false);
2766                 char *schematypename = map_multipart_sql_identifier_to_xml_name("SchemaType",
2767                                                                                                                                                 dbname,
2768                                                                                                                                                 nspname,
2769                                                                                                                                                 NULL);
2770
2771                 appendStringInfo(&result,
2772                                                  "    <xsd:element name=\"%s\" type=\"%s\" />\n",
2773                                                  xmlsn, schematypename);
2774         }
2775
2776         appendStringInfoString(&result,
2777                                                    "  </xsd:all>\n");
2778         appendStringInfoString(&result,
2779                                                    "</xsd:complexType>\n\n");
2780
2781         appendStringInfo(&result,
2782                                          "<xsd:element name=\"%s\" type=\"%s\"/>\n\n",
2783                                          xmlcn, catalogtypename);
2784
2785         return result.data;
2786 }
2787
2788
2789 /*
2790  * Map an SQL data type to an XML name; see SQL/XML:2003 section 9.9.
2791  */
2792 static const char *
2793 map_sql_type_to_xml_name(Oid typeoid, int typmod)
2794 {
2795         StringInfoData result;
2796
2797         initStringInfo(&result);
2798
2799         switch(typeoid)
2800         {
2801                 case BPCHAROID:
2802                         if (typmod == -1)
2803                                 appendStringInfo(&result, "CHAR");
2804                         else
2805                                 appendStringInfo(&result, "CHAR_%d", typmod - VARHDRSZ);
2806                         break;
2807                 case VARCHAROID:
2808                         if (typmod == -1)
2809                                 appendStringInfo(&result, "VARCHAR");
2810                         else
2811                                 appendStringInfo(&result, "VARCHAR_%d", typmod - VARHDRSZ);
2812                         break;
2813                 case NUMERICOID:
2814                         if (typmod == -1)
2815                                 appendStringInfo(&result, "NUMERIC");
2816                         else
2817                                 appendStringInfo(&result, "NUMERIC_%d_%d",
2818                                                                  ((typmod - VARHDRSZ) >> 16) & 0xffff,
2819                                                                  (typmod - VARHDRSZ) & 0xffff);
2820                         break;
2821                 case INT4OID:
2822                         appendStringInfo(&result, "INTEGER");
2823                         break;
2824                 case INT2OID:
2825                         appendStringInfo(&result, "SMALLINT");
2826                         break;
2827                 case INT8OID:
2828                         appendStringInfo(&result, "BIGINT");
2829                         break;
2830                 case FLOAT4OID:
2831                         appendStringInfo(&result, "REAL");
2832                         break;
2833                 case FLOAT8OID:
2834                         appendStringInfo(&result, "DOUBLE");
2835                         break;
2836                 case BOOLOID:
2837                         appendStringInfo(&result, "BOOLEAN");
2838                         break;
2839                 case TIMEOID:
2840                         if (typmod == -1)
2841                                 appendStringInfo(&result, "TIME");
2842                         else
2843                                 appendStringInfo(&result, "TIME_%d", typmod);
2844                         break;
2845                 case TIMETZOID:
2846                         if (typmod == -1)
2847                                 appendStringInfo(&result, "TIME_WTZ");
2848                         else
2849                                 appendStringInfo(&result, "TIME_WTZ_%d", typmod);
2850                         break;
2851                 case TIMESTAMPOID:
2852                         if (typmod == -1)
2853                                 appendStringInfo(&result, "TIMESTAMP");
2854                         else
2855                                 appendStringInfo(&result, "TIMESTAMP_%d", typmod);
2856                         break;
2857                 case TIMESTAMPTZOID:
2858                         if (typmod == -1)
2859                                 appendStringInfo(&result, "TIMESTAMP_WTZ");
2860                         else
2861                                 appendStringInfo(&result, "TIMESTAMP_WTZ_%d", typmod);
2862                         break;
2863                 case DATEOID:
2864                         appendStringInfo(&result, "DATE");
2865                         break;
2866                 case XMLOID:
2867                         appendStringInfo(&result, "XML");
2868                         break;
2869                 default:
2870                 {
2871                         HeapTuple tuple;
2872                         Form_pg_type typtuple;
2873
2874                         tuple = SearchSysCache(TYPEOID,
2875                                                                    ObjectIdGetDatum(typeoid),
2876                                                                    0, 0, 0);
2877                         if (!HeapTupleIsValid(tuple))
2878                                 elog(ERROR, "cache lookup failed for type %u", typeoid);
2879                         typtuple = (Form_pg_type) GETSTRUCT(tuple);
2880
2881                         appendStringInfoString(&result,
2882                                                                    map_multipart_sql_identifier_to_xml_name((typtuple->typtype == TYPTYPE_DOMAIN) ? "Domain" : "UDT",
2883                                                                                                                                                         get_database_name(MyDatabaseId),
2884                                                                                                                                                         get_namespace_name(typtuple->typnamespace),
2885                                                                                                                                                         NameStr(typtuple->typname)));
2886
2887                         ReleaseSysCache(tuple);
2888                 }
2889         }
2890
2891         return result.data;
2892 }
2893
2894
2895 /*
2896  * Map a collection of SQL data types to XML Schema data types; see
2897  * SQL/XML:2002 section 9.10.
2898  */
2899 static const char *
2900 map_sql_typecoll_to_xmlschema_types(List *tupdesc_list)
2901 {
2902         List       *uniquetypes = NIL;
2903         int                     i;
2904         StringInfoData result;
2905         ListCell   *cell0;
2906
2907         /* extract all column types used in the set of TupleDescs */
2908         foreach(cell0, tupdesc_list)
2909         {
2910                 TupleDesc tupdesc = (TupleDesc) lfirst(cell0);
2911
2912                 for (i = 0; i < tupdesc->natts; i++)
2913                 {
2914                         if (tupdesc->attrs[i]->attisdropped)
2915                                 continue;
2916                         uniquetypes = list_append_unique_oid(uniquetypes,
2917                                                                                                  tupdesc->attrs[i]->atttypid);
2918                 }
2919         }
2920
2921         /* add base types of domains */
2922         foreach(cell0, uniquetypes)
2923         {
2924                 Oid typid = lfirst_oid(cell0);
2925                 Oid basetypid = getBaseType(typid);
2926
2927                 if (basetypid != typid)
2928                         uniquetypes = list_append_unique_oid(uniquetypes, basetypid);
2929         }
2930
2931         /* Convert to textual form */
2932         initStringInfo(&result);
2933
2934         foreach(cell0, uniquetypes)
2935         {
2936                 appendStringInfo(&result, "%s\n",
2937                                                  map_sql_type_to_xmlschema_type(lfirst_oid(cell0),
2938                                                                                                                 -1));
2939         }
2940
2941         return result.data;
2942 }
2943
2944
2945 /*
2946  * Map an SQL data type to a named XML Schema data type; see SQL/XML
2947  * sections 9.11 and 9.15.
2948  *
2949  * (The distinction between 9.11 and 9.15 is basically that 9.15 adds
2950  * a name attribute, which this function does.  The name-less version
2951  * 9.11 doesn't appear to be required anywhere.)
2952  */
2953 static const char *
2954 map_sql_type_to_xmlschema_type(Oid typeoid, int typmod)
2955 {
2956         StringInfoData result;
2957         const char *typename = map_sql_type_to_xml_name(typeoid, typmod);
2958
2959         initStringInfo(&result);
2960
2961         if (typeoid == XMLOID)
2962         {
2963                 appendStringInfo(&result,
2964                                                  "<xsd:complexType mixed=\"true\">\n"
2965                                                  "  <xsd:sequence>\n"
2966                                                  "    <xsd:any name=\"element\" minOccurs=\"0\" maxOccurs=\"unbounded\" processContents=\"skip\"/>\n"
2967                                                  "  </xsd:sequence>\n"
2968                                                  "</xsd:complexType>\n");
2969         }
2970         else
2971         {
2972                 appendStringInfo(&result,
2973                                                  "<xsd:simpleType name=\"%s\">\n", typename);
2974
2975                 switch(typeoid)
2976                 {
2977                         case BPCHAROID:
2978                         case VARCHAROID:
2979                         case TEXTOID:
2980                                 if (typmod != -1)
2981                                         appendStringInfo(&result,
2982                                                                          "  <xsd:restriction base=\"xsd:string\">\n"
2983                                                                          "    <xsd:maxLength value=\"%d\"/>\n"
2984                                                                          "  </xsd:restriction>\n",
2985                                                                          typmod - VARHDRSZ);
2986                                 break;
2987
2988                         case BYTEAOID:
2989                                 appendStringInfo(&result,
2990                                                                  "  <xsd:restriction base=\"xsd:%s\">\n"
2991                                                                  "  </xsd:restriction>\n",
2992                                                                  xmlbinary == XMLBINARY_BASE64 ? "base64Binary" : "hexBinary");
2993
2994                         case NUMERICOID:
2995                                 if (typmod != -1)
2996                                         appendStringInfo(&result,
2997                                                                          "  <xsd:restriction base=\"xsd:decimal\">\n"
2998                                                                          "    <xsd:totalDigits value=\"%d\"/>\n"
2999                                                                          "    <xsd:fractionDigits value=\"%d\"/>\n"
3000                                                                          "  </xsd:restriction>\n",
3001                                                                          ((typmod - VARHDRSZ) >> 16) & 0xffff,
3002                                                                          (typmod - VARHDRSZ) & 0xffff);
3003                                 break;
3004
3005                         case INT2OID:
3006                                 appendStringInfo(&result,
3007                                                                  "  <xsd:restriction base=\"xsd:short\">\n"
3008                                                                  "    <xsd:maxInclusive value=\"%d\"/>\n"
3009                                                                  "    <xsd:minInclusive value=\"%d\"/>\n"
3010                                                                  "  </xsd:restriction>\n",
3011                                                                  SHRT_MAX, SHRT_MIN);
3012                                 break;
3013
3014                         case INT4OID:
3015                                 appendStringInfo(&result,
3016                                                                  "  <xsd:restriction base='xsd:int'>\n"
3017                                                                  "    <xsd:maxInclusive value=\"%d\"/>\n"
3018                                                                  "    <xsd:minInclusive value=\"%d\"/>\n"
3019                                                                  "  </xsd:restriction>\n",
3020                                                                  INT_MAX, INT_MIN);
3021                                 break;
3022
3023                         case INT8OID:
3024                                 appendStringInfo(&result,
3025                                                                  "  <xsd:restriction base=\"xsd:long\">\n"
3026                                                                  "    <xsd:maxInclusive value=\"" INT64_FORMAT "\"/>\n"
3027                                                                  "    <xsd:minInclusive value=\"" INT64_FORMAT "\"/>\n"
3028                                                                  "  </xsd:restriction>\n",
3029                                                                  (((uint64) 1) << (sizeof(int64) * 8 - 1)) - 1,
3030                                                                  (((uint64) 1) << (sizeof(int64) * 8 - 1)));
3031                                 break;
3032
3033                         case FLOAT4OID:
3034                                 appendStringInfo(&result,
3035                                                                  "  <xsd:restriction base=\"xsd:float\"></xsd:restriction>\n");
3036                                 break;
3037
3038                         case FLOAT8OID:
3039                                 appendStringInfo(&result,
3040                                                                  "  <xsd:restriction base=\"xsd:double\"></xsd:restriction>\n");
3041                                 break;
3042
3043                         case BOOLOID:
3044                                 appendStringInfo(&result,
3045                                                                  "  <xsd:restriction base=\"xsd:boolean\"></xsd:restriction>\n");
3046                                 break;
3047
3048                         case TIMEOID:
3049                         case TIMETZOID:
3050                         {
3051                                 const char *tz = (typeoid == TIMETZOID ? "(+|-)\\p{Nd}{2}:\\p{Nd}{2}" : "");
3052
3053                                 if (typmod == -1)
3054                                         appendStringInfo(&result,
3055                                                                          "  <xsd:restriction base=\"xsd:time\">\n"
3056                                                                          "    <xsd:pattern value=\"\\p{Nd}{2}:\\p{Nd}{2}:\\p{Nd}{2}(.\\p{Nd}+)?%s\"/>\n"
3057                                                                          "  </xsd:restriction>\n", tz);
3058                                 else if (typmod == 0)
3059                                         appendStringInfo(&result,
3060                                                                          "  <xsd:restriction base=\"xsd:time\">\n"
3061                                                                          "    <xsd:pattern value=\"\\p{Nd}{2}:\\p{Nd}{2}:\\p{Nd}{2}%s\"/>\n"
3062                                                                          "  </xsd:restriction>\n", tz);
3063                                 else
3064                                         appendStringInfo(&result,
3065                                                                          "  <xsd:restriction base=\"xsd:time\">\n"
3066                                                                          "    <xsd:pattern value=\"\\p{Nd}{2}:\\p{Nd}{2}:\\p{Nd}{2}.\\p{Nd}{%d}%s\"/>\n"
3067                                                                          "  </xsd:restriction>\n", typmod - VARHDRSZ, tz);
3068                                 break;
3069                         }
3070
3071                         case TIMESTAMPOID:
3072                         case TIMESTAMPTZOID:
3073                         {
3074                                 const char *tz = (typeoid == TIMESTAMPTZOID ? "(+|-)\\p{Nd}{2}:\\p{Nd}{2}" : "");
3075
3076                                 if (typmod == -1)
3077                                         appendStringInfo(&result,
3078                                                                          "  <xsd:restriction base=\"xsd:dateTime\">\n"
3079                                                                          "    <xsd:pattern value=\"\\p{Nd}{4}-\\p{Nd}{2}-\\p{Nd}{2}T\\p{Nd}{2}:\\p{Nd}{2}:\\p{Nd}{2}(.\\p{Nd}+)?%s\"/>\n"
3080                                                                          "  </xsd:restriction>\n", tz);
3081                                 else if (typmod == 0)
3082                                         appendStringInfo(&result,
3083                                                                          "  <xsd:restriction base=\"xsd:dateTime\">\n"
3084                                                                          "    <xsd:pattern value=\"\\p{Nd}{4}-\\p{Nd}{2}-\\p{Nd}{2}T\\p{Nd}{2}:\\p{Nd}{2}:\\p{Nd}{2}%s\"/>\n"
3085                                                                          "  </xsd:restriction>\n", tz);
3086                                 else
3087                                         appendStringInfo(&result,
3088                                                                          "  <xsd:restriction base=\"xsd:dateTime\">\n"
3089                                                                          "    <xsd:pattern value=\"\\p{Nd}{4}-\\p{Nd}{2}-\\p{Nd}{2}T\\p{Nd}{2}:\\p{Nd}{2}:\\p{Nd}{2}.\\p{Nd}{%d}%s\"/>\n"
3090                                                                          "  </xsd:restriction>\n", typmod - VARHDRSZ, tz);
3091                                 break;
3092                         }
3093
3094                         case DATEOID:
3095                                 appendStringInfo(&result,
3096                                                                  "  <xsd:restriction base=\"xsd:date\">\n"
3097                                                                  "    <xsd:pattern value=\"\\p{Nd}{4}-\\p{Nd}{2}-\\p{Nd}{2}\"/>\n"
3098                                                                  "  </xsd:restriction>\n");
3099                                 break;
3100
3101                         default:
3102                                 if (get_typtype(typeoid) == TYPTYPE_DOMAIN)
3103                                 {
3104                                         Oid base_typeoid;
3105                                         int32 base_typmod = -1;
3106
3107                                         base_typeoid = getBaseTypeAndTypmod(typeoid, &base_typmod);
3108
3109                                         appendStringInfo(&result,
3110                                                                          "  <xsd:restriction base=\"%s\">\n",
3111                                                                          map_sql_type_to_xml_name(base_typeoid, base_typmod));
3112                                 }
3113                                 break;
3114                 }
3115                 appendStringInfo(&result,
3116                                                  "</xsd:simpleType>\n");
3117         }
3118
3119         return result.data;
3120 }
3121
3122
3123 /*
3124  * Map an SQL row to an XML element, taking the row from the active
3125  * SPI cursor.  See also SQL/XML:2003 section 9.12.
3126  */
3127 static void
3128 SPI_sql_row_to_xmlelement(int rownum, StringInfo result, char *tablename,
3129                                                   bool nulls, bool tableforest,
3130                                                   const char *targetns, bool top_level)
3131 {
3132         int                     i;
3133         char       *xmltn;
3134
3135         if (tablename)
3136                 xmltn = map_sql_identifier_to_xml_name(tablename, true, false);
3137         else
3138         {
3139                 if (tableforest)
3140                         xmltn = "row";
3141                 else
3142                         xmltn = "table";
3143         }
3144
3145         if (tableforest)
3146                 xmldata_root_element_start(result, xmltn, NULL, targetns, top_level);
3147         else
3148                 appendStringInfoString(result, "<row>\n");
3149
3150         for(i = 1; i <= SPI_tuptable->tupdesc->natts; i++)
3151         {
3152                 char *colname;
3153                 Datum colval;
3154                 bool isnull;
3155
3156                 colname = map_sql_identifier_to_xml_name(SPI_fname(SPI_tuptable->tupdesc, i),
3157                                                                                                  true, false);
3158                 colval = SPI_getbinval(SPI_tuptable->vals[rownum],
3159                                                            SPI_tuptable->tupdesc,
3160                                                            i,
3161                                                            &isnull);
3162                 if (isnull)
3163                 {
3164                         if (nulls)
3165                                 appendStringInfo(result, "  <%s xsi:nil='true'/>\n", colname);
3166                 }
3167                 else
3168                         appendStringInfo(result, "  <%s>%s</%s>\n",
3169                                                          colname,
3170                                                          map_sql_value_to_xml_value(colval,
3171                                                                                                                 SPI_gettypeid(SPI_tuptable->tupdesc, i)),
3172                                                          colname);
3173         }
3174
3175         if (tableforest)
3176         {
3177                 xmldata_root_element_end(result, xmltn);
3178                 appendStringInfoChar(result, '\n');
3179         }
3180         else
3181                 appendStringInfoString(result, "</row>\n\n");
3182 }
3183
3184
3185 /*
3186  * XPath related functions
3187  */
3188
3189 #ifdef USE_LIBXML
3190 /* 
3191  * Convert XML node to text (dump subtree in case of element,
3192  * return value otherwise)
3193  */
3194 static text *
3195 xml_xmlnodetoxmltype(xmlNodePtr cur)
3196 {
3197         xmlChar                         *str;
3198         xmltype                         *result;
3199         size_t                          len;
3200         xmlBufferPtr            buf;
3201         
3202         if (cur->type == XML_ELEMENT_NODE)
3203         {
3204                 buf = xmlBufferCreate();
3205                 xmlNodeDump(buf, NULL, cur, 0, 1);
3206                 result = xmlBuffer_to_xmltype(buf);
3207                 xmlBufferFree(buf);
3208         }
3209         else
3210         {
3211                 str = xmlXPathCastNodeToString(cur);
3212                 len = strlen((char *) str);
3213                 result = (text *) palloc(len + VARHDRSZ);
3214                 SET_VARSIZE(result, len + VARHDRSZ);
3215                 memcpy(VARDATA(result), str, len);
3216         }
3217         
3218         return result;
3219 }
3220 #endif
3221
3222
3223 /*
3224  * Evaluate XPath expression and return array of XML values.
3225  *
3226  * As we have no support of XQuery sequences yet, this function seems
3227  * to be the most useful one (array of XML functions plays a role of
3228  * some kind of substitution for XQuery sequences).
3229  *
3230  * Workaround here: we parse XML data in different way to allow XPath for
3231  * fragments (see "XPath for fragment" TODO comment inside).
3232  */
3233 Datum
3234 xpath(PG_FUNCTION_ARGS)
3235 {
3236 #ifdef USE_LIBXML
3237         text       *xpath_expr_text = PG_GETARG_TEXT_P(0);
3238         xmltype    *data = PG_GETARG_XML_P(1);
3239         ArrayType  *namespaces = PG_GETARG_ARRAYTYPE_P(2);
3240         ArrayBuildState    *astate = NULL;
3241         xmlParserCtxtPtr        ctxt = NULL;
3242         xmlDocPtr                       doc = NULL;
3243         xmlXPathContextPtr      xpathctx = NULL;
3244         xmlXPathCompExprPtr     xpathcomp = NULL;
3245         xmlXPathObjectPtr       xpathobj = NULL;
3246         char       *datastr;
3247         int32           len;
3248         int32           xpath_len;
3249         xmlChar    *string;
3250         xmlChar    *xpath_expr;
3251         int                     i;
3252         int                     res_nitems;
3253         int                     ndim;
3254         Datum      *ns_names_uris;
3255         bool       *ns_names_uris_nulls;
3256         int                     ns_count;
3257
3258         /*
3259          * Namespace mappings are passed as text[].  If an empty array is
3260          * passed (ndim = 0, "0-dimensional"), then there are no namespace
3261          * mappings.  Else, a 2-dimensional array with length of the
3262          * second axis being equal to 2 should be passed, i.e., every
3263          * subarray contains 2 elements, the first element defining the
3264          * name, the second one the URI.  Example: ARRAY[ARRAY['myns',
3265          * 'http://example.com'], ARRAY['myns2', 'http://example2.com']].
3266          */
3267         ndim = ARR_NDIM(namespaces);
3268         if (ndim != 0)
3269         {
3270                 int                *dims;
3271
3272                 dims = ARR_DIMS(namespaces);
3273
3274                 if (ndim != 2 || dims[1] != 2)
3275                         ereport(ERROR,
3276                                         (errcode(ERRCODE_DATA_EXCEPTION),
3277                                          errmsg("invalid array for XML namespace mapping"),
3278                                          errdetail("The array must be two-dimensional with length of the second axis equal to 2.")));
3279
3280                 Assert(ARR_ELEMTYPE(namespaces) == TEXTOID);
3281
3282                 deconstruct_array(namespaces, TEXTOID, -1, false, 'i',
3283                                                   &ns_names_uris, &ns_names_uris_nulls,
3284                                                   &ns_count);
3285
3286                 Assert((ns_count % 2) == 0); /* checked above */
3287                 ns_count /= 2;                  /* count pairs only */
3288         }
3289         else
3290         {
3291                 ns_names_uris = NULL;
3292                 ns_names_uris_nulls = NULL;
3293                 ns_count = 0;
3294         }
3295
3296         datastr = VARDATA(data);
3297         len = VARSIZE(data) - VARHDRSZ;
3298         xpath_len = VARSIZE(xpath_expr_text) - VARHDRSZ;
3299         if (xpath_len == 0)
3300                 ereport(ERROR,
3301                                 (errcode(ERRCODE_DATA_EXCEPTION),
3302                                  errmsg("empty XPath expression")));
3303
3304         /*
3305          * To handle both documents and fragments, regardless of the fact
3306          * whether the XML datum has a single root (XML well-formedness),
3307          * we wrap the XML datum in a dummy element (<x>...</x>) and
3308          * extend the XPath expression accordingly.  To do it, throw away
3309          * the XML prolog, if any.
3310          */
3311         if (len >= 5 &&
3312                 xmlStrncmp((xmlChar *) datastr, (xmlChar *) "<?xml", 5) == 0)
3313         {
3314                 i = 5;
3315                 while (i < len &&
3316                            !(datastr[i - 1] == '?' && datastr[i] == '>'))
3317                         i++;
3318
3319                 if (i == len)
3320                         xml_ereport(ERROR, ERRCODE_INTERNAL_ERROR,
3321                                                 "could not parse XML data");
3322
3323                 ++i;
3324                 string = xmlStrncatNew((xmlChar *) "<x>",
3325                                                            (xmlChar *) datastr + i, len - i);
3326         }
3327         else
3328                 string = xmlStrncatNew((xmlChar *) "<x>",
3329                                                            (xmlChar *) datastr, len);
3330
3331         string = xmlStrncat(string, (xmlChar *) "</x>", 5);
3332         len += 7;
3333         xpath_expr = xmlStrncatNew((xmlChar *) "/x",
3334                                                            (xmlChar *) VARDATA(xpath_expr_text), xpath_len);
3335         xpath_len += 2;
3336
3337         xml_init();
3338
3339         /* We use a PG_TRY block to ensure libxml parser is cleaned up on error */
3340         PG_TRY();
3341         {
3342                 xmlInitParser();
3343                 /*
3344                  * redundant XML parsing (two parsings for the same value
3345                  * during one command execution are possible)
3346                  */
3347                 ctxt = xmlNewParserCtxt();
3348                 if (ctxt == NULL)
3349                         xml_ereport(ERROR, ERRCODE_INTERNAL_ERROR,
3350                                                 "could not allocate parser context");
3351                 doc = xmlCtxtReadMemory(ctxt, (char *) string, len, NULL, NULL, 0);
3352                 if (doc == NULL)
3353                         xml_ereport(ERROR, ERRCODE_INVALID_XML_DOCUMENT,
3354                                                 "could not parse XML data");
3355                 xpathctx = xmlXPathNewContext(doc);
3356                 if (xpathctx == NULL)
3357                         xml_ereport(ERROR, ERRCODE_INTERNAL_ERROR,
3358                                                 "could not allocate XPath context");
3359                 xpathctx->node = xmlDocGetRootElement(doc);
3360                 if (xpathctx->node == NULL)
3361                         xml_ereport(ERROR, ERRCODE_INTERNAL_ERROR,
3362                                                 "could not find root XML element");
3363
3364                 /* register namespaces, if any */
3365                 if (ns_count > 0)
3366                 {
3367                         for (i = 0; i < ns_count; i++)
3368                         {
3369                                 char *ns_name;
3370                                 char *ns_uri;
3371
3372                                 if (ns_names_uris_nulls[i * 2] ||
3373                                         ns_names_uris_nulls[i * 2 + 1])
3374                                         ereport(ERROR,
3375                                                         (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3376                                                          errmsg("neither namespace name nor URI may be null")));
3377                                 ns_name = _textout(ns_names_uris[i * 2]);
3378                                 ns_uri = _textout(ns_names_uris[i * 2 + 1]);
3379                                 if (xmlXPathRegisterNs(xpathctx,
3380                                                                            (xmlChar *) ns_name,
3381                                                                            (xmlChar *) ns_uri) != 0)
3382                                         ereport(ERROR, /* is this an internal error??? */
3383                                                         (errmsg("could not register XML namespace with name \"%s\" and URI \"%s\"",
3384                                                                         ns_name, ns_uri)));
3385                         }
3386                 }
3387
3388                 xpathcomp = xmlXPathCompile(xpath_expr);
3389                 if (xpathcomp == NULL)  /* TODO: show proper XPath error details */
3390                         xml_ereport(ERROR, ERRCODE_INTERNAL_ERROR,
3391                                                 "invalid XPath expression");
3392
3393                 xpathobj = xmlXPathCompiledEval(xpathcomp, xpathctx);
3394                 if (xpathobj == NULL)   /* TODO: reason? */
3395                         ereport(ERROR,
3396                                         (errmsg("could not create XPath object")));
3397
3398                 xmlXPathFreeCompExpr(xpathcomp);
3399                 xpathcomp = NULL;
3400
3401                 /* return empty array in cases when nothing is found */
3402                 if (xpathobj->nodesetval == NULL)
3403                         res_nitems = 0;
3404                 else
3405                         res_nitems = xpathobj->nodesetval->nodeNr;
3406
3407                 if (res_nitems)
3408                         for (i = 0; i < xpathobj->nodesetval->nodeNr; i++)
3409                         {
3410                                 Datum           elem;
3411                                 bool            elemisnull = false;
3412                                 elem = PointerGetDatum(xml_xmlnodetoxmltype(xpathobj->nodesetval->nodeTab[i]));
3413                                 astate = accumArrayResult(astate, elem,
3414                                                                                   elemisnull, XMLOID,
3415                                                                                   CurrentMemoryContext);
3416                         }
3417
3418                 xmlXPathFreeObject(xpathobj);
3419                 xpathobj = NULL;
3420                 xmlXPathFreeContext(xpathctx);
3421                 xpathctx = NULL;
3422                 xmlFreeDoc(doc);
3423                 doc = NULL;
3424                 xmlFreeParserCtxt(ctxt);
3425                 ctxt = NULL;
3426                 xmlCleanupParser();
3427         }
3428         PG_CATCH();
3429         {
3430                 if (xpathcomp)
3431                         xmlXPathFreeCompExpr(xpathcomp);
3432                 if (xpathobj)
3433                         xmlXPathFreeObject(xpathobj);
3434                 if (xpathctx)
3435                         xmlXPathFreeContext(xpathctx);
3436                 if (doc)
3437                         xmlFreeDoc(doc);
3438                 if (ctxt)
3439                         xmlFreeParserCtxt(ctxt);
3440                 xmlCleanupParser();
3441
3442                 PG_RE_THROW();
3443         }
3444         PG_END_TRY();
3445
3446         if (res_nitems == 0)
3447                 PG_RETURN_ARRAYTYPE_P(construct_empty_array(XMLOID));
3448         else
3449                 PG_RETURN_ARRAYTYPE_P(makeArrayResult(astate, CurrentMemoryContext));
3450 #else
3451         NO_XML_SUPPORT();
3452         return 0;
3453 #endif
3454 }