public inbox for [email protected]
help / color / mirror / Atom feedFrom: Steve Midgley <[email protected]>
To: Hui Jackson <[email protected]>
Cc: pgsql-sql <[email protected]>
Subject: Re: Using Transaction with if-else in prepared statement
Date: Wed, 25 May 2022 11:03:34 -0700
Message-ID: <CAJexoS+Xa2A1QN2BSmBKSqbKC5Yhs=K7RHqsniKonQMuFt14LA@mail.gmail.com> (raw)
In-Reply-To: <CAHXAyjx-2MhO0zoCt3Vr_2AW6sFVjN0tgDo_GPVg=DVCzQDQMQ@mail.gmail.com>
References: <CAHXAyjx-2MhO0zoCt3Vr_2AW6sFVjN0tgDo_GPVg=DVCzQDQMQ@mail.gmail.com>
On Wed, May 25, 2022 at 4:13 AM Hui Jackson <[email protected]> wrote:
> I am trying to make transaction in nodejs
> The logic will be check if sufficient coin in sender's amount, if
> sufficient then do transaction.
> I am new to postgres, not sure if this is a right way to do so, if you
> have a better solution, please let me know, thank you.
>
> const coin = 10
> const senderId = 1
> const receiverId = 2
> await pgPool.query(`
> DO $$
> BEGIN
> if (SELECT coin from app_user where id = $1) >= $3 THEN
> UPDATE app_user set coin = coin - $3 where id = $1;
> UPDATE app_user set coin = coin + $3 where id = $2;
> INSERT INTO coin_history(sender_id, receiver_id, amount)
> VALUES ($1, $2, $3)
>
> END IF;
> END;
> $$`,[senderId, receiverId, coin]);
>
> Error (node:10044) UnhandledPromiseRejectionWarning: error: bind message
> supplies 3 parameters, but prepared statement "" requires 0
>
For debugging, you might try to sending each select, update, and insert in
separate NodeJS query statements. You can do the IF work in NodeJS via a
select for data from Pg.
But at the core of your problem I believe is that you are not configuring
the postgres statement to receive parameters, but your injecting parameters
from Node. From the Pg docs on prepared statements:
https://www.postgresql.org/docs/current/sql-prepare.html
PREPARE fooplan (int, text, bool, numeric) AS
INSERT INTO foo VALUES($1, $2, $3, $4);
EXECUTE fooplan(1, 'Hunter Valley', 't', 200.00);
view thread (4+ messages) latest in thread
reply
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Reply to all the recipients using the --to and --cc options:
reply via email
To: [email protected]
Cc: [email protected], [email protected], [email protected]
Subject: Re: Using Transaction with if-else in prepared statement
In-Reply-To: <CAJexoS+Xa2A1QN2BSmBKSqbKC5Yhs=K7RHqsniKonQMuFt14LA@mail.gmail.com>
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
This inbox is served by agora; see mirroring instructions
for how to clone and mirror all data and code used for this inbox