I am trying to test transaction management in codeigniter. Below method is a function in a model class. If update_user_company_id method returns false, wrapper method save_user_and_company also returns. In this case, because the method returns before it reaches to

$this->db->trans_complete();

call, changes made by save_company and delete_company_requests methods are rolled back. This is what I want.

But what I want to learn is that instead of calling

$this->db->rollback();

I directly return from method. Is this approach safe? Is there a possibility that I may encounter a lock or some other problem in the future?

function save_user_and_company($user, $company_request) {

    $result[STATU] = ERROR;
    $this->db->trans_start();

    $company = $this->companies_dao->save_company($company_request->company_name, $user->id);
    if (!$company) {
        $result[MESSAGE] = COMPANY_SAVE_ERROR;
        return $result;
    }

    $company_request_result = $this->company_requests_model->delete_company_requests($company_request->id);
    if (!$company_request_result) {
        $result[MESSAGE] = COMPANY_REQUEST_DELETE_ERROR;
        return $result;
    }

    $user_update = $this->users_dao->update_user_company_id($user->id, $company->id);
    if (!$user_update) {
        $result[MESSAGE] = USER_UPDATE_ERROR;
        return $result;
    }
    $this->db->trans_complete();

    $result[STATU] = SUCCESS;
    $result[MESSAGE] = SUCCESSFUL;
    return $result;
}

Thanks in advance!

1

There are 1 best solutions below

0
On

Did you try like this....

Following code returns TRUE if transaction completes successfully.Otherwise it rollback your transaction and returns FALSE.Hope it will help you a lot..

function save_user_and_company($user, $company_request) {

    $this->db->trans_begin(); //Begins your transaction

    //Performs the transaction operations
    $company = $this->companies_dao->save_company($company_request->company_name, $user->id);
    $company_request_result = $this->company_requests_model->delete_company_requests($company_request->id);
    $user_update = $this->users_dao->update_user_company_id($user->id, $company->id);

    //Check whether transaction fails

    if ($this->db->trans_status() === FALSE)
    {
      $this->db->trans_rollback();
      $status = FALSE;
    }
   else
    {
      $this->db->trans_commit();
      $status = TRUE;
    }

    return $status;
}