use super::enums::{IndexAlgorithm, IndexType};
use super::names;
use crate::error::{Error, Result};
use crate::value::Value;
#[derive(Debug, Clone, PartialEq)]
pub struct Index {
pub name: String,
pub columns: Vec<String>,
pub kind: IndexType,
pub lengths: Vec<(String, i64)>,
pub orders: Vec<(String, String)>,
pub method: String,
pub operator_class: String,
pub collations: Vec<(String, String)>,
pub raw_columns: Vec<String>,
pub algorithm: Option<IndexAlgorithm>,
pub algorithm_args: Vec<Value>,
pub granularity: Option<i64>,
}
fn lookup<'a, T>(pairs: &'a [(String, T)], column: &str) -> Option<&'a T> {
pairs.iter().rev().find(|(c, _)| c == column).map(|(_, v)| v)
}
impl Index {
pub fn new(name: impl Into<String>, columns: Vec<String>, kind: IndexType) -> Self {
Index {
name: name.into(),
columns,
kind,
lengths: Vec::new(),
orders: Vec::new(),
method: String::new(),
operator_class: String::new(),
collations: Vec::new(),
raw_columns: Vec::new(),
algorithm: None,
algorithm_args: Vec::new(),
granularity: None,
}
}
pub fn validated(self) -> Result<Self> {
if self.algorithm.is_some() && !names::is_identifier(&self.name) {
return Err(Error::Validation(format!("Invalid index name: {}", self.name)));
}
if self.columns.is_empty() && self.raw_columns.is_empty() {
return Err(Error::Validation("Index requires at least one column.".into()));
}
if !self.method.is_empty() && !names::is_word(&self.method) {
return Err(Error::Validation(format!("Invalid index method: {}", self.method)));
}
if !self.operator_class.is_empty() && !names::is_dotted_word(&self.operator_class) {
return Err(Error::Validation(format!("Invalid operator class: {}", self.operator_class)));
}
for (_, collation) in &self.collations {
if !names::is_word(collation) {
return Err(Error::Validation(format!("Invalid collation: {collation}")));
}
}
if let Some(granularity) = self.granularity
&& granularity < 1
{
return Err(Error::Validation("Index granularity must be >= 1.".into()));
}
if let Some(algorithm) = self.algorithm
&& !self.algorithm_args.is_empty()
&& !algorithm.accepts_args()
{
return Err(Error::Validation(format!("{} does not accept algorithm arguments.", algorithm.as_str())));
}
Ok(self)
}
pub fn auto_name(prefix: &str, columns: &[String]) -> String {
let mut name = String::from(prefix);
for (i, column) in columns.iter().enumerate() {
if i > 0 {
name.push('_');
}
name.push_str(&names::sanitize(column));
}
name
}
pub fn length(&self, column: &str) -> Option<i64> {
lookup(&self.lengths, column).copied()
}
pub fn order(&self, column: &str) -> Option<&str> {
lookup(&self.orders, column).map(String::as_str)
}
pub fn collation(&self, column: &str) -> Option<&str> {
lookup(&self.collations, column).map(String::as_str)
}
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct IndexOptions {
pub unique: bool,
pub kind: Option<IndexType>,
pub method: String,
pub operator_class: String,
pub lengths: Vec<(String, i64)>,
pub orders: Vec<(String, String)>,
pub collations: Vec<(String, String)>,
pub raw_columns: Vec<String>,
pub concurrently: bool,
}
impl IndexOptions {
pub(crate) fn index(&self, name: &str, columns: &[&str]) -> Result<Index> {
let kind = if self.unique { IndexType::Unique } else { self.kind.unwrap_or(IndexType::Index) };
Index {
lengths: self.lengths.clone(),
orders: self.orders.clone(),
method: self.method.clone(),
operator_class: self.operator_class.clone(),
collations: self.collations.clone(),
raw_columns: self.raw_columns.clone(),
..Index::new(name, columns.iter().map(|c| (*c).to_owned()).collect(), kind)
}
.validated()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CheckConstraint {
pub name: String,
pub expression: String,
}
impl CheckConstraint {
pub fn new(name: impl Into<String>, expression: impl Into<String>) -> Result<Self> {
let name = name.into();
if !names::is_identifier(&name) {
return Err(Error::Validation(format!("Invalid check constraint name: {name}")));
}
Ok(CheckConstraint { name, expression: expression.into() })
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RenameColumn {
pub from: String,
pub to: String,
}
impl RenameColumn {
pub fn new(from: impl Into<String>, to: impl Into<String>) -> Self {
RenameColumn { from: from.into(), to: to.into() }
}
}