Skip to main content

table_join

Macro table_join 

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

Defines a joined table type for use in query! and query_lazy!.

table_join! creates a lightweight type that implements Table with a generated join clause. Use it as the table name in queries and as the #[sql(table = ...)] target for Output.

§Syntax

table_join!(<Driver1, Driver2> JoinedTableStructName | TableA INNER JOIN TableB ON TableA.id = TableB.a_id)
  • The driver list is optional; when omitted, default drivers from the build script via sql_build::build are used.
  • Supported join types: INNER JOIN, LEFT JOIN, RIGHT JOIN, CROSS JOIN.
  • CROSS JOIN omits the ON clause.
  • Multiple joins can be chained after the main table.

§Output mapping

  • Use #[sql(field = Table.column)] or #[sql(select = ...)] in Output structs.
  • LEFT JOIN makes the joined table optional; map its fields as Option<T>.
  • RIGHT JOIN makes tables to the left optional; map their fields as Option<T>.

§Examples

table_join!(ExampleJoin | ExampleTable INNER JOIN RelatedTable ON ExampleTable.id = RelatedTable.parent_id);

#[derive(Output)]
#[sql(table = ExampleJoin)]
struct JoinedOutput {
    #[sql(field = ExampleTable.str_field)]
    parent_name: String,
    #[sql(field = RelatedTable.data)]
    child_data: String,
}

let parent_id = 1;
let rows: Vec<JoinedOutput> = query!(&mut conn,
    SELECT Vec<JoinedOutput> FROM ExampleJoin
    WHERE RelatedTable.parent_id = {parent_id}
)
.await?;
table_join!(<ExampleDriver> ExampleLeftJoin | ExampleTable LEFT JOIN RelatedTable ON ExampleTable.id = RelatedTable.parent_id);

#[derive(Output)]
#[sql(table = ExampleLeftJoin)]
struct LeftJoinOutput {
    #[sql(select = ExampleTable.str_field || RelatedTable.data)]
    multi_table_data: Option<String>,
    #[sql(field = ExampleTable.str_field)]
    parent_name: String,
    #[sql(field = RelatedTable.data)]
    child_data: Option<String>,
}

let rows: Vec<LeftJoinOutput> = query!(&mut conn,
    SELECT Vec<LeftJoinOutput> FROM ExampleLeftJoin
    ORDER BY ExampleTable.id ASC
)
.await?;