Derive Macro DDLTemplate

Source
#[derive(DDLTemplate)]
{
    // Attributes available to this derive:
    #[column]
    #[table]
    #[db]
}
Expand description

DDLTemplate is a derive macro that generates Data Definition Language (DDL) statements for creating database tables based on the struct definition. This macro analyzes the struct fields and their types to generate appropriate CREATE TABLE statements.

§Attributes

DDLTemplate accepts the following attributes:

  • table: Specifies the name of the table in the database (mandatory).
  • column: Applied to individual fields to customize column properties such as:
    • Column type overrides
    • Constraints (PRIMARY KEY, NOT NULL, UNIQUE, etc.)
    • Default values
  • db: Specifies the target database type for database-specific DDL generation.

§Generated Functions

The macro generates the following functions:

  • create_table_sql(): Returns the CREATE TABLE statement as a string
  • drop_table_sql(): Returns the DROP TABLE statement as a string

§Example

use sqlx_template::DDLTemplate;

#[derive(DDLTemplate)]
#[table("users")]
pub struct User {
    #[column(primary_key, auto_increment)]
    pub id: i32,
    #[column(unique, not_null)]
    pub email: String,
    #[column(not_null)]
    pub password: String,
    #[column(default = "true")]
    pub active: bool,
    pub created_at: Option<chrono::DateTime<chrono::Utc>>,
}

// Usage:
let create_sql = User::create_table_sql();
let drop_sql = User::drop_table_sql();

§Note

This macro is useful for database migrations and schema management. The generated DDL statements are database-specific and should be tested with your target database system.