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 OR REPLACE FUNCTION compensation_${opTypeLower}_${namespace}_${tableName}_${childKey}_into_oplog_function()
      RETURNS TRIGGER AS \$\$
      BEGIN
        DECLARE
          flag_value INTEGER;
          meta_value INTEGER;
        BEGIN
          SELECT flag INTO flag_value FROM "$namespace"._electric_trigger_settings WHERE namespace = '$namespace' AND tablename = '$tableName';

          SELECT value INTO meta_value FROM "$namespace"._electric_meta WHERE key = 'compensations';

          IF flag_value = 1 AND meta_value = 1 THEN
            INSERT INTO "$namespace"._electric_oplog (namespace, tablename, optype, "primaryKey", "newRow", "oldRow", timestamp)
            SELECT
              '$fkTableNamespace',
              '$fkTableName',
              'COMPENSATION',
              ${removeSpaceAndNullValuesFromJson(createPKJsonObject(joinedFkPKs))},
              jsonb_build_object($joinedFkPKs),
              NULL,
              NULL
            FROM $fkTable
            WHERE "${foreignKey.parentKey}" = NEW."${foreignKey.childKey}";
          END IF;

          RETURN NEW;
        END;
      END;
      \$\$ LANGUAGE plpgsql;
      ''',
    '''
        CREATE TRIGGER compensation_${opTypeLower}_${namespace}_${tableName}_${childKey}_into_oplog
          AFTER $opType ON $table
            FOR EACH ROW
              EXECUTE FUNCTION compensation_${opTypeLower}_${namespace}_${tableName}_${childKey}_into_oplog_function();
      ''',
  ];
}