# HG changeset patch
# User Olaf Wintermann <olaf.wintermann@gmail.com>
# Date 1650364342 -7200
# Node ID 8f5c556120a5f6eaa50b1180b410e1c8e7dbf768
# Parent  14cd7137a3a88e927494ad19687ca675c574fd4f
fix error handling in pg_remove_res

diff -r 14cd7137a3a8 -r 8f5c556120a5 src/server/plugins/postgresql/pgtest.c
--- a/src/server/plugins/postgresql/pgtest.c	Mon Apr 18 17:31:45 2022 +0200
+++ b/src/server/plugins/postgresql/pgtest.c	Tue Apr 19 12:32:22 2022 +0200
@@ -274,8 +274,12 @@
     f1 = vfs_open(vfs, "/test_unlink1", O_RDONLY);
     UCX_TEST_ASSERT(f1 == NULL, "test file not deleted");
     
-    //int pgfd = lo_open(test_connection, oid, INV_READ);
-    //UCX_TEST_ASSERT(pgfd < 0, "large object not deleted");
+    PGresult *result = PQexec(test_connection, "savepoint sp;");
+    PQclear(result);
+    int pgfd = lo_open(test_connection, oid, INV_READ);
+    UCX_TEST_ASSERT(pgfd < 0, "large object not deleted");
+    result = PQexec(test_connection, "rollback to savepoint sp;");
+    PQclear(result);
     
     r = vfs_unlink(vfs, "/test_unlink1");
     UCX_TEST_ASSERT(r, "unlink should fail");
diff -r 14cd7137a3a8 -r 8f5c556120a5 src/server/plugins/postgresql/vfs.c
--- a/src/server/plugins/postgresql/vfs.c	Mon Apr 18 17:31:45 2022 +0200
+++ b/src/server/plugins/postgresql/vfs.c	Tue Apr 19 12:32:22 2022 +0200
@@ -472,12 +472,17 @@
 {
     // create transaction savepoint
     PGresult *result = PQexec(pg->connection, "savepoint del_res;");
-    if(PQresultStatus(result) != PGRES_COMMAND_OK) {
+    ExecStatusType execStatus = PQresultStatus(result);
+    PQclear(result);
+    if(execStatus != PGRES_COMMAND_OK) {
         return 1;
     }
     
     if(oid > 0) {
         if(lo_unlink(pg->connection, oid) != 1) {
+            // restore savepoint
+            result = PQexec(pg->connection, "rollback to savepoint del_res;");
+            PQclear(result);
             return 1; // error
         }
     }
@@ -496,14 +501,21 @@
             NULL,
             0);    // 0: result in text format
       
+    execStatus = PQresultStatus(result);
+    PQclear(result); 
     int ret = 0;
-    if(PQresultStatus(result) != PGRES_COMMAND_OK) {
+    
+    if(execStatus != PGRES_COMMAND_OK) {
         ret = 1;
         // restore savepoint
         result = PQexec(pg->connection, "rollback to savepoint del_res;");
         PQclear(result);
+    } else {
+        // we don't need the savepoint anymore
+        result = PQexec(pg->connection, "release savepoint del_res;");
+        PQclear(result);
     }
-    PQclear(result); 
+    
     return ret;
 }