pub mod alias;
pub mod clean_projection;
pub mod composite_field;
pub mod expr;
pub mod hybrid_expr;
pub mod join;
pub mod procedure_call;
pub mod projection;
pub mod typed_column;
pub mod typed_query;
use crate::common::qualified_name;
use crate::schema::{Event, IndexMeta, StoredFunction, StoredProcedure, Table, View};
use std::borrow::Cow;
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use std::sync::{Arc, OnceLock, RwLock};
pub use clean_projection::{AutoProjection, CleanProjectedQuery, CleanRow};
pub use composite_field::{CompositeField, CompositeFieldBuilder, CompositeFieldRef};
pub use procedure_call::{
call_function, call_procedure, FunctionCall, ParameterBinding, ProcedureCall,
};
pub use projection::{ProjectedQuery, ProjectionTarget, TypedRow};
pub use typed_column::{ColumnSelector, OrderBy, TypedColumn, WhereCondition};
pub use typed_query::{TypedQuery, TypedQueryBuilder};
#[derive(Debug, Clone)]
pub enum Source {
Table(Table),
View(View),
Event(Event),
Procedure(StoredProcedure),
Function(StoredFunction),
}
impl Source {
pub fn name(&self) -> &str {
match self {
Source::Table(table) => &table.name,
Source::View(view) => &view.name,
Source::Event(event) => &event.name,
Source::Procedure(proc) => &proc.name,
Source::Function(func) => &func.name,
}
}
pub fn schema(&self) -> Option<&str> {
match self {
Source::Table(table) => table.schema.as_deref(),
Source::View(view) => view.schema.as_deref(),
Source::Event(event) => event.schema.as_deref(),
Source::Procedure(proc) => proc.schema.as_deref(),
Source::Function(func) => func.schema.as_deref(),
}
}
pub fn is_materialized(&self) -> bool {
match self {
Source::Table(_) => false,
Source::View(view) => view.materialized,
Source::Event(_) => false,
Source::Procedure(_) => false,
Source::Function(_) => false,
}
}
pub fn qualified_name(&self) -> String {
qualified_name(self.schema(), self.name())
}
pub fn from_table(table: Table) -> Self {
Source::Table(table)
}
pub fn from_view(view: View) -> Self {
Source::View(view)
}
pub fn from_event(event: Event) -> Self {
Source::Event(event)
}
pub fn from_procedure(procedure: StoredProcedure) -> Self {
Source::Procedure(procedure)
}
pub fn from_function(function: StoredFunction) -> Self {
Source::Function(function)
}
}
#[derive(Debug)]
struct QueryCache {
cache: RwLock<HashMap<u64, String>>,
}
impl QueryCache {
fn new() -> Self {
Self {
cache: RwLock::new(HashMap::new()),
}
}
fn get(&self, hash: u64) -> Option<String> {
self.cache
.read()
.ok()
.and_then(|cache| cache.get(&hash).cloned())
}
fn insert(&self, hash: u64, sql: String) {
if let Ok(mut cache) = self.cache.write() {
if cache.len() > 1000 {
let keys: Vec<u64> = cache.keys().cloned().take(100).collect();
for key in keys {
cache.remove(&key);
}
}
cache.insert(hash, sql);
}
}
fn stats(&self) -> (usize, usize) {
if let Ok(cache) = self.cache.read() {
(cache.len(), 1000) } else {
(0, 0)
}
}
}
static QUERY_CACHE: OnceLock<Arc<QueryCache>> = OnceLock::new();
#[derive(Debug, Clone)]
pub struct IndexOptimizer {
available_indexes: Vec<IndexMeta>,
}
impl IndexOptimizer {
pub fn new(available_indexes: Vec<IndexMeta>) -> Self {
Self { available_indexes }
}
pub fn find_best_index(
&self,
where_conditions: &[String],
table_name: &str,
) -> Option<&IndexMeta> {
let table_indexes: Vec<&IndexMeta> = self
.available_indexes
.iter()
.filter(|idx| idx.table == table_name)
.collect();
if table_indexes.is_empty() {
return None;
}
let mut best_index = None;
let mut best_score = 0;
for index in table_indexes {
let score = self.score_index_for_conditions(index, where_conditions);
if score > best_score {
best_score = score;
best_index = Some(index);
}
}
best_index
}
fn score_index_for_conditions(&self, index: &IndexMeta, conditions: &[String]) -> usize {
let mut score = 0;
for condition in conditions {
for column in index.columns {
if condition.contains(column) {
score += 1;
}
}
}
if index.unique {
score += 2;
}
if matches!(index.index_type, crate::schema::IndexType::BTree) {
score += 1;
}
score
}
pub fn generate_index_hints(
&self,
table_name: &str,
where_conditions: &[String],
) -> Option<String> {
if let Some(index) = self.find_best_index(where_conditions, table_name) {
Some(format!("/* Use index: {} */", index.name))
} else {
None
}
}
pub fn can_use_index(&self, table_name: &str, columns: &[String]) -> bool {
self.available_indexes.iter().any(|idx| {
idx.table == table_name
&& columns
.iter()
.any(|col| idx.columns.contains(&col.as_str()))
})
}
}
#[derive(Debug, Clone, Hash)]
pub enum JoinType {
Inner,
Left,
Right,
Full,
}
#[derive(Debug, Clone)]
pub struct JoinClause {
pub join_type: JoinType,
pub target: Source,
pub condition: String,
}
impl Hash for JoinClause {
fn hash<H: Hasher>(&self, state: &mut H) {
self.join_type.hash(state);
self.target.name().hash(state);
self.condition.hash(state);
}
}
#[derive(Debug, Clone)]
pub struct Query {
pub from_source: Option<Source>,
pub select_columns: Vec<String>,
pub joins: Vec<JoinClause>,
pub where_clause: Option<String>,
pub group_by: Vec<String>,
pub having_clause: Option<String>,
pub order_by: Vec<String>,
pub limit: Option<usize>,
pub offset: Option<usize>,
pub index_optimizer: Option<IndexOptimizer>,
}
impl Hash for Query {
fn hash<H: Hasher>(&self, state: &mut H) {
if let Some(ref source) = self.from_source {
source.name().hash(state);
}
self.select_columns.hash(state);
self.joins.len().hash(state);
for join in &self.joins {
join.join_type.hash(state);
join.target.name().hash(state);
join.condition.hash(state);
}
self.where_clause.hash(state);
self.group_by.hash(state);
self.having_clause.hash(state);
self.order_by.hash(state);
self.limit.hash(state);
self.offset.hash(state);
}
}
impl Query {
pub fn new() -> Self {
Self {
from_source: None,
select_columns: Vec::new(),
joins: Vec::new(),
where_clause: None,
group_by: Vec::new(),
having_clause: None,
order_by: Vec::new(),
limit: None,
offset: None,
index_optimizer: None,
}
}
pub fn from(mut self, source: Source) -> Self {
self.from_source = Some(source);
self
}
pub fn from_table(mut self, table: Table) -> Self {
self.from_source = Some(Source::Table(table));
self
}
pub fn from_table_name(mut self, table_name: impl Into<String>) -> Self {
self.from_source = Some(Source::Table(Table::new(table_name)));
self
}
pub fn from_view(mut self, view: View) -> Self {
self.from_source = Some(Source::View(view));
self
}
pub fn call_procedure(mut self, procedure: StoredProcedure) -> Self {
self.from_source = Some(Source::Procedure(procedure));
self
}
pub fn call_function(mut self, function: StoredFunction) -> Self {
self.from_source = Some(Source::Function(function));
self
}
pub fn select_columns(mut self, columns: Vec<String>) -> Self {
self.select_columns = columns;
self
}
pub fn select_columns_str(mut self, columns: &[&str]) -> Self {
self.select_columns = columns.iter().map(|s| s.to_string()).collect();
self
}
pub fn filter(mut self, where_clause: impl Into<String>) -> Self {
self.where_clause = Some(where_clause.into());
self
}
pub fn filter_composite_field(mut self, field_ref: CompositeFieldRef) -> Self {
let condition = field_ref.sql_expression;
if let Some(existing) = self.where_clause {
self.where_clause = Some(format!("({}) AND ({})", existing, condition));
} else {
self.where_clause = Some(condition);
}
self
}
pub fn or_filter_composite_field(mut self, field_ref: CompositeFieldRef) -> Self {
let condition = field_ref.sql_expression;
if let Some(existing) = self.where_clause {
self.where_clause = Some(format!("({}) OR ({})", existing, condition));
} else {
self.where_clause = Some(condition);
}
self
}
pub fn order_by(mut self, column: impl Into<String>) -> Self {
self.order_by.push(column.into());
self
}
pub fn order_by_composite_field<T>(mut self, field: CompositeField<T>) -> Self {
self.order_by.push(field.to_sql_expression());
self
}
pub fn select_composite_field<T>(
mut self,
field: CompositeField<T>,
alias: Option<String>,
) -> Self {
let expression = if let Some(alias) = alias {
format!("{} AS \"{}\"", field.to_sql_expression(), alias)
} else {
field.to_sql_expression()
};
self.select_columns.push(expression);
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 inner_join(mut self, target: Source, condition: impl Into<String>) -> Self {
self.joins.push(JoinClause {
join_type: JoinType::Inner,
target,
condition: condition.into(),
});
self
}
pub fn left_join(mut self, target: Source, condition: impl Into<String>) -> Self {
self.joins.push(JoinClause {
join_type: JoinType::Left,
target,
condition: condition.into(),
});
self
}
pub fn right_join(mut self, target: Source, condition: impl Into<String>) -> Self {
self.joins.push(JoinClause {
join_type: JoinType::Right,
target,
condition: condition.into(),
});
self
}
pub fn full_join(mut self, target: Source, condition: impl Into<String>) -> Self {
self.joins.push(JoinClause {
join_type: JoinType::Full,
target,
condition: condition.into(),
});
self
}
pub fn inner_join_table(mut self, table: Table, condition: impl Into<String>) -> Self {
self.joins.push(JoinClause {
join_type: JoinType::Inner,
target: Source::Table(table),
condition: condition.into(),
});
self
}
pub fn inner_join_table_name(
mut self,
table_name: impl Into<String>,
condition: impl Into<String>,
) -> Self {
self.joins.push(JoinClause {
join_type: JoinType::Inner,
target: Source::Table(Table::new(table_name)),
condition: condition.into(),
});
self
}
pub fn left_join_table_name(
mut self,
table_name: impl Into<String>,
condition: impl Into<String>,
) -> Self {
self.joins.push(JoinClause {
join_type: JoinType::Left,
target: Source::Table(Table::new(table_name)),
condition: condition.into(),
});
self
}
pub fn right_join_table_name(
mut self,
table_name: impl Into<String>,
condition: impl Into<String>,
) -> Self {
self.joins.push(JoinClause {
join_type: JoinType::Right,
target: Source::Table(Table::new(table_name)),
condition: condition.into(),
});
self
}
pub fn group_by(mut self, column: impl Into<String>) -> Self {
self.group_by.push(column.into());
self
}
pub fn having(mut self, condition: impl Into<String>) -> Self {
self.having_clause = Some(condition.into());
self
}
pub fn select(mut self, expression: impl Into<String>) -> Self {
self.select_columns.push(expression.into());
self
}
pub fn count(mut self, column: impl Into<String>) -> Self {
self.select_columns
.push(format!("COUNT({})", column.into()));
self
}
pub fn sum(mut self, column: impl Into<String>) -> Self {
self.select_columns.push(format!("SUM({})", column.into()));
self
}
pub fn avg(mut self, column: impl Into<String>) -> Self {
self.select_columns.push(format!("AVG({})", column.into()));
self
}
pub fn max(mut self, column: impl Into<String>) -> Self {
self.select_columns.push(format!("MAX({})", column.into()));
self
}
pub fn min(mut self, column: impl Into<String>) -> Self {
self.select_columns.push(format!("MIN({})", column.into()));
self
}
pub fn with_indexes(mut self, indexes: Vec<IndexMeta>) -> Self {
self.index_optimizer = Some(IndexOptimizer::new(indexes));
self
}
pub fn get_index_hints(&self) -> Option<String> {
if let (Some(optimizer), Some(source), Some(where_clause)) =
(&self.index_optimizer, &self.from_source, &self.where_clause)
{
let conditions = vec![where_clause.clone()];
optimizer.generate_index_hints(source.name(), &conditions)
} else {
None
}
}
pub fn is_materialized_view(&self) -> bool {
self.from_source
.as_ref()
.map(|s| s.is_materialized())
.unwrap_or(false)
}
pub fn generate_refresh_sql(&self) -> Option<String> {
if let Some(ref source) = self.from_source {
if let Source::View(view) = source {
if view.materialized {
return view.generate_refresh_ddl();
}
}
}
None
}
pub fn is_procedure_call(&self) -> bool {
matches!(
self.from_source,
Some(Source::Procedure(_)) | Some(Source::Function(_))
)
}
pub fn generate_call_sql(&self, parameters: Vec<String>) -> String {
match &self.from_source {
Some(Source::Procedure(proc)) => {
let qualified_name = proc.qualified_name();
if parameters.is_empty() {
format!("CALL {}()", qualified_name)
} else {
format!("CALL {}({})", qualified_name, parameters.join(", "))
}
}
Some(Source::Function(func)) => {
let qualified_name = func.qualified_name();
if parameters.is_empty() {
format!("SELECT {}() as result", qualified_name)
} else {
format!(
"SELECT {}({}) as result",
qualified_name,
parameters.join(", ")
)
}
}
_ => panic!("generate_call_sql can only be used with procedure or function sources"),
}
}
pub fn to_sql(&self) -> String {
let mut hasher = std::collections::hash_map::DefaultHasher::new();
self.hash(&mut hasher);
let hash = hasher.finish();
if let Some(cache) = QUERY_CACHE.get() {
if let Some(cached_sql) = cache.get(hash) {
return cached_sql;
}
}
let sql = self.generate_sql_optimized();
if let Some(cache) = QUERY_CACHE.get() {
cache.insert(hash, sql.clone());
}
sql
}
fn generate_sql_optimized(&self) -> String {
let mut sql = String::with_capacity(512);
let select_keyword: Cow<'static, str> = Cow::Borrowed("SELECT");
let from_keyword: Cow<'static, str> = Cow::Borrowed(" FROM ");
let where_keyword: Cow<'static, str> = Cow::Borrowed(" WHERE ");
let group_by_keyword: Cow<'static, str> = Cow::Borrowed(" GROUP BY ");
let having_keyword: Cow<'static, str> = Cow::Borrowed(" HAVING ");
let order_by_keyword: Cow<'static, str> = Cow::Borrowed(" ORDER BY ");
let limit_keyword: Cow<'static, str> = Cow::Borrowed(" LIMIT ");
let offset_keyword: Cow<'static, str> = Cow::Borrowed(" OFFSET ");
if self.select_columns.is_empty() {
sql.push_str("SELECT *");
} else {
let cols: Vec<Cow<'_, str>> = self
.select_columns
.iter()
.map(|c| {
if c.contains('(') || c.contains(' ') || c.contains('.') {
Cow::Borrowed(c.as_str()) } else {
Cow::Owned(format!("\"{}\"", c)) }
})
.collect();
use std::fmt::Write;
write!(sql, "{} {}", select_keyword, cols.join(", ")).unwrap();
}
if let Some(ref source) = self.from_source {
match source {
Source::Procedure(_) | Source::Function(_) => {
return "-- Use generate_call_sql() for procedure/function calls".to_string();
}
_ => {
sql.push_str(&from_keyword);
sql.push_str(&source.qualified_name());
}
}
}
for join in &self.joins {
let join_keyword = match join.join_type {
JoinType::Inner => " INNER JOIN ",
JoinType::Left => " LEFT JOIN ",
JoinType::Right => " RIGHT JOIN ",
JoinType::Full => " FULL OUTER JOIN ",
};
sql.push_str(join_keyword);
sql.push_str(&join.target.qualified_name());
sql.push_str(" ON ");
sql.push_str(&join.condition);
}
if let Some(ref where_clause) = self.where_clause {
sql.push_str(&where_keyword);
sql.push_str(where_clause);
}
if !self.group_by.is_empty() {
sql.push_str(&group_by_keyword);
let group_cols: Vec<Cow<'_, str>> = self
.group_by
.iter()
.map(|c| {
if c.contains('.') {
Cow::Borrowed(c.as_str()) } else {
Cow::Owned(format!("\"{}\"", c)) }
})
.collect();
sql.push_str(&group_cols.join(", "));
}
if let Some(ref having_clause) = self.having_clause {
sql.push_str(&having_keyword);
sql.push_str(having_clause);
}
if !self.order_by.is_empty() {
sql.push_str(&order_by_keyword);
let order_cols: Vec<Cow<'_, str>> = self
.order_by
.iter()
.map(|c| {
if c.contains('.') || c.contains(' ') {
Cow::Borrowed(c.as_str()) } else {
Cow::Owned(format!("\"{}\"", c)) }
})
.collect();
sql.push_str(&order_cols.join(", "));
}
if let Some(limit) = self.limit {
sql.push_str(&limit_keyword);
sql.push_str(&limit.to_string());
}
if let Some(offset) = self.offset {
sql.push_str(&offset_keyword);
sql.push_str(&offset.to_string());
}
sql
}
pub fn cache_stats() -> (usize, usize) {
QUERY_CACHE
.get()
.map(|cache| cache.stats())
.unwrap_or((0, 0))
}
pub fn init_cache() {
let _ = QUERY_CACHE.set(Arc::new(QueryCache::new()));
}
pub fn generate_all_sql(&self) -> Vec<String> {
let mut statements = Vec::new();
statements.push(self.to_sql());
if let Some(refresh_sql) = self.generate_refresh_sql() {
statements.push(refresh_sql);
}
statements
}
}
impl Default for Query {
fn default() -> Self {
Self::new()
}
}
#[derive(Debug, Clone)]
pub struct Column<T> {
pub name: String,
pub table: Option<String>,
pub schema: Option<String>,
_phantom: std::marker::PhantomData<T>,
}
impl<T> Column<T> {
pub fn new(name: impl Into<String>) -> Self {
Self {
name: name.into(),
table: None,
schema: None,
_phantom: std::marker::PhantomData,
}
}
pub fn from_table(mut self, table: impl Into<String>) -> Self {
self.table = Some(table.into());
self
}
pub fn from_schema(mut self, schema: impl Into<String>) -> Self {
self.schema = Some(schema.into());
self
}
pub fn qualified_name(&self) -> String {
let mut parts = Vec::new();
if let Some(ref schema) = self.schema {
parts.push(format!("\"{}\"", schema));
}
if let Some(ref table) = self.table {
parts.push(format!("\"{}\"", table));
}
parts.push(format!("\"{}\"", self.name));
parts.join(".")
}
pub fn eq(self, _value: T) -> String {
format!("{} = ?", self.qualified_name())
}
pub fn gt(self, _value: T) -> String {
format!("{} > ?", self.qualified_name())
}
pub fn lt(self, _value: T) -> String {
format!("{} < ?", self.qualified_name())
}
pub fn like(self, _pattern: impl Into<String>) -> String {
format!("{} LIKE ?", self.qualified_name())
}
pub fn in_(self, _values: Vec<T>) -> String {
let placeholders: Vec<String> = (0.._values.len()).map(|_| "?".to_string()).collect();
format!("{} IN ({})", self.qualified_name(), placeholders.join(", "))
}
}