From: | Hui Jackson <jackhts4(at)gmail(dot)com> |
---|---|
To: | depesz(at)depesz(dot)com, science(at)misuse(dot)org |
Cc: | pgsql-sql(at)lists(dot)postgresql(dot)org |
Subject: | Re: Using Transaction with if-else in prepared statement |
Date: | 2022-05-26 10:00:49 |
Message-ID: | CAHXAyjyHmMqF=uUyk1enfTynGfU6ZbZviD-QSMCt7eL9x_p1Tg@mail.gmail.com |
Views: | Raw Message | Whole Thread | Download mbox | Resend email |
Thread: | |
Lists: | pgsql-sql |
Concluded both methods shared:
1. one query per each call for using prepared statement
await pgPool.query('BEGIN;');
const sender = (await pgPool.query('SELECT coin from app_user where id =
$1;',[senderId])).rows[0];
if(sender.coin >= amount){
await pgPool.query('UPDATE app_user set coin = coin - $1 where id = $2;',[
coin, senderId]);
await pgPool.query('UPDATE app_user set coin = coin + $1 where id = $2;',[
coin, receiverId]);
await pgPool.query('INSERT INTO coin_history(sender_id, receiver_id,
amount) VALUES ($1, $2, $3)',[senderId, receiverId, coin]);
await pgPool.query('COMMIT;');
}else{
await pgPool.query('END;');
}
2. Use constraint
CREATE TABLE app_user(
id integer,
coin numeric CHECK (coin >= 0)
);
hubert depesz lubaczewski <depesz(at)depesz(dot)com> 於 2022年5月26日週四 上午7:35寫道:
> On Wed, May 25, 2022 at 07:12:49PM +0800, Hui Jackson 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.
>
> I would do i by issuing *only*
> INSERT INTO coin_history(sender_id, receiver_id, amount) VALUES
> and then changing coin data with triggers plus adding constraints that
> app_user.coin can never be < 0.
>
> depesz
>
From | Date | Subject | |
---|---|---|---|
Next Message | Hui Jackson | 2022-06-05 11:10:01 | Strange behavior of transcations |
Previous Message | hubert depesz lubaczewski | 2022-05-25 23:35:56 | Re: Using Transaction with if-else in prepared statement |