@@ -702,50 +702,49 @@ static void
702702pgsm_ExecutorEnd (QueryDesc * queryDesc )
703703{
704704 int64 queryId = queryDesc -> plannedstmt -> queryId ;
705- PlanInfo plan_info ;
706- PlanInfo * plan_ptr = NULL ;
707-
708- /* Extract the plan information in case of SELECT statement */
709- if (queryDesc -> operation == CMD_SELECT && pgsm_enable_query_plan )
710- {
711- int plan_len ;
712- MemoryContext oldctx ;
713-
714- /*
715- * Run explain in a per query context so that there's no memory leak
716- * when executor ends.
717- */
718- oldctx = MemoryContextSwitchTo (queryDesc -> estate -> es_query_cxt );
719-
720- plan_len = strlcpy (plan_info .plan_text , pgsm_explain (queryDesc ), PLAN_TEXT_LEN );
721-
722- MemoryContextSwitchTo (oldctx );
723-
724- plan_info .plan_len = plan_len < PLAN_TEXT_LEN ? plan_len : PLAN_TEXT_LEN - 1 ;
725- plan_info .planid = pgsm_hash_string (plan_info .plan_text , plan_info .plan_len );
726- plan_ptr = & plan_info ;
727- }
728705
729706 if (queryId != INT64CONST (0 ) && pgsm_query_instr (queryDesc ) && pgsm_enabled (nesting_level ))
730707 {
708+ PlanInfo plan_info ;
709+ PlanInfo * plan_ptr = NULL ;
731710 pgsmQueryStats * stats ;
732711 struct rusage rusage_end ;
733712 SysInfo sys_info ;
734- int64 planid = plan_ptr ? plan_ptr -> planid : 0 ;
713+
714+ /* Extract the plan information in case of SELECT statement */
715+ if (queryDesc -> operation == CMD_SELECT && pgsm_enable_query_plan )
716+ {
717+ int plan_len ;
718+ MemoryContext oldctx ;
719+ char * plan_text ;
720+
721+ /*
722+ * Run explain in a per query context so that there's no memory
723+ * leak when executor ends.
724+ */
725+ oldctx = MemoryContextSwitchTo (queryDesc -> estate -> es_query_cxt );
726+ plan_text = pgsm_explain (queryDesc );
727+ MemoryContextSwitchTo (oldctx );
728+
729+ plan_len = strlcpy (plan_info .plan_text , plan_text , PLAN_TEXT_LEN );
730+ plan_info .plan_len = plan_len < PLAN_TEXT_LEN ? plan_len : PLAN_TEXT_LEN - 1 ;
731+ plan_info .planid = pgsm_hash_string (plan_info .plan_text , plan_info .plan_len );
732+ plan_ptr = & plan_info ;
733+ }
735734
736735 stats = pgsm_find_query_stats (queryId );
737736 if (stats == NULL )
738737 {
739738 int query_len = strlen (queryDesc -> sourceText );
740739
741- stats = pgsm_add_query_stats (queryId , planid ,
740+ stats = pgsm_add_query_stats (queryId , plan_ptr ? plan_ptr -> planid : 0 ,
742741 get_pgsm_query_id_hash (queryDesc -> sourceText , query_len ),
743742 queryDesc -> sourceText , query_len ,
744743 queryDesc -> operation );
745744 }
746745
747- if (stats -> key .planid == 0 && planid != 0 )
748- stats -> key .planid = planid ;
746+ if (stats -> key .planid == 0 && plan_ptr != NULL )
747+ stats -> key .planid = plan_ptr -> planid ;
749748
750749#if PG_VERSION_NUM < 190000
751750
0 commit comments