postgresqlrustrust-diesel

Concat several columns as new column in Rust Diesel 2.0.0


With Rust's Diesel (2.0.0), is there a way to concatenate several columns without raw SQL?

This works for PostgreSQL but it's not exactly elegant:

my_table::table
  .select((
    sql::<diesel::sql_types::Text>(&"CONCAT(col1, '-', col2, '-', col3) as id"),
    my_table::col1,
    my_table::col2,
    my_table::col3,
    my_table::col4,
  ))
  .filter(my_table::col1.eq("somevalue"))
  .get_result::<(String, String, i64, String, String)>(&mut conn)

Solution

  • You can use the sql_function! macro:

    Diesel only provides support for a very small number of SQL functions. This macro enables you to add additional functions from the SQL standard, as well as any custom functions your application might have.

    sql_function! {
        fn concat(a: Text, b: Text, c: BigInt, d: Text, e: Text) -> Text;
    }
    
    my_table::table
        .select((
            concat(my_table::col1, "-", my_table::col2, "-", my_table::col3),
            my_table::col1,
            my_table::col2,
            my_table::col3,
            my_table::col4,
        ))
        ...