Working migrations script from resources

This commit is contained in:
Imbus 2024-02-07 07:18:26 +01:00
parent aa1fdbeb2a
commit 9665dec8ae
3 changed files with 73 additions and 0 deletions

View file

@ -50,6 +50,28 @@ public class Database {
return true;
}
// Reads a file from the resources folder and returns the content as a string
private String readResourceFile(String fileName) {
String content = "";
try {
content = new String(getClass().getResourceAsStream(fileName).readAllBytes());
} catch (Exception e) {
e.printStackTrace();
}
return content;
}
public void runMigration() {
// This path needs to start with a /
String migration = readResourceFile("/migration.sql");
try {
Statement stmt = conn.createStatement();
stmt.execute(migration);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* Close the connection to the database.
*/

View file

@ -48,6 +48,7 @@ public class MainApplication extends Application {
alert.setContentText("Could not connect to the database! Check console for details.");
alert.showAndWait();
}
db.runMigration();
} catch(Exception e) {
e.printStackTrace();
}

View file

@ -0,0 +1,50 @@
PRAGMA foreign_keys = OFF;
DROP TABLE IF EXISTS Tickets;
DROP TABLE IF EXISTS Reservations;
DROP TABLE IF EXISTS Showings;
DROP TABLE IF EXISTS Movies;
DROP TABLE IF EXISTS Theaters;
PRAGMA foreign_keys = ON;
CREATE TABLE IF NOT EXISTS Users (
username VARCHAR(50) PRIMARY KEY,
name VARCHAR(100),
address VARCHAR(255),
telephone VARCHAR(20)
);
CREATE TABLE IF NOT EXISTS Theaters (
theater_id SERIAL PRIMARY KEY,
name VARCHAR(100) UNIQUE,
total_seats INTEGER
);
CREATE TABLE IF NOT EXISTS Movies (
movie_id SERIAL PRIMARY KEY,
name VARCHAR(255) UNIQUE
);
CREATE TABLE IF NOT EXISTS Showings (
showing_id SERIAL PRIMARY KEY,
movie_id INTEGER REFERENCES Movies(movie_id),
theater_id INTEGER REFERENCES Theaters(theater_id),
show_date DATE,
UNIQUE(movie_id, show_date)
);
CREATE TABLE IF NOT EXISTS Reservations (
reservation_id SERIAL PRIMARY KEY,
username VARCHAR(50) REFERENCES Users(username),
showing_id INTEGER REFERENCES Showings(showing_id),
reservation_number VARCHAR(50),
FOREIGN KEY (showing_id, reservation_number) REFERENCES Tickets(showing_id, reservation_number)
);
CREATE TABLE IF NOT EXISTS Tickets (
showing_id INTEGER REFERENCES Showings(showing_id),
reservation_number VARCHAR(50),
PRIMARY KEY (showing_id, reservation_number),
FOREIGN KEY (showing_id, reservation_number) REFERENCES Reservations(showing_id, reservation_number)
);