use std::error::Error;
use std::sync::Arc;
use serde_json::json;
use vlorql::{CompiledQuery, SchemaSnapshot, SqlDialect, VlorQl};
use vlorql_core::policy::PolicyConfig;
use vlorql_core::schema::{
ColumnSchema, ComparisonOperator, DataType, Expression, FromClause, Predicate, Projection,
QueryPlan, SchemaMetadata, TableSchema,
};
fn build_schema() -> Arc<SchemaSnapshot> {
Arc::new(SchemaSnapshot::new(
vec![TableSchema {
name: "users".to_owned(),
columns: vec![
ColumnSchema {
name: "id".to_owned(),
data_type: DataType::Int,
nullable: false,
description: None,
is_primary_key: true,
foreign_key: None,
},
ColumnSchema {
name: "name".to_owned(),
data_type: DataType::String,
nullable: false,
description: None,
is_primary_key: false,
foreign_key: None,
},
],
description: None,
primary_key: Some(vec!["id".to_owned()]),
}],
SchemaMetadata::default(),
))
}
fn canonical_plan() -> QueryPlan {
QueryPlan {
select: vec![
Projection::Column {
table: Some("users".to_owned()),
column: "id".to_owned(),
alias: None,
},
Projection::Column {
table: Some("users".to_owned()),
column: "name".to_owned(),
alias: Some("display_name".to_owned()),
},
],
from: FromClause::table("users".to_owned(), None),
r#where: Some(Predicate::Comparison {
left: Box::new(Expression::ColumnRef {
table: Some("users".to_owned()),
column: "id".to_owned(),
}),
op: ComparisonOperator::Gt,
right: Box::new(Expression::Literal {
value: json!(1000),
data_type: DataType::Int,
}),
}),
group_by: None,
having: None,
order_by: None,
limit: Some(50),
offset: Some(100),
joins: None,
ctes: None,
distinct: false,
distinct_on: None,
set_operation: None,
}
}
fn facade_for(dialect: SqlDialect) -> Result<VlorQl, Box<dyn Error>> {
let dialect_name = match dialect {
SqlDialect::Postgres => "postgres",
SqlDialect::Sqlite => "sqlite",
SqlDialect::MySql => "mysql",
};
Ok(VlorQl::builder()
.with_schema(build_schema())
.with_dialect_name(dialect_name)
.with_policy(PolicyConfig::default())
.build()?)
}
fn print_compiled(dialect: SqlDialect, plan: &QueryPlan) -> Result<CompiledQuery, Box<dyn Error>> {
let vlorql = facade_for(dialect)?;
let validated = vlorql.validate_only(plan)?;
let compiled = vlorql.compile_only(&validated)?;
println!("--- {dialect:?} ---");
println!("sql: {}", compiled.sql);
println!("placeholders: {:?}", parameter_placeholders(&compiled));
println!();
Ok(compiled)
}
fn parameter_placeholders(compiled: &CompiledQuery) -> Vec<String> {
compiled
.parameters
.iter()
.enumerate()
.map(|(index, _parameter)| match compiled.dialect {
SqlDialect::Postgres => format!("${}", index + 1),
_ => "?".to_owned(),
})
.zip(compiled.parameters.iter().map(|p| p.value.clone()))
.map(|(placeholder, value)| format!("{placeholder} = {value}"))
.collect()
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let plan = canonical_plan();
for dialect in [SqlDialect::Postgres, SqlDialect::Sqlite, SqlDialect::MySql] {
print_compiled(dialect, &plan)?;
}
let compiled: Vec<(SqlDialect, String)> =
[SqlDialect::Postgres, SqlDialect::Sqlite, SqlDialect::MySql]
.into_iter()
.map(|dialect| {
let vlorql = facade_for(dialect).expect("facade");
let validated = vlorql.validate_only(&plan).expect("validate");
let compiled = vlorql.compile_only(&validated).expect("compile");
(dialect, compiled.sql)
})
.collect();
println!("--- summary ---");
for (dialect, sql) in compiled {
println!("{dialect:?}: {} chars", sql.len());
}
Ok(())
}