|
| 1 | +use super::Function; |
| 2 | +use crate::ast::Table; |
| 3 | + |
| 4 | +#[derive(Debug, Clone, PartialEq)] |
| 5 | +#[cfg_attr(feature = "docs", doc(cfg(feature = "postgresql")))] |
| 6 | +#[cfg(all(feature = "json", feature = "postgresql"))] |
| 7 | +/// A representation of the `ROW_TO_JSON` function in the database. |
| 8 | +/// Only for `Postgresql` |
| 9 | +pub struct RowToJson<'a> { |
| 10 | + pub(crate) expr: Table<'a>, |
| 11 | + pub(crate) pretty_print: bool, |
| 12 | +} |
| 13 | + |
| 14 | +/// Return the given table in `JSON` format. |
| 15 | +/// |
| 16 | +/// Only available for `Postgresql` |
| 17 | +/// |
| 18 | +/// ```no_run |
| 19 | +/// # use quaint::{ast::*, visitor::{Visitor, Postgres}}; |
| 20 | +/// # fn main() -> Result<(), quaint::error::Error> { |
| 21 | +/// let cte = Select::default() |
| 22 | +/// .value(val!("hello_world").alias("toto")) |
| 23 | +/// .into_cte("one"); |
| 24 | +/// let select = Select::from_table("one") |
| 25 | +/// .value(row_to_json("one", false)) |
| 26 | +/// .with(cte); |
| 27 | +/// let result = api.conn().select(select).await?; |
| 28 | +/// |
| 29 | +/// assert_eq!( |
| 30 | +/// Value::Json(Some(serde_json::json!({ |
| 31 | +/// "toto": "hello_world" |
| 32 | +/// }))), |
| 33 | +/// result.into_single().unwrap()[0] |
| 34 | +/// ); |
| 35 | +/// # Ok(()) |
| 36 | +/// # } |
| 37 | +/// ``` |
| 38 | +#[cfg_attr(feature = "docs", doc(cfg(feature = "postgresql")))] |
| 39 | +#[cfg(all(feature = "json", feature = "postgresql"))] |
| 40 | +pub fn row_to_json<'a, T>(expr: T, pretty_print: bool) -> Function<'a> |
| 41 | +where |
| 42 | + T: Into<Table<'a>>, |
| 43 | +{ |
| 44 | + let fun = RowToJson { |
| 45 | + expr: expr.into(), |
| 46 | + pretty_print, |
| 47 | + }; |
| 48 | + |
| 49 | + fun.into() |
| 50 | +} |
0 commit comments