64 lines
2.1 KiB
Java
64 lines
2.1 KiB
Java
package services;
|
|
|
|
import apis.DatabaseApi;
|
|
import data.dtos.QueryDTO;
|
|
import data.repos.QueryResultsRepository;
|
|
|
|
import java.sql.*;
|
|
|
|
/**
|
|
* Responsible for storing the active connection between the application and the SQL server.
|
|
* It creates the connection to the PostgreSQL server and provides a way to execute read queries and persist their results.
|
|
* It uses DatabaseApi class for performing read queries.
|
|
*/
|
|
public class DatabaseService {
|
|
private static final String url = "jdbc:postgresql://localhost:5432/lunatech_covid";
|
|
private static final String user = "postgres";
|
|
private static final String password = "postgres";
|
|
|
|
private final DatabaseApi databaseApi;
|
|
private final Connection connection;
|
|
|
|
public DatabaseService() {
|
|
connection = getConnection();
|
|
databaseApi = new DatabaseApi();
|
|
}
|
|
|
|
/**
|
|
* Fetches read-query results and packages them to persist them (and so frees the connection).
|
|
*
|
|
* @param queryDTO The query with its arguments.
|
|
* @return Persisting (non-lazy) results from executing the query.
|
|
*/
|
|
public QueryResultsRepository executeReadReportsEndpoint(QueryDTO queryDTO) throws SQLException {
|
|
final PreparedStatement resultStatement = databaseApi.performReadQuery(queryDTO, connection);
|
|
|
|
final QueryResultsRepository resultSets = new QueryResultsRepository(queryDTO.statement().description);
|
|
do {
|
|
final ResultSet resultSet = resultStatement.getResultSet();
|
|
resultSets.addResult(resultSet);
|
|
}
|
|
while (resultStatement.getMoreResults());
|
|
|
|
return resultSets;
|
|
}
|
|
|
|
/**
|
|
* Connect to the PostgreSQL database
|
|
*
|
|
* @return a Connection object
|
|
*/
|
|
private Connection getConnection() {
|
|
Connection connection = null;
|
|
try {
|
|
connection = DriverManager.getConnection(url, user, password);
|
|
System.out.println("Connected to the PostgreSQL server successfully.");
|
|
} catch (SQLException e) {
|
|
System.out.println("Unable to connect to PostgreSQL server.");
|
|
throw new RuntimeException();
|
|
}
|
|
|
|
return connection;
|
|
}
|
|
}
|