← Complete program

Chapter 9 · Course 3 c09-m03

How do you undo a bad change?

Your goal Use a transaction to test then cancel writes, commit only the intended state and reject a second record with the same event key.

The lesson, the vocabulary, the worked example and the mission are separate blocks. You can follow them in order or return to the one you need.

Video explanation

This English explanation has English subtitles. Its examples may use a separate practice dataset; use the data stated in the written mission for your answers.

01

Story · optional context

The story so far

You are Aster Motors’ new data recruit. Noctis 01 vanished after the crash that hurt Luca, and Voss relies on an authorization bearing your ID. In Imani’s SQLite lab, you were able to create two different rows for event EXIT-7; this shows how a repeated trace can arise without two real decisions. Mara Sol now wants a rule rejecting the repeat and a way back if a test goes wrong. The original register remains untouched.

This course stands alone. A table contains rows; INSERT adds them and a key can prevent some duplicates. A transaction is like an envelope around a group of writes: keep all of them with COMMIT or cancel them with ROLLBACK. Here you will learn BEGIN, atomicity and UNIQUE in a SQLite copy. You can follow every state on paper without running SQL.

02

Before the lesson

Purpose of this course

Use a transaction to test then cancel writes, commit only the intended state and reject a second record with the same event key.

Topics covered

Read BEGIN, COMMIT and ROLLBACK as three transaction steps.; Explain atomicity with two writes canceled together.; Define UNIQUE(event_key) and predict its effect on a duplicate.; Understand that after a constraint error you must handle failure and return to a known state.

What you will learn

  • Read BEGIN, COMMIT and ROLLBACK as three transaction steps.
  • Explain atomicity with two writes canceled together.
  • Define UNIQUE(event_key) and predict its effect on a duplicate.
  • Understand that after a constraint error you must handle failure and return to a known state.

PART 1 · THE LESSON

Understand step by step

1

Lesson · explanation

Investigate on a copy while preserving the evidence

You are Aster Motors' new data recruit. Noctis 01 vanished after a crash that injured Luca. Voss displays an authorization bearing your ID and wants to blame you. Imani preserves the original register and gives you a SQLite copy for experiments. A database holds tables; a row in authorizations represents a recorded authorization here, not final proof of who created it.

Think of a precious notebook and a photocopy. You may mark the photocopy to discover what the software permits, while the notebook stays available for an independent investigation. On the copy, row A1 has event key EXIT-7 and written actor HERO-ID. That text names your ID in a row; it does not show whose fingers used the keyboard.

Ask three separate questions. What does the row say? It joins A1, EXIT-7, and HERO-ID. What does the program allow? A rule can accept or reject another row. What actually happened? Access logs, preserved sources, and the original register must help answer that. Mixing these questions would let Voss turn a technical demonstration into an unfair accusation.

Counterexample: changing the original register to show that an insert is possible. Even a successful test could damage or mix evidence. Every creation, insert, and cancellation in this lesson happens on a fresh laboratory copy. You can track the states on paper without installing SQLite or touching the real case file.

Pause and think

Does HERO-ID in A1 prove that you created A1?

See the explanation

No. It is the ID written in the copy; identifying the real author requires other checked traces.

2

Lesson · explanation

Read the table and its rules first

Our practice table is authorizations. Its plan is CREATE TABLE authorizations (id TEXT PRIMARY KEY, event_key TEXT NOT NULL UNIQUE, actor_id TEXT NOT NULL);. A schema is a table plan, like a form's headings and rules. id distinguishes rows, event_key identifies an event, and actor_id holds the claimed actor's ID. TEXT says that these values are stored as text.

PRIMARY KEY prevents the same id from naming two rows. NOT NULL requires a value in its column. UNIQUE prevents two rows here from sharing an event_key. Imagine two cloakroom tickets with different ticket numbers. A separate rule can still forbid both tickets from claiming to represent the same EXIT-7 exit.

A1 can have id = 'A1', event_key = 'EXIT-7', and actor_id = 'HERO-ID'. A temporary row can use id = 'TEMP', event_key = 'DRAFT', and actor_id = 'TEST', because its event key differs. A2 with id = 'A2' but event_key = 'EXIT-7' repeats A1's event key. Its new row ID does not erase that repetition.

Counterexample: assuming PRIMARY KEY on id alone prevents two authorizations for EXIT-7. A1 and A2 have different row IDs, so that rule alone would admit them. State the business question first: should an event key identify only one authorization? In this laboratory, yes. That is why the schema says event_key TEXT NOT NULL UNIQUE.

Pause and think

What rule stops A1 and A2 sharing EXIT-7 although their row IDs differ?

See the explanation

UNIQUE on event_key, with NOT NULL requiring a present event key.

3

Lesson · explanation

BEGIN opens work that is still pending

A transaction groups database changes into one attempt. BEGIN; explicitly starts that group in SQLite. The following INSERT statements belong to the open transaction until COMMIT; or ROLLBACK; ends it. INSERT simply means adding a row. Order matters: create the table before the first BEGIN, then start the insertion attempt.

Picture an open envelope on your desk. You place two cards inside: A1 for EXIT-7 and TEMP for DRAFT. You can inspect what you have placed there while working, but you have not yet chosen to keep this attempt. In the demonstration, both INSERT INTO authorizations (...) VALUES (...) commands sit between BEGIN; and the ending decision.

On paper, draw columns headed 'already committed rows' and 'rows in the open attempt'. Initially both are empty. After BEGIN and the two inserts, A1 and TEMP are in the open attempt; neither has received COMMIT. This picture prevents you from treating a row visible during your own unfinished work as a row already saved by a finished transaction.

Counterexample: believing that BEGIN saves the rows. It means 'start the group', not 'keep everything'. Likewise, writing two inserts and later calling only one of them confirmed ignores their shared decision. When you explain a result to the jury, show when the transaction began and exactly how it ended.

Pause and think

After BEGIN and two inserts, which command has already confirmed A1 and TEMP?

See the explanation

None. COMMIT has not happened; both rows belong to the open attempt.

4

Lesson · explanation

ROLLBACK removes writes from the open attempt

Suppose TEMP was a draft row added by mistake. Write ROLLBACK;. SQLite cancels both inserts in this transaction: A1 and TEMP disappear from the practice copy. SELECT COUNT(*) FROM authorizations; then returns 0 because the table was empty before the attempt. COUNT(*) counts existing rows; zero describes this copy after cancellation, not the real register.

This illustrates atomicity: you do not keep just the first card because it looked acceptable when the entire attempt needs redoing. Think of discarding a draft envelope that contains two pages. You return to a known starting point. The transaction gathers the writes, and ROLLBACK applies the decision to cancel the group that is still open.

The table authorizations still exists after this ROLLBACK, because it was created before the BEGIN in our example. Only the inserts inside this attempt are undone. If A1 had been committed before the attempt began, a later rollback would not erase it. Circle the commands between each BEGIN and its ending command to predict precisely what can disappear.

Counterexample: claiming ROLLBACK always returns the whole database to the day it was created. It is no unlimited time machine. It cancels changes in the transaction currently open. To check your reasoning, note the state before BEGIN, add the tentative changes, then restore that starting state when the attempt is canceled.

Pause and think

After A1 and TEMP in the first attempt followed by ROLLBACK, how many rows remain?

See the explanation

Zero. Both inserts in that attempt are canceled; the table created earlier remains.

5

Lesson · explanation

COMMIT keeps only the state you choose

After canceling the first attempt, open another transaction with BEGIN;. This time insert only A1: INSERT INTO authorizations (id, event_key, actor_id) VALUES ('A1', 'EXIT-7', 'HERO-ID');. Check the three values and the schema rule. Then write COMMIT;. The transaction ends and A1 remains in the copy. A fresh SELECT id, event_key FROM authorizations; shows A1 and EXIT-7.

Imagine writing a letter draft. You threw away both pages in the first attempt. In the second, you reread one page and placed it in the file. COMMIT is like deciding to keep that work. It says nothing by itself about whether the letter tells the truth. The saved row can still carry a misleading actor name.

Make a clear timeline: initial state empty; first BEGIN, A1 plus TEMP, ROLLBACK, empty again; second BEGIN, A1, COMMIT, A1 alone. Mara can use this sequence to explain why exactly one row appears at the end. If a later attempt fails, this previously committed A1 is its known starting point.

Counterexample: commit A1 and TEMP although TEMP is draft, then expect a later ROLLBACK to remove TEMP alone. Committing ends that transaction; undoing a future transaction does not undo the earlier decision. Review the intended rows and their meanings before committing, even in a laboratory copy.

Pause and think

Which row exists after the second BEGIN, insertion of A1, and COMMIT?

See the explanation

A1 with EXIT-7; TEMP was canceled earlier and was not inserted again.

6

Lesson · explanation

UNIQUE rejects A2 without erasing A1

The mission now begins: A1 with EXIT-7 is already committed. Imani starts a new attempt with BEGIN; and tries to add A2, whose id differs but whose event_key = 'EXIT-7' is the same. SQLite checks the schema when inserting. UNIQUE finds that an existing row already carries this key and rejects the failing statement. A2 never becomes a second kept authorization.

Think of a guard accepting ticket A1 for a particular exit. Ticket A2 then arrives with a different ticket number but the same exit label. The laboratory rule says that one event key may name only one authorization. The guard rejects the second ticket for that specific reason; merely changing the ticket number does not create another exit event.

Be precise about the error. Under SQLite's default behavior for this constraint, the failing INSERT is canceled, but the whole open transaction is not automatically canceled. Earlier writes in that transaction might still await a decision. The controlling program should handle the error, explicitly issue ROLLBACK;, and reread the table to confirm the expected state.

Counterexample: saying 'the engine automatically undid everything, so there is no need to check'. That confuses A2's rejection with cancellation of the whole attempt. If TEMP had been added in the same open transaction just before A2, A2's rejection alone would not prove TEMP vanished under the default rule. Explicit ROLLBACK closes the failed attempt cleanly.

Pause and think

A2 has a different row ID. Why is its insert still rejected?

See the explanation

Both rows would carry EXIT-7 in event_key, the column declared UNIQUE.

7

Lesson · explanation

Check the final state and the limits of the evidence

After A2 is rejected, end the open attempt with ROLLBACK;, then run SELECT id, event_key FROM authorizations;. Expect A1 with EXIT-7 and no A2. A1 remains because a previous transaction committed it. A2 is absent because its insert broke UNIQUE; the explicit rollback also removes any other pending writes made during this failed attempt.

Mara can show the jury a narrow but solid demonstration: in this copy with this schema, a second row bearing EXIT-7 is rejected. The transaction timeline explains why A1 remains. She must keep 'this rule blocks a duplicate' separate from 'the first row is authentic'. These are two different claims with different evidence needs.

Imani still needs to inspect access records, backups, logs, and the real authorization's source. actor_id = 'HERO-ID' is stored text, not a camera showing your hand on a keyboard. Even a duplicate-free table could contain a row created by Voss or someone else. The copy demonstrates a technical protection; it does not settle the crash or disappearance investigation.

Counterexample: declaring that UNIQUE proves your innocence or Voss's guilt. The rule only limits repeated keys in this table. If the business truly permits several legitimate attempts for one event, a finer key and rule are needed. Always ask which fact the database guarantees and which independent evidence is still missing.

Pause and think

What can you claim after ROLLBACK, and what cannot you claim?

See the explanation

A1 alone remains in the copy and A2 was rejected; this does not identify A1's real author.

Visual guide

Two tests, two decisions

  1. 1Test 1: BEGIN → A1 + TEMP → ROLLBACK → 0 rows
  2. 2Test 2: BEGIN → A1 → COMMIT → A1 remains
  3. 3New A2 with EXIT-7: UNIQUE rejects the duplicate

A rejected duplicate needs explicit error handling and handling of the open transaction.

SQL · query or table structure

Transactions on a fresh SQLite copy

CREATE TABLE authorizations (
    id TEXT PRIMARY KEY,
    event_key TEXT NOT NULL UNIQUE,
    actor_id TEXT NOT NULL
);

BEGIN;
INSERT INTO authorizations (id, event_key, actor_id)
VALUES ('A1', 'EXIT-7', 'HERO-ID');
INSERT INTO authorizations (id, event_key, actor_id)
VALUES ('TEMP', 'DRAFT', 'TEST');
ROLLBACK;
SELECT COUNT(*) AS rows_after_rollback FROM authorizations;

BEGIN;
INSERT INTO authorizations (id, event_key, actor_id)
VALUES ('A1', 'EXIT-7', 'HERO-ID');
COMMIT;
SELECT id, event_key FROM authorizations;

The first test adds two rows and cancels them; the first SELECT should count 0. The second inserts and commits A1; the last SELECT shows A1. A later insert of A2 with EXIT-7 would be rejected by UNIQUE.

PART 2 · WATCH IT WORK

A complete worked example

Follow each step, then the result

Worked example: follow table state

Initially authorizations is empty. The first test writes A1 then TEMP and ends with ROLLBACK. The second writes only A1 and ends with COMMIT.

  1. After BEGIN and the first two INSERT statements, the open test contains A1 and TEMP. No COMMIT has validated them.
  2. After ROLLBACK, neither insertion remains in the practice table: COUNT(*) = 0.
  3. After the new BEGIN, A1’s insertion and COMMIT, the table holds A1 with EXIT-7.
  4. An attempt to insert A2 with EXIT-7 must be rejected by UNIQUE. If in a transaction, handle the error, cancel the test and reread the table: previously committed A1 remains.
What this shows

Canceling a whole test and rejecting a repeated value are different protections. Neither replaces checking the facts’ origin.

How this helps with your mission

In Imani's lab you trace two trials before facing Voss's attempted extra row. The first places A1 and TEMP between BEGIN and ROLLBACK, so the row count returns to zero. The second places only A1 between BEGIN and COMMIT, leaving A1 with EXIT-7. In the mission, event_key TEXT NOT NULL UNIQUE protects that key. You open a new attempt, try A2 with the same EXIT-7, see the constraint error, handle it, and run ROLLBACK. When Mara rereads the table, A1 stands alone. She can explain this mechanism to the jury without claiming that it proves who entered A1 into the real register.

PART 3 · YOUR TURN

Use the lesson to solve the mission

Story scene · practical task

Mission: block the third false trace

In the story, Voss wants to produce another row bearing your ID. Imani gives you a SQLite copy whose rule says that one event_key may appear only once. A1 / EXIT-7 has already been committed. Mara asks you to try inserting A2 / EXIT-7 inside a transaction without changing the original register, then show state after failure.

Your task

  1. Write the schema rule forbidding two rows with EXIT-7.
  2. Describe the expected result of attempting to insert A2 with that event.
  3. Say how to end the failed test and what should remain visible.
  4. Explain why the demonstration still cannot prove who created A1 in the real register.

How to know you have succeeded

  • The rule is UNIQUE(event_key) with a present value.
  • A2 is rejected although its id differs from A1.
  • Handle the error, close the test with ROLLBACK, and retain committed A1 alone.
  • The constraint protects a rule in a copy; identity and authenticity need other evidence.
Open this mission in the browser workspace

Try code or SQL and keep a local draft. The mission questions are checked separately below.

Check the facts in your mission

Answer each factual question, then write your report in your own words. The program checks the choices; compare the report with the worked answer below.

1. The practice table starts empty. After `BEGIN`, you insert A1 and TEMP, then run `ROLLBACK`. How many rows remain?
2. Which declaration requires a present event key and forbids two rows with `EXIT-7`?
3. A1 / `EXIT-7` is already committed. In a new attempt, what happens if A2 also uses `EXIT-7`?
4. After A2's error, the program runs `ROLLBACK` and rereads `authorizations`. What state should it find?
5. What does this `UNIQUE` test on the copy actually establish?
See the worked answer
  1. Declare event_key TEXT NOT NULL UNIQUE. Its value must be present and differ from other rows.
  2. A1 already uses EXIT-7. Inserting A2 with EXIT-7 raises a constraint error; its different ID does not help.
  3. In the test opened by BEGIN, catch the error, run ROLLBACK, then SELECT id, event_key FROM authorizations;. A1, committed before that test, remains the only row.
  4. A duplicate-prevention rule does not confirm who typed A1 or whether the source is authentic. Imani checks original records and access traces.

You can keep or cancel a group of writes. Next, indexes will speed some searches without adding truth to the data.

Before you leave

Remember this

  • The SQLite copy lets you test while preserving the original register for investigation.
  • BEGIN opens a transaction; subsequent inserts belong to that attempt until it ends.
  • ROLLBACK cancels writes in the open transaction, such as A1 and TEMP in the first trial.
  • COMMIT keeps selected writes; committed A1 remains after that transaction ends.
  • event_key TEXT NOT NULL UNIQUE requires a present key and rejects A2 when A1 already uses EXIT-7.
  • With SQLite's default constraint behavior, a failed insert does not automatically cancel the entire transaction: handle the error, roll back, and check.
  • A unique key prevents a duplicate in the copy; it does not reveal who authored the existing row.

Continue with the integrated lessons

After the lesson and its mission, work through the additional lessons below in order. Each workshop supplies its own fictional data: do not merge identifiers or times from separate exercises into the story timeline.

A–Z

Part of the lesson · keep nearby

New words, explained

These are the names of ideas used in the lesson above. Return here whenever a word feels unfamiliar.

Transaction
A group of database operations treated as one unit of work.
BEGIN
Explicit start of a transaction in this SQLite exercise.
COMMIT
Confirmation that keeps the group’s changes.
ROLLBACK
Cancellation of changes in the still-open group.
Atomicity
The idea that a group of writes should be kept or canceled together as intended.
UNIQUE
A rule preventing two rows from sharing a value in a column declared unique.
Constraint
A rule the database imposes on values or relationships.

Télécharger le jeu de données de cet atelier. Sa préparation sur une base de test isolée est confiée à la personne qui administre l’atelier ; les lectures utilisent ensuite le compte et les paramètres qu’elle fournit.

Choisir les effets d’une suppression ou modification référencée

Une clé étrangère contrôle aussi ce qui arrive lorsque la référence parent est supprimée ou modifiée. ON DELETE définit le comportement pour une suppression ; ON UPDATE pour une modification de la clé référencée. Ces options décrivent les actions déclenchées sur les lignes enfants, pas sur n’importe quelle mise à jour d’une autre colonne du parent.

Avec InnoDB, RESTRICT et NO ACTION refusent immédiatement une opération qui casserait une référence ; l’absence d’action explicite correspond au comportement restrictif documenté. D’autres moteurs peuvent distinguer un contrôle immédiat d’un contrôle différé : ne transfère pas cette équivalence à tous les SGBD. Supprimer un profil utilisé est donc refusé tant que la contrainte restrictive demeure.

SET NULL remplace la référence enfant par NULL lorsque l’événement se produit. Les colonnes doivent autoriser NULL ; une référence obligatoire NOT NULL ne peut pas utiliser ce comportement de façon cohérente. Cela convient parfois à une classification facultative disparue, mais perdre un lien de lignage peut être contraire à l’exigence d’audit : conserver un parent désactivé plutôt que le supprimer peut être préférable.

CASCADE propage l’événement : ON DELETE CASCADE supprime les enfants liés, tandis que ON UPDATE CASCADE modifie leur valeur de référence. Une suppression peut donc toucher beaucoup de lignes au-delà de la table ciblée. Un exemple classique est une entité et ses détails strictement dépendants ; les livraisons historiques centrales ne doivent pas disparaître par accident parce qu’un format a été retiré.

Pour changer les options d’une clé, prépare une migration qui supprime puis recrée la contrainte avec toutes les options à conserver. Oublier ON DELETE lors de l’ajout d’ON UPDATE rétablit le comportement par défaut pour la suppression. Nommer les contraintes et vérifier SHOW CREATE TABLE permet de contrôler l’état final. Les DDL MySQL ne sont pas annulés comme de simples modifications de lignes.

Une clé technique stable ne devrait pas être renommée ou réattribuée pour reformater un affichage. L’exemple de changement d’identifiant sert à observer ON UPDATE, pas à recommander de réutiliser une identité supprimée. Une clé étrangère actuelle doit référencer une clé admissible ; la suggestion historique permettant n’importe quel simple index non unique n’est pas une base de conception portable.

Dans l’adaptation du cas d’élevage, le format obligatoire d’une livraison reste restrictif ; un profil facultatif pourrait utiliser SET NULL ; une fiche de profil entièrement dépendante d’un format pourrait être supprimée en cascade seulement si le contrat le permet. Les liens des deux entrées de lignage doivent faire l’objet d’un choix explicite de conservation. La règle métier et l’historisation gouvernent ce choix, pas seulement le nombre de commandes à taper.

Exemple appliqué aux données

CREATE TABLE parent_action (id INT PRIMARY KEY) ENGINE=InnoDB;
CREATE TABLE enfant_action (id INT PRIMARY KEY,parent_id INT,
 CONSTRAINT fk_action FOREIGN KEY(parent_id) REFERENCES parent_action(id)
 ON DELETE SET NULL ON UPDATE CASCADE) ENGINE=InnoDB;
INSERT INTO parent_action VALUES(1);
INSERT INTO enfant_action VALUES(1,1);
START TRANSACTION;
UPDATE parent_action SET id=2 WHERE id=1;
SELECT * FROM enfant_action;
DELETE FROM parent_action WHERE id=2;
SELECT * FROM enfant_action;
ROLLBACK;

Atelier sur les tables format_ref, profil_flux et livraison de la base de test.

À toi de jouer

Quelle différence existe entre CASCADE sur DELETE et CASCADE sur UPDATE ?

Voir la correction expliquée

La suppression du parent entraîne celle des enfants avec ON DELETE CASCADE ; la modification de la valeur parent est reportée dans leur référence avec ON UPDATE CASCADE. Ces effets doivent être testés sur des données isolées.

Références : Actions référentielles.

Adapté de Administrez vos bases de données avec MySQL, Chantal Gribaumont (Taguan), pages 136–141. Consulter le PDF source et ses illustrations · Provenance. Licence Creative Commons 6 2.0 (libellé exact de la couverture ; modalités précises non résolues)

Valider un ensemble de changements et comprendre ACID

Une transaction regroupe des changements dont la validation doit être cohérente. Au lieu du virement bancaire du livre, prenons une affectation de crédits de traitement : retirer cinquante unités d’une réserve et les ajouter à une autre ne doit pas rester à moitié effectué après une interruption. Les instructions s’exécutent successivement ; l’atomicité concerne l’effet validé, pas une exécution physique de toutes les commandes au même instant.

InnoDB prend en charge les transactions, contrairement aux modifications de tables MyISAM. Mélanger moteurs transactionnels et non transactionnels peut empêcher un retour complet. Les états de référence réimprimés aux pages218–221 renvoient aux mêmes tables et données déjà construites : notre atelier repart de la fixture de livraisons, sans réinitialisation destructive à chaque section.

Avec autocommit activé, une instruction transactionnelle est normalement validée automatiquement comme sa propre transaction. Cela ne signifie pas que MySQL ne travaille avec aucune transaction. SET SESSION autocommit=0 permet de grouper des changements jusqu’à COMMIT ou ROLLBACK. Le changement de session ne devient pas automatiquement la configuration d’une nouvelle connexion ; vérifier le connecteur et les valeurs de session est nécessaire.

COMMIT valide les changements de la transaction ; ROLLBACK annule les changements transactionnels encore ouverts. On voit ses propres écritures avant validation, tandis que la visibilité par d’autres connexions dépend du niveau d’isolation. Quitter une connexion avec une transaction InnoDB non validée entraîne normalement son annulation. Un COMMIT antérieur n’est pas annulé par un ROLLBACK ultérieur.

START TRANSACTION ouvre explicitement un groupe même si autocommit reste activé. Après son COMMIT ou ROLLBACK final, les instructions suivantes redeviennent soumises à l’autocommit courant. BEGIN ou BEGIN WORK sont d’autres formes dans certains contextes, mais BEGIN dans un programme stocké sert aussi à un bloc : START TRANSACTION rend l’intention transactionnelle plus claire.

SAVEPOINT nom pose un jalon ; ROLLBACK TO SAVEPOINT nom annule les changements postérieurs sans terminer toute la transaction ; RELEASE SAVEPOINT retire le jalon sans valider ses changements. Cette mécanique permet de conserver une première étape et d’annuler une seconde avant la validation globale. Elle ne crée pas une transaction imbriquée : START TRANSACTION à l’intérieur d’une transaction peut la valider implicitement.

Des opérations de définition et d’administration provoquent des validations implicites et ne sont pas annulables comme des UPDATE : créations ou suppressions de bases, tables, index, vues, routines et modifications de comptes notamment. Le livre généralisait ce principe à tous les DDL et LOAD DATA ; il faut consulter la liste précise actuelle et ses exceptions. CREATE/DROP TEMPORARY TABLE ont des particularités, et LOAD DATA ne provoque pas universellement un commit implicite pour tous les moteurs.

Changer autocommit de0 à1 peut aussi valider une transaction. LOCK TABLES et certaines formes de UNLOCK TABLES ont des interactions particulières ; ne place pas un DDL de préparation au milieu d’une opération que tu comptes annuler entièrement. Sépare migrations de schéma et transactions de données selon un plan documenté.

ACID signifie atomicité, cohérence, isolation et durabilité. L’atomicité évite un effet validé partiel ; la cohérence dépend aussi des contraintes et règles correctement écrites par l’application. Une transaction qui crédite le mauvais compte peut être atomique et pourtant incorrecte. L’isolation définit ce que les opérations concurrentes peuvent observer et modifier ; elle ne veut pas dire qu’aucune attente ou interaction n’existe.

La durabilité signifie qu’un changement validé doit survivre selon les garanties du moteur et de sa configuration. Le mot COMMIT ne supprime pas les risques liés au matériel, aux réglages de journalisation ou à une panne de stockage. Les sauvegardes et la reprise restent nécessaires. Un essai de ROLLBACK n’est pas une simulation complète de panne électrique.

Deux écritures sur une même ligne peuvent se bloquer par verrouillage. Une erreur1205 d’attente ne signifie pas toujours que toute la transaction a été automatiquement annulée, contrairement au texte historique : le traitement dépend notamment des paramètres et de l’erreur. Un deadlock peut annuler une transaction choisie. Le programme doit reconnaître le cas, effectuer le nettoyage transactionnel approprié et prévoir un rejeu borné quand le contrat l’autorise.

Exemple appliqué aux données

CREATE TABLE credits_traitement (id INT PRIMARY KEY,unites INT NOT NULL CHECK(unites>=0)) ENGINE=InnoDB;
INSERT INTO credits_traitement VALUES(1,1000),(2,200);
START TRANSACTION;
UPDATE credits_traitement SET unites=unites-50 WHERE id=1;
UPDATE credits_traitement SET unites=unites+50 WHERE id=2;
SAVEPOINT transfert_complet;
UPDATE credits_traitement SET unites=0 WHERE id=2;
ROLLBACK TO SAVEPOINT transfert_complet;
SELECT id,unites FROM credits_traitement ORDER BY id;
SELECT SUM(unites) AS total FROM credits_traitement;
ROLLBACK;
SELECT id,unites FROM credits_traitement ORDER BY id;

Sur base de test autorisée ; les essais de concurrence demandent plusieurs connexions distinctes.

À toi de jouer

Une erreur à la troisième instruction annule-t-elle toujours automatiquement toutes les instructions précédentes ?

Voir la correction expliquée

Non. Le type d’erreur, le moteur et la configuration déterminent le comportement. L’application doit traiter l’échec et terminer explicitement la transaction appropriée ; elle ne doit pas poursuivre puis COMMIT sans contrôle.

Références : Transactions · Validations implicites · Gestion erreurs InnoDB.

Adapté de Administrez vos bases de données avec MySQL, Chantal Gribaumont (Taguan), pages 218–232. Consulter le PDF source et ses illustrations · Provenance. Licence Creative Commons 6 2.0 (libellé exact de la couverture ; modalités précises non résolues)