[Part 3] Entity generation


2 min read

Now that we have something to work on top of, we can generate the entities from our schema. Yes, you read that right ๐Ÿ˜„ With the run of a single command, we can generate the rust implementations of our tables in database with the help of the sea-orm-cli. Refer here for more info on various options.


Create a folder called "entity" under src. Run the below command to generate the entities ( Make sure database is up and running, else the command would fail )

sea-orm-cli generate entity -o src/entity --with-serde both

We pass some extra options for which the explanation can be found in the above link and I strongly recommend you to understand the options available that might suit your use-case more.

After running the command, the entity directory will now contain 3 files.

  1. mod.rs -> Rust directory modules will have mod.rs which indicates that the directory is a rust module and has sub modules inside. Read more about rust modules in the official Rust book

  2. prelude.rs -> This is a file which can export the items you want to be visible to other modules when the entity module is used.

  3. todos.rs -> The rust code with SeaORM related imports for the todos table which we created earlier. I suggest to learn more about entities and possible options here

** In my opinion it is good not to make any changes to the files under the entity directly as they are auto generated and any changes added would be overridden when the sea-orm-cli generate command is run again for any reason.

Attach entity module to main

After the above process, attach the entity module to main.rs as rust analyses only modules that are registered in the main program in a binary project. Add the code "mod entity;" at the top of main.rs and after that it should look like below.

mod entity;

fn main() {
    println!("Hello, world!");

Quick check

Now that we have added some rust code, it is good to check if all modules are linked and no errors are prevailing by running the follow command

cargo check


If everything is good, then let's proceed in the next part to write the business logic of our todo service ๐Ÿ’ช๐Ÿป !

Did you find this article valuable?

Support Omprakash Sridharan by becoming a sponsor. Any amount is appreciated!