package net.ttddyy.dsproxy.test;

import org.flywaydb.core.Flyway;
import org.hsqldb.jdbc.JDBCDataSource;
import org.junit.rules.ExternalResource;

import javax.sql.DataSource;
import java.sql.Connection;

import static org.junit.Assert.fail;

/**
 * @author Tadaya Tsuyukubo
 */
public class DatabaseTestRule extends ExternalResource {

    public DataSource dataSource;

    @Override
    protected void before() throws Throwable {
        JDBCDataSource ds = new JDBCDataSource();
        ds.setDatabase("jdbc:hsqldb:mem:aname");
        ds.setUser("sa");

        Flyway flyway = new Flyway();
        flyway.setDataSource(ds);
        flyway.migrate();

        this.dataSource = ds;
    }

    @Override
    protected void after() {
        try {
            executeQuery(dataSource, "shutdown;");
        } catch (Exception e) {
            fail("Failed to shutdown database");
        }
    }

    private static void executeQuery(DataSource dataSource, String... queries) throws Exception {
        Connection conn = dataSource.getConnection();
        java.sql.Statement stmt = conn.createStatement();
        for (String query : queries) {
            stmt.execute(query);
        }
        conn.close();
    }


}

@@ -173,74 +173,8 @@
 rce;
-%0Aimport java.sql.Connection;%0A%0Aimport static org.junit.Assert.fail;
 %0A%0A/*
@@ -300,16 +300,44 @@
 ource;%0A%0A
+    private Flyway flyway;%0A%0A
     @Ove
@@ -388,16 +388,39 @@
 owable %7B
+%0A%0A        // prepare ds
 %0A       
@@ -541,24 +541,77 @@
 %22);%0A
-%0A        Flyway 
+        this.dataSource = ds;%0A%0A        // populate data%0A        this.
 flyw
@@ -633,24 +633,29 @@
 ();%0A        
+this.
 flyway.setDa
@@ -676,16 +676,21 @@
         
+this.
 flyway.m
@@ -704,38 +704,8 @@
 );%0A%0A
-        this.dataSource = ds;%0A
     
@@ -762,483 +762,29 @@
     
-try %7B%0A            executeQuery(dataSource, %22shutdown;%22);%0A        %7D catch (Exception e) %7B%0A            fail(%22Failed to shutdown database%22);%0A        %7D%0A    %7D%0A%0A    private static void executeQuery(DataSource dataSource, String... queries) throws Exception %7B%0A        Connection conn = dataSource.getConnection();%0A        java.sql.Statement stmt = conn.createStatement();%0A        for (String query : queries) %7B%0A            stmt.execute(query);%0A        %7D%0A        conn.close();%0A    %7D%0A
+flyway.clean();%0A    %7D
 %0A%0A%7D%0A

use flyway to clean up test data