Database Migration


pylite-orm comes with a built-in database migration tool lite-migr . It runs via command line, similar to Alembic or Aerich (though the name doesn't seem as elegant as theirs 🤔).

Initialization

For first-time use, run the following command in the current project folder:

lite-migr init

This will create a folder named migrations in the current project folder to store migration files, as well as a configuration file named migrate.toml .

The default content of the toml configuration file is as follows:

[migrate]
db_path = "./app.db"
migrations_dir = "./migrations"
models_dir = "./models"

Where db_path is the path to the database file, migrations_dir is the folder where migration files are stored, and models_dir is the folder where model files are stored.

You need to modify the paths in this configuration file according to your project's actual situation.


Creating Migrations

The command to create a migration is: lite-migr create <custom identifier name>

For example:

lite-migr create my_tables

The essence of creating a migration is comparing the differences between model files and the database, then generating migration files based on those differences. So if there are no differences, no migration file will be generated (and you'll receive a notification).

Generated migration files are all located in the migrations folder, with filenames consisting of a timestamp plus your custom identifier name, and a .py extension. This means you can open them to view and modify them.


Upgrading the Database

Once you have migration files, you can officially upgrade the database.

The command is:

lite-migr upgrade

After execution, the database will be updated according to the migration file content to keep it consistent with the data models: when there's no table, a new table will be created; when a table exists but differs from the model, the table will be modified according to the model.

Going forward, every time you modify a data model, you need to execute the create migration (create) and upgrade database (upgrade) commands to keep the database consistent with the models.


pylite-orm Philosophy

  1. Data model first

  2. Focus on data models, try to ignore the database's existence

💡 When migrating databases in production environments, please backup your data in advance to avoid cursing the pylite-orm author if data loss occurs.