dgilland / sqlservice

The missing SQLAlchemy ORM interface.
https://sqlservice.readthedocs.io
MIT License
179 stars 9 forks source link

Migrations ... #32

Closed tabebqena closed 2 years ago

tabebqena commented 3 years ago

I much appreciate your effort in this repository. So I have a suggestion. I know that this may be out of the scope of this package, but providing some hints in the documentations or fancy methods to integrate with migration tools as alembic will be much valuable.

dgilland commented 3 years ago

That seems like a reasonable thing to add.

There's nothing special required to integrate with alembic since sqlservice uses sqlalchemy's declarative base constructor. Just have to follow the instructions on https://alembic.sqlalchemy.org/en/latest/autogenerate.html and set target_metadata in the alembic env.py to your declarative base class' metadata attribute.

For example, let's say you have a model.py that contains the declarative base class:

# myproject/models/base.py
from sqlservice import as_declarative

@as_declarative()
class Model:
    pass

# Or using declarative_base
# from sqlservice import declarative_base
#
# Model = declarative_base()

Then in the alembic env.py file:

# env.py
from myproject.models.base import Model

target_metadata = Model.metadata
tabebqena commented 3 years ago

I appreciate your swift response. I will give it a try. thanks

tabebqena commented 2 years ago

As this may help someone. I was interested in integrating this library with Flask-Migrate. First I passed the SQLClient intsatnce to Migrate

from flask import Flask
from flask_migrate import Migrate
from sqlservice import SQLClient

app = Flask(__name__)

configs  = {SQL_DATABASE_URI : "sqlite:///data.sqlite"}    #  Complete your configs
client = SQLClient(**configs)
migrate = Migrate(app, db= client)

Then I tried the cli commands:

  flask db init 

I got error: AttributeError: The attribute 'get_engine' is not an attribute of Client nor is it a unique model class name in the declarative model class registry of <class 'sqlservice.model.ModelBase'>. Valid model names are: . If a model name is shown as a full module path, then that model class name is not unique and cannot be referenced via attribute access.

Solution:

 class MyClient(SQLClient):
      def get_engine(self, *args, **kwargs):
            return self.engine

 client = MySQLClient(**configs)
 migrate = Migrate(app, db= client)

Then all cli commands of Flask-Migrate are working up till now.