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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
|
/*
Postgres will serve as the index for managing all the files. Iteration through all messages is too slow
*/
package com.pinapelz;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.sql.*;
import java.util.Properties;
public class Database {
private Connection conn;
public Database(String host, String user, String password, String db){
try {
conn = createDBConnection(host, user, password, db);
System.out.println("[Database] Running schema.sql as necessary");
String schemaSQL = Files.readString(Path.of("schema.sql"));
Statement statement = conn.createStatement();
statement.execute(schemaSQL);
} catch (IOException | SQLException e) {
throw new RuntimeException(e);
}
}
public static Connection createDBConnection(String host, String user, String password, String db) throws IOException, SQLException {
String url = "jdbc:postgresql://"+host+"/"+db+"?sslmode=require&channel_binding=require";
Properties props = new Properties();
props.setProperty("user", user);
props.setProperty("password", password);
return DriverManager.getConnection(url, props);
}
public void recordFileMetadata(String channelId, String messageId, int rootDirId, String fileName, String description, int size, String mimeType) throws SQLException {
PreparedStatement ps = conn.prepareStatement("""
INSERT INTO files (
disc_channel_id,
disc_message_id,
directory_id,
file_name,
file_description,
size,
mime_type
)
VALUES (?, ?, ?, ?, ?, ?, ?)
""");
ps.setString(1, channelId);
ps.setString(2, messageId);
ps.setLong(3, rootDirId);
ps.setString(4, fileName);
ps.setString(5, description);
ps.setLong(6, size);
ps.setString(7, mimeType);
ps.executeUpdate();
}
public String[] getFileById(int fileId) {
String sql = """
SELECT
disc_channel_id,
disc_message_id,
file_name
FROM files
WHERE file_id = ?
""";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setInt(1, fileId);
try (ResultSet rs = ps.executeQuery()) {
if (!rs.next()) {
throw new RuntimeException("File not found for id=" + fileId);
}
String channelId = rs.getString("disc_channel_id");
String messageId = rs.getString("disc_message_id");
String fileName = rs.getString("file_name");
return new String[]{ channelId, messageId, fileName };
}
} catch (SQLException e) {
throw new RuntimeException("Failed to fetch file metadata", e);
}
}
}
|