Newer
Older
/*-------------------------------------------------------------------------
*
* xml.c
* XML data type support.
*
*
* Portions Copyright (c) 1996-2011, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
*
*-------------------------------------------------------------------------
*/
/*
* Generally, XML type support is only available when libxml use was
* configured during the build. But even if that is not done, the
* type and all the functions are available, but most of them will
* fail. For one thing, this avoids having to manage variant catalog
* installations. But it also has nice effects such as that you can
* dump a database containing XML type data even if the server is not
* linked with libxml. Thus, make sure xml_out() works even if nothing
*/
/*
* Notes on memory management:
*
* Sometimes libxml allocates global structures in the hope that it can reuse
* them later on. This makes it impractical to change the xmlMemSetup
* functions on-the-fly; that is likely to lead to trying to pfree() chunks
* allocated with malloc() or vice versa. Since libxml might be used by
* loadable modules, eg libperl, our only safe choices are to change the
* functions at postmaster/backend launch or not at all. Since we'd rather
* not activate libxml in sessions that might never use it, the latter choice
* is the preferred one. However, for debugging purposes it can be awfully
* handy to constrain libxml's allocations to be done in a specific palloc
* context, where they're easy to track. Therefore there is code here that
* can be enabled in debug builds to redirect libxml's allocations into a
* special context LibxmlContext. It's not recommended to turn this on in
* a production build because of the possibility of bad interactions with
* external modules.
*/
/* #define USE_LIBXMLCONTEXT */
#include "postgres.h"
#ifdef USE_LIBXML
#include <libxml/chvalid.h>
#include <libxml/parser.h>
#include <libxml/tree.h>
#include <libxml/uri.h>
#include <libxml/xmlerror.h>
#include <libxml/xmlwriter.h>
#include <libxml/xpath.h>
#include <libxml/xpathInternals.h>
Peter Eisentraut
committed
#include "catalog/namespace.h"
#include "catalog/pg_type.h"
Peter Eisentraut
committed
#include "commands/dbcommands.h"
#include "executor/executor.h"
Peter Eisentraut
committed
#include "executor/spi.h"
#include "fmgr.h"
Peter Eisentraut
committed
#include "lib/stringinfo.h"
#include "mb/pg_wchar.h"
Peter Eisentraut
committed
#include "miscadmin.h"
#include "nodes/execnodes.h"
#include "nodes/nodeFuncs.h"
#include "utils/array.h"
#include "utils/builtins.h"
#include "utils/date.h"
#include "utils/datetime.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/rel.h"
#include "utils/syscache.h"
#include "utils/xml.h"
/* GUC variables */
int xmlbinary;
int xmloption;
#ifdef USE_LIBXML
/* random number to identify PgXmlErrorContext */
#define ERRCXT_MAGIC 68275028
struct PgXmlErrorContext
{
int magic;
/* strictness argument passed to pg_xml_init */
PgXmlStrictness strictness;
/* current error status and accumulated message, if any */
bool err_occurred;
StringInfoData err_buf;
/* previous libxml error handling state (saved by pg_xml_init) */
xmlStructuredErrorFunc saved_errfunc;
void *saved_errcxt;
};
static void xml_errorHandler(void *data, xmlErrorPtr error);
static void xml_ereport_by_code(int level, int sqlcode,
const char *msg, int errcode);
static void chopStringInfoNewlines(StringInfo str);
static void appendStringInfoLineSeparator(StringInfo str);
#ifdef USE_LIBXMLCONTEXT
static MemoryContext LibxmlContext = NULL;
static void xml_memory_init(void);
static void *xml_palloc(size_t size);
static void *xml_repalloc(void *ptr, size_t size);
static void xml_pfree(void *ptr);
static char *xml_pstrdup(const char *string);
#endif /* USE_LIBXMLCONTEXT */
static xmlChar *xml_text2xmlChar(text *in);
static int parse_xml_decl(const xmlChar *str, size_t *lenp,
xmlChar **version, xmlChar **encoding, int *standalone);
static bool print_xml_decl(StringInfo buf, const xmlChar *version,
static xmlDocPtr xml_parse(text *data, XmlOptionType xmloption_arg,
Heikki Linnakangas
committed
bool preserve_whitespace, int encoding);
static text *xml_xmlnodetoxmltype(xmlNodePtr cur);
static int xml_xpathobjtoxmlarray(xmlXPathObjectPtr xpathobj,
ArrayBuildState **astate);
static StringInfo query_to_xml_internal(const char *query, char *tablename,
const char *xmlschema, bool nulls, bool tableforest,
const char *targetns, bool top_level);
static const char *map_sql_table_to_xmlschema(TupleDesc tupdesc, Oid relid,
bool nulls, bool tableforest, const char *targetns);
static const char *map_sql_schema_to_xmlschema_types(Oid nspid,
List *relid_list, bool nulls,
bool tableforest, const char *targetns);
static const char *map_sql_catalog_to_xmlschema_types(List *nspid_list,
bool nulls, bool tableforest,
const char *targetns);
static const char *map_sql_type_to_xml_name(Oid typeoid, int typmod);
static const char *map_sql_typecoll_to_xmlschema_types(List *tupdesc_list);
static const char *map_sql_type_to_xmlschema_type(Oid typeoid, int typmod);
static void SPI_sql_row_to_xmlelement(int rownum, StringInfo result,
char *tablename, bool nulls, bool tableforest,
const char *targetns, bool top_level);
Peter Eisentraut
committed
#define NO_XML_SUPPORT() \
ereport(ERROR, \
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED), \
errmsg("unsupported XML feature"), \
Peter Eisentraut
committed
errdetail("This functionality requires the server to be built with libxml support."), \
errhint("You need to rebuild PostgreSQL using --with-libxml.")))
Peter Eisentraut
committed
/* from SQL/XML:2008 section 4.9 */
Peter Eisentraut
committed
#define NAMESPACE_XSD "http://www.w3.org/2001/XMLSchema"
#define NAMESPACE_XSI "http://www.w3.org/2001/XMLSchema-instance"
#define NAMESPACE_SQLXML "http://standards.iso.org/iso/9075/2003/sqlxml"
#ifdef USE_LIBXML
static int
xmlChar_to_encoding(const xmlChar *encoding_name)
int encoding = pg_char_to_encoding((const char *) encoding_name);
if (encoding < 0)
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("invalid encoding name \"%s\"",
(const char *) encoding_name)));
return encoding;
}
#endif
/*
* xml_in uses a plain C string to VARDATA conversion, so for the time being
* we use the conversion function for the text datatype.
*
* This is only acceptable so long as xmltype and text use the same
* representation.
*/
Datum
xml_in(PG_FUNCTION_ARGS)
{
#ifdef USE_LIBXML
char *s = PG_GETARG_CSTRING(0);
xmltype *vardata;
xmlDocPtr doc;
vardata = (xmltype *) cstring_to_text(s);
/*
* Parse the data to check if it is well-formed XML data. Assume that
* ERROR occurred if parsing failed.
*/
Heikki Linnakangas
committed
doc = xml_parse(vardata, xmloption, true, GetDatabaseEncoding());
Peter Eisentraut
committed
xmlFreeDoc(doc);
PG_RETURN_XML_P(vardata);
#else
NO_XML_SUPPORT();
return 0;
#endif
}
#define PG_XML_DEFAULT_VERSION "1.0"
/*
* xml_out_internal uses a plain VARDATA to C string conversion, so for the
* time being we use the conversion function for the text datatype.
*
* This is only acceptable so long as xmltype and text use the same
* representation.
*/
static char *
xml_out_internal(xmltype *x, pg_enc target_encoding)
char *str = text_to_cstring((text *) x);
#ifdef USE_LIBXML
size_t len = strlen(str);
int standalone;
int res_code;
&len, &version, NULL, &standalone)) == 0)
{
StringInfoData buf;
initStringInfo(&buf);
if (!print_xml_decl(&buf, version, target_encoding, standalone))
{
/*
* If we are not going to produce an XML declaration, eat a single
* newline in the original string to prevent empty first lines in
* the output.
*/
if (*(str + len) == '\n')
len += 1;
}
appendStringInfoString(&buf, str + len);
pfree(str);
return buf.data;
}
xml_ereport_by_code(WARNING, ERRCODE_INTERNAL_ERROR,
"could not parse XML declaration in stored value",
res_code);
#endif
return str;
}
Datum
xml_out(PG_FUNCTION_ARGS)
{
* xml_out removes the encoding property in all cases. This is because we
* cannot control from here whether the datum will be converted to a
* different client encoding, so we'd do more harm than good by including
* it.
*/
PG_RETURN_CSTRING(xml_out_internal(x, 0));
}
Datum
xml_recv(PG_FUNCTION_ARGS)
{
#ifdef USE_LIBXML
StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
char *newstr;
Peter Eisentraut
committed
xmlDocPtr doc;
Heikki Linnakangas
committed
xmlChar *encodingStr = NULL;
int encoding;
* Read the data in raw format. We don't know yet what the encoding is, as
* that information is embedded in the xml declaration; so we have to
* parse that before converting to server encoding.
*/
nbytes = buf->len - buf->cursor;
str = (char *) pq_getmsgbytes(buf, nbytes);
/*
* We need a null-terminated string to pass to parse_xml_decl(). Rather
* than make a separate copy, make the temporary result one byte bigger
* than it needs to be.
*/
result = palloc(nbytes + 1 + VARHDRSZ);
SET_VARSIZE(result, nbytes + VARHDRSZ);
memcpy(VARDATA(result), str, nbytes);
str = VARDATA(result);
str[nbytes] = '\0';
Heikki Linnakangas
committed
parse_xml_decl((xmlChar *) str, NULL, NULL, &encodingStr, NULL);
/*
* If encoding wasn't explicitly specified in the XML header, treat it as
* UTF-8, as that's the default in XML. This is different from xml_in(),
* where the input has to go through the normal client to server encoding
* conversion.
*/
encoding = encodingStr ? xmlChar_to_encoding(encodingStr) : PG_UTF8;
* Parse the data to check if it is well-formed XML data. Assume that
* xml_parse will throw ERROR if not.
doc = xml_parse(result, xmloption, true, encoding);
Peter Eisentraut
committed
xmlFreeDoc(doc);
/* Now that we know what we're dealing with, convert to server encoding */
newstr = (char *) pg_do_encoding_conversion((unsigned char *) str,
nbytes,
Heikki Linnakangas
committed
encoding,
GetDatabaseEncoding());
if (newstr != str)
{
result = (xmltype *) cstring_to_text(newstr);
}
PG_RETURN_XML_P(result);
#else
NO_XML_SUPPORT();
return 0;
#endif
}
Datum
xml_send(PG_FUNCTION_ARGS)
{
* xml_out_internal doesn't convert the encoding, it just prints the right
* declaration. pq_sendtext will do the conversion.
*/
outval = xml_out_internal(x, pg_get_client_encoding());
pq_sendtext(&buf, outval, strlen(outval));
pfree(outval);
PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
}
#ifdef USE_LIBXML
static void
appendStringInfoText(StringInfo str, const text *t)
{
appendBinaryStringInfo(str, VARDATA(t), VARSIZE(t) - VARHDRSZ);
}
Peter Eisentraut
committed
#endif
static xmltype *
stringinfo_to_xmltype(StringInfo buf)
{
return (xmltype *) cstring_to_text_with_len(buf->data, buf->len);
}
Peter Eisentraut
committed
static xmltype *
cstring_to_xmltype(const char *string)
{
return (xmltype *) cstring_to_text(string);
}
Peter Eisentraut
committed
#ifdef USE_LIBXML
Peter Eisentraut
committed
static xmltype *
xmlBuffer_to_xmltype(xmlBufferPtr buf)
{
return (xmltype *) cstring_to_text_with_len((char *) xmlBufferContent(buf),
xmlBufferLength(buf));
Peter Eisentraut
committed
}
#endif
Datum
xmlcomment(PG_FUNCTION_ARGS)
{
#ifdef USE_LIBXML
text *arg = PG_GETARG_TEXT_P(0);
char *argdata = VARDATA(arg);
int len = VARSIZE(arg) - VARHDRSZ;
StringInfoData buf;
/* check for "--" in string or "-" at the end */
for (i = 1; i < len; i++)
{
if (argdata[i] == '-' && argdata[i - 1] == '-')
ereport(ERROR,
(errcode(ERRCODE_INVALID_XML_COMMENT),
errmsg("invalid XML comment")));
}
if (len > 0 && argdata[len - 1] == '-')
ereport(ERROR,
(errcode(ERRCODE_INVALID_XML_COMMENT),
errmsg("invalid XML comment")));
initStringInfo(&buf);
appendStringInfo(&buf, "<!--");
appendStringInfoText(&buf, arg);
appendStringInfo(&buf, "-->");
PG_RETURN_XML_P(stringinfo_to_xmltype(&buf));
#else
NO_XML_SUPPORT();
return 0;
#endif
}
/*
* TODO: xmlconcat needs to merge the notations and unparsed entities
* of the argument values. Not very important in practice, though.
*/
xmltype *
xmlconcat(List *args)
{
#ifdef USE_LIBXML
int global_standalone = 1;
bool global_version_no_value = false;
initStringInfo(&buf);
foreach(v, args)
{
xmltype *x = DatumGetXmlP(PointerGetDatum(lfirst(v)));
size_t len;
int standalone;
char *str;
len = VARSIZE(x) - VARHDRSZ;
str = text_to_cstring((text *) x);
parse_xml_decl((xmlChar *) str, &len, &version, NULL, &standalone);
if (standalone == 0 && global_standalone == 1)
global_standalone = 0;
if (standalone < 0)
global_standalone = -1;
if (!version)
global_version_no_value = true;
else if (!global_version)
global_version = version;
else if (xmlStrcmp(version, global_version) != 0)
global_version_no_value = true;
appendStringInfoString(&buf, str + len);
pfree(str);
}
if (!global_version_no_value || global_standalone >= 0)
{
StringInfoData buf2;
initStringInfo(&buf2);
(!global_version_no_value) ? global_version : NULL,
0,
global_standalone);
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
appendStringInfoString(&buf2, buf.data);
buf = buf2;
}
return stringinfo_to_xmltype(&buf);
#else
NO_XML_SUPPORT();
return NULL;
#endif
}
/*
* XMLAGG support
*/
Datum
xmlconcat2(PG_FUNCTION_ARGS)
{
if (PG_ARGISNULL(0))
{
if (PG_ARGISNULL(1))
PG_RETURN_NULL();
else
PG_RETURN_XML_P(PG_GETARG_XML_P(1));
}
else if (PG_ARGISNULL(1))
PG_RETURN_XML_P(PG_GETARG_XML_P(0));
else
PG_RETURN_XML_P(xmlconcat(list_make2(PG_GETARG_XML_P(0),
PG_GETARG_XML_P(1))));
}
Datum
texttoxml(PG_FUNCTION_ARGS)
{
text *data = PG_GETARG_TEXT_P(0);
PG_RETURN_XML_P(xmlparse(data, xmloption, true));
}
Datum
xmltotext(PG_FUNCTION_ARGS)
{
/* It's actually binary compatible. */
}
text *
xmltotext_with_xmloption(xmltype *data, XmlOptionType xmloption_arg)
{
if (xmloption_arg == XMLOPTION_DOCUMENT && !xml_is_document(data))
ereport(ERROR,
(errcode(ERRCODE_NOT_AN_XML_DOCUMENT),
errmsg("not an XML document")));
/* It's actually binary compatible, save for the above check. */
return (text *) data;
xmltype *
xmlelement(XmlExprState *xmlExpr, ExprContext *econtext)
{
#ifdef USE_LIBXML
XmlExpr *xexpr = (XmlExpr *) xmlExpr->xprstate.expr;
xmltype *result;
List *named_arg_strings;
List *arg_strings;
int i;
ListCell *arg;
ListCell *narg;
PgXmlErrorContext *xmlerrcxt;
volatile xmlBufferPtr buf = NULL;
volatile xmlTextWriterPtr writer = NULL;
/*
* We first evaluate all the arguments, then start up libxml and create
* the result. This avoids issues if one of the arguments involves a call
* to some other function or subsystem that wants to use libxml on its own
* terms.
*/
named_arg_strings = NIL;
i = 0;
foreach(arg, xmlExpr->named_args)
{
Datum value;
bool isnull;
char *str;
value = ExecEvalExpr(e, econtext, &isnull, NULL);
if (isnull)
str = NULL;
else
str = map_sql_value_to_xml_value(value, exprType((Node *) e->expr), false);
named_arg_strings = lappend(named_arg_strings, str);
i++;
}
arg_strings = NIL;
foreach(arg, xmlExpr->args)
{
Datum value;
bool isnull;
char *str;
value = ExecEvalExpr(e, econtext, &isnull, NULL);
/* here we can just forget NULL elements immediately */
if (!isnull)
{
str = map_sql_value_to_xml_value(value,
exprType((Node *) e->expr), true);
arg_strings = lappend(arg_strings, str);
}
}
/* now safe to run libxml */
xmlerrcxt = pg_xml_init(PG_XML_STRICTNESS_ALL);
PG_TRY();
{
buf = xmlBufferCreate();
if (buf == NULL || xmlerrcxt->err_occurred)
xml_ereport(xmlerrcxt, ERROR, ERRCODE_OUT_OF_MEMORY,
"could not allocate xmlBuffer");
writer = xmlNewTextWriterMemory(buf, 0);
if (writer == NULL || xmlerrcxt->err_occurred)
xml_ereport(xmlerrcxt, ERROR, ERRCODE_OUT_OF_MEMORY,
"could not allocate xmlTextWriter");
xmlTextWriterStartElement(writer, (xmlChar *) xexpr->name);
forboth(arg, named_arg_strings, narg, xexpr->arg_names)
{
char *str = (char *) lfirst(arg);
char *argname = strVal(lfirst(narg));
if (str)
xmlTextWriterWriteAttribute(writer,
(xmlChar *) argname,
(xmlChar *) str);
}
foreach(arg, arg_strings)
{
char *str = (char *) lfirst(arg);
xmlTextWriterWriteRaw(writer, (xmlChar *) str);
}
xmlTextWriterEndElement(writer);
/* we MUST do this now to flush data out to the buffer ... */
xmlFreeTextWriter(writer);
writer = NULL;
result = xmlBuffer_to_xmltype(buf);
}
PG_CATCH();
{
if (writer)
xmlFreeTextWriter(writer);
if (buf)
xmlBufferFree(buf);
pg_xml_done(xmlerrcxt, true);
PG_RE_THROW();
}
PG_END_TRY();
xmlBufferFree(buf);
pg_xml_done(xmlerrcxt, false);
return result;
#else
NO_XML_SUPPORT();
return NULL;
#endif
}
xmltype *
xmlparse(text *data, XmlOptionType xmloption_arg, bool preserve_whitespace)
{
#ifdef USE_LIBXML
Peter Eisentraut
committed
xmlDocPtr doc;
Heikki Linnakangas
committed
doc = xml_parse(data, xmloption_arg, preserve_whitespace,
GetDatabaseEncoding());
Peter Eisentraut
committed
xmlFreeDoc(doc);
return (xmltype *) data;
#else
NO_XML_SUPPORT();
return NULL;
#endif
}
xmltype *
xmlpi(char *target, text *arg, bool arg_is_null, bool *result_is_null)
{
#ifdef USE_LIBXML
StringInfoData buf;
if (pg_strcasecmp(target, "xml") == 0)
ereport(ERROR,
errmsg("invalid XML processing instruction"),
errdetail("XML processing instruction target name cannot be \"%s\".", target)));
* Following the SQL standard, the null check comes after the syntax check
* above.
*/
*result_is_null = arg_is_null;
if (*result_is_null)
initStringInfo(&buf);
appendStringInfo(&buf, "<?%s", target);
if (arg != NULL)
{
string = text_to_cstring(arg);
if (strstr(string, "?>") != NULL)
ereport(ERROR,
(errcode(ERRCODE_INVALID_XML_PROCESSING_INSTRUCTION),
errmsg("invalid XML processing instruction"),
errdetail("XML processing instruction cannot contain \"?>\".")));
appendStringInfoChar(&buf, ' ');
appendStringInfoString(&buf, string + strspn(string, " "));
pfree(string);
}
appendStringInfoString(&buf, "?>");
result = stringinfo_to_xmltype(&buf);
pfree(buf.data);
return result;
#else
NO_XML_SUPPORT();
return NULL;
#endif
}
xmltype *
xmlroot(xmltype *data, text *version, int standalone)
{
#ifdef USE_LIBXML
char *str;
size_t len;
int orig_standalone;
StringInfoData buf;
len = VARSIZE(data) - VARHDRSZ;
str = text_to_cstring((text *) data);
parse_xml_decl((xmlChar *) str, &len, &orig_version, NULL, &orig_standalone);
if (version)
orig_version = xml_text2xmlChar(version);
Peter Eisentraut
committed
else
Peter Eisentraut
committed
switch (standalone)
case XML_STANDALONE_YES:
orig_standalone = 1;
break;
case XML_STANDALONE_NO:
orig_standalone = 0;
Peter Eisentraut
committed
break;
case XML_STANDALONE_NO_VALUE:
orig_standalone = -1;
Peter Eisentraut
committed
break;
case XML_STANDALONE_OMITTED:
/* leave original value */
Peter Eisentraut
committed
break;
}
initStringInfo(&buf);
print_xml_decl(&buf, orig_version, 0, orig_standalone);
appendStringInfoString(&buf, str + len);
Peter Eisentraut
committed
return stringinfo_to_xmltype(&buf);
#else
NO_XML_SUPPORT();
return NULL;
#endif
}
/*
* Validate document (given as string) against DTD (given as external link)
*
* This has been removed because it is a security hole: unprivileged users
* should not be able to use Postgres to fetch arbitrary external files,
* which unfortunately is exactly what libxml is willing to do with the DTD
* parameter.
*/
Datum
xmlvalidate(PG_FUNCTION_ARGS)
{
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("xmlvalidate is not implemented")));
return 0;
}
xml_is_document(xmltype *arg)
{
#ifdef USE_LIBXML
bool result;
volatile xmlDocPtr doc = NULL;
MemoryContext ccxt = CurrentMemoryContext;
/* We want to catch ereport(INVALID_XML_DOCUMENT) and return false */
Heikki Linnakangas
committed
doc = xml_parse((text *) arg, XMLOPTION_DOCUMENT, true,
GetDatabaseEncoding());
result = true;
}
PG_CATCH();
{
MemoryContext ecxt;
ecxt = MemoryContextSwitchTo(ccxt);
errdata = CopyErrorData();
if (errdata->sqlerrcode == ERRCODE_INVALID_XML_DOCUMENT)
{
FlushErrorState();
result = false;
}
else
{
MemoryContextSwitchTo(ecxt);
PG_RE_THROW();
}
}
PG_END_TRY();
if (doc)
xmlFreeDoc(doc);
return result;
NO_XML_SUPPORT();
return false;
#ifdef USE_LIBXML
/*
* pg_xml_init_library --- set up for use of libxml
*
* This should be called by each function that is about to use libxml
* facilities but doesn't require error handling. It initializes libxml
* and verifies compatibility with the loaded libxml version. These are
* once-per-session activities.
*
* TODO: xmlChar is utf8-char, make proper tuning (initdb with enc!=utf8 and
* check)
*/
void
{
static bool first_time = true;
if (first_time)
/* Stuff we need do only once per session */
/*
* Currently, we have no pure UTF-8 support for internals -- check if
* we can work.
*/
if (sizeof(char) != sizeof(xmlChar))
ereport(ERROR,
(errmsg("could not initialize XML library"),
errdetail("libxml2 has incompatible char type: sizeof(char)=%u, sizeof(xmlChar)=%u.",
(int) sizeof(char), (int) sizeof(xmlChar))));
#ifdef USE_LIBXMLCONTEXT
/* Set up libxml's memory allocation our way */
xml_memory_init();
/* Check library compatibility */
LIBXML_TEST_VERSION;
first_time = false;
/*
* pg_xml_init --- set up for use of libxml and register an error handler
*
* This should be called by each function that is about to use libxml
* facilities and requires error handling. It initializes libxml with
* pg_xml_init_library() and establishes our libxml error handler.
*
* strictness determines which errors are reported and which are ignored.
*
* Calls to this function MUST be followed by a PG_TRY block that guarantees
* that pg_xml_done() is called during either normal or error exit.
*
* This is exported for use by contrib/xml2, as well as other code that might
* wish to share use of this module's libxml error handler.
*/
PgXmlErrorContext *
pg_xml_init(PgXmlStrictness strictness)
{
PgXmlErrorContext *errcxt;
void *new_errcxt;
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
/* Do one-time setup if needed */
pg_xml_init_library();
/* Create error handling context structure */
errcxt = (PgXmlErrorContext *) palloc(sizeof(PgXmlErrorContext));
errcxt->magic = ERRCXT_MAGIC;
errcxt->strictness = strictness;
errcxt->err_occurred = false;
initStringInfo(&errcxt->err_buf);
/*
* Save original error handler and install ours. libxml originally didn't
* distinguish between the contexts for generic and for structured error
* handlers. If we're using an old libxml version, we must thus save
* the generic error context, even though we're using a structured
* error handler.
*/
errcxt->saved_errfunc = xmlStructuredError;
#ifdef HAVE_XMLSTRUCTUREDERRORCONTEXT
errcxt->saved_errcxt = xmlStructuredErrorContext;
#else
errcxt->saved_errcxt = xmlGenericErrorContext;
#endif
xmlSetStructuredErrorFunc((void *) errcxt, xml_errorHandler);
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
/*
* Verify that xmlSetStructuredErrorFunc set the context variable we
* expected it to. If not, the error context pointer we just saved is not
* the correct thing to restore, and since that leaves us without a way to
* restore the context in pg_xml_done, we must fail.
*
* The only known situation in which this test fails is if we compile with
* headers from a libxml2 that doesn't track the structured error context
* separately (<= 2.7.3), but at runtime use a version that does, or vice
* versa. The libxml2 authors did not treat that change as constituting
* an ABI break, so the LIBXML_TEST_VERSION test in pg_xml_init_library
* fails to protect us from this.
*/
#ifdef HAVE_XMLSTRUCTUREDERRORCONTEXT
new_errcxt = xmlStructuredErrorContext;
#else
new_errcxt = xmlGenericErrorContext;
#endif
if (new_errcxt != (void *) errcxt)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("could not set up XML error handler"),
errhint("This probably indicates that the version of libxml2"
" being used is not compatible with the libxml2"
" header files that PostgreSQL was built with.")));
return errcxt;
}
/*
* pg_xml_done --- restore previous libxml error handling
*
* Resets libxml's global error-handling state to what it was before
* pg_xml_init() was called.
*
* This routine verifies that all pending errors have been dealt with
* (in assert-enabled builds, anyway).
*/