Skip to main content

DatabaseSetup

Derive Macro DatabaseSetup 

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

Composes database structure from nested types.

Implements DatabaseSetup by calling setup on each field (in order), which makes it easy to group tables or other setup structs into reusable schemas.

  • Works with named or tuple structs.
  • Use #[sql(drivers = Driver1, Driver2)] to select supported drivers when no defaults are configured in the build script via sql_build::build.
  • Errors include the field name and type to help trace failing setup calls.

§Basic usage

#[derive(Table)]
struct DocUsers {
    #[sql(primary_key)]
    id: i32,
    email: String,
}

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

#[derive(DatabaseSetup)]
struct DocSchema {
    users: DocUsers,
    posts: DocPosts,
}

§Nested setup groups

#[derive(Table)]
struct DocUsers {
    #[sql(primary_key)]
    id: i32,
    name: String,
}

#[derive(Table)]
struct DocPosts {
    #[sql(primary_key)]
    id: i32,
    #[sql(foreign_key = DocUsers, cascade)]
    user_id: i32,
    title: String,
}

#[derive(Table)]
struct DocComments {
    #[sql(primary_key)]
    id: i32,
    #[sql(foreign_key = DocPosts, cascade)]
    post_id: i32,
    body: String,
}

#[derive(DatabaseSetup)]
#[sql(drivers = ExampleDriver)]
struct UserTables {
    users: DocUsers,
}

#[derive(DatabaseSetup)]
struct ContentTables {
    posts: DocPosts,
    comments: DocComments,
}

§Notes

  • Every field must implement DatabaseSetup for the selected driver(s).
  • Setup order follows field order;