Schema

diesel creates a schema file that contains macro calls that generate a DSL language to use in the sources of your crate. A schema of tables that have relations to each other need extra declarations. Let's explore a generated schema in the src/schema.rs file to see how it differs from the simple schema we created earlier in this chapter.

The first table is users. It has the same columns we declared in the SQL file:

table! {
users (id) {
id -> Int4,
email -> Text,
}
}

The table! macro will be expanded during compilation to some type and trait implementations that you can see with the following command:

cargo rustc -- -Z unstable-options --pretty=expanded

This command prints all expanded macros to a Terminal.

The diesel tool has also generated a DSL declaration for the channels table:

table! {
channels (id) {
id -> Int4,
user_id -> Int4,
title -> Text,
is_public -> Bool,
created_at -> Timestamp,
updated_at -> Timestamp,
}
}

For the memberships table, we have this declaration:

table! {
memberships (id) {
id -> Int4,
channel_id -> Int4,
user_id -> Int4,
}
}

And for the messages table, we have this declaration:

table! {
messages (id) {
id -> Int4,
timestamp -> Timestamp,
channel_id -> Int4,
user_id -> Int4,
text -> Text,
}
}

But you might have noticed that the table declarations don't contain any information about relations. Relations created by the joinable! macro expect a table name and a parent table with the ID column name:

joinable!(channels -> users (user_id));
joinable!(memberships -> channels (channel_id));
joinable!(memberships -> users (user_id));
joinable!(messages -> channels (channel_id));
joinable!(messages -> users (user_id));

All relations are listed with the joinable! macro, but the schema also contains a allow_tables_to_appear_in_same_query! macro call that represents which tables can be used in JOIN queries:

allow_tables_to_appear_in_same_query!(
channels,
memberships,
messages,
users,
);

Since we have a complete schema declaration with all relations, we can declare models with the same relations as native Rust structs.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.191.86