cleaned up database controller

This commit is contained in:
Arnaud Vergnet 2021-01-04 09:01:43 +01:00
parent 08b916c5c5
commit c2f53e89ec
2 changed files with 138 additions and 86 deletions

7
.idea/sqldialects.xml Normal file
View file

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="SqlDialectMappings">
<file url="file://$PROJECT_DIR$/src/main/java/fr/insa/clavardator/db/DatabaseController.java" dialect="GenericSQL" />
<file url="PROJECT" dialect="SQLite" />
</component>
</project>

View file

@ -5,6 +5,7 @@ import fr.insa.clavardator.chat.Message;
import fr.insa.clavardator.users.User; import fr.insa.clavardator.users.User;
import fr.insa.clavardator.users.UserInformation; import fr.insa.clavardator.users.UserInformation;
import fr.insa.clavardator.util.Log; import fr.insa.clavardator.util.Log;
import org.intellij.lang.annotations.Language;
import java.sql.*; import java.sql.*;
import java.util.ArrayList; import java.util.ArrayList;
@ -16,90 +17,133 @@ public class DatabaseController {
public DatabaseController() { public DatabaseController() {
} }
/**
* Connects to the main database
*/
public void connect() { public void connect() {
connectToDatabase("clavardator"); connectToDatabase("clavardator");
} }
/**
* Connects to the test database.
* @implNote DO NOT USE OUTSIDE OF TESTS
*/
public void connectToTestDb() { public void connectToTestDb() {
connectToDatabase("clavardator_test"); connectToDatabase("clavardator_test");
} }
/**
* Connects to the database of the given name
* @param dbName The database to connect to
*/
private void connectToDatabase(String dbName) { private void connectToDatabase(String dbName) {
try { try {
Class.forName("org.sqlite.JDBC"); Class.forName("org.sqlite.JDBC");
connection = DriverManager.getConnection("jdbc:sqlite:" + dbName + ".db"); connection = DriverManager.getConnection("jdbc:sqlite:" + dbName + ".db");
Log.v(getClass().getSimpleName(), "Opened database successfully"); Log.v(getClass().getSimpleName(), "Opened database '" + dbName + "' successfully");
} catch (ClassNotFoundException | SQLException e) { } catch (ClassNotFoundException | SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
/**
* Closes the connection to the current database
*/
public void close() { public void close() {
try { try {
connection.close(); connection.close();
} catch (SQLException throwables) { } catch (SQLException e) {
throwables.printStackTrace(); e.printStackTrace();
} }
} }
public void initTables() { /**
* Executes a simple update statement
*
* @param sqlQuery The query to execute
* @throws SQLException SQL error
*/
private void executeUpdate(@Language("SQL") String sqlQuery) throws SQLException {
Statement statement = connection.createStatement();
final int rowsModified = statement.executeUpdate(sqlQuery);
Log.v(getClass().getSimpleName(), rowsModified + " rows modified");
statement.close();
}
/**
* Creates the table used to store messages
* @throws SQLException SQL error
*/
private void createMessageTable() throws SQLException {
Log.v(getClass().getSimpleName(), "Creating table message...");
executeUpdate("CREATE TABLE IF NOT EXISTS message " +
"(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," +
" timestamp DATETIME NOT NULL, " +
" sender INTEGER NOT NULL, " +
" recipient INTEGER NOT NULL, " +
" text TEXT, " +
" file_path TEXT)");
}
/**
* Creates the table used to store users
* @throws SQLException SQL error
*/
private void createUserTable() throws SQLException {
Log.v(getClass().getSimpleName(), "Creating table user...");
executeUpdate("CREATE TABLE IF NOT EXISTS user " +
"(id INTEGER PRIMARY KEY NOT NULL," +
" username INTEGER NOT NULL)");
}
/**
* Creates all needed tables
*/
private void createTables() {
try { try {
Statement stmtMessageTable = connection.createStatement(); createMessageTable();
String messageTableSql = createUserTable();
"CREATE TABLE IF NOT EXISTS message " + } catch (SQLException e) {
"(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," + e.printStackTrace();
" timestamp DATETIME NOT NULL, " +
" sender INTEGER NOT NULL, " +
" recipient INTEGER NOT NULL, " +
" text TEXT, " +
" file_path TEXT)";
Log.v(getClass().getSimpleName(), "Creating table message...");
int rowsModified = stmtMessageTable.executeUpdate(messageTableSql);
Log.v(getClass().getSimpleName(), rowsModified + " rows modified");
stmtMessageTable.close();
Statement stmtUserTable = connection.createStatement();
String userTableSql =
"CREATE TABLE IF NOT EXISTS user " +
"(id INTEGER PRIMARY KEY NOT NULL," +
" username INTEGER NOT NULL)";
Log.v(getClass().getSimpleName(), "Creating table user...");
rowsModified = stmtUserTable.executeUpdate(userTableSql);
Log.v(getClass().getSimpleName(), rowsModified + " rows modified");
stmtUserTable.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
} }
} }
/**
* Destroys the message table
* @throws SQLException SQL error
*/
private void dropMessageTable() throws SQLException {
Log.v(getClass().getSimpleName(), "Dropping table message...");
executeUpdate("DROP TABLE IF EXISTS message");
}
/**
* Destroys the user table
* @throws SQLException SQL error
*/
private void dropUserTable() throws SQLException {
Log.v(getClass().getSimpleName(), "Dropping table user...");
executeUpdate("DROP TABLE IF EXISTS user");
}
/**
* Destroys all tables
*/
private void dropTables() {
try {
dropMessageTable();
dropUserTable();
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* Destroys and recreates all tables
*/
public void resetTables() { public void resetTables() {
try { dropTables();
Statement dropMessage = connection.createStatement(); createTables();
String dropMessageSql = "DROP TABLE IF EXISTS message";
Log.v(getClass().getSimpleName(), "Dropping table message...");
int rowsModified = dropMessage.executeUpdate(dropMessageSql);
Log.v(getClass().getSimpleName(), rowsModified + " rows modified");
dropMessage.close();
Statement dropUser = connection.createStatement();
String dropUserSql = "DROP TABLE IF EXISTS user";
Log.v(getClass().getSimpleName(), "Dropping table user...");
rowsModified = dropUser.executeUpdate(dropUserSql);
Log.v(getClass().getSimpleName(), rowsModified + " rows modified");
dropUser.close();
initTables();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
} }
@ -129,20 +173,20 @@ public class DatabaseController {
if (callback != null) { if (callback != null) {
callback.onUsersFetched(userList); callback.onUsersFetched(userList);
} }
} catch (SQLException throwables) { } catch (SQLException e) {
throwables.printStackTrace(); e.printStackTrace();
} }
} }
/** /**
* Adds a message to the database for this user * Adds a message to the database for this user.
* If the user does not exist, we create it.
* *
* @param message The message to add to the database * @param message The message to add to the database
* @param callback Function called when the request is done * @param callback Function called when the request is done
*/ */
public void addMessage(Message message, MessageCallback callback) { public void addMessage(Message message, MessageCallback callback) {
try { try {
// Insert the new message // Insert the new message
final String insertMessageSql = final String insertMessageSql =
@ -166,40 +210,41 @@ public class DatabaseController {
Log.v(getClass().getSimpleName(), rowsModified + " rows modified"); Log.v(getClass().getSimpleName(), rowsModified + " rows modified");
insertMsgStmt.close(); insertMsgStmt.close();
// Insert the user if not already existing
final String insertUserSql =
"INSERT OR IGNORE INTO user " +
"(id, username) " +
"VALUES (?, ?)";
PreparedStatement insertUserStmt = connection.prepareStatement(insertUserSql);
// Add sender
insertUserStmt.setInt(1, message.getSender().id);
insertUserStmt.setString(2, message.getSender().getUsername());
Log.v(getClass().getSimpleName(), "Inserting sender into db... "); Log.v(getClass().getSimpleName(), "Inserting sender into db... ");
rowsModified = insertUserStmt.executeUpdate(); addUser(message.getSender());
Log.v(getClass().getSimpleName(), rowsModified + " rows modified"); Log.v(getClass().getSimpleName(), "Inserting recipient into db... ");
addUser(message.getRecipient());
// Add recipient
insertUserStmt.setInt(1, message.getRecipient().id);
insertUserStmt.setString(2, message.getRecipient().getUsername());
Log.v(getClass().getSimpleName(), "Inserting recipient into db");
rowsModified = insertUserStmt.executeUpdate();
Log.v(getClass().getSimpleName(), rowsModified + " rows modified");
insertUserStmt.close();
if (callback != null) { if (callback != null) {
callback.onMessageSaved(); callback.onMessageSaved();
} }
} catch (SQLException throwables) { } catch (SQLException e) {
throwables.printStackTrace(); e.printStackTrace();
} }
} }
/**
* Inserts the given user if not existing
*
* @param user The user information to store
* @throws SQLException SQL error
*/
private void addUser(UserInformation user) throws SQLException {
final String insertUserSql =
"INSERT OR IGNORE INTO user " +
"(id, username) " +
"VALUES (?, ?)";
PreparedStatement statement = connection.prepareStatement(insertUserSql);
// Add sender
statement.setInt(1, user.id);
statement.setString(2, user.getUsername());
final int rowsModified = statement.executeUpdate();
Log.v(getClass().getSimpleName(), rowsModified + " rows modified");
statement.close();
}
/** /**
* Get the chat history for a given time frame * Gets the chat history for a given time frame
* *
* @param user the user for which to retrieve the history * @param user the user for which to retrieve the history
* @param from the starting date * @param from the starting date
@ -243,8 +288,8 @@ public class DatabaseController {
if (callback != null) { if (callback != null) {
callback.onHistoryFetched(chatHistory); callback.onHistoryFetched(chatHistory);
} }
} catch (SQLException throwables) { } catch (SQLException e) {
throwables.printStackTrace(); e.printStackTrace();
} }
} }