title: PostgreSQL query not using INDEX when RLS (Row Level Security) is enabled
body: <p>I am using <strong>PostgreSQL 10.1</strong>, going right to the point...</p>
  
  <p>Lets say I have a <strong>TABLE</strong>:</p>
  
  <pre><code>CREATE TABLE public.document (
      id uuid PRIMARY KEY,
  
      title   text,
      content text NOT NULL
  );
  </code></pre>
  
  <p>Together with a <strong>GIN INDEX</strong> on it:</p>
  
  <pre><code>CREATE INDEX document_idx ON public.document USING GIN(
      to_tsvector(
          'english',
          content || ' ' || COALESCE(title, '')
      )
  );
  </code></pre>
  
  <p>And a basic fulltext search query:</p>
  
  <pre><code>SELECT * FROM public.document WHERE (
      to_tsvector(
          'english',
          content || ' ' || COALESCE(title, '')
      ) @@ plainto_tsquery('english', fulltext_search_documents.search_text)
  )
  </code></pre>
  
  <p>Regardless of the <strong>public.document</strong> table size, the query is (you already know it) hella fast! The planner uses the INDEX and everything works out great.</p>
  
  <p>Now I introduce some basic access control through <strong>RLS (Row Level Security)</strong>, firstly I enable it:</p>
  
  <pre><code>ALTER TABLE public.document ENABLE ROW LEVEL SECURITY;
  </code></pre>
  
  <p>and then I add the policy:</p>
  
  <pre><code>CREATE POLICY document_policy ON public.document FOR SELECT
      USING (EXISTS (
          SELECT 1 FROM public.user WHERE (is_current_user) AND ('r' = ANY(privileges))
      ));
  </code></pre>
  
  <p>To keep things simple the <strong>is_current_user</strong> is another query which checks exactly that.</p>
  
  <p>Now the <strong>fulltext search query</strong> is flattened with <strong>document_policy query</strong> and by doing so the planner executes a <strong>Seq Scan</strong> instead of <strong>Index Scan</strong> resulting in a 300x slower query!</p>
  
  <p>I think the question is pretty obvious, how can I fix this so that the fulltext search query stays fast?</p>
  
  <p>Thanks in advance!</p>