Introduction
Sea-ORM is an amazing ORM that aims to be a write code once and run on any popular Relational Database with current support for MySQL, PostgreSQL, MariaDB and SQLite. In this tutorial, SeaORM with be used with async-std as the async runtime, rustls for database TLS connections and sqlx-mysql for the MySQL database backend.
Installation of dependencies and tools
-
Install SeaORM-Cli that will help in reading a database schema and generating the relevant
Entity,ModelandRelationof every table in our selected database (schema).$ cargo install sea-orm-cli -
Create a new Rust Cargo project
$ cargo new SimpleCrud --name simple-crud -
Switch to the new cargo project
$ cd simple-crud -
Add SeaORM as a dependency in
Cargo.tomlfileIf you have
cargo editinstalled, run$ cargo add sea-orm --no-default-features --features "runtime-async-std-rustls sqlx-mysql macros"or if you don't have
cargo editinstalled, you can install it by running$ cargo install cargo-edit -
Add the async runtime
$ cargo add anyhow $ cargo add async-std --features attributesYou can also add them manually in the
Cargo.tomlfilesea-orm = { version = "0.5", features = [ "runtime-async-std-rustls", "sqlx-mysql", "macros" ], default-features = false} anyhow = "1" async-std = "1" -
Make sure that your database server is running, then login and create a database called
fruit_markets.CREATE DATABASE fruit_markets; -
Create a new user in the database called
webmasterand with a passwordmaster_char# Step1: Create a new user CREATE USER 'webmaster'@'localhost' IDENTIFIED BY 'master_char'; # Step 2: Allow the user to have Read, Write access to all tables in database `fruit_markets` GRANT ALL PRIVILEGES ON fruit_markets . * TO 'webmaster'@'localhost'; # Step 3: Enable the above settings FLUSH PRIVILEGES; # Step 4: Logout of the database exit
We are all set to perform CRUD operations from the MySQL database side.
Symbols Used
To show added or removed code from files, we will use comments or
+ to show added code
- to show removed code
... is used to show only part of the existing code instead of rewriting already existing code in the examples.
$ shows an operation is done on the console/shell
This will make it easier to visualize changes to a file
In the next chapter, we will create simple CRUD operations.