3030#include "utils/numeric.h"
3131#include "utils/ruleutils.h"
3232#include "utils/syscache.h"
33+ #include "utils/snapmgr.h"
3334
3435#if PG_VERSION_NUM >=100000
3536#include "utils/regproc.h"
@@ -682,6 +683,7 @@ merge_range_partitions_internal(Oid parent, Oid *parts, uint32 nparts)
682683* last ;
683684FmgrInfo cmp_proc ;
684685int i ;
686+ Snapshot fresh_snapshot ;
685687
686688prel = get_pathman_relation_info (parent );
687689shout_if_prel_is_invalid (parent ,prel ,PT_RANGE );
@@ -739,6 +741,13 @@ merge_range_partitions_internal(Oid parent, Oid *parts, uint32 nparts)
739741if (SPI_connect ()!= SPI_OK_CONNECT )
740742elog (ERROR ,"could not connect using SPI" );
741743
744+ /*
745+ * Get latest snapshot to see data that might have been
746+ * added to partitions before this transaction has started,
747+ * but was committed a moment before we acquired the locks.
748+ */
749+ fresh_snapshot = RegisterSnapshot (GetLatestSnapshot ());
750+
742751/* Migrate the data from all partition to the first one */
743752for (i = 1 ;i < nparts ;i ++ )
744753{
@@ -749,10 +758,24 @@ merge_range_partitions_internal(Oid parent, Oid *parts, uint32 nparts)
749758get_qualified_rel_name (parts [i ]),
750759get_qualified_rel_name (parts [0 ]));
751760
752- SPI_exec (query ,0 );
761+ SPIPlanPtr plan = SPI_prepare (query ,0 ,NULL );
762+
763+ if (!plan )
764+ elog (ERROR ,"%s: SPI_prepare returned %d" ,
765+ CppAsString (merge_range_partitions ),
766+ SPI_result );
767+
768+ SPI_execute_snapshot (plan ,NULL ,NULL ,
769+ fresh_snapshot ,
770+ InvalidSnapshot ,
771+ false, true,0 );
772+
753773pfree (query );
754774}
755775
776+ /* Free snapshot */
777+ UnregisterSnapshot (fresh_snapshot );
778+
756779SPI_finish ();
757780
758781/* Drop obsolete partitions */