import { Transaction } from "https://deno.land/x/postgres@v0.19.2/query/transaction.ts";
Rollbacks are a mechanism to undo transaction operations without compromising the data that was modified during the transaction.
Calling a rollback without arguments will terminate the current transaction and undo all changes.
import { Client } from "https://deno.land/x/postgres/mod.ts";
const client = new Client();
const transaction = client.createTransaction("transaction");
// Very very important operations that went very, very wrong
await transaction.rollback(); // Like nothing ever happened
Savepoints can be used to rollback specific changes part of a transaction.
import { Client } from "https://deno.land/x/postgres/mod.ts";
const client = new Client();
const transaction = client.createTransaction("transaction");
// Important operations I don't want to rollback
const savepoint = await transaction.savepoint("before_disaster");
await transaction.queryArray`UPDATE MY_TABLE SET X = 0`; // Oops, update without where
// These are all the same, everything that happened between the savepoint and the rollback gets undone
await transaction.rollback(savepoint);
await transaction.rollback('before_disaster')
await transaction.rollback({ savepoint: 'before_disaster'})
await transaction.commit(); // Commits all other changes
The chain
option allows you to undo the current transaction and restart it with the same parameters in a single statement
import { Client } from "https://deno.land/x/postgres/mod.ts";
const client = new Client();
const transaction = client.createTransaction("transaction");
// Transaction operations I want to undo
await transaction.rollback({ chain: true }); // All changes are undone, but the following statements will be executed inside a transaction as well
await transaction.queryArray`DELETE SOMETHING FROM SOMEWHERE`; // Still inside the transaction
await transaction.commit(); // The transaction finishes for good