createNoFkUpdateTrigger method

  1. @override
List<String> createNoFkUpdateTrigger(
  1. QualifiedTablename table,
  2. List<String> pk
)
override

Create a trigger that prevents updates to the primary key.

Implementation

@override
List<String> createNoFkUpdateTrigger(
  QualifiedTablename table,
  List<String> pk,
) {
  final namespace = table.namespace;
  final tablename = table.tablename;

  return [
    '''
      CREATE OR REPLACE FUNCTION update_ensure_${namespace}_${tablename}_primarykey_function()
      RETURNS TRIGGER AS \$\$
      BEGIN
        ${pk.map(
          (col) => '''
IF OLD."$col" IS DISTINCT FROM NEW."$col" THEN
          RAISE EXCEPTION 'Cannot change the value of column $col as it belongs to the primary key';
        END IF;''',
        ).join('\n')}
        RETURN NEW;
      END;
      \$\$ LANGUAGE plpgsql;
    ''',
    '''
      CREATE TRIGGER update_ensure_${namespace}_${tablename}_primarykey
        BEFORE UPDATE ON $table
          FOR EACH ROW
            EXECUTE FUNCTION update_ensure_${namespace}_${tablename}_primarykey_function();
    ''',
  ];
}