alchemy-modelgen

Create sqlalchemy python model files by defining tables and columns in a YAML file


Keywords
yaml, database-schema, database-migration, schema-versions
License
MIT
Install
pip install alchemy-modelgen==0.1.6.1

Documentation

sqlalchemy-modelgen

codecov PyPI

Create sqlalchemy python model files by defining tables and columns in a yaml file or by specifying database url

Installation

pip install alchemy-modelgen

Usage

  1. Initialize modelgen folder:
  2. modelgen init -d /path/to/YOUR_FOLDER
    cd /path/to/YOUR_FOLDER
    

  3. Create sqlalchemy model code from:
  4. (Option 1) yaml template:

    For details on how to write the yaml file, please follow docs

    modelgen createmodel --source yaml --path templates/example.yaml --alembic # path to your schema yaml file 
    

    (Option 2) existing database:

    modelgen createmodel --source database --path mysql+mysqlconnector://root:example@localhost:3306/modelgen --outfile models/YOUR_FILENAME.py --alembic
    

  5. Running alembic migrations:
  6. modelgen migrate revision --autogenerate -m "COMMIT_MESSAGE" -p mysql+mysqlconnector://root:example@localhost:3306/modelgen
    
    modelgen migrate upgrade head -p mysql+mysqlconnector://root:example@localhost:3306/modelgen
    

    The arguments passed after modelgen migrate are based on alembic. Any command true for alembic can be used with modelgen migrate.

    The database url can be passed using -p or --path argument, or can be set in the environment by the env var DATABASE_URI. If DATABASE_URI is set, -p or --path will be ignored


  7. Alter table support:
  • Change column type, length, add contraint, etc in the yaml file. Then run:
modelgen createmodel --source yaml --path templates/example.yaml --alembic
modelgen migrate revision --autogenerate -m "COMMIT_MESSAGE" -p mysql+mysqlconnector://root:example@localhost:3306/modelgen

modelgen migrate upgrade head -p mysql+mysqlconnector://root:example@localhost:3306/modelgen

    Credits

  • The code that reads the structure of an existing database and generates the appropriate SQLAlchemy model code is based on agronholm/sqlacodegen's repository (Copyright (c) Alex Grönholm), license: MIT License