1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
use crate::prelude::*;
use std::borrow::Cow;
#[derive(Debug, Clone, PartialEq)]
/// Holds the expressions on which to perform a full-text search
pub struct TextSearch<'a> {
pub(crate) exprs: Vec<Expression<'a>>,
}
/// Performs a full-text search. Use it in combination with the `.matches()` comparable.
///
/// ```rust
/// # use quaint::{ast::*, visitor::{Visitor, Postgres}};
/// # fn main() -> Result<(), quaint::error::Error> {
/// let search: Expression = text_search(&[Column::from("name"), Column::from("ingredients")]).into();
/// let query = Select::from_table("recipes").so_that(search.matches("chicken"));
/// let (sql, params) = Postgres::build(query)?;
///
/// assert_eq!(
/// "SELECT \"recipes\".* FROM \"recipes\" \
/// WHERE to_tsvector(concat_ws(' ', \"name\",\"ingredients\")) @@ to_tsquery($1)", sql
/// );
///
/// assert_eq!(params, vec![Value::from("chicken")]);
/// # Ok(())
/// # }
/// ```
#[cfg(any(feature = "postgresql", feature = "mysql"))]
pub fn text_search<'a, T: Clone>(exprs: &[T]) -> super::Function<'a>
where
T: Into<Expression<'a>>,
{
let exprs: Vec<Expression> = exprs.iter().map(|c| c.clone().into()).collect();
let fun = TextSearch { exprs };
fun.into()
}
#[derive(Debug, Clone, PartialEq)]
/// Holds the expressions & query on which to perform a text-search ranking compute
pub struct TextSearchRelevance<'a> {
pub(crate) exprs: Vec<Expression<'a>>,
pub(crate) query: Cow<'a, str>,
}
/// Computes the relevance score of a full-text search query against some expressions.
///
/// ```rust
/// # use quaint::{ast::*, visitor::{Visitor, Postgres}};
/// # fn main() -> Result<(), quaint::error::Error> {
/// let relevance: Expression = text_search_relevance(&[Column::from("name"), Column::from("ingredients")], "chicken").into();
/// let query = Select::from_table("recipes").so_that(relevance.greater_than(0.1));
/// let (sql, params) = Postgres::build(query)?;
///
/// assert_eq!(
/// "SELECT \"recipes\".* FROM \"recipes\" WHERE \
/// ts_rank(to_tsvector(concat_ws(' ', \"name\",\"ingredients\")), to_tsquery($1)) > $2", sql
/// );
///
/// assert_eq!(params, vec![Value::from("chicken"), Value::from(0.1)]);
/// # Ok(())
/// # }
/// ```
#[cfg(any(feature = "postgresql", feature = "mysql"))]
pub fn text_search_relevance<'a, E: Clone, Q>(exprs: &[E], query: Q) -> super::Function<'a>
where
E: Into<Expression<'a>>,
Q: Into<Cow<'a, str>>,
{
let exprs: Vec<Expression> = exprs.iter().map(|c| c.clone().into()).collect();
let fun = TextSearchRelevance {
exprs,
query: query.into(),
};
fun.into()
}