Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8776275
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T19:01:04+00:00 2026-06-13T19:01:04+00:00

I’m using PostgreSQL 9.1. My database is structured so that there is actual tables

  • 0

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.

I have 2 kind of triggers:

  1. Before INSERT trigger to add some extra information to tables when they are created (eg. create_time).
  2. Before UPDATE trigger and before DELETE triggers to copy old values from actual table to history table.

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.

Is there any reasonable way to do that?

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.

All triggers are structured as follows:

CREATE OR REPLACE FUNCTION before_delete_customer() RETURNS trigger AS $BODY$
BEGIN
    INSERT INTO _customer (
        edited_by,
        edit_time,
        field1,
        field2,
        ...,
        fieldN
    ) VALUES (
        -1, // <- This should be user id.
        NOW(),
        OLD.field1,
        OLD.field2,
        ...,
        OLD.fieldN
    );
    RETURN OLD;
END; $BODY$
LANGUAGE plpgsql
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-13T19:01:05+00:00Added an answer on June 13, 2026 at 7:01 pm

    Options include:

    • When you open a connection, CREATE TEMPORARY TABLE current_app_user(username text); INSERT INTO current_app_user(username) VALUES ('the_user');. Then in your trigger, SELECT username FROM current_app_user to get the current username, possibly as a subquery.

    • In postgresql.conf create an entry for a custom GUC like my_app.username = 'unknown';. Whenever you create a connection run SET my_app.username = 'the_user';. Then in triggers, use the current_setting('my_app.username') function to obtain the value. Effectively, you’re abusing the GUC machinery to provide session variables. Read the documentation appropriate to your server version, as custom GUCs changed in 9.2.

    • Adjust your application so that it has database roles for every application user. SET ROLE to that user before doing work. This not only lets you use the built-in current_user variable-like function to SELECT current_user;, it also allows you to enforce security in the database. See this question. You could log in directly as the user instead of using SET ROLE, but that tends to make connection pooling hard.

    In both all three cases you’re connection pooling you must be careful to DISCARD ALL; when you return a connection to the pool. (Though it is not documented as doing so, DISCARD ALL does a RESET ROLE).

    Common setup for demos:

    CREATE TABLE tg_demo(blah text);
    INSERT INTO tg_demo(blah) VALUES ('spam'),('eggs');
    
    -- Placeholder; will be replaced by demo functions
    CREATE OR REPLACE FUNCTION get_app_user() RETURNS text AS $$
    SELECT 'unknown';
    $$ LANGUAGE sql;
    
    CREATE OR REPLACE FUNCTION tg_demo_trigger() RETURNS trigger AS $$
    BEGIN
        RAISE NOTICE 'Current user is: %',get_app_user();
        RETURN NULL;
    END;
    $$ LANGUAGE plpgsql;
    
    CREATE TRIGGER tg_demo_tg
    AFTER INSERT OR UPDATE OR DELETE ON tg_demo 
    FOR EACH ROW EXECUTE PROCEDURE tg_demo_trigger();
    

    Using a GUC:

    • In the CUSTOMIZED OPTIONS section of postgresql.conf, add a line like myapp.username = 'unknown_user'. On PostgreSQL versions older than 9.2 you also have to set custom_variable_classes = 'myapp'.
    • Restart PostgreSQL. You will now be able to SHOW myapp.username and get the value unknown_user.

    Now you can use SET myapp.username = 'the_user'; when you establish a connection, or alternately SET LOCAL myapp.username = 'the_user'; after BEGINning a transaction if you want it to be transaction-local, which is convenient for pooled connections.

    The get_app_user function definition:

    CREATE OR REPLACE FUNCTION get_app_user() RETURNS text AS $$
        SELECT current_setting('myapp.username');
    $$ LANGUAGE sql;
    

    Demo using SET LOCAL for transaction-local current username:

    regress=> BEGIN;
    BEGIN
    regress=> SET LOCAL myapp.username = 'test_user';
    SET
    regress=> INSERT INTO tg_demo(blah) VALUES ('42');
    NOTICE:  Current user is: test_user
    INSERT 0 1
    regress=> COMMIT;
    COMMIT
    regress=> SHOW myapp.username;
     myapp.username 
    ----------------
     unknown_user
    (1 row)
    

    If you use SET instead of SET LOCAL the setting won’t get reverted at commit/rollback time, so it’s persistent across the session. It is still reset by DISCARD ALL:

    regress=> SET myapp.username = 'test';
    SET
    regress=> SHOW myapp.username;
     myapp.username 
    ----------------
     test
    (1 row)
    
    regress=> DISCARD ALL;
    DISCARD ALL
    regress=> SHOW myapp.username;
     myapp.username 
    ----------------
     unknown_user
    (1 row)
    

    Also, note that you can’t use SET or SET LOCAL with server-side bind parameters. If you want to use bind parameters (“prepared statements”), consider using the function form set_config(...). See system adminstration functions

    Using a temporary table

    This approach requires the use of a trigger (or helper function called by a trigger, preferably) that tries to read a value from a temporary table every session should have. If the temporary table cannot be found, a default value is supplied. This is likely to be somewhat slow. Test carefully.

    The get_app_user() definition:

    CREATE OR REPLACE FUNCTION get_app_user() RETURNS text AS $$
    DECLARE
        cur_user text;
    BEGIN
        BEGIN
            cur_user := (SELECT username FROM current_app_user);
        EXCEPTION WHEN undefined_table THEN
            cur_user := 'unknown_user';
        END;
        RETURN cur_user;
    END;
    $$ LANGUAGE plpgsql VOLATILE;
    

    Demo:

    regress=> CREATE TEMPORARY TABLE current_app_user(username text);
    CREATE TABLE
    regress=> INSERT INTO current_app_user(username) VALUES ('testuser');
    INSERT 0 1
    regress=> INSERT INTO tg_demo(blah) VALUES ('42');
    NOTICE:  Current user is: testuser
    INSERT 0 1
    regress=> DISCARD ALL;
    DISCARD ALL
    regress=> INSERT INTO tg_demo(blah) VALUES ('42');
    NOTICE:  Current user is: unknown_user
    INSERT 0 1
    

    Secure session variables

    There’s also a proposal to add “secure session variables” to PostgreSQL. These are a bit like package variables. As of PostgreSQL 12 the feature has not been included, but keep an eye out and speak up on the hackers list if this is something you need.

    Advanced: your own extension with shared memory area

    For advanced uses you can even have your own C extension register a shared memory area and communicate between backends using C function calls that read/write values in a DSA segment. See the PostgreSQL programming examples for details. You’ll need C knowledge, time, and patience.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

That's pretty much it. I'm using Nokogiri to scrape a web page what has
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I know there's a lot of other questions out there that deal with this
Let's say I'm outputting a post title and in our database, it's Hello Y&#8217;all
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
I am reading a book about Javascript and jQuery and using one of the
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I've got a string that has curly quotes in it. I'd like to replace
I have a small JavaScript validation script that validates inputs based on Regex. I

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.