title: Passing user id to PostgreSQL triggers
body: <p>I'm using PostgreSQL 9.1. My database is structured so that there is actual tables that my application uses. For every table there is history table that stores only change history. History tables contain same fields that actual tables plus fields form some extra information eg. edit time. History tables are only handled by triggers.</p>
  
  <p>I have 2 kind of triggers:</p>
  
  <ol>
  <li><code>Before INSERT</code> trigger to add some extra information to tables when they are created (eg. create_time).</li>
  <li><code>Before UPDATE</code> trigger and <code>before DELETE</code> triggers to copy old values from actual table to history table.</li>
  </ol>
  
  <p>Problem is that I'd like to use triggers to store also the id of user who made those changes. And by id I mean id from php application, not PostgreSQL user id.</p>
  
  <p>Is there any reasonable way to do that?</p>
  
  <p>With INSERT and UPDATE it could be possible to just add extra field for id to actual tables and pass user id to SQL as part of SQL query. As far as I know this doesn't work with DELETE.</p>
  
  <p>All triggers are structured as follows:</p>
  
  <pre><code>CREATE OR REPLACE FUNCTION before_delete_customer() RETURNS trigger AS $BODY$
  BEGIN
      INSERT INTO _customer (
          edited_by,
          edit_time,
          field1,
          field2,
          ...,
          fieldN
      ) VALUES (
          -1, // &lt;- This should be user id.
          NOW(),
          OLD.field1,
          OLD.field2,
          ...,
          OLD.fieldN
      );
      RETURN OLD;
  END; $BODY$
  LANGUAGE plpgsql
  </code></pre>