· 4 years ago · May 06, 2021, 11:32 AM
1package haven.Kerrigan;
2
3import java.io.File;
4import java.sql.Connection;
5import java.sql.DriverManager;
6import java.sql.SQLException;
7import java.sql.Statement;
8
9import org.sqlite.JDBC;
10
11public class DatabaseCache {
12 private static final String CONNECTION_NAME = "jdbc:sqlite:./cache/cache.db";
13 private static DatabaseCache cacheInstance = null;
14
15 private Connection connection;
16
17 private DatabaseCache() throws SQLException {
18 File file = new File("./cache");
19 if (file.mkdirs()) {
20 DriverManager.registerDriver(new JDBC());
21 this.connection = DriverManager.getConnection(CONNECTION_NAME);
22 createTables();
23 } else {
24 System.out.println("Failed to create cache database '/cache/cache.db'");
25 }
26 }
27
28 public static synchronized DatabaseCache instance() throws SQLException {
29 if (cacheInstance == null)
30 cacheInstance = new DatabaseCache();
31 return cacheInstance;
32 }
33
34 public void markContainer(long grid, int offset, String resource) {
35 try {
36 var prepared = this.connection.prepareStatement("SELECT id FROM containers WHERE grid = ? AND offset = ?;");
37 prepared.setLong(0, grid);
38 prepared.setInt(1, offset);
39 var result = prepared.executeQuery();
40 if (result.first()) {
41 // Updating
42 var id = result.getInt(0);
43 var updating = this.connection.prepareStatement("UPDATE containers SET resource = ? WHERE id = ?;");
44 updating.setString(0, resource);
45 updating.setInt(1, id);
46 updating.execute();
47 } else {
48 // Inserting
49 var inserting = this.connection.prepareStatement("INSERT INTO containers(grid, offset, resource) VALUES(?, ?, ?);");
50 inserting.setLong(0, grid);
51 inserting.setInt(1, offset);
52 inserting.setString(2, resource);
53 inserting.execute();
54 }
55 } catch (SQLException e) {
56 e.printStackTrace();
57 }
58 }
59
60 private void createTables() {
61 try (Statement statement = this.connection.createStatement()) {
62 statement.executeUpdate("""
63 CREATE TABLE IF NOT EXISTS "containers" (
64 "id" INTEGER,
65 "grid" INTEGER NOT NULL DEFAULT 0,
66 "offset" INTEGER NOT NULL DEFAULT 0,
67 "resource" TEXT,
68 PRIMARY KEY("id")
69 );
70 """);
71 } catch (SQLException e) {
72 e.printStackTrace();
73 }
74 }
75}