1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#[derive(Clone, Debug)]
pub struct Cancel {
    cancel: *mut pq_sys::pg_cancel,
}

impl Cancel {
    /**
     * Requests that the server abandon processing of the current command.
     *
     * See [PQcancel](https://www.postgresql.org/docs/current/libpq-cancel.html#LIBPQ-PQCANCEL).
     */
    pub fn request(&self) -> std::result::Result<(), String> {
        log::debug!("Canceling");

        let capacity = 256;
        let c_error = crate::ffi::new_cstring(capacity);
        let ptr_error = c_error.into_raw();

        let sucess = unsafe { pq_sys::PQcancel(self.into(), ptr_error, capacity as i32) };
        let error = crate::ffi::from_raw(ptr_error);

        if sucess == 1 {
            Ok(())
        } else {
            Err(error)
        }
    }
}

#[doc(hidden)]
impl From<*mut pq_sys::pg_cancel> for Cancel {
    fn from(cancel: *mut pq_sys::pg_cancel) -> Self {
        Self { cancel }
    }
}

#[doc(hidden)]
impl Into<*mut pq_sys::pg_cancel> for &Cancel {
    fn into(self) -> *mut pq_sys::pg_cancel {
        self.cancel
    }
}

impl Drop for Cancel {
    fn drop(&mut self) {
        unsafe {
            pq_sys::PQfreeCancel(self.cancel);
        }
    }
}