package com.alttd.altitudeweb.setup; import com.alttd.altitudeweb.database.Databases; import com.alttd.altitudeweb.database.web_db.KeyPairMapper; import com.alttd.altitudeweb.database.web_db.SettingsMapper; import lombok.extern.slf4j.Slf4j; import org.apache.ibatis.session.SqlSession; import org.jetbrains.annotations.NotNull; import java.sql.SQLException; import java.sql.Statement; @Slf4j public class InitializeWebDb { protected static void init() { log.info("Initializing WebDb"); Connection.getConnection(Databases.DEFAULT, (configuration) -> { configuration.addMapper(SettingsMapper.class); configuration.addMapper(KeyPairMapper.class); }).join() .runQuery(SqlSession -> { createSettingsTable(SqlSession); createKeyTable(SqlSession); createPrivilegedUsersTable(SqlSession); createPrivilegesTable(SqlSession); }); log.debug("Initialized WebDb"); } private static void createSettingsTable(@NotNull SqlSession sqlSession) { String query = """ CREATE TABLE IF NOT EXISTS db_connection_settings ( internal_name VARCHAR(255) NOT NULL, name VARCHAR(255) NOT NULL, username VARCHAR(255) NOT NULL, password VARCHAR(255) NOT NULL, host VARCHAR(255) NOT NULL, port INT NOT NULL, CONSTRAINT pk_internal_name PRIMARY KEY (internal_name) ); """; try (Statement statement = sqlSession.getConnection().createStatement()) { statement.execute(query); } catch (SQLException e) { throw new RuntimeException(e); } } private static void createKeyTable(@NotNull SqlSession sqlSession) { String query = """ CREATE TABLE IF NOT EXISTS key_pair ( id int NOT NULL AUTO_INCREMENT PRIMARY KEY, private_key TEXT NOT NULL, public_key TEXT NOT NULL, created_at TIMESTAMP NOT NULL ); """; try (Statement statement = sqlSession.getConnection().createStatement()) { statement.execute(query); } catch (SQLException e) { throw new RuntimeException(e); } } private static void createPrivilegedUsersTable(@NotNull SqlSession sqlSession) { String query = """ CREATE TABLE IF NOT EXISTS privileged_users ( id int NOT NULL AUTO_INCREMENT PRIMARY KEY, uuid VARCHAR(36) NOT NULL ); """; try (Statement statement = sqlSession.getConnection().createStatement()) { statement.execute(query); } catch (SQLException e) { throw new RuntimeException(e); } } private static void createPrivilegesTable(@NotNull SqlSession sqlSession) { String query = """ CREATE TABLE IF NOT EXISTS privileges ( id int NOT NULL AUTO_INCREMENT PRIMARY KEY, user_id int NOT NULL, privileges VARCHAR(36) NOT NULL, CONSTRAINT fk_privileges_user FOREIGN KEY (user_id) REFERENCES privileged_users(id) ON DELETE CASCADE ON UPDATE CASCADE ); """; try (Statement statement = sqlSession.getConnection().createStatement()) { statement.execute(query); } catch (SQLException e) { throw new RuntimeException(e); } } }