Creating migrations

This command creates a migrations folder, where you can store migrations using the following command:

diesel migration generate <name>

This command creates a migration called <name> and stores it in the  migrations folder. For example, if you set the name of the created migration to create_tables, you will see in the following structure in the migrations folder:

migrations/
└── 2018-11-22-192300_create_tables/
├── up.sql
└── down.sql

For every migration, the generate command creates a folder and a pair of files:

  • up.sql: Statements for applying migrations
  • down.sql: Statements for reverting migrations

All migrations are handwritten. Add all the necessary statements for the migrations yourself. For our example, we need the following statements in the up.sql file:

CREATE TABLE users (
id TEXT PRIMARY KEY NOT NULL,
name TEXT NOT NULL,
email TEXT NOT NULL
);

The opposite statement is in the down.sql file:

DROP TABLE users;

Applying the up.sql script creates the users database with the same struct we used in the previous chapter. The revert script drops the users table.

Now, we can create the database and apply all the migrations with this command:

DATABASE_URL=test.db diesel migration run

We set DATABASE_URL to test.db to create a SQLite database in the current folder. The run command runs all the migrations in order. You can have multiple migrations and move from one structure level to another, both forward and backward.

Be careful! You can have multiple migrations, but you can't have competing migrations from different projects to the same database. The problem of automatic migrations is that you can't do it from multiple services, or you can't even start a microservice if it will try to migrate the database after another microservice has already migrated it.

We have created migrations, and now we have to declare the data structure in Rust sources.

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

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