[GENERAL] Do not INSERT if UPDATE fails - Mailing list pgsql-general

From Alexander Farber
Subject [GENERAL] Do not INSERT if UPDATE fails
Date
Msg-id CAADeyWjpRHqP3ySQK1gctu2DpUYvRVXYA9Bvdg-WES8QO4wd9g@mail.gmail.com
Whole thread Raw
Responses Re: [GENERAL] Do not INSERT if UPDATE fails  (Scott Marlowe <scott.marlowe@gmail.com>)
Re: [GENERAL] Do not INSERT if UPDATE fails  ("David G. Johnston" <david.g.johnston@gmail.com>)
List pgsql-general
Good evening,

I have a custom SQL function in PostgreSQL 9.5.7 which adds a "log entry" to the table words_payments and then updates "vip_until" column in another table:

CREATE OR REPLACE FUNCTION words_buy_vip(
        in_sid text,
        in_social integer,
        in_tid text,
        in_item text,
        in_price float,
        in_ip inet)
        RETURNS integer AS
$func$
        INSERT INTO words_payments (
                sid,
                social,
                tid,
                paid,
                price,
                ip
        ) VALUES (
                in_sid,
                in_social,
                in_tid,
                CURRENT_TIMESTAMP,
                in_price,
                in_ip
        );

        UPDATE    words_users u
        SET       vip_until = CURRENT_TIMESTAMP + interval '1 year'
        FROM      words_social s
        WHERE     s.sid = in_sid
        AND       s.social = in_social
        AND       u.uid = s.uid
        AND       (u.vip_until IS NULL OR u.vip_until < CURRENT_TIMESTAMP)
        RETURNING u.uid;

$func$ LANGUAGE sql;

However if the user record is not found or the user already has vip_until >= CURRENT_TIMESTAMP (i.e. the user has already purchased "vip status") I would like to cancel the INSERT.

Is there please a way to rewrite the above function, without switching from SQL to PL/pgSQL?

Regards
Alex

pgsql-general by date:

Previous
From: Chris Travers
Date:
Subject: Re: [GENERAL] bidirectional mapping?
Next
From: Edmundo Robles
Date:
Subject: [GENERAL] Would you add a --dry-run to pg_restore?