5

I'm looking for a way binding models to different databases (schema is identical in all databases), for instance - separated by countries

class User():
    __tablename__ = 'user'

    id = Column(Integer, primary_key=True)
    name = Column(VARCHAR(255))
    age = Column(Integer)

This model is shared between multiple databases:

postgresql://postgres:@localhost/US

postgresql://postgres:@localhost/RU

Multiple binds is possible using flask: Flask-SQLAlchemy multiple databases and binds but bind key is hardcoded in the model http://flask-sqlalchemy.pocoo.org/2.1/binds/

Is there a way binding it dynamically to the model?

1
  • Hello, Did you manage to get a solution for this? Commented Sep 19, 2022 at 6:24

2 Answers 2

1

See the get_bind method of sqlalchemy's documentation for the full documentation on how sqlalchemy chooses to bind tables.

Ignoring flask, my recommendation would be to set the bind argument on your session objects based on which country you'd like to access. So for example say sess is your session object. you could execute

sess.bind = choose_bind_from_request_data(r)

You'd want to make sure the session had no active transaction when you change the bind, although it would be a better design to create a new session and set the bind rather than changing the bind on an existing session.

It doesn't look like it is easy to dynamically choose a per-table bind, although as pointed out above dynamic per-session binds are easy.

Sign up to request clarification or add additional context in comments.

2 Comments

multiple binds are mapped using sqlalchemy mapper object - docs.sqlalchemy.org/en/latest/orm/…. this object have three different types of mapping: docs.sqlalchemy.org/en/latest/orm/mapping_styles.html. is it possible binding a request arg with bind using mapper?
What if we're building a SaaS application where the number of databases (one DB per tenant on MySQL since no "schemas") is constantly in flux (companies coming & going)? Basically we're looking for a way to dynamically generate the bind path (inclusive of DB Name) with a variable (customer ID).
1

the suggested solution for this case (vertical partitioning): http://docs.sqlalchemy.org/en/latest/orm/persistence_techniques.html#custom-vertical-partitioning

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.