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
use crate::column::ColumnIndex;
use crate::error::Error;
use crate::ext::ustr::UStr;
use crate::mssql::{Mssql, MssqlArguments, MssqlColumn, MssqlTypeInfo};
use crate::statement::Statement;
use crate::HashMap;
use either::Either;
use std::borrow::Cow;
use std::sync::Arc;

#[derive(Debug, Clone)]
pub struct MssqlStatement<'q> {
    pub(crate) sql: Cow<'q, str>,
    pub(crate) metadata: Arc<MssqlStatementMetadata>,
}

#[derive(Debug, Default, Clone)]
pub(crate) struct MssqlStatementMetadata {
    pub(crate) columns: Vec<MssqlColumn>,
    pub(crate) column_names: HashMap<UStr, usize>,
}

impl<'q> Statement<'q> for MssqlStatement<'q> {
    type Database = Mssql;

    fn to_owned(&self) -> MssqlStatement<'static> {
        MssqlStatement::<'static> {
            sql: Cow::Owned(self.sql.clone().into_owned()),
            metadata: self.metadata.clone(),
        }
    }

    fn sql(&self) -> &str {
        &self.sql
    }

    fn parameters(&self) -> Option<Either<&[MssqlTypeInfo], usize>> {
        None
    }

    fn columns(&self) -> &[MssqlColumn] {
        &self.metadata.columns
    }

    impl_statement_query!(MssqlArguments);
}

impl ColumnIndex<MssqlStatement<'_>> for &'_ str {
    fn index(&self, statement: &MssqlStatement<'_>) -> Result<usize, Error> {
        statement
            .metadata
            .column_names
            .get(*self)
            .ok_or_else(|| Error::ColumnNotFound((*self).into()))
            .map(|v| *v)
    }
}

#[cfg(feature = "any")]
impl<'q> From<MssqlStatement<'q>> for crate::any::AnyStatement<'q> {
    #[inline]
    fn from(statement: MssqlStatement<'q>) -> Self {
        crate::any::AnyStatement::<'q> {
            columns: statement
                .metadata
                .columns
                .iter()
                .map(|col| col.clone().into())
                .collect(),
            column_names: std::sync::Arc::new(statement.metadata.column_names.clone()),
            parameters: None,
            sql: statement.sql,
        }
    }
}