* constraint names.)
  *
  * Note: it is theoretically possible to get a collision anyway, if someone
- * else chooses the same name concurrently.  This is fairly unlikely to be
+ * else chooses the same name concurrently.  We shorten the race condition
+ * window by checking for conflicting relations using SnapshotDirty, but
+ * that doesn't close the window entirely.  This is fairly unlikely to be
  * a problem in practice, especially if one is holding an exclusive lock on
  * the relation identified by name1.  However, if choosing multiple names
  * within a single command, you'd better create the new object and do
    int         pass = 0;
    char       *relname = NULL;
    char        modlabel[NAMEDATALEN];
+   SnapshotData SnapshotDirty;
+   Relation    pgclassrel;
+
+   /* prepare to search pg_class with a dirty snapshot */
+   InitDirtySnapshot(SnapshotDirty);
+   pgclassrel = table_open(RelationRelationId, AccessShareLock);
 
    /* try the unmodified label first */
    strlcpy(modlabel, label, sizeof(modlabel));
 
    for (;;)
    {
+       ScanKeyData key[2];
+       SysScanDesc scan;
+       bool        collides;
+
        relname = makeObjectName(name1, name2, modlabel);
 
-       if (!OidIsValid(get_relname_relid(relname, namespaceid)))
+       /* is there any conflicting relation name? */
+       ScanKeyInit(&key[0],
+                   Anum_pg_class_relname,
+                   BTEqualStrategyNumber, F_NAMEEQ,
+                   CStringGetDatum(relname));
+       ScanKeyInit(&key[1],
+                   Anum_pg_class_relnamespace,
+                   BTEqualStrategyNumber, F_OIDEQ,
+                   ObjectIdGetDatum(namespaceid));
+
+       scan = systable_beginscan(pgclassrel, ClassNameNspIndexId,
+                                 true /* indexOK */ ,
+                                 &SnapshotDirty,
+                                 2, key);
+
+       collides = HeapTupleIsValid(systable_getnext(scan));
+
+       systable_endscan(scan);
+
+       /* break out of loop if no conflict */
+       if (!collides)
        {
            if (!isconstraint ||
                !ConstraintNameExists(relname, namespaceid))
        snprintf(modlabel, sizeof(modlabel), "%s%d", label, ++pass);
    }
 
+   table_close(pgclassrel, AccessShareLock);
+
    return relname;
 }