use crate::values::PostgresValue;
use drizzle_core::{SQL, ToSQL, Token};
use std::marker::PhantomData;
use std::ops::Deref;
pub trait CTEDefinition<'a> {
fn cte_definition(&self) -> SQL<'a, PostgresValue<'a>>;
}
#[derive(Clone, Debug)]
pub struct CTEView<'a, Table, Query> {
pub table: Table,
name: &'static str,
query: Query,
_phantom: PhantomData<PostgresValue<'a>>,
}
impl<'a, Table, Query> CTEView<'a, Table, Query>
where
Query: ToSQL<'a, PostgresValue<'a>>,
{
pub fn new(table: Table, name: &'static str, query: Query) -> Self {
Self {
table,
name,
query,
_phantom: PhantomData,
}
}
pub fn cte_name(&self) -> &'static str {
self.name
}
pub fn query(&self) -> &Query {
&self.query
}
}
impl<'a, Table, Query> CTEDefinition<'a> for CTEView<'a, Table, Query>
where
Query: ToSQL<'a, PostgresValue<'a>>,
{
fn cte_definition(&self) -> SQL<'a, PostgresValue<'a>> {
SQL::raw(self.name)
.push(Token::AS)
.append(self.query.to_sql().parens())
}
}
impl<'a, Table, Query> CTEDefinition<'a> for &CTEView<'a, Table, Query>
where
Query: ToSQL<'a, PostgresValue<'a>>,
{
fn cte_definition(&self) -> SQL<'a, PostgresValue<'a>> {
SQL::raw(self.name)
.push(Token::AS)
.append(self.query.to_sql().parens())
}
}
impl<'a, Table, Query> Deref for CTEView<'a, Table, Query> {
type Target = Table;
fn deref(&self) -> &Self::Target {
&self.table
}
}
impl<'a, Table, Query> ToSQL<'a, PostgresValue<'a>> for CTEView<'a, Table, Query>
where
Query: ToSQL<'a, PostgresValue<'a>>,
{
fn to_sql(&self) -> SQL<'a, PostgresValue<'a>> {
SQL::ident(self.name)
}
}