Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 17 additions & 4 deletions src/main/java/fr/bastoup/bperipherals/database/DBFactory.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,13 @@
import fr.bastoup.bperipherals.util.Config;

import java.sql.*;
import java.util.SortedMap;
import java.util.TreeMap;

public class DBFactory {
private static final String URL_PREFIX = "jdbc:sqlite:";
private static final String URL_SUFFIX = "?limit_attached=0&page_size=1024&max_page_count=%d";
private final SortedMap<String, Connection> conn_map=new TreeMap<>();

static {
try {
Expand All @@ -27,7 +30,17 @@ public static DBFactory getInstance() {
}

public Connection getConnection(String path) throws SQLException {
return DriverManager.getConnection(URL_PREFIX + path + String.format(URL_SUFFIX, Config.MAX_DATABASE_SIZE), null, null);
Connection conn=conn_map.get(path);
if(conn!=null && !conn.isClosed()){
return conn;
}
if(conn!=null) { //if closed remove it
conn_map.remove(path);
conn=null;
}
conn=DriverManager.getConnection(URL_PREFIX + path + String.format(URL_SUFFIX, Config.MAX_DATABASE_SIZE), null, null);
conn_map.put(path, conn);
return conn;
}

public SQLResult executeSQL(String path, String sql) {
Expand All @@ -46,11 +59,11 @@ public SQLResult executeSQL(String path, String sql) {
res = new UpdateResult(statement.getUpdateCount());
}
statement.close();
con.close();
//con.close();
} catch (SQLException e) {
res = new ErrorResult(e.getMessage());
} finally {
DBUtil.closeAll(statement, con, resultSet);
DBUtil.closeAll(statement, resultSet);
}
return res;
}
Expand All @@ -76,7 +89,7 @@ public SQLResult executePrepared(String path, PeripheralDatabase.CCPreparedState
} catch (SQLException e) {
res = new ErrorResult(e.getMessage());
} finally {
DBUtil.closeAll(prepStatement, con, resultSet);
DBUtil.closeAll(prepStatement, resultSet);
}
return res;
}
Expand Down
9 changes: 1 addition & 8 deletions src/main/java/fr/bastoup/bperipherals/database/DBUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -63,21 +63,14 @@ public static Map<String, Object> factorizeResults(SQLResult res) throws LuaExce
return ret;
}

public static void closeAll(Statement statement, Connection con, ResultSet resultSet) {
public static void closeAll(Statement statement, ResultSet resultSet) {
if (statement != null) {
try {
statement.close();
} catch (SQLException ignore) {
}
}

if (con != null) {
try {
con.close();
} catch (SQLException ignore) {
}
}

if (resultSet != null) {
try {
resultSet.close();
Expand Down