tank-core 0.49.0

Core of Tank: the Rust data layer. This is intended to be used by drivers to implement a backend.
Documentation
use crate::{
    AnyQuery, BoxQueryBuilder, ColumnDef, Dataset, Driver, Entity, Expression,
    ExpressionCollection, NA, Query, SelectQuery, SelectQueryBuilder, SqlWriter, TableRef, Value,
    future::Either,
};
use std::{borrow::Cow, iter, marker::PhantomData};

type NoSelect = SelectQueryBuilder<NA, NA, NA, NA, NA, NA, NA>;

pub type InsertSelectQueryBuilder<S, F = NA, W = NA, G = NA, H = NA, O = NA, L = NA> =
    SelectQueryBuilder<S, F, W, G, H, O, L, InsertIntoQueryBuilder<NA, NA>>;

pub struct InsertIntoQueryBuilder<Values, Update> {
    pub(crate) table: TableRef,
    pub(crate) columns: Cow<'static, [ColumnDef]>,
    pub(crate) values: Values,
    pub(crate) update: bool,
    pub(crate) _update: PhantomData<Update>,
}

impl<V, U> InsertIntoQueryBuilder<V, U> {
    fn with<Values, Update>(
        self,
        values: Values,
        update: bool,
    ) -> InsertIntoQueryBuilder<Values, Update> {
        InsertIntoQueryBuilder {
            table: self.table,
            columns: self.columns,
            values,
            update,
            _update: PhantomData,
        }
    }
}

impl InsertIntoQueryBuilder<NA, NA> {
    /// Insert entities, the columns and their values.
    pub fn values<'a, E, Entities>(
        mut self,
        entities: Entities,
    ) -> InsertIntoQueryBuilder<impl Iterator<Item = impl Iterator<Item = Value<'a>>> + Clone, NA>
    where
        E: Entity + 'a,
        Entities: IntoIterator<Item = &'a E>,
        Entities::IntoIter: Clone,
    {
        // A table named by hand takes the columns and primary key of the entities.
        if self.table.columns.is_empty() {
            self.table.columns = E::columns().into();
            self.table.primary_key = E::table().primary_key.clone();
        }
        self.columns = Cow::Borrowed(E::columns());
        self.with(entities.into_iter().map(E::row_values), false)
    }

    /// Name the columns of the values or of the SELECT that follow.
    pub fn columns<Name: Into<Cow<'static, str>>>(
        mut self,
        columns: impl IntoIterator<Item = Name>,
    ) -> InsertIntoQueryBuilder<(), NA> {
        self.columns = Cow::Owned(columns.into_iter().map(ColumnDef::new).collect());
        self.with((), false)
    }

    /// Insert the rows of a SELECT, continued like any SELECT, matched to the table columns by position.
    pub fn select<S: ExpressionCollection>(self, select: S) -> InsertSelectQueryBuilder<S> {
        self.with((), false).select(select)
    }
}

impl InsertIntoQueryBuilder<(), NA> {
    /// Insert rows of expressions following the columns order.
    pub fn values<Rows>(self, rows: Rows) -> InsertIntoQueryBuilder<Rows::IntoIter, NA>
    where
        Rows: IntoIterator,
        Rows::IntoIter: Clone,
        Rows::Item: IntoIterator,
        <Rows::Item as IntoIterator>::Item: Expression,
    {
        self.with(rows.into_iter(), false)
    }

    /// Insert the rows of a SELECT, continued like any SELECT, into the columns.
    pub fn select<S: ExpressionCollection>(self, select: S) -> InsertSelectQueryBuilder<S> {
        SelectQueryBuilder {
            select,
            from: None,
            where_expr: None,
            group_by: None,
            having: None,
            order_by: None,
            limit: None,
            offset: None,
            distinct: false,
            _l: PhantomData,
            insert: self.with(NA, false),
        }
    }
}

impl<R> InsertIntoQueryBuilder<R, NA>
where
    Self: InsertIntoQuery,
{
    /// Update the existing rows on a conflict on the table primary key (upsert).
    pub fn update(self) -> InsertIntoQueryBuilder<R, bool> {
        InsertIntoQueryBuilder {
            table: self.table,
            columns: self.columns,
            values: self.values,
            update: true,
            _update: PhantomData,
        }
    }
}

impl<R, U> InsertIntoQuery for InsertIntoQueryBuilder<R, U>
where
    R: IntoIterator + Clone,
    R::Item: IntoIterator,
    <R::Item as IntoIterator>::Item: Expression,
{
    type From = NA;

    fn get_table(&self) -> &TableRef {
        &self.table
    }

    fn get_columns(&self) -> &[ColumnDef] {
        &self.columns
    }

    fn get_values(
        &self,
    ) -> Either<
        impl Iterator<Item = impl Iterator<Item = impl Expression>>,
        &impl SelectQuery<Self::From>,
    > {
        Either::<_, &NoSelect>::Left(self.values.clone().into_iter().map(IntoIterator::into_iter))
    }

    fn get_update(&self) -> bool {
        self.update
    }
}

impl<S, F, W, G, H, O, L> InsertSelectQueryBuilder<S, F, W, G, H, O, L>
where
    S: ExpressionCollection,
    F: Dataset,
    W: Expression,
    G: ExpressionCollection,
    H: Expression,
    O: ExpressionCollection,
{
    /// Builds the query for `driver`.
    pub fn build<D: Driver>(&self, driver: &D) -> Query<D> {
        let mut query = AnyQuery::default();
        self.write_into(&driver.sql_writer(), &mut query);
        query.into()
    }

    /// Writes the statement into an existing query.
    pub fn write_into(&self, writer: &impl SqlWriter, out: &mut AnyQuery) {
        writer.write_insert(out, self);
    }

    /// Erases the builder into a [`BoxQueryBuilder`], to store it and run it later on any executor.
    pub fn boxed(self) -> BoxQueryBuilder
    where
        Self: 'static,
    {
        BoxQueryBuilder::new(move |writer, out| self.write_into(writer, out))
    }
}

impl<S, F, W, G, H, O, L> InsertIntoQuery for InsertSelectQueryBuilder<S, F, W, G, H, O, L>
where
    S: ExpressionCollection,
    F: Dataset,
    W: Expression,
    G: ExpressionCollection,
    H: Expression,
    O: ExpressionCollection,
{
    type From = F;

    fn get_table(&self) -> &TableRef {
        &self.insert.table
    }

    fn get_columns(&self) -> &[ColumnDef] {
        &self.insert.columns
    }

    fn get_values(
        &self,
    ) -> Either<
        impl Iterator<Item = impl Iterator<Item = impl Expression>>,
        &impl SelectQuery<Self::From>,
    > {
        Either::<iter::Empty<iter::Empty<NA>>, _>::Right(self)
    }

    fn get_update(&self) -> bool {
        false
    }
}

/// INSERT INTO table (columns) VALUES (values), ... [ON CONFLICT (primary key) DO UPDATE SET ...]
///
/// Use `Sql().insert_into(table)` to start.
/// Then `values(&entities)`, `columns(names).values(rows)` or `select(columns).from(dataset)...`.
pub trait InsertIntoQuery {
    /// Dataset of the SELECT producing the rows, unused for rows of values.
    type From: Dataset;
    /// Get the table the rows are inserted into.
    fn get_table(&self) -> &TableRef;
    /// Get the columns, empty for all the table columns in order.
    fn get_columns(&self) -> &[ColumnDef];
    /// Get rows of expression cells, or the SELECT producing the inserted rows.
    fn get_values(
        &self,
    ) -> Either<
        impl Iterator<Item = impl Iterator<Item = impl Expression>>,
        &impl SelectQuery<Self::From>,
    >;
    /// Whether existing rows are updated on a primary key conflict.
    fn get_update(&self) -> bool;
}

impl<T: InsertIntoQuery> InsertIntoQuery for &T {
    type From = T::From;

    fn get_table(&self) -> &TableRef {
        (**self).get_table()
    }

    fn get_columns(&self) -> &[ColumnDef] {
        (**self).get_columns()
    }

    fn get_values(
        &self,
    ) -> Either<
        impl Iterator<Item = impl Iterator<Item = impl Expression>>,
        &impl SelectQuery<Self::From>,
    > {
        (**self).get_values()
    }

    fn get_update(&self) -> bool {
        (**self).get_update()
    }
}

impl<V, U> InsertIntoQueryBuilder<V, U>
where
    Self: InsertIntoQuery,
{
    /// Builds the query for `driver`.
    pub fn build<D: Driver>(&self, driver: &D) -> Query<D> {
        let mut query = AnyQuery::default();
        self.write_into(&driver.sql_writer(), &mut query);
        query.into()
    }

    /// Writes the statement into an existing query.
    pub fn write_into(&self, writer: &impl SqlWriter, out: &mut AnyQuery) {
        writer.write_insert(out, self);
    }

    /// Erases the builder into a [`BoxQueryBuilder`], to store it and run it later on any executor.
    pub fn boxed(self) -> BoxQueryBuilder
    where
        Self: 'static,
    {
        BoxQueryBuilder::new(move |writer, out| self.write_into(writer, out))
    }
}