webmarker-server/src/main/java/net/mindoverflow/webmarker/utils/sql/SQLiteManager.java

114 lines
3.6 KiB
Java

package net.mindoverflow.webmarker.utils.sql;
import net.mindoverflow.webmarker.utils.config.ConfigManager;
import net.mindoverflow.webmarker.utils.messaging.MessageLevel;
import net.mindoverflow.webmarker.utils.messaging.Messenger;
import net.mindoverflow.webmarker.utils.sql.primitives.SQLDataType;
import net.mindoverflow.webmarker.utils.sql.primitives.SQLTable;
import java.sql.*;
import java.util.List;
public class SQLiteManager {
private final Messenger msg = new Messenger();
private Connection connection;
public void initialize()
{
msg.send(MessageLevel.INFO, "Connecting to SQLite database: ");
String url = "jdbc:sqlite:" + ConfigManager.FileType.DATABASE_FILE.file.getAbsolutePath();
try {
connection = DriverManager.getConnection(url);
if(connection != null && !connection.isClosed())
{
msg.sendLine(MessageLevel.NONE, "OK");
doInitialSetup();
}
} catch (SQLException throwables) {
msg.sendLine(MessageLevel.NONE, "FATAL");
throwables.printStackTrace();
msg.critical("Error connecting to SQLite database!");
System.exit(1);
}
}
private void doInitialSetup()
{
for(FDatabaseTable currentTable : FDatabaseTable.values())
{
if(!tableExists(currentTable))
{
msg.info("Creating SQLite table `" + currentTable.getTable().getTableSQLName() + "`");
createTable(currentTable);
}
}
}
private boolean tableExists(FDatabaseTable tableEnum)
{
String name = tableEnum.getTable().getTableSQLName();
try
{
DatabaseMetaData meta = connection.getMetaData();
ResultSet result = meta.getTables(null, null, name, null);
while(result.next())
{
String tableName = result.getString("TABLE_NAME");
if(tableName != null && tableName.equals(name.toLowerCase())) return true;
}
} catch (SQLException e)
{
e.printStackTrace();
msg.critical("Error checking SQLite table " + name + "!");
System.exit(1);
}
return false;
}
private void createTable(FDatabaseTable tableEnum)
{
SQLTable table = tableEnum.getTable();
List<FDatabaseColumn> columns = table.getColumns();
List<SQLDataType> dataTypes = table.getDataTypes();
StringBuilder query = new StringBuilder("CREATE TABLE IF NOT EXISTS ").append(table.getTableSQLName()).append(" (");
int pos = 0;
for(FDatabaseColumn column : columns)
{
query.append(column.getColumn().getColumnSQLName()).append(" ").append(dataTypes.get(pos).getSQLName());
pos++;
if(pos < columns.size()) // we don't want to append a colon to the last entry
{ query.append(", "); }
}
query.append(");");
executeUpdate(query.toString());
}
private void executeUpdate(String query)
{
try
{
if(connection == null || connection.isClosed())
{
msg.critical("Lost connection to SQLite database!");
System.exit(1);
}
Statement statement = connection.createStatement();
statement.executeUpdate(query);
} catch (SQLException e)
{
e.printStackTrace();
msg.critical("Error executing SQLite update!");
System.exit(1);
}
}
}