PostgreSQL: DBLink weird permission/connection error
Here is what I think is happening.  I don't think it is a bug.


You have a view.  That view is somewhat complex but it is a dynamically rewritten query.
The planner is pretty smart.  It will ignore UNION clauses where the search criteria will not produce an output result.
You are not executing what you think you are.  (EXPLAIN ANALYSE should show you this)


My recommendations:


Wrap the whole result set in a plpgsql function.  Wrap that function in the view.  OR
Use a WITH clause.  I am less sure about this one.  I think the with clause might result in running the whole thing consistently but not 100% sure, and it is not guaranteed in future versions.  Therefore wrapping in a function is probably better.


I think what the planner is seeing is:

"Oh we don't need to execute the first and third portions of the view because they are not in the output!  Let's skip and only run the second portion!"  This is a feature, not a bug (and it is what allows table partitioning to be useful).