stuff
authorRobert Haas <rhaas@postgresql.org>
Mon, 7 Jul 2025 19:41:28 +0000 (15:41 -0400)
committerRobert Haas <rhaas@postgresql.org>
Mon, 7 Jul 2025 19:41:28 +0000 (15:41 -0400)
contrib/pg_plan_advice/pgpa_collector.c

index 7fffc553761797f1eea4a59dc57ed43609fa7cd1..8f9222fdf731ffde551e07610aa54b1891ad96f3 100644 (file)
@@ -110,7 +110,7 @@ static pgpa_collected_advice *pgpa_make_collected_advice(Oid userid,
 static void pgpa_store_local_advice(pgpa_collected_advice *ca);
 static void pgpa_trim_local_advice(int limit);
 static void pgpa_store_shared_advice(dsa_pointer ca_pointer);
-static void pgpa_trim_shared_advice(int limit);
+static void pgpa_trim_shared_advice(dsa_area *area, int limit);
 
 /* Helper function to extract the query string from pgpa_collected_advice */
 static inline const char *
@@ -346,7 +346,7 @@ pgpa_store_shared_advice(dsa_pointer ca_pointer)
        ++sa->next_id;
 
        /* If we've exceeded the storage limit, discard old data. */
-       pgpa_trim_shared_advice(pg_plan_advice_shared_collection_limit);
+       pgpa_trim_shared_advice(area, pg_plan_advice_shared_collection_limit);
 
        /* Release lock on shared state. */
        LWLockRelease(&state->lock);
@@ -410,9 +410,8 @@ pgpa_trim_local_advice(int limit)
  * specified limit.
  */
 static void
-pgpa_trim_shared_advice(int limit)
+pgpa_trim_shared_advice(dsa_area *area, int limit)
 {
-       dsa_area   *area = pg_plan_advice_dsa_area();
        pgpa_shared_advice *sa = shared_collector;
        uint64          current_count;
        uint64          trim_count;
@@ -483,9 +482,28 @@ Datum
 pg_clear_collected_shared_advice(PG_FUNCTION_ARGS)
 {
        pgpa_shared_state *state = pg_plan_advice_attach();
+       dsa_area   *area = pg_plan_advice_dsa_area();
 
        LWLockAcquire(&state->lock, LW_EXCLUSIVE);
-       pgpa_trim_shared_advice(0);
+
+       /*
+        * If we're not attached to the shared advice collector yet, fix that now;
+        * but if the collector doesn't even exist, we can return without doing
+        * anything else.
+        */
+       if (shared_collector == NULL)
+       {
+               if (state->shared_collector == InvalidDsaPointer)
+               {
+                       LWLockRelease(&state->lock);
+                       return (Datum) 0;
+               }
+               shared_collector = dsa_get_address(area, state->shared_collector);
+       }
+
+       /* Do the real work */
+       pgpa_trim_shared_advice(area, 0);
+
        LWLockRelease(&state->lock);
 
        PG_RETURN_VOID();