SQLite Migrate

0.1b0 · active · verified Thu Apr 16

sqlite-migrate is a simple database migration system for SQLite, built upon the sqlite-utils library. It allows users to define database schema changes and data manipulations as Python functions within numbered files, which can then be applied incrementally. The current version is 0.1b0, with releases occurring periodically to address bugs and introduce new features during its beta phase.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a simple migration, apply it to an SQLite database, and verify the changes. It involves creating a temporary migration file and directory, then using the `Migrations` class to execute the migration.

import sqlite_utils
from sqlite_migrate import Migrations
import os

# 1. Prepare a temporary database file
db_path = "quickstart.db"
if os.path.exists(db_path):
    os.remove(db_path)
db = sqlite_utils.Database(db_path)

# 2. Define a migration in a temporary directory
migrations_dir = "./qs_migrations"
os.makedirs(migrations_dir, exist_ok=True)
migration_file_path = os.path.join(migrations_dir, "001_create_users_table.py")

with open(migration_file_path, "w") as f:
    f.write("""
def migrate(db):
    db["users"].create({"id": int, "name": str}, pk="id", if_not_exists=True)
    db["users"].insert({"id": 1, "name": "Alice"})
""")

# 3. Initialize Migrations and apply them
migrations = Migrations(db, [migrations_dir])
migrations.apply()

print(f"Database '{db_path}' migrated successfully.")
print(f"Tables: {db.table_names()}")
print(f"Users count: {db['users'].count()}")

# 4. Clean up temporary files
os.remove(migration_file_path)
os.rmdir(migrations_dir)
os.remove(db_path)

view raw JSON →