Skip to main content

custom_sql_function

Macro custom_sql_function 

Source
custom_sql_function!() { /* proc-macro */ }
Expand description

Define a custom SQL function for use in query! and query_lazy!.

Registers a SQL function name and argument-count validation so the query macros can parse calls like MyFunc(column, "arg") and enforce argument counts at compile time.

§Syntax

custom_sql_function!(FunctionName; "SQL_FUNCTION_NAME"; 0 | 1 | 2 | Any);
  • FunctionName: Rust identifier used to generate the macro name.
  • "SQL_FUNCTION_NAME": SQL function name emitted in generated SQL.
  • args: Argument count specification:
    • A number (e.g., 2) for exact argument count
    • Multiple numbers separated by | (e.g., 1 | 2) for multiple allowed counts
    • Any for any number of arguments

§Examples

custom_sql_function!(Capitalize; "UPPER"; 1);

let rows: Vec<ExprTestData> = query!(&mut conn,
    SELECT Vec<ExprTestData> FROM ExprTestTable
    WHERE Capitalize(str_field) = "HELLO"
)
.await?;
custom_sql_function!(SubstrSlice; "SUBSTR"; 2 | 3);

let two_args: Vec<ExprTestData> = query!(&mut conn,
    SELECT Vec<ExprTestData> FROM ExprTestTable
    WHERE substrSlice(str_field, 2) = "ello"
)
.await?;

let three_args: Vec<ExprTestData> = query!(&mut conn,
    SELECT Vec<ExprTestData> FROM ExprTestTable
    WHERE substrSLICE(str_field, 2, 3) = "ell"
)
.await?;
custom_sql_function!(CoalesceAnyDoc; "COALESCE"; Any);

let rows: Vec<ExprTestData> = query!(&mut conn,
    SELECT Vec<ExprTestData> FROM ExprTestTable
    WHERE CoalesceAnyDoc(nullable_field, str_field, "fallback") = "hello"
)
.await?;

§Notes

  • Function names are case-insensitive in queries, but the emitted SQL name preserves casing.
  • The macro only validates SQL syntax; the function must exist in your database.
  • Any disables argument-count validation; otherwise invalid counts cause a compile-time error.