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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
use std::{borrow::Cow, fmt};

use super::IndexOps;
use crate::{
    datamodel::attributes::FieldAttribute,
    value::{Constant, Function, Text},
};

/// Input parameters for a field in a model index definition.
#[derive(Debug, Clone)]
pub struct IndexFieldInput<'a> {
    pub(crate) name: Cow<'a, str>,
    pub(crate) sort_order: Option<Cow<'a, str>>,
    pub(crate) length: Option<u32>,
    pub(crate) ops: Option<IndexOps<'a>>,
}

impl<'a> IndexFieldInput<'a> {
    /// Create a new indexed field.
    ///
    /// ```ignore
    /// @@index([foobar])
    /// //       ^^^^^^ name
    /// ```
    pub fn new(name: impl Into<Cow<'a, str>>) -> Self {
        Self {
            name: name.into(),
            sort_order: None,
            length: None,
            ops: None,
        }
    }

    /// Define the sort order of the indexed field.
    ///
    /// ```ignore
    /// @@index([foobar(sort: Desc)])
    /// //                    ^^^^ here
    /// ```
    pub fn sort_order(&mut self, sort_order: impl Into<Cow<'a, str>>) {
        self.sort_order = Some(sort_order.into());
    }

    /// Define the length of the indexed field.
    ///
    /// ```ignore
    /// @@index([foobar(length: 32)])
    /// //                      ^^ here
    /// ```
    pub fn length(&mut self, length: u32) {
        self.length = Some(length);
    }

    /// Define index operators for the field.
    ///
    /// ```ignore
    /// @@index([foobar(ops: MinMaxFoobarOps), type: Brin])
    /// //                      ^^ here
    /// ```
    pub fn ops(&mut self, ops: IndexOps<'a>) {
        self.ops = Some(ops);
    }
}

impl<'a> From<IndexFieldInput<'a>> for Function<'a> {
    fn from(definition: IndexFieldInput<'a>) -> Self {
        let name: Vec<_> = definition
            .name
            .split('.')
            .map(|name| Constant::new_no_validate(Cow::Borrowed(name)))
            .map(|constant| constant.into_inner())
            .collect();

        let mut fun = Function::from(Constant::new_no_validate(Cow::Owned(name.join("."))));

        if let Some(length) = definition.length {
            fun.push_param(("length", Constant::new_no_validate(length)));
        }

        if let Some(sort_order) = definition.sort_order {
            fun.push_param(("sort", Constant::new_no_validate(sort_order)));
        }

        if let Some(ops) = definition.ops {
            fun.push_param(("ops", ops));
        }

        fun
    }
}

/// Options for a field-level unique attribute.
#[derive(Debug)]
pub struct UniqueFieldAttribute<'a>(FieldAttribute<'a>);

impl<'a> Default for UniqueFieldAttribute<'a> {
    fn default() -> Self {
        Self(FieldAttribute::new(Function::new("unique")))
    }
}

impl<'a> UniqueFieldAttribute<'a> {
    /// Define the sort order of the inline field index.
    ///
    /// ```ignore
    /// @unique(sort: Asc)
    /// //            ^^^ here
    /// ```
    pub fn sort_order(&mut self, value: impl Into<Cow<'a, str>>) {
        self.0.push_param(("sort", Constant::new_no_validate(value.into())));
    }

    /// Define the length of the inline field index.
    ///
    /// ```ignore
    /// @unique(length: 32)
    /// //              ^^ here
    /// ```
    pub fn length(&mut self, length: u32) {
        self.0.push_param(("length", Constant::new_no_validate(length)));
    }

    /// Define the length clustering of the inline field index.
    ///
    /// ```ignore
    /// @unique(clustered: true)
    /// //                 ^^^^ here
    /// ```
    pub fn clustered(&mut self, value: bool) {
        self.0.push_param(("clustered", Constant::new_no_validate(value)))
    }

    /// Define the constraint name.
    ///
    /// ```ignore
    /// @unique(map: "key_foo")
    /// //            ^^^^^^^ here
    /// ```
    pub fn map(&mut self, value: impl Into<Cow<'a, str>>) {
        self.0.push_param(("map", Text::new(value.into())))
    }
}

impl<'a> fmt::Display for UniqueFieldAttribute<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}