import { postgres } from "https://deno.land/x/miranda@0.0.6/src/deps.ts";
const { Transaction } = postgres;
Rollbacks are a mechanism to undo transaction operations without compromising the data that was modified during the transaction
A rollback can be executed the following way
import { Client } from "../client.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
Calling a rollback without arguments will terminate the current transaction and undo all changes, but it can be used in conjuction with the savepoint feature to rollback specific changes like the following
import { Client } from "../client.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
await transaction.rollback(savepoint); // "before_disaster" would work as well
// Everything that happened between the savepoint and the rollback gets undone
await transaction.commit(); // Commits all other changes
The rollback method allows you to specify a "chain" option, that allows you to not only undo the current transaction but to restart it with the same parameters in a single statement
import { Client } from "../client.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
However, the "chain" option can't be used alongside a savepoint, even though they are similar
A savepoint is meant to reset progress up to a certain point, while a chained rollback is meant to reset all progress and start from scratch
import { Client } from "../client.ts";
const client = new Client();
const transaction = client.createTransaction("transaction");
// @ts-expect-error
await transaction.rollback({ chain: true, savepoint: "my_savepoint" }); // Error, can't both return to savepoint and reset transaction