Models
Models is a work in progress implementation for a sql migration management tool. Beware, this is still under development, and some API's may be broken in the future.
Basic Tutorial
install the CLI by running the following command:
$ cargo install models-cli
Now run the following command to create an environment file with the DATABASE_URL
variable set:
$ echo "DATABASE_URL=sqlite://database.db" > .env
Alternatively it can be set as a environment variable with the following command:
$ export DATABASE_URL=sqlite://database.db
We now can create the database running the following command:
$ models database create
This command will have created an sqlite file called database.db
.
You can now derive the Model
trait on your structures,
and models
will manage the migrations for you. For example, write at src/main.rs
:
use Model;
If you now run the following command, your migrations should be automatically created.
$ models generate
The output should look like this:
Generated: migrations/1632280793452 user
Generated: migrations/1632280793459 post
Generated: migrations/1632280793465 postlike
Generated: migrations/1632280793471 comment
Generated: migrations/1632280793476 commentlike
You can check out the generated migrations at the migrations/
folder.
To execute these migrations you can execute the following command:
models migrate run
The output should look like this:
Applied 1631716729974/migrate user (342.208µs)
Applied 1631716729980/migrate post (255.958µs)
Applied 1631716729986/migrate comment (287.792µs)
Applied 1631716729993/migrate postlike (349.834µs)
Applied 1631716729998/migrate commentlike (374.625µs)
If we later modify those structures in our application, we can generate new migrations to update the tables.
Avaibale Attributes
primary_key
It's used to mark the primary key fo the table.
: i32,
id
for tables with multicolumn primary keys, the following syntax is used:
: i32,
second_id: i32,
first_id
This is equivalent to
PRIMARY KEY (first_id, second_id),
foreign_key
It is used to mark a foreign key constraint.
: i32,
user
It can also specify on_delete
and on_update
constraints:
: i32,
user_id
This is equivalent to
FOREIGN KEY (user_id) REFERENCES user (id) ON DELETE CASCADE,
default
It can be used to set a default value for a column.
// when using SQLite use 0 or 1
is_admin: bool,
text: String,
number: i32,
unique
It is used to mark a unique constraint.
: String,
email
For multicolumn unique constraints the following syntax is used:
: String,
post_id: i32,
user_id
This is equivalent to
UNIQUE (user_id, post_id),