-- Policy to allow users to view their own note_access entries
CREATEPOLICY"Users can view their own note access"ONnote_access
FORSELECT
TOauthenticated
USING(user_id=(SELECTauth.uid()));
-- Policy to allow users to view notes shared with their tablos
CREATEPOLICY"Users can view notes shared with their tablos"ONnote_access
FORSELECT
TOauthenticated
USING(
is_active=TRUE
AND(
-- Shared with all tablos (tablo_id is NULL)
tablo_idISNULL
-- Or shared with a specific tablo where the user has access
OREXISTS(
SELECT1FROMtablo_access
WHEREtablo_access.tablo_id=note_access.tablo_id
ANDtablo_access.user_id=(SELECTauth.uid())
ANDtablo_access.is_active=TRUE
)
)
);
-- Policy to allow users to insert their own note_access entries
CREATEPOLICY"Users can insert their own note access"ONnote_access
FORINSERT
TOauthenticated
WITHCHECK(user_id=(SELECTauth.uid()));
-- Policy to allow users to update their own note_access entries
CREATEPOLICY"Users can update their own note access"ONnote_access
FORUPDATE
TOauthenticated
USING(user_id=(SELECTauth.uid()))
WITHCHECK(user_id=(SELECTauth.uid()));
-- Policy to allow users to delete their own note_access entries
CREATEPOLICY"Users can delete their own note access"ONnote_access
FORDELETE
TOauthenticated
USING(user_id=(SELECTauth.uid()));
-- Add comments to document the tables
COMMENTONTABLEshared_notesIS
'Tracks which notes are shared publicly with Row Level Security';
COMMENTONCOLUMNshared_notes.note_idIS
'Foreign key reference to notes.id';
COMMENTONCOLUMNshared_notes.user_idIS
'Foreign key reference to auth.users.id - owner of the note';
COMMENTONCOLUMNshared_notes.is_publicIS
'When TRUE, the note is publicly accessible via /notes/public/:noteId';
COMMENTONTABLEnote_accessIS
'Tracks which notes are shared with tablos. When tablo_id IS NULL and is_active = TRUE, the note is shared with all user tablos. Uses partial unique indexes to handle NULL values correctly.';
COMMENTONCOLUMNnote_access.tablo_idIS
'Foreign key reference to tablos.id - NULL means shared with all user tablos. Partial unique indexes ensure only one NULL per (note_id, user_id) combination.';