@Test
public void updateWorkflowInstance() throws InterruptedException {

  WorkflowInstance i1 = constructWorkflowInstanceBuilder().setStatus(created).build();
  long id = dao.insertWorkflowInstance(i1);
  List<Long> ids = dao.pollNextWorkflowInstanceIds(1);
  assertThat(ids, contains(id));
  DateTime started = now();
  final WorkflowInstance i2 = new WorkflowInstance.Builder(
      dao.getWorkflowInstance(id, EnumSet.of(CURRENT_STATE_VARIABLES), null)).setStatus(inProgress).setState("updateState")
          .setStateText("update text").setStartedIfNotSet(started).build();
  final WorkflowInstance polledInstance = dao.getWorkflowInstance(id, emptySet(), null);
  assertThat(polledInstance.status, equalTo(executing));
  final DateTime originalModifiedTime = polledInstance.modified;
  sleep(1);
  WorkflowInstanceAction action = constructActionBuilder(id).build();
  WorkflowInstance newWorkflow = constructWorkflowInstanceBuilder().setBusinessKey("newKey").build();
  dao.updateWorkflowInstanceAfterExecution(i2, action, noChildWorkflows, asList(newWorkflow), false);
  jdbc.query("select * from nflow_workflow where id = " + id, new RowCallbackHandler() {
    @Override
    public void processRow(ResultSet rs) throws SQLException {
      assertThat(rs.getString("status"), equalTo(inProgress.name()));
      assertThat(rs.getString("state"), equalTo(i2.state));
      assertThat(rs.getString("state_text"), equalTo(i2.stateText));
      assertThat(rs.getTimestamp("next_activation").getTime(), equalTo(i2.nextActivation.toDate().getTime()));
      assertThat(rs.getInt("executor_id") != 0, equalTo(i2.status == executing));
      assertThat(rs.getTimestamp("modified").getTime(), greaterThan(originalModifiedTime.getMillis()));
      assertThat(rs.getTimestamp("started").getTime(), is(equalTo(started.getMillis())));
    }
  });
  QueryWorkflowInstances query = new QueryWorkflowInstances.Builder().setBusinessKey("newKey").build();
  List<WorkflowInstance> instances = dao.queryWorkflowInstances(query);
  assertThat(instances.size(), is(1));
  for (WorkflowInstance instance : instances) {
    assertThat(instance.parentWorkflowId, is(nullValue()));
    assertThat(instance.businessKey, is("newKey"));
  }
}