EventTriggerList.utils.ts43 lines · main
| 1 | import { |
| 2 | ident, |
| 3 | joinSqlFragments, |
| 4 | keyword, |
| 5 | literal, |
| 6 | safeSql, |
| 7 | type SafeSqlFragment, |
| 8 | } from '@supabase/pg-meta' |
| 9 | |
| 10 | import type { DatabaseEventTrigger } from '@/data/database-event-triggers/database-event-triggers-query' |
| 11 | |
| 12 | export type EventTrigger = Omit<DatabaseEventTrigger, 'function_definition'> & { |
| 13 | function_definition: SafeSqlFragment | null |
| 14 | } |
| 15 | |
| 16 | export const generateEventTriggerCreateSQL = (trigger: EventTrigger): SafeSqlFragment => { |
| 17 | const parts: SafeSqlFragment[] = [] |
| 18 | |
| 19 | if (trigger.function_definition) { |
| 20 | const hasTrailingSemicolon = /;\s*$/.test(trigger.function_definition) |
| 21 | parts.push( |
| 22 | hasTrailingSemicolon ? trigger.function_definition : safeSql`${trigger.function_definition};` |
| 23 | ) |
| 24 | } |
| 25 | |
| 26 | if (trigger.event && trigger.function_schema && trigger.function_name) { |
| 27 | parts.push(safeSql`DROP EVENT TRIGGER IF EXISTS ${ident(trigger.name)};`) |
| 28 | |
| 29 | const tagClause = |
| 30 | trigger.tags && trigger.tags.length > 0 |
| 31 | ? safeSql`\nWHEN TAG IN (${joinSqlFragments( |
| 32 | trigger.tags.map((tag) => literal(tag)), |
| 33 | ', ' |
| 34 | )})` |
| 35 | : safeSql`` |
| 36 | |
| 37 | parts.push(safeSql`CREATE EVENT TRIGGER ${ident(trigger.name)} |
| 38 | ON ${keyword(trigger.event)}${tagClause} |
| 39 | EXECUTE FUNCTION ${ident(trigger.function_schema)}.${ident(trigger.function_name)}();`) |
| 40 | } |
| 41 | |
| 42 | return parts.length > 0 ? joinSqlFragments(parts, '\n\n') : safeSql`` |
| 43 | } |