Skip to main content

Table

Derive Macro Table 

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

Defines a SQL table schema.

Implements Table, DatabaseSetup, Output, Insert, and Update for the struct, for usage inside of query! macros. Table names default to the struct name converted to snake_case.

§Basic usage

#[derive(Table)]
#[sql(table_name = "doc_users")]
struct DocUserTable {
    #[sql(primary_key)]
    #[sql(auto_increment)]
    id: i32,
    #[sql(unique)]
    email: String,
    #[sql(default = "guest".to_string())]
    role: String,
    nickname: Option<String>,
}

§Field attributes

  • #[sql(primary_key)] marks a column as part of the primary key.
  • #[sql(auto_increment)] enables auto-increment for the column (driver-dependent).
  • #[sql(unique)] adds a UNIQUE constraint.
  • #[sql(default = expr)] sets a column default (the expression is type-checked).
  • #[sql(bytes)] stores the field as a binary blob using bincode + serde.
  • #[sql(foreign_key = TableStruct)] creates a foreign key to another table.
  • #[sql(foreign_key = TableStruct, cascade)] enables ON DELETE/UPDATE CASCADE.

Option<T> fields are treated as nullable; all other fields are NOT NULL by default.

§Foreign keys

#[derive(Table)]
#[sql(no_version)]
struct PostTable {
    #[sql(primary_key)]
    id: i32,
    title: String,
}

#[derive(Table)]
#[sql(version = 2)]
#[sql(table_name = "doc_comments")]
// Auto generated by build script
#[sql(unique_id = "43af18d0-f056-4b18-9958-3fadb41e4334")]
struct CommentTable {
    #[sql(primary_key)]
    #[sql(auto_increment)]
    id: i32,
    #[sql(foreign_key = PostTable, cascade)]
    post_id: i32,
    body: String,
}

§Composite primary keys

#[derive(Table)]
struct DocMembershipTable {
    #[sql(primary_key)]
    org_id: i32,
    #[sql(primary_key)]
    user_id: i32,
    joined_at: i64,
}

§Table attributes

  • #[sql(table_name = "...")] overrides the generated snake_case name.
  • #[sql(drivers = Driver1, Driver2)] sets the supported drivers when no default driver is configured in the build script via sql_build::build.
  • #[sql(no_version)] disables migrations for this table (feature migrations).
  • #[sql(version = 1)] enables migrations and sets the table version (feature migrations).
  • #[sql(unique_id = "...")] is auto generated and used by the build script for migration tracking.
  • #[sql(version_test = 1)] sets a temporary version for migration testing, requires unique_id.

§Notes

  • Some drivers require at least one primary key; if none is specified, compilation will fail.
  • Auto-increment may be restricted when using composite primary keys, depending on the driver.
  • #[sql(bytes)] requires the field type to implement serde::Serialize/Deserialize.