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
77
78
79
80
use crate::cassandra::data_type::ConstDataType;

use crate::cassandra::iterator::FieldIterator;
use crate::cassandra::util::{Protected, ProtectedInner};
use crate::cassandra::value::Value;
use crate::cassandra_sys::cass_column_meta_data_type;
use crate::cassandra_sys::cass_column_meta_field_by_name_n;
use crate::cassandra_sys::cass_column_meta_name;
use crate::cassandra_sys::cass_column_meta_type;
use crate::cassandra_sys::cass_iterator_fields_from_column_meta;
use crate::cassandra_sys::CassColumnMeta as _CassColumnMeta;
use crate::cassandra_sys::CassColumnType as _CassColumnType;

use std::marker::PhantomData;
use std::os::raw::c_char;
use std::slice;
use std::str;

/// Column metadata
//
// Borrowed immutably.
#[derive(Debug)]
pub struct ColumnMeta<'a>(*const _CassColumnMeta, PhantomData<&'a _CassColumnMeta>);

impl ProtectedInner<*const _CassColumnMeta> for ColumnMeta<'_> {
    fn inner(&self) -> *const _CassColumnMeta {
        self.0
    }
}

impl Protected<*const _CassColumnMeta> for ColumnMeta<'_> {
    fn build(inner: *const _CassColumnMeta) -> Self {
        if inner.is_null() {
            panic!("Unexpected null pointer")
        };
        ColumnMeta(inner, PhantomData)
    }
}

impl<'a> ColumnMeta<'a> {
    /// returns an iterator over the fields of this column
    pub fn field_iter(&self) -> FieldIterator<'a> {
        unsafe { FieldIterator::build(cass_iterator_fields_from_column_meta(self.0)) }
    }

    /// Gets the name of the column.
    pub fn name(&self) -> String {
        let mut name = std::ptr::null();
        let mut name_length = 0;
        unsafe {
            cass_column_meta_name(self.0, &mut name, &mut name_length);
            let slice = slice::from_raw_parts(name as *const u8, name_length);
            str::from_utf8(slice).expect("must be utf8").to_owned()
        }
    }

    /// Gets the type of the column.
    pub fn get_type(&self) -> _CassColumnType {
        unsafe { cass_column_meta_type(self.0) }
    }

    /// Gets the data type of the column.
    pub fn data_type(&self) -> ConstDataType<'a> {
        unsafe { ConstDataType::build(cass_column_meta_data_type(self.0)) }
    }

    /// Gets a metadata field for the provided name. Metadata fields allow direct
    /// access to the column data found in the underlying "columns" metadata table.
    pub fn field_by_name(&self, name: &str) -> Option<Value<'a>> {
        unsafe {
            let name_ptr = name.as_ptr() as *const c_char;
            let field = cass_column_meta_field_by_name_n(self.0, name_ptr, name.len());
            if field.is_null() {
                None
            } else {
                Some(Value::build(field))
            }
        }
    }
}