Logo hdtoledo
hdtoledo.dev
Módulos_del_Sistema
MÓDULO_TEÓRICO

Secure Sales (Transactions)

Transactions and ACID Protection

What if the power goes out? (Transactions and ACID)

Imagine this terrifying scenario in the store: Juan buys a carton of milk and pays with a $20 bill. To register this, Doña Pepa's system has to do two things:

  1. Subtract 1 carton of milk from the inventory (UPDATE Inventory).
  2. Add $20 to the cash register (UPDATE Cash).

The system successfully subtracts the milk. But right before adding the $20 to the cash register... THE POWER GOES OUT! The computer shuts down. When Pepa turns it back on, the milk has disappeared from the inventory, but the money never came in. A total financial disaster!


The Protection Bubble: BEGIN and COMMIT

To avoid these tragedies, relational databases have a superpower called Transactions. A transaction is like creating a temporary protection bubble around your operations.

You tell the database: "I'm going to do several things. Take note, but DO NOT make them permanent until I give you the final order".

sql
-- 1. We create the protection bubble BEGIN TRANSACTION; -- 2. We make our changes (they aren't permanent yet) UPDATE Inventory SET amount = amount - 1 WHERE id_product = 2; -- We subtract the milk UPDATE Cash SET balance = balance + 20; -- We add the money -- 3. Everything went perfectly! Make it permanent. COMMIT;

The COMMIT command is the final seal. Only when it reaches that line is the data truly saved to the hard drive.


The Panic Button: ROLLBACK

But what happens in the scenario where the power goes out or the system crashes before reaching the COMMIT? The database, upon rebooting, realizes there was an unclosed bubble and automatically hits its panic button: ROLLBACK.

The ROLLBACK undoes absolutely everything that was inside the bubble, leaving the data exactly as it was before starting. It's as if the sale never happened: the milk reappears in the inventory and the money is not added.

All or Nothing. This bulletproof "All or nothing" superpower is known in the technical world as ACID (Atomicity, Consistency, Isolation, and Durability). Don't worry about memorizing the acronym, just remember this: ACID means your data will never be left half-done, not even if the computer explodes.

With this, Doña Pepa can sleep peacefully. In the next lesson we will see how to create virtual "Security Cameras" so Pepa's employees can see information without being able to modify it using Views.