# Best Practices ## When to Create Versions ✅ **DO:** Let triggers handle versioning automatically ❌ **DON'T:** Manually call versioning functions ❌ **DON'T:** Bypass triggers with direct SQL ## Performance - Run `cleanup_old_versions()` monthly - Keep 50-100 versions per entity - Use indexes for queries - Implement pagination for large version lists ## Security - Never expose `created_by` user IDs to public - Always check RLS policies - Validate rollback permissions server-side - Use session variables for attribution ## Testing Test version creation on: - INSERT (creates version_number: 1) - UPDATE (increments version_number) - Rollback (creates new version with change_type='restored') ## Attribution Always set `app.current_user_id` to original submitter, NOT moderator. ```typescript // ✅ CORRECT await supabase.rpc('set_session_variable', { key: 'app.current_user_id', value: submission.user_id, // Original submitter }); // ❌ WRONG await supabase.rpc('set_session_variable', { key: 'app.current_user_id', value: auth.uid(), // Moderator who approved }); ```