use crate::builders::traits::{
ConditionalBuilder, InspectableBuilder, SchemaBuilder, ValidatableBuilder,
};
use crate::builders::validation::BuilderValidationError;
use anyhow::Result;
#[derive(Debug, Clone)]
pub struct InformationSchemaBuilder {
table: InformationSchemaTable,
select_columns: Vec<String>,
where_conditions: Vec<WhereCondition>,
order_by: Vec<String>,
limit: Option<usize>,
offset: Option<usize>,
}
#[derive(Debug, Clone, PartialEq)]
pub enum InformationSchemaTable {
Schemata,
Tables,
Columns,
Indexes,
Constraints,
Functions,
Procedures,
Triggers,
Views,
Sequences,
UserDefinedTypes,
Routines,
}
#[derive(Debug, Clone)]
pub enum WhereCondition {
Equals(String, String),
In(String, Vec<String>),
Like(String, String),
NotNull(String),
IsNull(String),
Custom(String),
}
impl InformationSchemaBuilder {
pub fn new() -> Self {
Self {
table: InformationSchemaTable::Schemata,
select_columns: Vec::new(),
where_conditions: Vec::new(),
order_by: Vec::new(),
limit: None,
offset: None,
}
}
pub fn table(mut self, table: InformationSchemaTable) -> Self {
self.table = table;
self
}
pub fn select_column(mut self, column: &str) -> Self {
self.select_columns.push(column.to_string());
self
}
pub fn select_columns(mut self, columns: &[&str]) -> Self {
self.select_columns
.extend(columns.iter().map(|s| s.to_string()));
self
}
pub fn where_condition(mut self, condition: WhereCondition) -> Self {
self.where_conditions.push(condition);
self
}
pub fn where_equals(mut self, column: &str, value: &str) -> Self {
self.where_conditions.push(WhereCondition::Equals(
column.to_string(),
value.to_string(),
));
self
}
pub fn where_in(mut self, column: &str, values: &[&str]) -> Self {
self.where_conditions.push(WhereCondition::In(
column.to_string(),
values.iter().map(|s| s.to_string()).collect(),
));
self
}
pub fn where_like(mut self, column: &str, pattern: &str) -> Self {
self.where_conditions.push(WhereCondition::Like(
column.to_string(),
pattern.to_string(),
));
self
}
pub fn where_not_null(mut self, column: &str) -> Self {
self.where_conditions
.push(WhereCondition::NotNull(column.to_string()));
self
}
pub fn where_is_null(mut self, column: &str) -> Self {
self.where_conditions
.push(WhereCondition::IsNull(column.to_string()));
self
}
pub fn where_custom(mut self, condition: &str) -> Self {
self.where_conditions
.push(WhereCondition::Custom(condition.to_string()));
self
}
pub fn order_by(mut self, column: &str) -> Self {
self.order_by.push(column.to_string());
self
}
pub fn order_by_desc(mut self, column: &str) -> Self {
self.order_by.push(format!("{} DESC", column));
self
}
pub fn limit(mut self, limit: usize) -> Self {
self.limit = Some(limit);
self
}
pub fn offset(mut self, offset: usize) -> Self {
self.offset = Some(offset);
self
}
pub fn to_sql(&self) -> String {
let mut sql = String::from("SELECT ");
if self.select_columns.is_empty() {
sql.push('*');
} else {
sql.push_str(&self.select_columns.join(", "));
}
sql.push_str(" FROM information_schema.");
sql.push_str(&self.table.to_string());
if !self.where_conditions.is_empty() {
sql.push_str(" WHERE ");
let conditions: Vec<String> = self
.where_conditions
.iter()
.map(|cond| self.format_condition(cond))
.collect();
sql.push_str(&conditions.join(" AND "));
}
if !self.order_by.is_empty() {
sql.push_str(" ORDER BY ");
sql.push_str(&self.order_by.join(", "));
}
if let Some(limit) = self.limit {
sql.push_str(&format!(" LIMIT {}", limit));
}
if let Some(offset) = self.offset {
sql.push_str(&format!(" OFFSET {}", offset));
}
sql
}
fn format_condition(&self, condition: &WhereCondition) -> String {
match condition {
WhereCondition::Equals(column, value) => {
format!("{} = '{}'", column, value)
}
WhereCondition::In(column, values) => {
let values_str = values
.iter()
.map(|v| format!("'{}'", v))
.collect::<Vec<_>>()
.join(", ");
format!("{} IN ({})", column, values_str)
}
WhereCondition::Like(column, pattern) => {
format!("{} LIKE '{}'", column, pattern)
}
WhereCondition::NotNull(column) => {
format!("{} IS NOT NULL", column)
}
WhereCondition::IsNull(column) => {
format!("{} IS NULL", column)
}
WhereCondition::Custom(condition) => condition.clone(),
}
}
}
impl InformationSchemaTable {
pub fn to_string(&self) -> String {
match self {
InformationSchemaTable::Schemata => "schemata",
InformationSchemaTable::Tables => "tables",
InformationSchemaTable::Columns => "columns",
InformationSchemaTable::Indexes => "statistics",
InformationSchemaTable::Constraints => "table_constraints",
InformationSchemaTable::Functions => "routines",
InformationSchemaTable::Procedures => "routines",
InformationSchemaTable::Triggers => "triggers",
InformationSchemaTable::Views => "views",
InformationSchemaTable::Sequences => "sequences",
InformationSchemaTable::UserDefinedTypes => "user_defined_types",
InformationSchemaTable::Routines => "routines",
}
.to_string()
}
}
impl SchemaBuilder for InformationSchemaBuilder {
type Output = String;
type Error = BuilderValidationError;
fn build(self) -> Result<Self::Output, Self::Error> {
if !self.is_valid() {
let errors = self.validation_errors();
return Err(BuilderValidationError::Generic(format!(
"Validation failed: {}",
errors.join(", ")
)));
}
Ok(self.to_sql())
}
}
impl ValidatableBuilder for InformationSchemaBuilder {
fn is_valid(&self) -> bool {
!self.select_columns.is_empty() || self.table == InformationSchemaTable::Schemata
}
fn validation_errors(&self) -> Vec<String> {
let mut errors = Vec::new();
if self.select_columns.is_empty() && self.table != InformationSchemaTable::Schemata {
errors.push("No columns selected".to_string());
}
errors
}
}
impl ConditionalBuilder for InformationSchemaBuilder {
fn when<F>(mut self, condition: bool, config_fn: F) -> Self
where
F: FnOnce(&mut Self),
{
if condition {
config_fn(&mut self);
}
self
}
}
impl InspectableBuilder for InformationSchemaBuilder {
fn debug_info(&self) -> String {
format!(
"InformationSchemaBuilder {{ table: {:?}, columns: {:?}, conditions: {} }}",
self.table,
self.select_columns,
self.where_conditions.len()
)
}
fn summary(&self) -> String {
format!(
"Query {} with {} columns and {} conditions",
self.table.to_string(),
self.select_columns.len(),
self.where_conditions.len()
)
}
}
pub fn information_schema() -> InformationSchemaBuilder {
InformationSchemaBuilder::new()
}
pub fn schemas() -> InformationSchemaBuilder {
InformationSchemaBuilder::new()
.table(InformationSchemaTable::Schemata)
.select_column("schema_name")
}
pub fn tables() -> InformationSchemaBuilder {
InformationSchemaBuilder::new()
.table(InformationSchemaTable::Tables)
.select_columns(&["table_schema", "table_name"])
}
pub fn columns() -> InformationSchemaBuilder {
InformationSchemaBuilder::new()
.table(InformationSchemaTable::Columns)
.select_columns(&["table_schema", "table_name", "column_name", "data_type"])
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_schema_query() {
let query = schemas().where_in("schema_name", &["auth", "app"]).to_sql();
assert_eq!(
query,
"SELECT schema_name FROM information_schema.schemata WHERE schema_name IN ('auth', 'app')"
);
}
#[test]
fn test_tables_query() {
let query = tables()
.where_equals("table_schema", "auth")
.order_by("table_name")
.to_sql();
assert_eq!(
query,
"SELECT table_schema, table_name FROM information_schema.tables WHERE table_schema = 'auth' ORDER BY table_name"
);
}
#[test]
fn test_columns_query() {
let query = columns()
.where_equals("table_schema", "auth")
.where_equals("table_name", "users")
.to_sql();
assert_eq!(
query,
"SELECT table_schema, table_name, column_name, data_type FROM information_schema.columns WHERE table_schema = 'auth' AND table_name = 'users'"
);
}
}