-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDatabaseModule.java
More file actions
68 lines (61 loc) · 2.16 KB
/
Copy pathDatabaseModule.java
File metadata and controls
68 lines (61 loc) · 2.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package openconsignment.di;
import dagger.Module;
import dagger.Provides;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Objects;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.inject.Singleton;
import openconsignment.common.Constants;
import openconsignment.common.Utils;
@Module
@SuppressWarnings("unused")
public class DatabaseModule {
@Provides
@Singleton
static Connection provideConnection() {
try {
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:" + Constants.DATABASE_FILE_NAME);
initDatabase(conn);
return conn;
} catch (ClassNotFoundException | SQLException ex) {
Utils.showAlert(ex.toString());
Logger.getLogger(DatabaseModule.class.getName()).log(Level.SEVERE, ex.toString(), ex);
throw new RuntimeException(ex);
}
}
private static void initDatabase(Connection conn) {
try {
String initSQL = getInitSQL();
try (Statement st = conn.createStatement()) {
conn.setAutoCommit(false);
for (String statement : initSQL.split(";")) {
String cleanedStatement = statement.trim();
if (!cleanedStatement.isEmpty()) {
st.execute(cleanedStatement);
}
}
conn.commit();
} catch (Exception e) {
conn.rollback();
throw e;
} finally {
conn.setAutoCommit(true);
}
} catch (Exception ex) {
Logger.getLogger(DatabaseModule.class.getName()).log(Level.SEVERE, ex.toString(), ex);
}
}
private static String getInitSQL() throws IOException {
return new String(
Objects.requireNonNull(DatabaseModule.class.getResourceAsStream("/sql/init.sql"))
.readAllBytes(),
StandardCharsets.UTF_8);
}
}