|
| 1 | +import { DBAdapter, LockContext } from '../../db/DBAdapter.js'; |
| 2 | +import { CreateDiffTriggerOptions, DiffTriggerOperation, TriggerManager } from './TriggerManager.js'; |
| 3 | + |
| 4 | +export type TriggerManagerImplOptions = { |
| 5 | + db: DBAdapter; |
| 6 | +}; |
| 7 | + |
| 8 | +export class TriggerManagerImpl implements TriggerManager { |
| 9 | + constructor(protected options: TriggerManagerImplOptions) {} |
| 10 | + |
| 11 | + protected get db() { |
| 12 | + return this.options.db; |
| 13 | + } |
| 14 | + |
| 15 | + protected async removeTriggers(tx: LockContext, triggerIds: string[]) { |
| 16 | + for (const triggerId of triggerIds) { |
| 17 | + await tx.execute(/* sql */ `DROP TRIGGER IF EXISTS ${triggerId}; `); |
| 18 | + } |
| 19 | + } |
| 20 | + |
| 21 | + async createDiffTrigger(options: CreateDiffTriggerOptions) { |
| 22 | + const { source, destination, columns, operations, when } = options; |
| 23 | + |
| 24 | + if (operations.length == 0) { |
| 25 | + throw new Error('At least one operation must be specified for the trigger.'); |
| 26 | + } |
| 27 | + |
| 28 | + if (columns && columns.length == 0) { |
| 29 | + throw new Error('At least one column must be specified for the trigger.'); |
| 30 | + } |
| 31 | + |
| 32 | + const whenCondition = when ? `WHEN ${when}` : ''; |
| 33 | + |
| 34 | + const { id: uuid } = await this.db.get<{ id: string }>(/* sql */ ` |
| 35 | + SELECT |
| 36 | + uuid () as id |
| 37 | + `); |
| 38 | + |
| 39 | + const id = uuid.replace(/-/g, '_'); // Replace dashes with underscores for SQLite compatibility |
| 40 | + |
| 41 | + const triggerIds: string[] = []; |
| 42 | + |
| 43 | + const jsonFragment = (source: 'NEW' | 'OLD' = 'NEW') => |
| 44 | + columns |
| 45 | + ? `json_object(${columns.map((col) => `'${col}', json_extract(${source}.data, '$.${col}')`).join(', ')})` |
| 46 | + : `${source}.data`; |
| 47 | + |
| 48 | + /** |
| 49 | + * Declare the cleanup function early since if any of the init steps fail, |
| 50 | + * we need to ensure we can cleanup the created resources. |
| 51 | + * We unfortunately cannot rely on transaction rollback. |
| 52 | + */ |
| 53 | + const cleanup = async () => |
| 54 | + this.db.writeLock(async (tx) => { |
| 55 | + await this.removeTriggers(tx, triggerIds); |
| 56 | + await tx.execute(/* sql */ `DROP TABLE IF EXISTS ${destination};`); |
| 57 | + }); |
| 58 | + |
| 59 | + try { |
| 60 | + await this.db.writeLock(async (tx) => { |
| 61 | + await tx.execute(/* sql */ `CREATE TEMP TABLE ${destination} (id TEXT, operation TEXT, change TEXT);`); |
| 62 | + |
| 63 | + if (operations.includes(DiffTriggerOperation.INSERT)) { |
| 64 | + const insertTriggerId = `ps_temp_trigger_insert_${id}`; |
| 65 | + triggerIds.push(insertTriggerId); |
| 66 | + |
| 67 | + await tx.execute(/* sql */ ` |
| 68 | + CREATE TEMP TRIGGER ${insertTriggerId} AFTER INSERT ON ${source} ${whenCondition} BEGIN |
| 69 | + INSERT INTO |
| 70 | + ${destination} (id, operation, change) |
| 71 | + VALUES |
| 72 | + ( |
| 73 | + NEW.id, |
| 74 | + 'INSERT', |
| 75 | + ${jsonFragment('NEW')} |
| 76 | + ); |
| 77 | +
|
| 78 | + END; |
| 79 | + `); |
| 80 | + } |
| 81 | + |
| 82 | + if (operations.includes(DiffTriggerOperation.UPDATE)) { |
| 83 | + const updateTriggerId = `ps_temp_trigger_update_${id}`; |
| 84 | + triggerIds.push(updateTriggerId); |
| 85 | + |
| 86 | + await tx.execute(/* sql */ ` |
| 87 | + CREATE TEMP TRIGGER ${updateTriggerId} AFTER |
| 88 | + UPDATE ON ${source} ${whenCondition} BEGIN |
| 89 | + INSERT INTO |
| 90 | + ${destination} (id, operation, change) |
| 91 | + VALUES |
| 92 | + ( |
| 93 | + NEW.id, |
| 94 | + 'UPDATE', |
| 95 | + --- Reports both the new and old values in JSON format |
| 96 | + json_object ( |
| 97 | + 'new', |
| 98 | + ${jsonFragment('NEW')}, |
| 99 | + 'old', |
| 100 | + ${jsonFragment('OLD')} |
| 101 | + ) |
| 102 | + ); |
| 103 | +
|
| 104 | + END; |
| 105 | + `); |
| 106 | + } |
| 107 | + |
| 108 | + if (operations.includes(DiffTriggerOperation.DELETE)) { |
| 109 | + const deleteTriggerId = `ps_temp_trigger_delete_${id}`; |
| 110 | + triggerIds.push(deleteTriggerId); |
| 111 | + |
| 112 | + // Create delete trigger for basic JSON |
| 113 | + await tx.execute(/* sql */ ` |
| 114 | + CREATE TEMP TRIGGER ${deleteTriggerId} AFTER DELETE ON ${source} ${whenCondition} BEGIN |
| 115 | + INSERT INTO |
| 116 | + ${destination} (id, operation) |
| 117 | + VALUES |
| 118 | + (NEW.id, 'DELETE'); |
| 119 | +
|
| 120 | + END; |
| 121 | + `); |
| 122 | + } |
| 123 | + }); |
| 124 | + } catch (error) { |
| 125 | + await cleanup(); |
| 126 | + throw error; |
| 127 | + } |
| 128 | + |
| 129 | + return cleanup; |
| 130 | + } |
| 131 | +} |
0 commit comments