0

I'm working on a project where I need to calculate the final cost (gasto) for each expense by applying various taxes. I also need to implement Row-Level Security (RLS) to restrict data access based on the user ID.

Context:

  • I have a table called gastos that stores individual expenses.
  • I have another table called taxesValues that stores different types of taxes.
  • A third table, gastosAppliedTaxes, establishes a many-to-many relationship between gastos and taxesValues, indicating which taxes are applied to each expense.
  • I initially used a view called final_gastos to calculate the final cost (gasto) for each expense after applying the taxes. The view essentially joins gastos, taxesValues, and gastosAppliedTaxes to perform this calculation.

Why Materialized View?

I opted for a materialized view for two main reasons:

  1. Performance: Materialized views store the result of the query, making data retrieval faster, especially when dealing with complex joins and calculations.

  2. Row-Level Security (RLS): Unlike regular views, materialized views in PostgreSQL allow for the application of RLS policies. This is crucial for my application as I need to restrict data based on the user ID.

Questions:

  1. Materialized Views for RLS:
    Given the above, I switched from using a view to a materialized view called final_gastos so that I can apply RLS. Is this a good approach? Are there any downsides or better alternatives?

  2. Supabase UI Limitations:
    I noticed that the Supabase UI doesn't show policies for materialized views and lacks a UI for setting policies like it does for normal tables. Is this a limitation of Supabase, or am I missing something?

2 Answers 2

2

RLS policies are set on tables and not views. When you have a view, the RLS of underlying tables are respected if the view is a security invoker. I believe in Postgres, materialized views do not support RLS at the moment.

You can create a security invoker view like this:

CREATE VIEW .. WITH (security_invoker=on)
Sign up to request clarification or add additional context in comments.

Comments

-2

RLS

BEGIN;
CREATE POLICY "all" ON "public"."table_a" USING ( user_id= auth.uid() );
COMMIT; 

Materialized Views

  • hypothesis that: m_view_1 has column user_id of table_a with foreign key

Mix view (repeat join table_a)

create or replace view
  view_1 with(security_invoker= true) as
select m_view_1.* from m_view_1 join table_a on m_view_1.user_id= table_a.user_id;

Conclusion

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.