55 lines
2.4 KiB
Java
55 lines
2.4 KiB
Java
package apis;
|
|
|
|
import data.dtos.QueryDTO;
|
|
import org.postgresql.util.PSQLException;
|
|
|
|
import java.sql.*;
|
|
import java.util.Date;
|
|
|
|
/**
|
|
* The `DatabaseApi` class is a DAO that provides a way to communicate with the database to perform read operations and return the results.
|
|
* It contains a single method `performReadQuery()` that takes a `QueryDTO` and a `Connection` object as parameters and
|
|
* returns a `PreparedStatement` object. It throws `SQLException` in case of any SQL error or `IllegalArgumentException`
|
|
* in case of any missing argument or extra argument.
|
|
* <p>
|
|
* The class can be abstracted and implemented into constituent action-specific APIs when there is a need for more than a single READ action.
|
|
*/
|
|
public class DatabaseApi {
|
|
/**
|
|
* Creates and executes a PreparedStatement, given the QueryDTO.
|
|
* @param queryDTO The query in the form of the queryDTO
|
|
* @param connection SQL server connection
|
|
* @return The executed prepared statement, containing the results of the query
|
|
* @throws IllegalArgumentException in case of any missing argument or extra argument.
|
|
*/
|
|
public PreparedStatement performReadQuery(QueryDTO queryDTO, Connection connection) throws SQLException {
|
|
// Set template
|
|
PreparedStatement statement = connection.prepareStatement(queryDTO.statement().statementTemplate);
|
|
|
|
try {
|
|
// Add in arguments
|
|
for(int argIndex = 0; argIndex < queryDTO.templateArgs().length; argIndex++) {
|
|
final Object curentArg = queryDTO.templateArgs()[argIndex];
|
|
|
|
// parameter indexing starts at 1
|
|
if (curentArg instanceof Date)
|
|
statement.setDate(argIndex + 1, new java.sql.Date(((Date) curentArg).getTime()));
|
|
else
|
|
statement.setString(argIndex + 1, curentArg.toString());
|
|
|
|
}
|
|
|
|
statement.execute();
|
|
} catch (PSQLException e) {
|
|
if (e.getMessage().startsWith("No value specified for parameter"))
|
|
throw new IllegalArgumentException("The templates present in the query, were not correctly mapped to their replacement variables.");
|
|
else if (e.getMessage().startsWith("The column index is out of range:")) {
|
|
throw new IllegalArgumentException("Are you trying to supply replacement variables, when they are not needed?");
|
|
}
|
|
throw e;
|
|
}
|
|
|
|
return statement;
|
|
}
|
|
|
|
} |