Installation
pip install migration-sql
Library structure
The library is composed mainly of 2 classes DB
, Version
and method migrate()
:
-
DB
: represents a database connection. To create this object, you need to provide the database host, port, username, password and database name. -
Version
: represents a migration version that will be run and recorded in the database when the migration is applied successfully. It has theversion_code
which needs to be unique, acomment
that is usually migration purpose andsql_text
which is the SQL query that will be applied to the database orsql_file
that points to the sql file that you want to run. -
migrate(versions, dbs)
: this method will apply all necessary versions on all databases listed indbs
. To avoid discrepancies between databases, if the migration fails on any of the database the whole migration process will be aborted and the database will stay intact.
How to use
Here is a code snippet on how to apply migrations on a database
from migration_sql import DB, Version, migrate
all_versions = [
Version("v0", "dumb query works", "select 1"),
Version("v1", "create a table", """
CREATE TABLE `user` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
);
"""),
Version("v2", "the migration script can come from a file too", sql_file="examples/v2.sql"),
Version("v3", "the migration is not limited to DDL, DML is also OK!", sql_text="""
INSERT INTO `user` (`id`, `name`) VALUES ('1', 'John Wick');
""")
]
dbs = [
DB("127.0.0.1", 3306, "root", "root", "my_database")
]
migrate(all_versions, dbs)
Dev
To run all the tests:
cd tests/; ./run_test.sh
To install locally the library during development
First, uninstall migration-sql
pip uninstall migration-sql
Then install it on local
python setup.py install
Or symlink it
python setup.py develop
Build and upload to pypi
./upload_pypi.sh