1use super::enums::{IndexAlgorithm, IndexType};
5use super::names;
6use crate::error::{Error, Result};
7use crate::value::Value;
8
9#[derive(Debug, Clone, PartialEq)]
19pub struct Index {
20 pub name: String,
22 pub columns: Vec<String>,
24 pub kind: IndexType,
26 pub lengths: Vec<(String, i64)>,
28 pub orders: Vec<(String, String)>,
30 pub method: String,
32 pub operator_class: String,
34 pub collations: Vec<(String, String)>,
36 pub raw_columns: Vec<String>,
38 pub algorithm: Option<IndexAlgorithm>,
40 pub algorithm_args: Vec<Value>,
42 pub granularity: Option<i64>,
44}
45
46fn lookup<'a, T>(pairs: &'a [(String, T)], column: &str) -> Option<&'a T> {
47 pairs.iter().rev().find(|(c, _)| c == column).map(|(_, v)| v)
48}
49
50impl Index {
51 pub fn new(name: impl Into<String>, columns: Vec<String>, kind: IndexType) -> Self {
54 Index {
55 name: name.into(),
56 columns,
57 kind,
58 lengths: Vec::new(),
59 orders: Vec::new(),
60 method: String::new(),
61 operator_class: String::new(),
62 collations: Vec::new(),
63 raw_columns: Vec::new(),
64 algorithm: None,
65 algorithm_args: Vec::new(),
66 granularity: None,
67 }
68 }
69
70 pub fn validated(self) -> Result<Self> {
78 if self.algorithm.is_some() && !names::is_identifier(&self.name) {
79 return Err(Error::Validation(format!("Invalid index name: {}", self.name)));
80 }
81 if self.columns.is_empty() && self.raw_columns.is_empty() {
82 return Err(Error::Validation("Index requires at least one column.".into()));
83 }
84 if !self.method.is_empty() && !names::is_word(&self.method) {
85 return Err(Error::Validation(format!("Invalid index method: {}", self.method)));
86 }
87 if !self.operator_class.is_empty() && !names::is_dotted_word(&self.operator_class) {
88 return Err(Error::Validation(format!("Invalid operator class: {}", self.operator_class)));
89 }
90 for (_, collation) in &self.collations {
91 if !names::is_word(collation) {
92 return Err(Error::Validation(format!("Invalid collation: {collation}")));
93 }
94 }
95 if let Some(granularity) = self.granularity
96 && granularity < 1
97 {
98 return Err(Error::Validation("Index granularity must be >= 1.".into()));
99 }
100 if let Some(algorithm) = self.algorithm
101 && !self.algorithm_args.is_empty()
102 && !algorithm.accepts_args()
103 {
104 return Err(Error::Validation(format!("{} does not accept algorithm arguments.", algorithm.as_str())));
105 }
106 Ok(self)
107 }
108
109 pub fn auto_name(prefix: &str, columns: &[String]) -> String {
115 let mut name = String::from(prefix);
116 for (i, column) in columns.iter().enumerate() {
117 if i > 0 {
118 name.push('_');
119 }
120 name.push_str(&names::sanitize(column));
121 }
122 name
123 }
124
125 pub fn length(&self, column: &str) -> Option<i64> {
127 lookup(&self.lengths, column).copied()
128 }
129
130 pub fn order(&self, column: &str) -> Option<&str> {
132 lookup(&self.orders, column).map(String::as_str)
133 }
134
135 pub fn collation(&self, column: &str) -> Option<&str> {
137 lookup(&self.collations, column).map(String::as_str)
138 }
139}
140
141#[derive(Debug, Clone, Default, PartialEq)]
145pub struct IndexOptions {
146 pub unique: bool,
148 pub kind: Option<IndexType>,
151 pub method: String,
153 pub operator_class: String,
155 pub lengths: Vec<(String, i64)>,
157 pub orders: Vec<(String, String)>,
159 pub collations: Vec<(String, String)>,
161 pub raw_columns: Vec<String>,
163 pub concurrently: bool,
165}
166
167impl IndexOptions {
168 pub(crate) fn index(&self, name: &str, columns: &[&str]) -> Result<Index> {
171 let kind = if self.unique { IndexType::Unique } else { self.kind.unwrap_or(IndexType::Index) };
172 Index {
173 lengths: self.lengths.clone(),
174 orders: self.orders.clone(),
175 method: self.method.clone(),
176 operator_class: self.operator_class.clone(),
177 collations: self.collations.clone(),
178 raw_columns: self.raw_columns.clone(),
179 ..Index::new(name, columns.iter().map(|c| (*c).to_owned()).collect(), kind)
180 }
181 .validated()
182 }
183}
184
185#[derive(Debug, Clone, PartialEq, Eq)]
189pub struct CheckConstraint {
190 pub name: String,
192 pub expression: String,
194}
195
196impl CheckConstraint {
197 pub fn new(name: impl Into<String>, expression: impl Into<String>) -> Result<Self> {
202 let name = name.into();
203 if !names::is_identifier(&name) {
204 return Err(Error::Validation(format!("Invalid check constraint name: {name}")));
205 }
206 Ok(CheckConstraint { name, expression: expression.into() })
207 }
208}
209
210#[derive(Debug, Clone, PartialEq, Eq)]
214pub struct RenameColumn {
215 pub from: String,
217 pub to: String,
219}
220
221impl RenameColumn {
222 pub fn new(from: impl Into<String>, to: impl Into<String>) -> Self {
224 RenameColumn { from: from.into(), to: to.into() }
225 }
226}