Re: COPY FROM with RLS

From: jian he <jian(dot)universality(at)gmail(dot)com>
To: PostgreSQL-development <pgsql-hackers(at)postgresql(dot)org>
Subject: Re: COPY FROM with RLS
Date: 2026-05-10 14:23:26
Message-ID: CACJufxFdt0+R6C5ZByAK3DpMEXbb=3Hc0XyRTPvbjpc9sPt=gQ@mail.gmail.com
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

On Tue, Oct 28, 2025 at 8:12 PM jian he <jian(dot)universality(at)gmail(dot)com> wrote:
>
> hi.
>
> While working on other COPY related patches, I wonder
> whether it's doable to implement RLS for COPY FROM.
>
> COPY FROM is more simple that INSERT. we don't need to consider
> INSERT RETURNING and INSERT ON CONFLICT DO UPDATE,
> also no need to worry about MERGE ... INSERT.
> we also don't need to consider SELECT privilege.
> security policy only applies to table and partitioned tables, so don't
> need to worry about
> VIEW INSTEAD OF TRIGGER and foreign tables.
>
> However, there's another complication that makes implementation difficult — a
> policy can contain a subquery.
> I'm not sure how to handle that properly, so error out whenever a policy
> contains a sublink/subquery. (maybe it's doable, seems hard....).
>

Hi. I implemented a hack to make it work with RLS policies that
contain subqueries; I'm not sure how valid it is.

IF (check_enable_rls(RelationGetRelid(cstate->rel), InvalidOid,
false) == RLS_ENABLED)
is true, then we construct a dummy query string:

INSERT INTO "%s"."%s" DEFAULT VALUES

(where %s.%s is replaced by the schema-qualified relation name) and
then run it through the following pipeline:
pg_analyze_and_rewrite_fixedparams()
pg_plan_query()
CreateQueryDesc()
ExecutorStart()

Obviously, ExecutorRun() cannot be used because the data source for COPY FROM is
an external file rather than a normal query execution.

The main hack is to bypass ExecutorRun() completely and only use ExecutorStart()
to initialize the required executor structures (EState, PlanState,
ResultRelInfo, etc.) for ExecWithCheckOptions (which is part of
ExecutorRun normally).

In DoCopy we did converting COPY (REL) TO,to a SelectStmt when REL have RLS.

--
jian
https://www.enterprisedb.com/

Attachment Content-Type Size
v2-0001-COPY-FROM-with-RLS.patch text/x-patch 29.2 KB

In response to

Browse pgsql-hackers by date

  From Date Subject
Next Message SATYANARAYANA NARLAPURAM 2026-05-10 14:38:38 [PATCH] Postpone PROPERTY GRAPH creation in pg_dump to POST-DATA when it depends on a unique constraint
Previous Message ChenhuiMo 2026-05-10 14:12:15 [PATCH] Make NumericVar storage semantics explicit