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
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user