static Oid     get_relid_from_relname(text *relname_text);
 static char *generate_relation_name(Oid relid);
 static char *connstr_strip_password(const char *connstr);
+static void dblink_security_check(PGconn *conn, remoteConn *rcon, const char *connstr);
 
 /* Global */
 List      *res_id = NIL;
                        else \
                        { \
                                connstr = conname_or_str; \
+                               dblink_security_check(conn, rcon, connstr); \
                                conn = PQconnectdb(connstr); \
                                if (PQstatus(conn) == CONNECTION_BAD) \
                                { \
        if (connname)
                rcon = (remoteConn *) palloc(sizeof(remoteConn));
 
-       /* for non-superusers, check that server requires a password */
-       if (!superuser())
-       {
-               /* this attempt must fail */
-               conn = PQconnectdb(connstr_strip_password(connstr));
-
-               if (PQstatus(conn) == CONNECTION_OK)
-               {
-                       PQfinish(conn);
-                       if (rcon)
-                               pfree(rcon);
-
-                       ereport(ERROR,
-                                       (errcode(ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED),
-                                        errmsg("password is required"),
-                                        errdetail("Non-superuser cannot connect if the server does not request a password."),
-                                        errhint("Target server's authentication method must be changed.")));
-               }
-               else
-                       PQfinish(conn);
-       }
+       /* check password used if not superuser */
+       dblink_security_check(conn, rcon, connstr);
        conn = PQconnectdb(connstr);
 
        MemoryContextSwitchTo(oldcontext);
 
        return result.data;
 }
+
+static void
+dblink_security_check(PGconn *conn, remoteConn *rcon, const char *connstr)
+{
+       if (!superuser())
+       {
+               /* this attempt must fail */
+               conn = PQconnectdb(connstr_strip_password(connstr));
+
+               if (PQstatus(conn) == CONNECTION_OK)
+               {
+                       PQfinish(conn);
+                       if (rcon)
+                               pfree(rcon);
+
+                       ereport(ERROR,
+                                       (errcode(ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED),
+                                        errmsg("password is required"),
+                                        errdetail("Non-superuser cannot connect if the server does not request a password."),
+                                        errhint("Target server's authentication method must be changed.")));
+               }
+               else
+                       PQfinish(conn);
+       }
+}