1package dev.keii.goldenage.migration;
2
3import dev.keii.goldenage.GoldenAge;
4import dev.keii.goldenage.utils.DatabaseUtility;
5
6import java.sql.PreparedStatement;
7import java.sql.ResultSet;
8import java.sql.SQLException;
9import java.sql.Statement;
10
11public abstract class Migration {
12 public DatabaseUtility db;
13 public Migrator migrator;
14
15 public Migration(Migrator migrator)
16 {
17 this.db = migrator.db;
18 this.migrator = migrator;
19 }
20
21 public abstract void up(Statement stmt) throws SQLException;
22 public abstract void down(Statement stmt) throws SQLException;
23
24 public void migrate(int batch) throws SQLException {
25 Statement stmt = db.getConnection().createStatement();
26 if(!hasBeenMigrated()) {
27 up(stmt);
28 createMigrationEntry(batch);
29 GoldenAge.getLogger().info(this.getClass().getSimpleName());
30 }
31 db.getConnection().commit();
32 stmt.close();
33 }
34
35 public void rollback(int batch) throws SQLException {
36 Statement stmt = db.getConnection().createStatement();
37 if(isInBatch(batch)) {
38 down(stmt);
39 deleteMigrationEntry();
40 GoldenAge.getLogger().info(this.getClass().getSimpleName());
41 }
42 db.getConnection().commit();
43 stmt.close();
44 }
45
46 public boolean hasBeenMigrated() throws SQLException {
47 PreparedStatement stmt = db.getConnection().prepareStatement("SELECT * FROM migrations WHERE migration = ? LIMIT 1");
48 stmt.setString(1, this.getClass().getSimpleName());
49 ResultSet rs = stmt.executeQuery();
50 boolean a = rs.next();
51 stmt.close();
52 rs.close();
53
54 return a;
55 }
56
57 public boolean isInBatch(int batch) throws SQLException {
58 PreparedStatement stmt = db.getConnection().prepareStatement("SELECT batch FROM migrations WHERE migration = ? LIMIT 1");
59 stmt.setString(1, this.getClass().getSimpleName());
60 ResultSet rs = stmt.executeQuery();
61
62 if(rs.next())
63 {
64 boolean inBatch = rs.getInt(1) == batch;
65 stmt.close();
66 rs.close();
67
68 return inBatch;
69 }
70
71 return false;
72 }
73
74 public void createMigrationEntry(int batch) throws SQLException {
75 PreparedStatement stmt = db.getConnection().prepareStatement("INSERT INTO migrations(migration, batch) VALUES(?, ?);");
76 stmt.setString(1, this.getClass().getSimpleName());
77 stmt.setInt(2, batch);
78 stmt.execute();
79 db.getConnection().commit();
80 stmt.close();
81 }
82
83 public void deleteMigrationEntry() throws SQLException {
84 PreparedStatement stmt = db.getConnection().prepareStatement("DELETE FROM migrations WHERE migration = ?");
85 stmt.setString(1, this.getClass().getSimpleName());
86 stmt.execute();
87 db.getConnection().commit();
88 stmt.close();
89 }
90}