Skip to content

Commit 1501c24

Browse files
update when and operations
1 parent 1a193ba commit 1501c24

File tree

2 files changed

+21
-36
lines changed

2 files changed

+21
-36
lines changed

packages/common/src/client/triggers/TriggerManager.ts

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -129,11 +129,6 @@ interface BaseCreateDiffTriggerOptions {
129129
*/
130130
source: string;
131131

132-
/**
133-
* Operations to track changes for.
134-
*/
135-
operations: DiffTriggerOperation[];
136-
137132
/**
138133
* Columns to track and report changes for.
139134
* Defaults to all columns in the source table.
@@ -142,7 +137,7 @@ interface BaseCreateDiffTriggerOptions {
142137
columns?: string[];
143138

144139
/**
145-
* Optional condition to filter when the triggers should fire.
140+
* Condition to filter when the triggers should fire.
146141
* This corresponds to a SQLite [WHEN](https://sqlite.org/lang_createtrigger.html) clause in the trigger body.
147142
* This is useful for only triggering on specific conditions.
148143
* For example, you can use it to only trigger on certain values in the NEW row.
@@ -155,12 +150,13 @@ interface BaseCreateDiffTriggerOptions {
155150
*
156151
* @example
157152
* {
158-
* 'INSERT': sanitizeSQL`json_extract(NEW.data, '$.list_id') = ${sanitizeUUID(list.id)}`
159-
* 'UPDATE': sanitizeSQL`NEW.id = 'abcd' AND json_extract(NEW.data, '$.status') = 'active'`
153+
* 'INSERT': sanitizeSQL`json_extract(NEW.data, '$.list_id') = ${sanitizeUUID(list.id)}`,
154+
* 'INSERT': `TRUE`,
155+
* 'UPDATE': sanitizeSQL`NEW.id = 'abcd' AND json_extract(NEW.data, '$.status') = 'active'`,
160156
* 'DELETE': sanitizeSQL`json_extract(OLD.data, '$.list_id') = 'abcd'`
161157
* }
162158
*/
163-
when?: Partial<Record<DiffTriggerOperation, string>>;
159+
when: Partial<Record<DiffTriggerOperation, string>>;
164160

165161
/**
166162
* Hooks which allow execution during the trigger creation process.
@@ -319,7 +315,11 @@ export interface TriggerManager {
319315
* source: 'lists',
320316
* destination: 'ps_temp_lists_diff',
321317
* columns: ['name'],
322-
* operations: [DiffTriggerOperation.INSERT, DiffTriggerOperation.UPDATE, DiffTriggerOperation.DELETE]
318+
* when: {
319+
* [DiffTriggerOperation.INSERT]: 'TRUE',
320+
* [DiffTriggerOperation.UPDATE]: 'TRUE',
321+
* [DiffTriggerOperation.DELETE]: 'TRUE'
322+
* }
323323
* });
324324
* ```
325325
*/
@@ -340,7 +340,6 @@ export interface TriggerManager {
340340
* const dispose = database.triggers.trackTableDiff({
341341
* source: 'todos',
342342
* columns: ['list_id'],
343-
* operations: [DiffTriggerOperation.INSERT],
344343
* when: {
345344
* [DiffTriggerOperation.INSERT]: sanitizeSQL`json_extract(NEW.data, '$.list_id') = ${sanitizeUUID(someIdVariable)}`
346345
* },

packages/common/src/client/triggers/TriggerManagerImpl.ts

Lines changed: 11 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -49,12 +49,16 @@ export class TriggerManagerImpl implements TriggerManager {
4949

5050
async createDiffTrigger(options: CreateDiffTriggerOptions) {
5151
await this.db.waitForReady();
52-
const { source, destination, columns, operations, when, hooks } = options;
53-
52+
const { source, destination, columns, when, hooks } = options;
53+
const operations = Object.keys(when) as DiffTriggerOperation[];
5454
if (operations.length == 0) {
55-
throw new Error('At least one operation must be specified for the trigger.');
55+
throw new Error('At least one WHEN operation must be specified for the trigger.');
5656
}
5757

58+
const whenClauses = Object.fromEntries(
59+
Object.entries(when).map(([operation, filter]) => [operation, `WHEN ${filter}`])
60+
);
61+
5862
/**
5963
* Allow specifying the View name as the source.
6064
* We can lookup the internal table name from the schema.
@@ -67,23 +71,6 @@ export class TriggerManagerImpl implements TriggerManager {
6771
const replicatedColumns = columns ?? sourceDefinition.columns.map((col) => col.name);
6872

6973
const internalSource = sourceDefinition.internalName;
70-
71-
const invalidWhenOperations =
72-
when && Object.keys(when).filter((operation) => operations.includes(operation as DiffTriggerOperation) == false);
73-
if (invalidWhenOperations?.length) {
74-
throw new Error(
75-
`Invalid 'when' conditions provided for operations: ${invalidWhenOperations.join(', ')}. ` +
76-
`These operations are not included in the 'operations' array: ${operations.join(', ')}.`
77-
);
78-
}
79-
80-
const whenConditions = Object.fromEntries(
81-
Object.values(DiffTriggerOperation).map((operation) => [
82-
operation,
83-
when?.[operation] ? `WHEN ${when[operation]}` : ''
84-
])
85-
) as Record<DiffTriggerOperation, string>;
86-
8774
const triggerIds: string[] = [];
8875

8976
const id = await this.getUUID();
@@ -143,7 +130,7 @@ export class TriggerManagerImpl implements TriggerManager {
143130
triggerIds.push(insertTriggerId);
144131

145132
await tx.execute(/* sql */ `
146-
CREATE TEMP TRIGGER ${insertTriggerId} AFTER INSERT ON ${internalSource} ${whenConditions[
133+
CREATE TEMP TRIGGER ${insertTriggerId} AFTER INSERT ON ${internalSource} ${whenClauses[
147134
DiffTriggerOperation.INSERT
148135
]} BEGIN
149136
INSERT INTO
@@ -166,7 +153,7 @@ export class TriggerManagerImpl implements TriggerManager {
166153

167154
await tx.execute(/* sql */ `
168155
CREATE TEMP TRIGGER ${updateTriggerId} AFTER
169-
UPDATE ON ${internalSource} ${whenConditions[DiffTriggerOperation.UPDATE]} BEGIN
156+
UPDATE ON ${internalSource} ${whenClauses[DiffTriggerOperation.UPDATE]} BEGIN
170157
INSERT INTO
171158
${destination} (id, operation, timestamp, value, previous_value)
172159
VALUES
@@ -188,7 +175,7 @@ export class TriggerManagerImpl implements TriggerManager {
188175

189176
// Create delete trigger for basic JSON
190177
await tx.execute(/* sql */ `
191-
CREATE TEMP TRIGGER ${deleteTriggerId} AFTER DELETE ON ${internalSource} ${whenConditions[
178+
CREATE TEMP TRIGGER ${deleteTriggerId} AFTER DELETE ON ${internalSource} ${whenClauses[
192179
DiffTriggerOperation.DELETE
193180
]} BEGIN
194181
INSERT INTO
@@ -220,7 +207,7 @@ export class TriggerManagerImpl implements TriggerManager {
220207
}
221208

222209
async trackTableDiff(options: TrackDiffOptions): Promise<TriggerRemoveCallback> {
223-
const { source, when, columns, operations, hooks, throttleMs = DEFAULT_WATCH_THROTTLE_MS } = options;
210+
const { source, when, columns, hooks, throttleMs = DEFAULT_WATCH_THROTTLE_MS } = options;
224211

225212
await this.db.waitForReady();
226213

@@ -307,7 +294,6 @@ export class TriggerManagerImpl implements TriggerManager {
307294
source,
308295
destination,
309296
columns: contextColumns,
310-
operations,
311297
when,
312298
hooks
313299
});

0 commit comments

Comments
 (0)