createFkCompensationTrigger method

  1. @override
List<String> createFkCompensationTrigger(
  1. String opType,
  2. QualifiedTablename table,
  3. String childKey,
  4. QualifiedTablename fkTable,
  5. String joinedFkPKs,
  6. ForeignKey foreignKey,
)
override

Creates a trigger that logs compensations for operations into the oplog.

Implementation

@override
List<String> createFkCompensationTrigger(
  String opType,
  QualifiedTablename table,
  String childKey,
  QualifiedTablename fkTable,
  String joinedFkPKs,
  ForeignKey foreignKey,
) {
  final namespace = table.namespace;
  final tableName = table.tablename;
  final fkTableNamespace = fkTable.namespace;
  final fkTableName = fkTable.tablename;

  final opTypeLower = opType.toLowerCase();
  return [
    '''
      CREATE TRIGGER compensation_${opTypeLower}_${namespace}_${tableName}_${childKey}_into_oplog
        AFTER $opType ON $table
        WHEN 1 = (SELECT flag from _electric_trigger_settings WHERE namespace = '$namespace' AND tablename = '$tableName') AND
             1 = (SELECT value from _electric_meta WHERE key = 'compensations')
      BEGIN
        INSERT INTO _electric_oplog (namespace, tablename, optype, primaryKey, newRow, oldRow, timestamp)
        SELECT '$fkTableNamespace', '$fkTableName', 'COMPENSATION', ${createPKJsonObject(joinedFkPKs)}, json_object($joinedFkPKs), NULL, NULL
        FROM $fkTable WHERE "${foreignKey.parentKey}" = new."${foreignKey.childKey}";
      END;
    ''',
  ];
}