package com.xfestudio.xfeservermanager.infra.persistence;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.AtomicMoveNotSupportedException;
import java.nio.file.StandardCopyOption;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.time.Clock;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/** Connection factory and monotonic migration runner for a SQLite database. */
public final class SqliteDatabase {
private final String jdbcUrl;
private final Path databaseFile;
private final Clock clock;
public SqliteDatabase(Path databaseFile, Clock clock) {
Objects.requireNonNull(databaseFile, "databaseFile");
this.clock = Objects.requireNonNull(clock, "clock");
Path absolute = databaseFile.toAbsolutePath().normalize();
this.databaseFile = absolute;
try {
Path parent = absolute.getParent();
if (parent != null) {
Files.createDirectories(parent);
}
Class.forName("org.sqlite.JDBC");
} catch (IOException exception) {
throw new PersistenceException("cannot create database directory", exception);
} catch (ClassNotFoundException exception) {
throw new PersistenceException("SQLite JDBC driver is unavailable", exception);
}
this.jdbcUrl = "jdbc:sqlite:" + absolute;
}
public Connection openConnection() throws SQLException {
Connection connection = DriverManager.getConnection(jdbcUrl);
try {
try (var statement = connection.createStatement()) {
statement.execute("PRAGMA busy_timeout=5000");
statement.execute("PRAGMA foreign_keys=ON");
statement.execute("PRAGMA journal_mode=WAL");
statement.execute("PRAGMA synchronous=NORMAL");
}
return connection;
} catch (SQLException exception) {
try {
connection.close();
} catch (SQLException closeFailure) {
exception.addSuppressed(closeFailure);
}
throw exception;
}
}
public synchronized void migrate() {
List<Migration> migrations = loadMigrations();
try {
boolean hasApplied;
boolean hasPending = false;
try (Connection inspection = openConnection()) {
ensureMigrationTable(inspection);
hasApplied = hasAppliedMigrations(inspection);
for (Migration migration : migrations) {
hasPending |= !isApplied(inspection, migration.version());
}
}
if (!hasPending) {
return;
}
if (hasApplied) {
checkpoint();
createMigrationBackup();
}
} catch (Exception exception) {
throw new PersistenceException("database pre-migration backup failed", exception);
}
try (Connection connection = openConnection()) {
connection.setAutoCommit(false);
try {
ensureMigrationTable(connection);
for (Migration migration : migrations) {
if (!isApplied(connection, migration.version())) {
apply(connection, migration);
}
}
connection.commit();
} catch (Exception exception) {
connection.rollback();
throw exception;
} finally {
connection.setAutoCommit(true);
}
} catch (Exception exception) {
if (exception instanceof PersistenceException persistenceException) {
throw persistenceException;
}
throw new PersistenceException("database migration failed", exception);
}
}
private void createMigrationBackup() throws IOException {
Path backup = databaseFile.resolveSibling(databaseFile.getFileName() + ".pre-migration.bak");
Path temporary = backup.resolveSibling(backup.getFileName() + ".tmp");
Files.copy(databaseFile, temporary, StandardCopyOption.REPLACE_EXISTING);
try {
Files.move(
temporary,
backup,
StandardCopyOption.ATOMIC_MOVE,
StandardCopyOption.REPLACE_EXISTING);
} catch (AtomicMoveNotSupportedException ignored) {
Files.move(temporary, backup, StandardCopyOption.REPLACE_EXISTING);
}
}
public void checkpoint() {
try (Connection connection = openConnection()) {
checkpoint(connection, databaseFile.getFileName().toString());
} catch (SQLException exception) {
throw new PersistenceException("database checkpoint failed", exception);
}
}
/** Verifies SQLite's checkpoint result instead of treating a busy result as success. */
static void checkpoint(Connection connection, String description) throws SQLException {
// PASSIVE reports an incomplete checkpoint immediately, avoiding a long busy timeout when
// an active reader still needs WAL frames. TRUNCATE is attempted only after all frames are
// known to be copied into the main database.
verifyCheckpoint(connection, "PASSIVE", description);
verifyCheckpoint(connection, "TRUNCATE", description);
}
private static void verifyCheckpoint(
Connection connection, String mode, String description) throws SQLException {
try (var statement = connection.createStatement();
var result = statement.executeQuery("PRAGMA wal_checkpoint(" + mode + ")")) {
if (!result.next()) {
throw new SQLException("SQLite returned no checkpoint status for " + description);
}
int busy = result.getInt(1);
int logFrames = result.getInt(2);
int checkpointedFrames = result.getInt(3);
if (busy != 0 || (logFrames >= 0 && checkpointedFrames < logFrames)) {
throw new SQLException("SQLite checkpoint is busy for " + description
+ " (busy=" + busy + ", log=" + logFrames
+ ", checkpointed=" + checkpointedFrames + ')');
}
}
}
private static void ensureMigrationTable(Connection connection) throws SQLException {
try (var statement = connection.createStatement()) {
statement.execute("CREATE TABLE IF NOT EXISTS schema_migrations ("
+ "version INTEGER PRIMARY KEY, description TEXT NOT NULL, applied_at INTEGER NOT NULL)");
}
}
private static boolean isApplied(Connection connection, int version) throws SQLException {
try (var query = connection.prepareStatement(
"SELECT 1 FROM schema_migrations WHERE version = ?")) {
query.setInt(1, version);
try (var result = query.executeQuery()) {
return result.next();
}
}
}
private static boolean hasAppliedMigrations(Connection connection) throws SQLException {
try (var query = connection.createStatement().executeQuery(
"SELECT 1 FROM schema_migrations LIMIT 1")) {
return query.next();
}
}
private void apply(Connection connection, Migration migration) throws SQLException {
for (String statementSql : splitStatements(readResource(migration.resource()))) {
if (!statementSql.isBlank()) {
try (var statement = connection.createStatement()) {
statement.execute(statementSql);
}
}
}
try (var insert = connection.prepareStatement(
"INSERT INTO schema_migrations(version, description, applied_at) VALUES(?, ?, ?)")) {
insert.setInt(1, migration.version());
insert.setString(2, migration.description());
insert.setLong(3, clock.instant().toEpochMilli());
insert.executeUpdate();
}
}
private static List<Migration> loadMigrations() {
String index = readResource("db/migration/index.txt");
List<Migration> migrations = new ArrayList<>();
for (String line : index.lines().toList()) {
String trimmed = line.trim();
if (trimmed.isEmpty() || trimmed.startsWith("#")) {
continue;
}
String[] values = trimmed.split("\\|", 3);
if (values.length != 3) {
throw new PersistenceException("invalid migration index entry: " + trimmed);
}
migrations.add(new Migration(Integer.parseInt(values[0]), values[1], values[2]));
}
migrations.sort(java.util.Comparator.comparingInt(Migration::version));
for (int position = 1; position < migrations.size(); position++) {
if (migrations.get(position - 1).version() == migrations.get(position).version()) {
throw new PersistenceException(
"duplicate migration version " + migrations.get(position).version());
}
}
return List.copyOf(migrations);
}
static List<String> splitStatements(String script) {
List<String> statements = new ArrayList<>();
StringBuilder current = new StringBuilder();
boolean singleQuote = false;
for (int index = 0; index < script.length(); index++) {
char value = script.charAt(index);
if (value == '\'') {
if (singleQuote && index + 1 < script.length() && script.charAt(index + 1) == '\'') {
current.append(value).append(script.charAt(++index));
continue;
}
singleQuote = !singleQuote;
}
if (value == ';' && !singleQuote) {
statements.add(current.toString().trim());
current.setLength(0);
} else {
current.append(value);
}
}
if (!current.toString().isBlank()) {
statements.add(current.toString().trim());
}
return statements;
}
private static String readResource(String resource) {
ClassLoader loader = SqliteDatabase.class.getClassLoader();
try (var input = loader.getResourceAsStream(resource)) {
if (input == null) {
throw new PersistenceException("missing resource " + resource);
}
try (var reader = new BufferedReader(
new InputStreamReader(input, StandardCharsets.UTF_8))) {
return reader.lines().collect(java.util.stream.Collectors.joining("\n"));
}
} catch (IOException exception) {
throw new PersistenceException("cannot read resource " + resource, exception);
}
}
private record Migration(int version, String description, String resource) {}
}
package com.xfestudio.xfeservermanager.infra.persistence;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.AtomicMoveNotSupportedException;
import java.nio.file.StandardCopyOption;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.time.Clock;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/** Connection factory and monotonic migration runner for a SQLite database. */
public final class SqliteDatabase {
private final String jdbcUrl;
private final Path databaseFile;
private final Clock clock;
public SqliteDatabase(Path databaseFile, Clock clock) {
Objects.requireNonNull(databaseFile, "databaseFile");
this.clock = Objects.requireNonNull(clock, "clock");
Path absolute = databaseFile.toAbsolutePath().normalize();
this.databaseFile = absolute;
try {
Path parent = absolute.getParent();
if (parent != null) {
Files.createDirectories(parent);
}
Class.forName("org.sqlite.JDBC");
} catch (IOException exception) {
throw new PersistenceException("cannot create database directory", exception);
} catch (ClassNotFoundException exception) {
throw new PersistenceException("SQLite JDBC driver is unavailable", exception);
}
this.jdbcUrl = "jdbc:sqlite:" + absolute;
}
public Connection openConnection() throws SQLException {
Connection connection = DriverManager.getConnection(jdbcUrl);
try {
try (var statement = connection.createStatement()) {
statement.execute("PRAGMA busy_timeout=5000");
statement.execute("PRAGMA foreign_keys=ON");
statement.execute("PRAGMA journal_mode=WAL");
statement.execute("PRAGMA synchronous=NORMAL");
}
return connection;
} catch (SQLException exception) {
try {
connection.close();
} catch (SQLException closeFailure) {
exception.addSuppressed(closeFailure);
}
throw exception;
}
}
public synchronized void migrate() {
List<Migration> migrations = loadMigrations();
try {
boolean hasApplied;
boolean hasPending = false;
try (Connection inspection = openConnection()) {
ensureMigrationTable(inspection);
hasApplied = hasAppliedMigrations(inspection);
for (Migration migration : migrations) {
hasPending |= !isApplied(inspection, migration.version());
}
}
if (!hasPending) {
return;
}
if (hasApplied) {
checkpoint();
createMigrationBackup();
}
} catch (Exception exception) {
throw new PersistenceException("database pre-migration backup failed", exception);
}
try (Connection connection = openConnection()) {
connection.setAutoCommit(false);
try {
ensureMigrationTable(connection);
for (Migration migration : migrations) {
if (!isApplied(connection, migration.version())) {
apply(connection, migration);
}
}
connection.commit();
} catch (Exception exception) {
connection.rollback();
throw exception;
} finally {
connection.setAutoCommit(true);
}
} catch (Exception exception) {
if (exception instanceof PersistenceException persistenceException) {
throw persistenceException;
}
throw new PersistenceException("database migration failed", exception);
}
}
private void createMigrationBackup() throws IOException {
Path backup = databaseFile.resolveSibling(databaseFile.getFileName() + ".pre-migration.bak");
Path temporary = backup.resolveSibling(backup.getFileName() + ".tmp");
Files.copy(databaseFile, temporary, StandardCopyOption.REPLACE_EXISTING);
try {
Files.move(
temporary,
backup,
StandardCopyOption.ATOMIC_MOVE,
StandardCopyOption.REPLACE_EXISTING);
} catch (AtomicMoveNotSupportedException ignored) {
Files.move(temporary, backup, StandardCopyOption.REPLACE_EXISTING);
}
}
public void checkpoint() {
try (Connection connection = openConnection()) {
checkpoint(connection, databaseFile.getFileName().toString());
} catch (SQLException exception) {
throw new PersistenceException("database checkpoint failed", exception);
}
}
/** Verifies SQLite's checkpoint result instead of treating a busy result as success. */
static void checkpoint(Connection connection, String description) throws SQLException {
// PASSIVE reports an incomplete checkpoint immediately, avoiding a long busy timeout when
// an active reader still needs WAL frames. TRUNCATE is attempted only after all frames are
// known to be copied into the main database.
verifyCheckpoint(connection, "PASSIVE", description);
verifyCheckpoint(connection, "TRUNCATE", description);
}
private static void verifyCheckpoint(
Connection connection, String mode, String description) throws SQLException {
try (var statement = connection.createStatement();
var result = statement.executeQuery("PRAGMA wal_checkpoint(" + mode + ")")) {
if (!result.next()) {
throw new SQLException("SQLite returned no checkpoint status for " + description);
}
int busy = result.getInt(1);
int logFrames = result.getInt(2);
int checkpointedFrames = result.getInt(3);
if (busy != 0 || (logFrames >= 0 && checkpointedFrames < logFrames)) {
throw new SQLException("SQLite checkpoint is busy for " + description
+ " (busy=" + busy + ", log=" + logFrames
+ ", checkpointed=" + checkpointedFrames + ')');
}
}
}
private static void ensureMigrationTable(Connection connection) throws SQLException {
try (var statement = connection.createStatement()) {
statement.execute("CREATE TABLE IF NOT EXISTS schema_migrations ("
+ "version INTEGER PRIMARY KEY, description TEXT NOT NULL, applied_at INTEGER NOT NULL)");
}
}
private static boolean isApplied(Connection connection, int version) throws SQLException {
try (var query = connection.prepareStatement(
"SELECT 1 FROM schema_migrations WHERE version = ?")) {
query.setInt(1, version);
try (var result = query.executeQuery()) {
return result.next();
}
}
}
private static boolean hasAppliedMigrations(Connection connection) throws SQLException {
try (var query = connection.createStatement().executeQuery(
"SELECT 1 FROM schema_migrations LIMIT 1")) {
return query.next();
}
}
private void apply(Connection connection, Migration migration) throws SQLException {
for (String statementSql : splitStatements(readResource(migration.resource()))) {
if (!statementSql.isBlank()) {
try (var statement = connection.createStatement()) {
statement.execute(statementSql);
}
}
}
try (var insert = connection.prepareStatement(
"INSERT INTO schema_migrations(version, description, applied_at) VALUES(?, ?, ?)")) {
insert.setInt(1, migration.version());
insert.setString(2, migration.description());
insert.setLong(3, clock.instant().toEpochMilli());
insert.executeUpdate();
}
}
private static List<Migration> loadMigrations() {
String index = readResource("db/migration/index.txt");
List<Migration> migrations = new ArrayList<>();
for (String line : index.lines().toList()) {
String trimmed = line.trim();
if (trimmed.isEmpty() || trimmed.startsWith("#")) {
continue;
}
String[] values = trimmed.split("\\|", 3);
if (values.length != 3) {
throw new PersistenceException("invalid migration index entry: " + trimmed);
}
migrations.add(new Migration(Integer.parseInt(values[0]), values[1], values[2]));
}
migrations.sort(java.util.Comparator.comparingInt(Migration::version));
for (int position = 1; position < migrations.size(); position++) {
if (migrations.get(position - 1).version() == migrations.get(position).version()) {
throw new PersistenceException(
"duplicate migration version " + migrations.get(position).version());
}
}
return List.copyOf(migrations);
}
static List<String> splitStatements(String script) {
List<String> statements = new ArrayList<>();
StringBuilder current = new StringBuilder();
boolean singleQuote = false;
for (int index = 0; index < script.length(); index++) {
char value = script.charAt(index);
if (value == '\'') {
if (singleQuote && index + 1 < script.length() && script.charAt(index + 1) == '\'') {
current.append(value).append(script.charAt(++index));
continue;
}
singleQuote = !singleQuote;
}
if (value == ';' && !singleQuote) {
statements.add(current.toString().trim());
current.setLength(0);
} else {
current.append(value);
}
}
if (!current.toString().isBlank()) {
statements.add(current.toString().trim());
}
return statements;
}
private static String readResource(String resource) {
ClassLoader loader = SqliteDatabase.class.getClassLoader();
try (var input = loader.getResourceAsStream(resource)) {
if (input == null) {
throw new PersistenceException("missing resource " + resource);
}
try (var reader = new BufferedReader(
new InputStreamReader(input, StandardCharsets.UTF_8))) {
return reader.lines().collect(java.util.stream.Collectors.joining("\n"));
}
} catch (IOException exception) {
throw new PersistenceException("cannot read resource " + resource, exception);
}
}
private record Migration(int version, String description, String resource) {}
}