8

In a trigger I want to see what sql query triggered this trigger. I used current_query() function of postgresql (8.4).

Everything is fine, but if trigger is executed by prepared statement I get placeholders ($1) instead of correct values. for example (logged query):

delete from some_table where id=$1

Is there a way to get/have this values/parameters?

Edited (example added):

--table for saving query
create table log_table (
query text
)

--table for trigger
create table some_table (
id text
)
--function itself
CREATE FUNCTION save_query() RETURNS trigger AS $$
    switch $TG_op {
    DELETE {
            spi_exec "INSERT INTO log_table (query) VALUES (current_query())"
        }
    default {
            return OK
        }
    }
    return OK
$$ LANGUAGE pltcl;

Creating a trigger:

create trigger test_trigger before delete on some_table for each row execute procedure save_query();

Prepared statement is executed from hibernate.

Edit again (java part added)

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class DeleteUsingPreparedStmt {

    public static void main(String[] args) {
        try {
            String deleteString = "delete from floors where id = ? ";
            final int idToDelte = 1;

            Class.forName("org.postgresql.Driver");
            String url = "jdbc:postgresql://127.0.0.1:5432/YOUR_DATABASE";
            Connection conn = DriverManager.getConnection(url, "user", "password");

            PreparedStatement deleteStmt = conn.prepareStatement(deleteString);
            deleteStmt.setInt(1, idToDelte);
            deleteStmt.executeUpdate();
        } catch (Exception e) {
            //hide me :)
        }
    }
}

You need a jdbc driver - click.

2
  • Could you write down example code for this in your question ? Aug 18, 2011 at 12:48
  • 2
    Edited question. I simplified code a bit, but it works in the same manner. Aug 18, 2011 at 12:56

1 Answer 1

6

Here is some working code (for Debian users: just install postgresql-pltcl-8.4 package and run CREATE LANGUAGE pltcl;)

CREATE TABLE log_table (
    id serial,
    query text
);

CREATE TABLE floors (
    id serial,
    value text
);

INSERT INTO floors(value) VALUES ('aaa'), ('bbb');

CREATE OR REPLACE FUNCTION save_query() RETURNS trigger AS $$
    switch $TG_op {
        DELETE {
            spi_exec "INSERT INTO log_table (query) VALUES (current_query())"
        }
        default {
            return OK
        }
    }
    return OK
$$ LANGUAGE pltcl;

CREATE TRIGGER test_trigger
    BEFORE DELETE ON floors
    FOR EACH ROW
    EXECUTE PROCEDURE save_query();

However I can't get placeholders in prepared statement (it returns EXECUTE deleteFromFloors(2);):

TABLE log_table;
 id | query 
----+-------
(0 rows)
DELETE FROM floors WHERE id = 1;
DELETE 1
TABLE log_table;
 id |              query               
----+----------------------------------
  1 | DELETE FROM floors WHERE id = 1;
(1 row)
PREPARE deleteFromFloors(integer) AS
    DELETE FROM floors WHERE id = $1;
PREPARE
EXECUTE deleteFromFloors(2);
DELETE 1
TABLE log_table;
 id |              query               
----+----------------------------------
  1 | DELETE FROM floors WHERE id = 1;
  2 | EXECUTE deleteFromFloors(2);
(2 rows)

EDIT:

As a workaround use OLD record (represented as array in Tcl), fetch id column from there and use replace function to put it instead of $1. Here you have two solutions: PL/pgSQL and PL/Tcl:

CREATE OR REPLACE FUNCTION save_query() RETURNS TRIGGER AS $$
BEGIN
    INSERT INTO log_table (query)
        VALUES (replace(current_query(), '$1', OLD.id::text));
    RETURN OLD;
END;
$$ LANGUAGE plpgsql;

CREATE OR REPLACE FUNCTION save_query() RETURNS trigger AS $$
    switch $TG_op {
        DELETE {
            spi_exec "INSERT INTO log_table (query)
                VALUES (replace(current_query(), '\$1', '$OLD(id)'))"
        }
        default {
            return OK
        }
    }
    return OK
$$ LANGUAGE pltcl;

Result:

java -classpath '.:postgresql-8.4-702.jdbc4.jar' DeleteUsingPreparedStmt

TABLE log_table;
 id |              query              
----+---------------------------------
  1 | delete from floors where id = 1

(1 row)

4
  • What you wrote is a correct behaviour of this trigger. It saves a current query - so 'EXECUTE deleteFromFloors(2)'. However from java, which calls a 'delete from floors where id = ?' a different query (with $1) is saved. Let me write a piece of code in java to show it. Aug 18, 2011 at 13:48
  • Added a java part. You answer will be helpful to others, but I cannot vote up due to low ranking. Aug 18, 2011 at 14:08
  • 1
    @Michał: Added solution (getting id from available OLD record/array) Aug 18, 2011 at 16:17
  • You are right, I'm already doing something similar to that - compare OLD and NEW column values of update records... Why I haven't thought about it.. so simple, THANKS. Aug 19, 2011 at 6:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.