如何纠正尝试回滚时发生的语法错误?

问题描述 投票:0回答:1

我正在尝试回滚,但有语法错误。我想制作一个交易脚本来处理汇款。你能帮我吗?

DROP TABLE clients, accounts, transactions;

CREATE TABLE IF NOT EXISTS clients
(
    id int PRIMARY KEY,
    name varchar
);

CREATE TABLE IF NOT EXISTS accounts
(
    id int PRIMARY KEY,
    balance float,
    client int,
    FOREIGN KEY (client) REFERENCES clients(id),
    CHECK (balance >= -500)
);

CREATE TABLE IF NOT EXISTS transactions
(
    id int PRIMARY KEY,
    payer int,
    recipient int,
    amount float,
    FOREIGN KEY (payer) REFERENCES clients(id),
    FOREIGN KEY (recipient) REFERENCES clients(id)
);


INSERT INTO clients VALUES (10, 'Client 1');
INSERT INTO clients VALUES (14, 'Client 2');
INSERT INTO clients VALUES (25, 'Client 3');

INSERT INTO accounts VALUES (2, 300, 10);
INSERT INTO accounts VALUES (8, 2000, 14);
INSERT INTO accounts VALUES (12, 650, 25);

CREATE OR REPLACE FUNCTION update_accounts()
RETURNS TRIGGER AS $$
BEGIN
    SAVEPOINT before_transaction;
    
    -- amount from the payer's balance
    UPDATE accounts
    SET balance = balance - NEW.amount
    WHERE client = NEW.payer;

    -- amount to the recipient's balance
    UPDATE accounts
    SET balance = balance + NEW.amount
    WHERE client = NEW.recipient;
    RETURN NEW;
    EXCEPTION
        WHEN OTHERS THEN
            RAISE NOTICE 'An error occured during the transaction. Each account must have a balance of at least -500.';
            ROLLBACK TO before_transaction;
END;
$$ LANGUAGE plpgsql;


CREATE TRIGGER new_transaction
AFTER INSERT ON transactions
FOR EACH ROW
EXECUTE FUNCTION update_accounts();


INSERT INTO transactions VALUES (1, 10, 14, 1000);
SELECT * FROM accounts;

我尝试使用“ROLLBACK”,但也出现错误(不是语法错误,但仍然是错误)。

谢谢您的帮助!

syntax transactions plpgsql rollback
1个回答
0
投票

不能在函数中使用

SAVEPOINT
ROLLBACK TO SAVEPOINT
等事务控制语句。最简单的解决方案是省略这两个语句,它们在您的代码中是不必要的。

© www.soinside.com 2019 - 2024. All rights reserved.