Derive Macro Columns

Source
#[derive(Columns)]
{
    // Attributes available to this derive:
    #[group]
}
Expand description

Columns is a derive macro that generates column name constants and utility functions for database operations. This macro creates static string constants for each field in the struct, making it easier to reference column names in queries.

§Attributes

Columns accepts the following attributes:

  • group: Groups fields together for specific operations (optional).

§Generated Functions

The macro generates the following for each field:

  • A constant with the column name (e.g., COLUMN_ID for field id)
  • Utility functions for accessing column names programmatically

§Example

use sqlx_template::Columns;

#[derive(Columns)]
pub struct User {
    pub id: i32,
    pub email: String,
    #[group = "personal"]
    pub name: String,
    #[group = "personal"]
    pub age: i32,
}

// Usage:
// User::COLUMN_ID returns "id"
// User::COLUMN_EMAIL returns "email"
// User::COLUMN_NAME returns "name"
// User::COLUMN_AGE returns "age"

§Note

This macro is useful for maintaining consistency between struct field names and database column names, and provides compile-time safety when referencing columns.