# File lib/rubyrep/replication_extenders/postgresql_replication.rb, line 39
      def create_or_replace_replication_trigger_function(params)
        # first check, if PL/SQL is already activated and if not, do so.
        if select_all("select lanname from pg_language where lanname = 'plpgsql'").empty?
          execute "CREATE LANGUAGE plpgsql"
        end

        activity_check = ""
        if params[:exclude_rr_activity] then
          activity_check = "PERFORM ACTIVE FROM \#{schema_prefix}\#{params[:activity_table]};\nIF FOUND THEN\nRETURN NULL;\nEND IF;\n"
        end

        version_string = select_value("select version();")
        version = version_string.gsub(/^\s*postgresql\s*([0-9.]+).*$/i, '\1')
        if version >= '8.4'
          modification_check = "IF NEW IS NOT DISTINCT FROM OLD THEN\nRETURN NULL;\nEND IF;\n"
        else
          modification_check = ""
        end

        # now create the trigger
        execute("CREATE OR REPLACE FUNCTION \"\#{params[:trigger_name]}\"() RETURNS TRIGGER AS $change_trigger$\nBEGIN\n\#{activity_check}\nIF (TG_OP = 'DELETE') THEN\nINSERT INTO \#{schema_prefix}\#{params[:log_table]}(change_table, change_key, change_type, change_time)\nSELECT '\#{params[:table]}', \#{key_clause('OLD', params)}, 'D', now();\nELSIF (TG_OP = 'UPDATE') THEN\n\#{modification_check}\nINSERT INTO  \#{schema_prefix}\#{params[:log_table]}(change_table, change_key, change_new_key, change_type, change_time)\nSELECT '\#{params[:table]}', \#{key_clause('OLD', params)}, \#{key_clause('NEW', params)}, 'U', now();\nELSIF (TG_OP = 'INSERT') THEN\nINSERT INTO  \#{schema_prefix}\#{params[:log_table]}(change_table, change_key, change_type, change_time)\nSELECT '\#{params[:table]}', \#{key_clause('NEW', params)}, 'I', now();\nEND IF;\nRETURN NULL; -- result is ignored since this is an AFTER trigger\nEND;\n$change_trigger$ LANGUAGE plpgsql;\n")

      end