Database Functions and Triggers
This page documents the key database functions and triggers defined insql/modules/core_cmms/04_functions_triggers.sql.
Permission Functions
me_has_permission
Checks if the current authenticated user has a specific permission.sql/modules/core_cmms/04_functions_triggers.sql
Role and Permission Management
set_role_permissions
Sets all permissions for a role (replaces existing permissions).p_role_id: Role ID to updatep_permission_ids: Array of permission UUIDs to assign
sql/modules/core_cmms/04_functions_triggers.sql
sync_permissions_from_registry
Synchronizes permissions table with the frontend permission registry.p_permissions: JSONB array of permission definitions from frontend
sql/modules/core_cmms/04_functions_triggers.sql
User Management Functions
update_user_password
Admin function to reset a user’s password.p_user_id: UUID of user to updatep_new_password: New plaintext password (will be hashed)
SECURITY DEFINER - runs with elevated privileges. Access controlled by RLS.
Source: sql/modules/core_cmms/04_functions_triggers.sql
Ticket Functions
handle_ticket_updated
Trigger function that updates theupdated_at timestamp on ticket changes.
sql/modules/core_cmms/04_functions_triggers.sql
Notification Functions
create_notification_event
Creates a notification event that triggers notification deliveries.p_category: Notification category (assignments, comments, status_changes, etc.)p_actor_user_id: User who triggered the notificationp_title: Notification titlep_body: Notification body textp_data: Additional JSON datap_recipient_user_ids: Array of recipient user UUIDsp_channel_mask: Delivery channels (1=in-app, 2=push, 3=both)
sql/modules/core_cmms/16_notifications.sql
For more notification functions, see Notifications Database Schema.
View Definitions
v_tickets_compat
Compatibility view for reporting, joins tickets with location and assignee data.sql/modules/core_cmms/06_views.sql
Trigger Summary
| Trigger | Table | Event | Function | Purpose |
|---|---|---|---|---|
| ticket_updated_trigger | tickets | BEFORE UPDATE | handle_ticket_updated | Update timestamp |
| user_updated_trigger | users | BEFORE UPDATE | handle_user_updated | Update timestamp |
| assignee_updated_trigger | assignees | BEFORE UPDATE | handle_assignee_updated | Update timestamp |
| notification_event_trigger | notification_events | AFTER INSERT | handle_notification_event | Create deliveries and outbox entries |
Function Security
Best Practices
Use RPC Wrappers
Always call functions through Supabase RPC API, never construct raw SQL
Check Permissions
Verify user permissions before calling admin functions
Handle Errors
Functions may raise exceptions - implement proper error handling
Test Thoroughly
Test functions with different user roles and edge cases
Next Steps
Core Tables
Review the database schema
RLS Policies
Understand row-level security
RBAC System
Learn about the permission system