package io.trygvis.queue; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Collections; import java.util.Date; import java.util.List; import static java.util.Arrays.asList; import static org.springframework.transaction.annotation.Propagation.MANDATORY; @Component public class TaskDao { @Autowired private JdbcTemplate jdbcTemplate; @Transactional(propagation = MANDATORY) public long insert(String queue, Date scheduled, String arguments) { jdbcTemplate.update("INSERT INTO task(id, run_count, queue, scheduled, arguments) " + "VALUES(nextval('task_seq'), 0, ?, ?, ?)", queue, scheduled, arguments); return jdbcTemplate.queryForObject("SELECT currval('task_seq')", Long.class); } @Transactional(propagation = MANDATORY) public Task findById(long id) { return jdbcTemplate.queryForObject("SELECT " + TaskRowMapper.fields + " FROM task WHERE id=?", new TaskRowMapper(), id); } @Transactional(propagation = MANDATORY) public List findByNameAndCompletedIsNull(String name) { return jdbcTemplate.query("SELECT " + TaskRowMapper.fields + " FROM task WHERE queue=? AND completed IS NULL", new TaskRowMapper(), name); } @Transactional(propagation = MANDATORY) public void update(Task task) { jdbcTemplate.update("UPDATE task SET scheduled=?, last_run=?, run_count=?, completed=? WHERE id=?", task.scheduled, task.lastRun, task.runCount, task.completed, task.id); } private class TaskRowMapper implements RowMapper { public static final String fields = "id, queue, scheduled, last_run, run_count, completed, arguments"; public Task mapRow(ResultSet rs, int rowNum) throws SQLException { String arguments = rs.getString(7); return new Task( rs.getLong(1), rs.getString(2), rs.getTimestamp(3), rs.getTimestamp(4), rs.getInt(5), rs.getTimestamp(6), arguments != null ? asList(arguments.split(" ")) : Collections.emptyList()); } } }