Skip to content

set_session affects all models instead of a single instance/session #121

Open
@FeehGb

Description

I'm working on a multi-tenancy project and using the sqlalchemy-mixin library. While setting the session for a specific model using the set_session method, I encountered an issue: it seems to change the session for all models globally instead of only the intended one.

This behavior disrupts the isolation needed for my multi-tenancy setup, where different tenants require separate database sessions.

Here is a simplified example to illustrate the issue:

from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
from sqlalchemy_mixin import AllFeaturesMixin, set_session

class BaseModel(AllFeaturesMixin):
    pass

# Create two separate sessions
engine_1 = create_engine("sqlite:///:memory:")
engine_2 = create_engine("sqlite:///:memory:")
Session1 = sessionmaker(bind=engine_1)
Session2 = sessionmaker(bind=engine_2)

session1 = Session1()
session2 = Session2()

# Attach session1 to BaseModel
BaseModel.set_session(session1)

# Attempt to use session2 for another instance
BaseModel.set_session(session2)

# Now BaseModel appears to use session2 for all instances instead of session1
assert BaseModel._session == session2  # True for all models globally

Expected behavior:
The set_session method should allow configuring the session per model instance/session without affecting the others.

Observed behavior:
The set_session method changes the session globally for all models.

Is this behavior intended? If so, could you suggest an alternative approach for per-session or per-instance configuration that works seamlessly with sqlalchemy-mixin?

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions