lib.rs 1.9 KB
Newer Older
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 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
#![allow(unused)]
#![allow(non_camel_case_types)]

use std::os::raw::c_void;
use std::os::raw::c_char;
use std::os::raw::c_int;
use std::ffi::CString;
use std::ffi::CStr;

mod bindings;
use bindings::*;

pub struct Tdengine {
    conn: *mut c_void,
}

/// - **TODO**:  doc
impl Tdengine {

    //! - **TODO**: implement default param.
    //! 
    //! > refer to https://stackoverflow.com/questions/24047686/default-function-arguments-in-rust
    pub fn new(ip: &str, username: &str, passwd: &str, db: &str, port: i32) -> Result<Tdengine, &'static str> {
        unsafe {
            taos_init();
            let mut conn = taos_connect(str_into_raw(ip),
                                        str_into_raw(username),
                                        str_into_raw(passwd),
                                        str_into_raw(db),
                                        port as c_int);
            if conn.is_null() {
                Err("connect error")
            } else {
                println!("connected to {}:{} user:{}, db:{}", ip, port, username, db);
                Ok(Tdengine {conn})
            }
        }
    }

    // - **TODO**: check error code
    pub fn query(self: &Tdengine, s: &str) {
        unsafe {
            if taos_query(self.conn, str_into_raw(s)) == 0 {
                println!("query '{}' ok", s);
            } else {
                println!("query '{}' error: {}", s, raw_into_str(taos_errstr(self.conn)));
            }
        }
    }
}

impl Drop for Tdengine {
    fn drop(&mut self) {
        unsafe {taos_close(self.conn);}
    }
}

fn str_into_raw(s: &str) -> *mut c_char {
    if s.is_empty() {
        0 as *mut c_char
    } else {
        CString::new(s).unwrap().into_raw()
    }
}

fn raw_into_str<'a>(raw: *mut c_char) -> &'static str {
    unsafe {CStr::from_ptr(raw).to_str().unwrap()}
}

#[cfg(test)]
mod tests {
    #[test]
    fn it_works() {
        assert_eq!(2 + 2, 4);
    }
}