createOplogTrigger method

  1. @override
List<String> createOplogTrigger(
  1. SqlOpType opType,
  2. QualifiedTablename table,
  3. String newPKs,
  4. String newRows,
  5. String oldRows,
)
override

Create a trigger that logs operations into the oplog.

Implementation

@override
List<String> createOplogTrigger(
  SqlOpType opType,
  QualifiedTablename table,
  String newPKs,
  String newRows,
  String oldRows,
) {
  final namespace = table.namespace;
  final tableName = table.tablename;

  final opTypeLower = opType.name.toLowerCase();
  final pk = createPKJsonObject(newPKs);
  // Update has both the old and the new row
  // Delete only has the old row
  final newRecord =
      opType == SqlOpType.delete ? 'NULL' : createJsonObject(newRows);
  // Insert only has the new row
  final oldRecord =
      opType == SqlOpType.insert ? 'NULL' : createJsonObject(oldRows);

  return [
    '''
CREATE TRIGGER ${opTypeLower}_${namespace}_${tableName}_into_oplog
AFTER ${opType.text} ON $table
WHEN 1 = (SELECT flag from _electric_trigger_settings WHERE namespace = '$namespace' AND tablename = '$tableName')
BEGIN
INSERT INTO _electric_oplog (namespace, tablename, optype, primaryKey, newRow, oldRow, timestamp)
VALUES ('$namespace', '$tableName', '${opType.text}', $pk, $newRecord, $oldRecord, NULL);
END;''',
  ];
}