SHA256
17 12 25
Ещё промежуточный комит верии - не работает :) 2
This commit is contained in:
@@ -13,47 +13,30 @@ import java.sql.Statement;
|
||||
public final class SqliteDbController {
|
||||
|
||||
private static volatile SqliteDbController instance;
|
||||
private final Connection connection;
|
||||
|
||||
private final String jdbcUrl;
|
||||
|
||||
private SqliteDbController() {
|
||||
try {
|
||||
// Подгружаем драйвер SQLite
|
||||
Class.forName("org.sqlite.JDBC");
|
||||
} catch (ClassNotFoundException e) {
|
||||
throw new RuntimeException("SQLite JDBC driver not found", e);
|
||||
}
|
||||
|
||||
String dbPath = AppConfig.getInstance().getParam("db.path");
|
||||
|
||||
if (dbPath == null || dbPath.isBlank()) {
|
||||
throw new RuntimeException("Config param 'db.path' is not set in application.properties");
|
||||
}
|
||||
|
||||
Path dbFile = Paths.get(dbPath);
|
||||
|
||||
// 👉 Если файла БД нет — создаём новую БД через DatabaseInitializer
|
||||
if (!Files.exists(dbFile)) {
|
||||
System.out.println("[DB] Файл БД не найден: " + dbFile.toAbsolutePath());
|
||||
System.out.println("[DB] Создаём новую БД с помощью DatabaseInitializer...");
|
||||
|
||||
// можно передать пустой массив аргументов
|
||||
DatabaseInitializer.createNewDB(new String[0]);
|
||||
}
|
||||
|
||||
String url = "jdbc:sqlite:" + dbPath;
|
||||
|
||||
try {
|
||||
this.connection = DriverManager.getConnection(url);
|
||||
this.connection.setAutoCommit(true);
|
||||
|
||||
// ВАЖНО: включаем поддержку внешних ключей для этого соединения
|
||||
try (Statement st = this.connection.createStatement()) {
|
||||
st.execute("PRAGMA foreign_keys = ON");
|
||||
}
|
||||
|
||||
} catch (SQLException e) {
|
||||
throw new RuntimeException("Failed to connect to SQLite database: " + url, e);
|
||||
}
|
||||
this.jdbcUrl = "jdbc:sqlite:" + dbPath;
|
||||
}
|
||||
|
||||
public static SqliteDbController getInstance() {
|
||||
@@ -67,15 +50,26 @@ public final class SqliteDbController {
|
||||
return instance;
|
||||
}
|
||||
|
||||
public Connection getConnection() {
|
||||
return connection;
|
||||
/**
|
||||
* Каждый вызов возвращает НОВОЕ соединение.
|
||||
* Закрывать обязан вызывающий код (try-with-resources).
|
||||
*/
|
||||
public Connection getConnection() throws SQLException {
|
||||
Connection conn = DriverManager.getConnection(jdbcUrl);
|
||||
conn.setAutoCommit(true);
|
||||
|
||||
try (Statement st = conn.createStatement()) {
|
||||
st.execute("PRAGMA foreign_keys = ON");
|
||||
st.execute("PRAGMA journal_mode = WAL");
|
||||
st.execute("PRAGMA synchronous = NORMAL");
|
||||
st.execute("PRAGMA busy_timeout = 5000");
|
||||
}
|
||||
|
||||
return conn;
|
||||
}
|
||||
|
||||
/** Теперь close() не нужен. */
|
||||
public void close() {
|
||||
try {
|
||||
connection.close();
|
||||
} catch (SQLException e) {
|
||||
// логировать по необходимости
|
||||
}
|
||||
// no-op
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,10 +5,6 @@ import shine.db.entities.BlockchainStateEntry;
|
||||
|
||||
import java.sql.*;
|
||||
|
||||
/**
|
||||
* DAO для таблицы blockchain_state.
|
||||
* 1 строка = 1 blockchainId, линии 0..7 в колонках.
|
||||
*/
|
||||
public final class BlockchainStateDAO {
|
||||
|
||||
private static volatile BlockchainStateDAO instance;
|
||||
@@ -25,7 +21,8 @@ public final class BlockchainStateDAO {
|
||||
return instance;
|
||||
}
|
||||
|
||||
public BlockchainStateEntry getByBlockchainId(long blockchainId) throws SQLException {
|
||||
// --- Новый вариант: работа на переданном соединении ---
|
||||
public BlockchainStateEntry getByBlockchainId(Connection conn, long blockchainId) throws SQLException {
|
||||
String sql = """
|
||||
SELECT
|
||||
blockchain_id,
|
||||
@@ -48,7 +45,7 @@ public final class BlockchainStateDAO {
|
||||
WHERE blockchain_id = ?
|
||||
""";
|
||||
|
||||
try (PreparedStatement ps = db.getConnection().prepareStatement(sql)) {
|
||||
try (PreparedStatement ps = conn.prepareStatement(sql)) {
|
||||
ps.setLong(1, blockchainId);
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
if (!rs.next()) return null;
|
||||
@@ -57,11 +54,15 @@ public final class BlockchainStateDAO {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* UPSERT: если строки нет — вставка, если есть — обновление.
|
||||
* Это один вызов из кода, и один SQL.
|
||||
*/
|
||||
public void upsert(BlockchainStateEntry e) throws SQLException {
|
||||
// Старый вариант: сам открывает/закрывает conn
|
||||
public BlockchainStateEntry getByBlockchainId(long blockchainId) throws SQLException {
|
||||
try (Connection conn = db.getConnection()) {
|
||||
return getByBlockchainId(conn, blockchainId);
|
||||
}
|
||||
}
|
||||
|
||||
// --- Новый вариант: UPSERT на переданном соединении ---
|
||||
public void upsert(Connection conn, BlockchainStateEntry e) throws SQLException {
|
||||
long now = System.currentTimeMillis();
|
||||
if (e.getUpdatedAtMs() <= 0) e.setUpdatedAtMs(now);
|
||||
|
||||
@@ -124,8 +125,7 @@ public final class BlockchainStateDAO {
|
||||
updated_at_ms = excluded.updated_at_ms
|
||||
""";
|
||||
|
||||
try (PreparedStatement ps = db.getConnection().prepareStatement(sql)) {
|
||||
|
||||
try (PreparedStatement ps = conn.prepareStatement(sql)) {
|
||||
int i = 1;
|
||||
ps.setLong(i++, e.getBlockchainId());
|
||||
ps.setString(i++, nn(e.getUserLogin()));
|
||||
@@ -141,11 +141,17 @@ public final class BlockchainStateDAO {
|
||||
}
|
||||
|
||||
ps.setLong(i++, e.getUpdatedAtMs());
|
||||
|
||||
ps.executeUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
// Старый вариант: сам открывает/закрывает conn
|
||||
public void upsert(BlockchainStateEntry e) throws SQLException {
|
||||
try (Connection conn = db.getConnection()) {
|
||||
upsert(conn, e);
|
||||
}
|
||||
}
|
||||
|
||||
private BlockchainStateEntry mapRow(ResultSet rs) throws SQLException {
|
||||
BlockchainStateEntry e = new BlockchainStateEntry();
|
||||
e.setBlockchainId(rs.getLong("blockchain_id"));
|
||||
|
||||
Reference in New Issue
Block a user