From 31ba80d8fafa6746184b74adb2248b463b689293 Mon Sep 17 00:00:00 2001
From: Jim Jones <jim.jones@uni-muenster.de>
Date: Tue, 24 Nov 2026 14:23:11 +0100
Subject: [PATCH v1] Allow cancelling xpath_table()

xpath_table() in contrib/xml2 loops over every row returned by its
query and, for each document, re-evaluates all XPath expressions once
per output row, without checking for interrupts.  A document with many
matching nodes can therefore keep the backend busy for a long time,
during which it ignores query cancel, statement_timeout and
pg_terminate_backend().

Add CHECK_FOR_INTERRUPTS() to both loops.  They run in PostgreSQL code,
outside any libxml2 callback, and the existing PG_TRY block already
frees the libxml2 objects on error.
---
 contrib/xml2/xpath.c | 5 +++++
 1 file changed, 5 insertions(+)

diff --git a/contrib/xml2/xpath.c b/contrib/xml2/xpath.c
index 4cb924541e3..cd4c0f6c04e 100644
--- a/contrib/xml2/xpath.c
+++ b/contrib/xml2/xpath.c
@@ -11,6 +11,7 @@
 #include "fmgr.h"
 #include "funcapi.h"
 #include "lib/stringinfo.h"
+#include "miscadmin.h"
 #include "utils/builtins.h"
 #include "utils/tuplestore.h"
 #include "utils/xml.h"
@@ -772,6 +773,8 @@ xpath_table(PG_FUNCTION_ARGS)
 			char	   *xmldoc;
 			HeapTuple	ret_tuple;
 
+			CHECK_FOR_INTERRUPTS();
+
 			/* Extract the row data as C Strings */
 			spi_tuple = tuptable->vals[i];
 			pkey = SPI_getvalue(spi_tuple, spi_tupdesc, 1);
@@ -810,6 +813,8 @@ xpath_table(PG_FUNCTION_ARGS)
 
 				do
 				{
+					CHECK_FOR_INTERRUPTS();
+
 					/* Now evaluate the set of xpaths. */
 					had_values = false;
 					for (j = 0; j < numpaths; j++)
-- 
2.56.1

