Aller au contenu principal

TP3 - Migration de Schéma avec Flyway

Objectifs du TP​

Dans ce TP, vous allez:

  1. ✅ Configurer Flyway dans un projet Spring Boot
  2. ✅ Créer des scripts de migration versionnés
  3. ✅ Simuler une évolution de schéma de base de données
  4. ✅ Gérer les données initiales avec Flyway
  5. ✅ Utiliser les migrations répétables

Durée estimée: 1h30


Contexte​

Vous développez une application e-commerce. Au fil du temps, le schéma évolue:

  1. V1: Création des tables de base (users, products)
  2. V2: Ajout de colonnes (email aux users)
  3. V3: Création de la table orders
  4. V4: Ajout d'index pour la performance
  5. V5: Insertion de données de référence

Partie 1: Configuration du Projet​

1.1 Créer le Projet​

Créez un nouveau projet Spring Boot avec:

  • Artifact: flyway-demo
  • Dependencies:
    • Spring Web
    • Spring Data JPA
    • H2 Database
    • PostgreSQL Driver
    • Flyway Migration
    • Lombok

1.2 Dépendances Maven​

<!-- pom.xml - Vérifiez que Flyway est présent -->
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
</dependency>

<!-- Pour PostgreSQL (optionnel) -->
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-database-postgresql</artifactId>
</dependency>

1.3 Structure des Dossiers​

src/main/resources/
├── application.properties
├── application-dev.properties
├── application-prod.properties
└── db/
└── migration/
├── V1__create_users_table.sql
├── V2__add_email_to_users.sql
├── V3__create_products_table.sql
├── V4__create_orders_table.sql
├── V5__add_indexes.sql
├── V6__insert_reference_data.sql
└── R__create_views.sql

1.4 Configuration​

# application.properties
spring.profiles.active=dev

# Flyway
spring.flyway.enabled=true
spring.flyway.locations=classpath:db/migration
spring.flyway.baseline-on-migrate=false

# Logging
logging.level.org.flywaydb=DEBUG
# application-dev.properties
spring.datasource.url=jdbc:h2:mem:flywaydb;DB_CLOSE_DELAY=-1
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=

spring.h2.console.enabled=true
spring.h2.console.path=/h2-console

# JPA ne gère PAS le schéma - Flyway s'en charge!
spring.jpa.hibernate.ddl-auto=validate
spring.jpa.show-sql=true

Partie 2: Première Migration - Users​

2.1 Script V1​

Créez le fichier src/main/resources/db/migration/V1__create_users_table.sql:

-- V1__create_users_table.sql
-- Création de la table des utilisateurs

CREATE TABLE users (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
password VARCHAR(100) NOT NULL,
first_name VARCHAR(50),
last_name VARCHAR(50),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,

CONSTRAINT uk_users_username UNIQUE (username)
);

-- Commentaire pour documentation
COMMENT ON TABLE users IS 'Table des utilisateurs de l''application';

2.2 Entité Correspondante​

// src/main/java/com/example/flywaydemo/model/User.java
package com.example.flywaydemo.model;

import jakarta.persistence.*;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.time.LocalDateTime;

@Entity
@Table(name = "users")
@Data
@NoArgsConstructor
public class User {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(nullable = false, unique = true, length = 50)
private String username;

@Column(nullable = false, length = 100)
private String password;

@Column(name = "first_name", length = 50)
private String firstName;

@Column(name = "last_name", length = 50)
private String lastName;

@Column(name = "created_at")
private LocalDateTime createdAt = LocalDateTime.now();

@Column(name = "updated_at")
private LocalDateTime updatedAt = LocalDateTime.now();
}

2.3 Tester​

# Démarrer l'application
mvn spring-boot:run

# Vérifier les logs - vous devriez voir:
# Flyway Community Edition
# Successfully validated 1 migration
# Migrating schema "PUBLIC" to version "1 - create users table"
# Successfully applied 1 migration

Vérification H2:

  1. Ouvrir http://localhost:8080/h2-console
  2. URL: jdbc:h2:mem:flywaydb
  3. Vérifier que la table users existe
  4. Vérifier que la table flyway_schema_history existe
SELECT * FROM flyway_schema_history;

Partie 3: Évolution du Schéma​

3.1 V2 - Ajouter une Colonne​

-- V2__add_email_to_users.sql
-- Ajout de la colonne email

ALTER TABLE users ADD COLUMN email VARCHAR(100);

-- Créer un index sur l'email
CREATE UNIQUE INDEX idx_users_email ON users(email);

Mise à jour de l'entité:

// Ajouter dans User.java
@Column(unique = true, length = 100)
private String email;

3.2 V3 - Nouvelle Table Products​

-- V3__create_products_table.sql
-- Table des produits

CREATE TABLE products (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
description TEXT,
price DECIMAL(10, 2) NOT NULL,
stock_quantity INT NOT NULL DEFAULT 0,
category VARCHAR(50),
active BOOLEAN DEFAULT TRUE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,

CONSTRAINT chk_price_positive CHECK (price >= 0),
CONSTRAINT chk_stock_positive CHECK (stock_quantity >= 0)
);
// Product.java
package com.example.flywaydemo.model;

import jakarta.persistence.*;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.math.BigDecimal;
import java.time.LocalDateTime;

@Entity
@Table(name = "products")
@Data
@NoArgsConstructor
public class Product {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(nullable = false, length = 100)
private String name;

@Column(columnDefinition = "TEXT")
private String description;

@Column(nullable = false, precision = 10, scale = 2)
private BigDecimal price;

@Column(name = "stock_quantity", nullable = false)
private Integer stockQuantity = 0;

@Column(length = 50)
private String category;

@Column(nullable = false)
private Boolean active = true;

@Column(name = "created_at")
private LocalDateTime createdAt = LocalDateTime.now();
}

3.3 V4 - Table Orders avec FK​

-- V4__create_orders_table.sql
-- Table des commandes avec relation vers users

CREATE TABLE orders (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
user_id BIGINT NOT NULL,
order_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
status VARCHAR(20) DEFAULT 'PENDING',
total_amount DECIMAL(12, 2) NOT NULL,
shipping_address TEXT,

CONSTRAINT fk_orders_user FOREIGN KEY (user_id)
REFERENCES users(id) ON DELETE CASCADE
);

-- Table de liaison orders-products
CREATE TABLE order_items (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
order_id BIGINT NOT NULL,
product_id BIGINT NOT NULL,
quantity INT NOT NULL,
unit_price DECIMAL(10, 2) NOT NULL,

CONSTRAINT fk_order_items_order FOREIGN KEY (order_id)
REFERENCES orders(id) ON DELETE CASCADE,
CONSTRAINT fk_order_items_product FOREIGN KEY (product_id)
REFERENCES products(id)
);

3.4 V5 - Index pour Performance​

-- V5__add_indexes.sql
-- Ajout d'index pour améliorer les performances

-- Index sur la date de commande
CREATE INDEX idx_orders_date ON orders(order_date);

-- Index sur le statut
CREATE INDEX idx_orders_status ON orders(status);

-- Index sur l'utilisateur
CREATE INDEX idx_orders_user ON orders(user_id);

-- Index sur la catégorie de produit
CREATE INDEX idx_products_category ON products(category);

-- Index sur les produits actifs
CREATE INDEX idx_products_active ON products(active) WHERE active = TRUE;

3.5 V6 - Données de Référence​

-- V6__insert_reference_data.sql
-- Insertion des données de référence

-- Utilisateur admin
INSERT INTO users (username, password, email, first_name, last_name)
VALUES ('admin', '$2a$10$hashedpassword', 'admin@example.com', 'Admin', 'System');

-- Catégories de produits (via produits de démo)
INSERT INTO products (name, description, price, stock_quantity, category) VALUES
('Laptop Pro', 'Ordinateur portable haute performance', 1299.99, 50, 'ELECTRONICS'),
('Smartphone X', 'Téléphone dernière génération', 899.99, 100, 'ELECTRONICS'),
('T-Shirt Basic', 'T-shirt 100% coton', 19.99, 500, 'CLOTHING'),
('Jeans Classic', 'Jean coupe droite', 49.99, 200, 'CLOTHING'),
('Livre Java', 'Guide complet Java', 39.99, 75, 'BOOKS');

Partie 4: Migrations Répétables​

4.1 Créer une Vue​

Les migrations répétables sont réexécutées si le fichier change.

-- R__create_views.sql
-- Vue des produits actifs avec stock

CREATE OR REPLACE VIEW v_available_products AS
SELECT
id,
name,
price,
stock_quantity,
category
FROM products
WHERE active = TRUE
AND stock_quantity > 0;

-- Vue des statistiques par catégorie
CREATE OR REPLACE VIEW v_category_stats AS
SELECT
category,
COUNT(*) as product_count,
AVG(price) as avg_price,
SUM(stock_quantity) as total_stock
FROM products
WHERE active = TRUE
GROUP BY category;

4.2 Tester​

Modifiez la vue et redémarrez:

-- Modifiez R__create_views.sql
CREATE OR REPLACE VIEW v_available_products AS
SELECT
id,
name,
price,
stock_quantity,
category,
'IN_STOCK' as availability -- Nouvelle colonne!
FROM products
WHERE active = TRUE
AND stock_quantity > 0;

Au redémarrage, Flyway détecte le changement de checksum et réexécute le script.


Partie 5: Vérification et Commandes​

5.1 Vérifier l'État des Migrations​

Ouvrez la console H2 et exécutez:

-- Historique complet des migrations
SELECT
installed_rank,
version,
description,
type,
installed_on,
execution_time,
success
FROM flyway_schema_history
ORDER BY installed_rank;

Résultat attendu:

installed_rankversiondescriptiontypesuccess
11create users tableSQLtrue
22add email to usersSQLtrue
33create products tableSQLtrue
44create orders tableSQLtrue
55add indexesSQLtrue
66insert reference dataSQLtrue
7NULLcreate viewsSQLtrue

5.2 Commandes Maven (Optionnel)​

Ajoutez le plugin Flyway dans pom.xml:

<plugin>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-maven-plugin</artifactId>
<configuration>
<url>jdbc:h2:file:./target/flywaydb</url>
<user>sa</user>
<password></password>
</configuration>
</plugin>
# Voir l'état
mvn flyway:info

# Appliquer les migrations
mvn flyway:migrate

# Valider
mvn flyway:validate

Partie 6: Gestion des Erreurs​

6.1 Simuler une Erreur​

Créez un script avec une erreur:

-- V7__broken_migration.sql
-- Script avec erreur de syntaxe

CREATE TABLE broken_table (
id BIGINT PRIMARY KEY
name VARCHAR(50) -- Virgule manquante!
);

Redémarrez l'application → Erreur!

6.2 Corriger​

  1. Option A: Corriger le script et utiliser repair (dev seulement)
# Marquer comme résolu
mvn flyway:repair

# Réappliquer
mvn flyway:migrate
  1. Option B: Supprimer le fichier V7 et la ligne dans flyway_schema_history

  2. Option C (Production): Créer V8 pour corriger

-- V8__fix_broken_table.sql
-- Correction de l'erreur V7

DROP TABLE IF EXISTS broken_table;

CREATE TABLE broken_table (
id BIGINT PRIMARY KEY,
name VARCHAR(50)
);

6.3 Règle d'Or​

danger

NE JAMAIS modifier un script de migration déjà exécuté en production!

Créez toujours un NOUVEAU script pour corriger les problèmes.


Partie 7: Migration PostgreSQL​

7.1 Configuration Production​

# application-prod.properties
spring.datasource.url=jdbc:postgresql://localhost:5432/flywaydb
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.username=postgres
spring.datasource.password=secret

spring.h2.console.enabled=false

spring.jpa.hibernate.ddl-auto=validate
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect

# Flyway
spring.flyway.enabled=true
spring.flyway.clean-disabled=true

7.2 Adapter les Scripts (si nécessaire)​

Certaines syntaxes diffèrent entre H2 et PostgreSQL:

-- H2
CREATE TABLE users (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
...
);

-- PostgreSQL
CREATE TABLE users (
id BIGSERIAL PRIMARY KEY,
...
);

Solution: Utiliser des scripts spécifiques par environnement:

db/migration/
├── h2/
│ └── V1__create_tables.sql
└── postgresql/
└── V1__create_tables.sql
# application-dev.properties
spring.flyway.locations=classpath:db/migration/h2

# application-prod.properties
spring.flyway.locations=classpath:db/migration/postgresql

Partie 8: Endpoint de Vérification​

8.1 Controller pour Vérifier les Migrations​

// src/main/java/com/example/flywaydemo/controller/MigrationController.java
package com.example.flywaydemo.controller;

import org.flywaydb.core.Flyway;
import org.flywaydb.core.api.MigrationInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/migrations")
public class MigrationController {

@Autowired
private Flyway flyway;

@GetMapping
public List<Map<String, Object>> getMigrations() {
return Arrays.stream(flyway.info().all())
.map(this::toMap)
.collect(Collectors.toList());
}

@GetMapping("/pending")
public List<Map<String, Object>> getPendingMigrations() {
return Arrays.stream(flyway.info().pending())
.map(this::toMap)
.collect(Collectors.toList());
}

private Map<String, Object> toMap(MigrationInfo info) {
return Map.of(
"version", info.getVersion() != null ? info.getVersion().toString() : "N/A",
"description", info.getDescription(),
"type", info.getType().name(),
"state", info.getState().name(),
"installedOn", info.getInstalledOn() != null ? info.getInstalledOn().toString() : "N/A"
);
}
}

Test:

curl http://localhost:8080/api/migrations

Résumé​

Fichiers Créés​

FichierDescription
V1__create_users_table.sqlTable users de base
V2__add_email_to_users.sqlAjout colonne email
V3__create_products_table.sqlTable products
V4__create_orders_table.sqlTables orders et order_items
V5__add_indexes.sqlIndex de performance
V6__insert_reference_data.sqlDonnées initiales
R__create_views.sqlVues (répétable)

Commandes Clés​

CommandeAction
mvn flyway:infoVoir l'état des migrations
mvn flyway:migrateAppliquer les migrations
mvn flyway:validateValider la cohérence
mvn flyway:repairRéparer l'historique
mvn flyway:cleanNettoyer la BDD (DANGEREUX!)

Ce Que Vous Avez Appris​

  1. ✅ Configurer Flyway avec Spring Boot
  2. ✅ Nommer correctement les scripts (V1__, V2__, R__)
  3. ✅ Créer des migrations incrémentales
  4. ✅ Gérer les données de référence
  5. ✅ Utiliser les migrations répétables pour les vues
  6. ✅ Corriger les erreurs de migration

🎯 Module Terminé!​

Félicitations! Vous avez complété le Module 7 sur les bases de données et transactions.

Récapitulatif du module:

  • Chapitre 1: Configuration des Datasources (HikariCP)
  • Chapitre 2: Gestion des Transactions (@Transactional)
  • Chapitre 3: Migration avec Flyway
  • Chapitre 4: Migration avec Liquibase
  • TP1: Configuration Datasource
  • TP2: Transactions et Rollback
  • TP3: Migration Flyway (ce TP)

➡️ Retour au Module 7


⬅️ Retour au Plan de Cours