Function scooby::postgres::statements::select

source ·
pub fn select(expressions: impl IntoIteratorOfSameType<Expression>) -> Select
Expand description

Create a new SELECT statement with given expressions.

Returns a Select structure that allows adding additional clauses. Call to_string to finalize and get SQL.

Supported clauses

ClauseMethod
ALLfrom
DISTINCTdistinct
DISTINCT ONdistinct_on
FROMfrom
WHEREwhere_
GROUP BYgroup_by
HAVINGhaving
ORDER BYorder_by
LIMITlimit
OFFSEToffset

Specifying a WITH clause

To create a SELECT statement with a WITH clause, start with with instead of this function.

Useful traits to import

  • Orderable to easily stick DESC/ASC/etc. on strings
  • Joinable to easily create joins from string table names
  • Aliasable to easily make x AS y aliases for columns and such

Examples

use scooby::postgres::select;

let sql = select("1 + 1").to_string();

assert_eq!(sql, "SELECT 1 + 1")
use scooby::postgres::{select, Joinable, Orderable, Aliasable};

let sql = select(("country.name".as_("name"), "COUNT(*)".as_("count")))
    .from(
        "Country"
            .as_("country")
            .inner_join("City".as_("city"))
            .on("city.country_id = country.id"),
    )
    .where_("city.population > 1000000")
    .group_by("country.name")
    .order_by("count".desc())
    .limit(10)
    .to_string();

assert_eq!(sql, "SELECT country.name AS name, COUNT(*) AS count FROM Country AS country INNER JOIN City AS city ON city.country_id = country.id WHERE city.population > 1000000 GROUP BY country.name ORDER BY count DESC LIMIT 10");