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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
|
/*
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);
}
}
public ResultSet getFilesByDirectoryId(int directoryId, String search, String mimeTypeFilter, String sortBy) {
StringBuilder sql = new StringBuilder("""
SELECT
file_id,
file_name,
file_description,
size,
mime_type,
created_at
FROM files
WHERE directory_id = ?
""");
if (search != null && !search.trim().isEmpty()) {
sql.append(" AND (LOWER(file_name) LIKE ? OR LOWER(file_description) LIKE ?)");
}
if (mimeTypeFilter != null && !mimeTypeFilter.trim().isEmpty()) {
sql.append(" AND mime_type LIKE ?");
}
switch (sortBy) {
case "file_name":
sql.append(" ORDER BY file_name ASC");
break;
case "size":
sql.append(" ORDER BY size DESC");
break;
default:
sql.append(" ORDER BY created_at DESC");
break;
}
try {
PreparedStatement ps = conn.prepareStatement(sql.toString());
int paramIndex = 1;
ps.setInt(paramIndex++, directoryId);
if (search != null && !search.trim().isEmpty()) {
String searchPattern = "%" + search.toLowerCase() + "%";
ps.setString(paramIndex++, searchPattern);
ps.setString(paramIndex++, searchPattern);
}
if (mimeTypeFilter != null && !mimeTypeFilter.trim().isEmpty()) {
ps.setString(paramIndex++, mimeTypeFilter + "%");
}
return ps.executeQuery();
} catch (SQLException e) {
throw new RuntimeException("Failed to fetch filtered files for directory", e);
}
}
public ResultSet getAllDirectories() {
String sql = """
SELECT
directory_id,
path,
created_at,
(SELECT COUNT(*) FROM files WHERE directory_id = directories.directory_id) as file_count
FROM directories
ORDER BY path ASC
""";
try {
PreparedStatement ps = conn.prepareStatement(sql);
return ps.executeQuery();
} catch (SQLException e) {
throw new RuntimeException("Failed to fetch directories", e);
}
}
public ResultSet getDirectoryById(int directoryId) {
String sql = """
SELECT
directory_id,
path,
created_at,
(SELECT COUNT(*) FROM files WHERE directory_id = directories.directory_id) as file_count
FROM directories
WHERE directory_id = ?
""";
try {
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, directoryId);
return ps.executeQuery();
} catch (SQLException e) {
throw new RuntimeException("Failed to fetch directory", e);
}
}
public int createDirectory(String path) throws SQLException {
String sql = """
INSERT INTO directories (path)
VALUES (?)
ON CONFLICT (path) DO UPDATE SET path = EXCLUDED.path
RETURNING directory_id
""";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setString(1, path);
try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
return rs.getInt("directory_id");
}
throw new SQLException("Failed to get directory ID");
}
}
}
public boolean deleteFile(int fileId) throws SQLException {
String sql = """
DELETE FROM files
WHERE file_id = ?
""";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setInt(1, fileId);
int rowsAffected = ps.executeUpdate();
return rowsAffected > 0;
}
}
public boolean deleteDirectory(int directoryId) throws SQLException {
// Check if directory has files
String checkSql = """
SELECT COUNT(*) as file_count
FROM files
WHERE directory_id = ?
""";
try (PreparedStatement checkPs = conn.prepareStatement(checkSql)) {
checkPs.setInt(1, directoryId);
try (ResultSet rs = checkPs.executeQuery()) {
if (rs.next() && rs.getInt("file_count") > 0) {
throw new SQLException("Cannot delete directory: contains files");
}
}
}
if (directoryId == 1) {
throw new SQLException("Cannot delete root directory");
}
String deleteSql = """
DELETE FROM directories
WHERE directory_id = ?
""";
try (PreparedStatement deletePs = conn.prepareStatement(deleteSql)) {
deletePs.setInt(1, directoryId);
int rowsAffected = deletePs.executeUpdate();
return rowsAffected > 0;
}
}
}
|