I have the following function:
CREATE FUNCTION user_delete(IN id INT4)
RETURNS VOID
AS
$BODY$
BEGIN
SELECT * FROM \"user\" WHERE user_id = id FOR U
You can use:
GET DIAGNOSTICS integer_var = ROW_COUNT;
.. and let the function return the count. Details in the manual.
Example:
CREATE OR REPLACE FUNCTION user_delete(id int, OUT del_ct int) AS
$func$
DECLARE
i int; -- helper var
BEGIN
DELETE FROM user_role WHERE user_id = $1;
GET DIAGNOSTICS del_ct = ROW_COUNT; -- init
DELETE FROM user_permission WHERE user_id = $1;
GET DIAGNOSTICS i = ROW_COUNT; del_ct := del_ct + i;
DELETE FROM permission_cache WHERE user_id = $1;
GET DIAGNOSTICS i = ROW_COUNT; del_ct := del_ct + i;
DELETE FROM access WHERE user_id = $1;
GET DIAGNOSTICS i = ROW_COUNT; del_ct := del_ct + i;
DELETE FROM "user" WHERE user_id = $1;
GET DIAGNOSTICS i = ROW_COUNT; del_ct := del_ct + i;
END
$func$ LANGUAGE plpgsql;
You had this as 1st statement:
SELECT * FROM "user" WHERE user_id = $1 FOR UPDATE;
Invalid syntax - inside a plpgsql function you need to use PERFORM
for SELECT
statements without target:
PERFORM * FROM "user" WHERE user_id = $1 FOR UPDATE;
But the ensuing DELETE
statement locks the row just as well. No need for manual locking with FOR UPDATE to begin with.
The added OUT del_ct int
declares an OUT
parameter that can be assigned like any variable and is returned at the end of the function automatically. It also obviates the need for an explicit RETURNS
declaration.