@@ -646,6 +646,8 @@ choose_range_partition_name(Oid parent_relid, Oid parent_nsp)
646646Oid save_userid ;
647647int save_sec_context ;
648648bool need_priv_escalation = !superuser ();/* we might be a SU */
649+ char * relname ;
650+ int attempts_cnt = 1000 ;
649651
650652part_seq_relid = get_relname_relid (build_sequence_name_internal (parent_relid ),
651653parent_nsp );
@@ -661,16 +663,34 @@ choose_range_partition_name(Oid parent_relid, Oid parent_nsp)
661663save_sec_context |SECURITY_LOCAL_USERID_CHANGE );
662664}
663665
664- /* Get next integer for partition name */
665- part_num = DirectFunctionCall1 (nextval_oid ,ObjectIdGetDatum (part_seq_relid ));
666+ /* Generate unique name */
667+ while (true)
668+ {
669+ /* Get next integer for partition name */
670+ part_num = DirectFunctionCall1 (nextval_oid ,ObjectIdGetDatum (part_seq_relid ));
671+
672+ relname = psprintf ("%s_" UINT64_FORMAT ,
673+ get_rel_name (parent_relid ),
674+ (uint64 )DatumGetInt64 (part_num ));/* can't use UInt64 on 9.5 */
675+
676+ /*
677+ * If we found a unique name or attemps number exceeds some reasonable
678+ * value then we quit
679+ *
680+ * XXX Should we throw an exception if max attempts number is reached?
681+ */
682+ if (get_relname_relid (relname ,parent_nsp )== InvalidOid || attempts_cnt < 0 )
683+ break ;
684+
685+ pfree (relname );
686+ attempts_cnt -- ;
687+ }
666688
667689/* Restore user's privileges */
668690if (need_priv_escalation )
669691SetUserIdAndSecContext (save_userid ,save_sec_context );
670692
671- return psprintf ("%s_" UINT64_FORMAT ,
672- get_rel_name (parent_relid ),
673- (uint64 )DatumGetInt64 (part_num ));/* can't use UInt64 on 9.5 */
693+ return relname ;
674694}
675695
676696/* Choose a good name for a HASH partition */