AltitudeBot/src/main/java/com/alttd/database/queries/QueriesStaffJoinDate.java
Teriuihi f2864ade8a Add UPSERT behavior to setJoinDate query
Modified the SQL query in the setJoinDate method to use "ON DUPLICATE KEY UPDATE" for updating the date if the userId already exists. This ensures that duplicate entries are handled correctly by updating the existing record rather than creating a new one.
2024-08-26 19:15:03 +02:00

65 lines
2.3 KiB
Java

package com.alttd.database.queries;
import com.alttd.DTO.JoinDate;
import com.alttd.database.Database;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
public class QueriesStaffJoinDate {
public static Optional<JoinDate> getJoinDate(long userId) {
String sql = "SELECT date FROM staff_join_date WHERE user_id = ?";
try (PreparedStatement preparedStatement = Database.getDatabase().getConnection().prepareStatement(sql)) {
preparedStatement.setLong(1, userId);
ResultSet resultSet = preparedStatement.executeQuery();
if (!resultSet.next())
return Optional.empty();
Instant date = Instant.ofEpochMilli(resultSet.getLong("date"));
if (date == null) {
return Optional.empty();
}
return Optional.of(new JoinDate(userId, date));
} catch (SQLException exception) {
exception.printStackTrace();
return Optional.empty();
}
}
public static void setJoinDate(long userId, Instant date) {
String sql = "INSERT INTO staff_join_date (user_id, date) VALUES (?, ?) ON DUPLICATE KEY UPDATE date = VALUES(date)";
try (PreparedStatement preparedStatement = Database.getDatabase().getConnection().prepareStatement(sql)) {
preparedStatement.setLong(1, userId);
preparedStatement.setLong(2, date.toEpochMilli());
preparedStatement.executeUpdate();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public static List<JoinDate> getAllJoinDates() {
String sql = "SELECT * FROM staff_join_date";
try (PreparedStatement preparedStatement = Database.getDatabase().getConnection().prepareStatement(sql)) {
ResultSet resultSet = preparedStatement.executeQuery();
List<JoinDate> joinDates = new ArrayList<>();
while (resultSet.next())
joinDates.add(new JoinDate(resultSet.getLong("user_id"), Instant.ofEpochMilli(resultSet.getLong("date"))));
return joinDates;
} catch (SQLException exception) {
exception.printStackTrace();
return null;
}
}
}