package com.erigitic.data;

import com.erigitic.TotalEconomy;
import org.slf4j.Logger;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.asset.Asset;
import org.spongepowered.api.service.sql.SqlService;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Optional;
import org.apache.ibatis.jdbc.ScriptRunner;

public class Database {
    private final TotalEconomy plugin;
    private final Logger logger;
    private final String connectionString;
    private final String database;
    private SqlService sql;

    public Database() {
        plugin = TotalEconomy.getPlugin();
        logger = plugin.getLogger();
        connectionString = plugin.getDefaultConfiguration().getConnectionString();
        database = getDatabase();
    }

    public Connection getConnection() throws SQLException {
        return getDataSource().getConnection();
    }

    public void setup() {
        String filePath = String.format("schema/%s.sql", database);
        Optional<Asset> sqlFileOpt = plugin.getPluginContainer().getAsset(filePath);

        if (sqlFileOpt.isPresent()) {
            runSqlScript(sqlFileOpt.get());
            return;
        }

        logger.error("Could not find SQL file");
    }

    private DataSource getDataSource() throws SQLException {
        if (sql == null) {
            sql = Sponge.getServiceManager().provide(SqlService.class).get();
        }

        return sql.getDataSource(connectionString);
    }

    private String getDatabase() {
        return connectionString.split("jdbc:")[1].split(":")[0];
    }

    private void runSqlScript(Asset sqlScript) {
        try (Connection conn = getConnection();
             InputStreamReader reader = new InputStreamReader(sqlScript.getUrl().openStream())
        ) {
            logger.info("Successfully connected");

            ScriptRunner runner = new ScriptRunner(conn);
            runner.runScript(reader);

            logger.info("Database successfully setup");
        } catch (SQLException e) {
            logger.error("Unable to connect to the database");
        } catch (IOException e) {
            logger.error("Could not read SQL file");
        }
    }
}

@@ -1018,68 +1018,44 @@
     
-String filePath = String.format(%22schema/%25s.sql%22, database);%0A
+if (database.equals(%22mysql%22)) %7B%0A    
     
@@ -1128,28 +1128,37 @@
 set(
-filePath
+%22schema/mysql.sql%22
 );%0A
-%0A
         
 if (
@@ -1153,20 +1153,20 @@
         
-if (
+    
 sqlFileO
@@ -1173,17 +1173,17 @@
 pt.i
-s
+f
 Present(
 )) %7B
@@ -1182,54 +1182,26 @@
 ent(
-)) %7B%0A            runSqlScript(sqlFileOpt.get()
+this::runSqlScript
 );%0A 

Fix potential path traversal vulnerability