Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore(RLS): Improve policy comparison #6064

Draft
wants to merge 3 commits into
base: master
Choose a base branch
from
Draft

Conversation

jfagoagas
Copy link
Member

@jfagoagas jfagoagas commented Dec 9, 2024

Motivation

When an RLS policy is applied to a query, the conditions specified in the policy are evaluated for each row that the query touches. In queries affecting thousands of rows, this behavior can drastically reduce query performance, as the overhead of executing these functions adds up quickly. -- https://supabase.com/docs/guides/database/database-advisors?queryGroups=lint&lint=0003_auth_rls_initplan#the-performance-issue

Description

Improve Postgres Row Level Security policies:

  • Remove the CASE since it is not needed, a comparison with null returns false, so calling current_setting('setting', True) is more than enough.
  • Wrap current_setting in a subquery to be executed in an InitPlan which will be executed just once and then the result will be cached for the rest of the rows.

TODO

  • Pending to create migrations to replace these policies.

Checklist

License

By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license.

@jfagoagas jfagoagas force-pushed the improve-rls-policies branch from d3a5485 to a2e5801 Compare December 12, 2024 13:28
Copy link
Member

@vicferpoy vicferpoy left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the improvement! However, we are missing changes on migrations. This change will only exist for users who don't have the initial migration applied.

@@ -82,6 +78,10 @@ def create_sql(self, model: Any, schema_editor: Any) -> Any:
policy_queries = ""
grant_queries = ""
for statement in self.statements:
# SELECT and DELETE uses USING since applies to rows selected
# INSERT uses WITH CHECK becauseonly applies in cases where records are being added
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
# INSERT uses WITH CHECK becauseonly applies in cases where records are being added
# INSERT uses WITH CHECK because only applies in cases where records are being added

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants