113 lines
3.0 KiB
Java
113 lines
3.0 KiB
Java
package wtf.beatrice.nounspicker.utils;
|
|
|
|
import java.sql.Connection;
|
|
import java.sql.DriverManager;
|
|
import java.sql.SQLException;
|
|
import java.sql.Statement;
|
|
import java.util.ArrayList;
|
|
import java.util.List;
|
|
|
|
public class DatabaseManager
|
|
{
|
|
|
|
private final static String sqliteURL = "jdbc:sqlite:%path%";
|
|
private Connection dbConnection = null;
|
|
private ConsoleLogger logger;
|
|
private final String dbPath;
|
|
|
|
public DatabaseManager(String dbPath)
|
|
{
|
|
this.dbPath = dbPath;
|
|
logger = new ConsoleLogger(getClass());
|
|
}
|
|
|
|
public boolean connect()
|
|
{
|
|
String url = sqliteURL.replace("%path%", dbPath);
|
|
|
|
if(!close()) return false;
|
|
|
|
try {
|
|
dbConnection = DriverManager.getConnection(url);
|
|
logger.log("Database connection established!");
|
|
return true;
|
|
} catch (SQLException e) {
|
|
logger.err(e.getMessage());
|
|
return false;
|
|
}
|
|
|
|
}
|
|
|
|
public boolean close()
|
|
{
|
|
if (dbConnection != null)
|
|
{
|
|
try {
|
|
if(!dbConnection.isClosed())
|
|
{
|
|
dbConnection.close();
|
|
}
|
|
} catch (SQLException e) {
|
|
logger.err(e.getMessage());
|
|
return false;
|
|
}
|
|
|
|
dbConnection = null;
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
public boolean initDb()
|
|
{
|
|
List<String> newTables = new ArrayList<>();
|
|
|
|
newTables.add("CREATE TABLE IF NOT EXISTS players (" +
|
|
"player text NOT NULL," +
|
|
"main_pronoun_id integer," +
|
|
"secondary_pronoun_id integer" +
|
|
");");
|
|
|
|
newTables.add("CREATE TABLE IF NOT EXISTS pronouns (\" +\n" +
|
|
" \"pronoun text,\" +\n" +
|
|
" \"id integer\" +\n" +
|
|
" \");");
|
|
|
|
for(String sql : newTables)
|
|
{
|
|
try (Statement stmt = dbConnection.createStatement()) {
|
|
// execute the statement
|
|
stmt.execute(sql);
|
|
} catch (SQLException e) {
|
|
logger.err(e.getMessage());
|
|
return false;
|
|
}
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
/**
|
|
* DB STRUCTURE
|
|
* TABLE 1: PLAYERS
|
|
* -----------------------------------------------------------------
|
|
* | name | main_pronoun_id | secondary_pronoun_id |
|
|
* -----------------------------------------------------------------
|
|
* | AstroBea | 1 | 2 |
|
|
* | Notch | 3 | 1 |
|
|
* -----------------------------------------------------------------
|
|
*
|
|
*
|
|
* TABLE 2: PRONOUNS
|
|
* --------------------------
|
|
* | pronoun | id |
|
|
* --------------------------
|
|
* | she | 1 |
|
|
* | her | 2 |
|
|
* | he | 3 |
|
|
* --------------------------
|
|
*
|
|
*/
|
|
|
|
}
|