Skip to content

add identity_token API to ormexecutecontext #7832

Closed as not planned
Closed as not planned

Description

@gricey432

Describe the bug

Using a single Session to query identical tables in different schemas using Query.execution_options emits the correct SQL however it seems like the Session's identity map is turning the different results into the same instance of the model.

To Reproduce

Postgresql

CREATE SCHEMA test_1;
CREATE TABLE test_1.example (
    id SERIAL,
    name text COLLATE pg_catalog."default",
    CONSTRAINT example_pkey PRIMARY KEY (id)
);
INSERT INTO test_1.example ("name") VALUES ('1 name');
CREATE SCHEMA test_2;
CREATE TABLE test_2.example (
    id SERIAL,
    name text COLLATE pg_catalog."default",
    CONSTRAINT example_pkey PRIMARY KEY (id)
);
INSERT INTO test_2.example ("name") VALUES ('2 name');
import sqlalchemy as sa
from sqlalchemy.orm import Session
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class MyTable(Base):
    __tablename__ = 'example'

    id = sa.Column(sa.Integer, primary_key=True)
    name = sa.Column(sa.Text)

engine: sa.engine.Engine = sa.create_engine(
    'postgresql://webapp:webapp@localhost:5432/test',
    echo="debug",
)

conn = engine.connect()
sess = Session(conn)

base_qry = sess.query(MyTable).filter(MyTable.id == 1)

obj1 = base_qry.execution_options(schema_translate_map={None: "test_1"}).one()
print(obj1.name)  # 1 name
obj2 = base_qry.execution_options(schema_translate_map={None: "test_2"}).one()
print(obj2.name)  # 1 name
print(obj1 is obj2)  # True

Error

2022-03-21 13:48:17,794 INFO sqlalchemy.engine.Engine SELECT test_1.example.id AS example_id, test_1.example.name AS example_name 
FROM test_1.example 
WHERE test_1.example.id = %(id_1)s
2022-03-21 13:48:17,794 INFO sqlalchemy.engine.Engine [generated in 0.00025s] {'id_1': 1}
2022-03-21 13:48:17,799 DEBUG sqlalchemy.engine.Engine Col ('example_id', 'example_name')
2022-03-21 13:48:17,799 DEBUG sqlalchemy.engine.Engine Row (1, '1 name')
1 name
2022-03-21 13:48:17,800 INFO sqlalchemy.engine.Engine SELECT test_2.example.id AS example_id, test_2.example.name AS example_name 
FROM test_2.example 
WHERE test_2.example.id = %(id_1)s
2022-03-21 13:48:17,800 INFO sqlalchemy.engine.Engine [cached since 0.006008s ago] {'id_1': 1}
2022-03-21 13:48:17,802 DEBUG sqlalchemy.engine.Engine Col ('example_id', 'example_name')
2022-03-21 13:48:17,803 DEBUG sqlalchemy.engine.Engine Row (1, '2 name')
1 name
True

Versions

  • OS: Windows 10
  • Python: 3.9.1
  • SQLAlchemy: 1.4.32
  • Database: Postgresql 11.14
  • DBAPI (eg: psycopg, cx_oracle, mysqlclient): psycopg2-binary 2.9.3

Additional context

I'm not sure if this is a dupe / related to #7471, that ticket seems to be focused a bit more on joining between the tables / the public schema. I think mine's a bit simpler

Activity

  1. added
    requires triage
    on Mar 21, 2022
  2. added
    question
    and removed
    requires triage
    on Mar 21, 2022
  3. zzzeek commented on Mar 21, 2022

    @zzzeek
    Member

    hi there -

    I would advise using different sessions for different schema translates. It would not be expected that schema translate map would be taken into account on a per-object basis. There may be some ways to make it work with events. At the moment this should just be a documented limitation.

  4. added
    expected behavior
    on Mar 21, 2022
  5. added a commit that references this issue on Mar 21, 2022
    4373bd2
  6. zzzeek commented on Mar 21, 2022

    @zzzeek
    Member
  7. zzzeek commented on Mar 21, 2022

    @zzzeek
    Member

    oh, I completely forgot about this a well. The use case you are doing is supported, with some limitations, when using the horizontal sharding extension and we even have a test suite for some varieties of it. I'll update the doc with this info.

  8. zzzeek commented on Mar 21, 2022

    @zzzeek
    Member

    I added a new example that will be up on the site soon. it's a little rough right now but sharding is the API that provides this kind of thing.

  9. zzzeek commented on Mar 22, 2022

    @zzzeek
    Member

    Another way this can be made public API on the "read" side as your example requests, would be a means of passing through the "identity_token" for a given statement. The example below is a full POC for your example above, assuming the rows were added to the database using normal means:

    import sqlalchemy as sa
    from sqlalchemy import event
    from sqlalchemy.orm import Session
    from sqlalchemy.ext.declarative import declarative_base
    
    Base = declarative_base()
    
    
    class MyTable(Base):
        __tablename__ = "example"
    
        id = sa.Column(sa.Integer, primary_key=True)
        name = sa.Column(sa.Text)
    
    
    engine: sa.engine.Engine = sa.create_engine(
        "postgresql://scott:tiger@localhost/test",
        echo="debug",
    )
    
    with engine.begin() as conn:
        Base.metadata.drop_all(
            conn.execution_options(schema_translate_map={None: "test_schema"})
        )
        Base.metadata.drop_all(
            conn.execution_options(schema_translate_map={None: "test_schema_2"})
        )
    
        Base.metadata.create_all(
            conn.execution_options(schema_translate_map={None: "test_schema"})
        )
        Base.metadata.create_all(
            conn.execution_options(schema_translate_map={None: "test_schema_2"})
        )
    
    
    map1 = {None: "test_schema"}
    map2 = {None: "test_schema_2"}
    
    with Session(engine.execution_options(schema_translate_map=map1)) as sess:
        sess.add(MyTable(name="this is schema one"))
        sess.commit()
    
    with Session(engine.execution_options(schema_translate_map=map2)) as sess:
        sess.add(MyTable(name="this is schema two"))
        sess.commit()
    
    
    with Session(engine) as sess:
    
        @event.listens_for(sess, "do_orm_execute")
        def do_orm_execute(context):
            desired_schema = context.execution_options.get("desired_schema", None)
            if desired_schema:
                context.update_execution_options(
                    schema_translate_map={None: desired_schema},
    
                    # this part is ugly, so ORMExecuteState may be added
                    # an identity_token attribute that you can set here
                    _sa_orm_load_options=context.load_options
                    + {"_refresh_identity_token": desired_schema},
                )
    
        base_qry = sess.query(MyTable).filter(MyTable.id == 1)
    
        obj1 = base_qry.execution_options(desired_schema="test_schema").one()
    
        assert obj1.name == "this is schema one"
    
        obj2 = base_qry.execution_options(desired_schema="test_schema_2").one()
    
        assert obj2.name == "this is schema two"
    
        assert obj1 is not obj2

    as you can see above, there's one line of private API stuff, I can add a new attribute to ORMExecuteState that allows this to be set via public API and that would be safe for 1.4. I'd need to know what it is you need to do exactly.

  10. 3 remaining items

  11. zzzeek commented on Mar 23, 2022

    @zzzeek
    Member

    I had a look myself and started thinking the identity_token could be the place, but I'm always hesitant to reach too far into internals (We're currently stuck on 1.3 cause of touching internals that changed in 1.4). Using a single Session does have some desirable simplicity as well as keeping transactions across multiple schemas more straightfoward.

    But your last example there is much more self-contained than what I imagined I'd have to do to get to the identity_token. I'll work on rolling that into my actual codebase and see how it goes.

    My example uses 1.4-only APIs, none of that is in 1.3. for 1.3, take a look at the source code for horizontal_shard.py, you likely have to build a subclass of Session . identity_token is there but the internal mechanics of how an ORM statement runs, entirely different

  12. added
    use case
    and removed
    expected behavior
    on Mar 23, 2022
  13. added this to the 2.0 milestone on Mar 23, 2022
  14. changed the title [-]Session identity map doesn't differentiate on schema_translate_map[/-] [+]add identity_token API to ormexecutestate[/+] on Mar 23, 2022
  15. zzzeek commented on Mar 23, 2022

    @zzzeek
    Member

    milestoning at 2.0 for visibility, this can be backported to 1.4 if it's just the single identity_token element on ORMExecuteContext

  16. changed the title [-]add identity_token API to ormexecutestate[/-] [+]add identity_token API to ormexecutecontext[/+] on Mar 23, 2022
  17. gricey432 commented on Mar 23, 2022

    @gricey432
    Author

    OK so does your use case require SELECT only?

    No, full CRUD, I just showed SELECT as it was the simplest reproduction.

    My example uses 1.4-only APIs, none of that is in 1.3. for 1.3

    That's fine, the internals binding us to 1.3 are Session and Connection hacks to achieve this behaviour. So if this works we can upgrade to 1.4. I'd prefer to be up to date anyway, 2.0 looks amazing.

    For reference, we're currently achieving this in 1.3 using connection._branch() in a custom sessionmaker.

    It creates one base connection per thread, then when asked for a Session for a tenant_id it branches the base connection and sets the execution options on that. Then returns a Session for the configured connection. This achieves:

    • Session identity_map isolation
    • Single transaction across Sessions
    • bulk_insert_mappings, and Alembic all still work (we're planning on losing this, but it does currently work)
    # noinspection PyPep8Naming
    class tenant_scoped_session(object):
        """
        Provides scoped management of sqlalchemy Session objects.
    
        Based on and implements the same interface as sqlalchemy.orm.scoping.scoped_session
        See that object for more detailed docs on the functions
    
        This adds the ability to track multiple Session objects per thread or scope, and then manage them individually or
        in bulk
    
        This also performs the initial scoping of a new session to a tenant if needed
        """
    
        engine: Optional[Engine]
        session_class: Type[Session]
        _base_connection_registry: Dict[int, Connection]  # Store a connection per thread
        session_registry: Dict[int, Dict[Optional[int], Session]]
    
        def __init__(self) -> None:
            self.engine = None
            self.session_class = Session
            self._base_connection_registry = {}
            self.session_registry = defaultdict(dict)
    
        @classmethod
        def _scope(cls):
            return threading.get_ident()
    
        def __call__(self, tenant_id: Optional[int] = None) -> Session:
            """
            Finds the session in the session registry or creates it if it's missing. If there's no existing thread
            connection inside the connection registry, create one and then use it to make a scoped connection. When tenant_id
            is not None, use it in schema_translate_map for the connection clone to map tables to the correct schema,
            otherwise create a normal session and assign it to a None key inside the session registry.
    
            This functionality relies heavily on Connection::_branch, which is removed in Sqlalchemy 2
            """
            session_registry = self.session_registry[self._scope()]
    
            # Try return an existing session
            try:
                return session_registry[tenant_id]
            except KeyError:
                # Thread base connection
                if self._scope() not in self._base_connection_registry:
                    self._base_connection_registry[self._scope()] = Connection(self.engine)
    
                # Scoped connection branched off base connection
                # Branching allows the connections to share counters
                base_connection = self._base_connection_registry[self._scope()]
                scoped_connection = base_connection._branch()
    
                # Modify Connection._execution_options instead using Connection.execution_options directly to avoid the
                # call to _clone inside Connection.execution_options on the branched connection. This way we won't be using
                # a shallow copy of the branched connection, and should just establish session with the branched one.
                if tenant_id:
                    execution_opt = {
                        "schema_translate_map": {
                            None: f"tenant_{tenant_id}",
                        }
                    }
                    scoped_connection._execution_options = scoped_connection._execution_options.union(execution_opt)
                    if base_connection._has_events or base_connection.engine._has_events:
                        base_connection.dispatch.set_connection_execution_options(scoped_connection, execution_opt)
                    base_connection.dialect.set_connection_execution_options(scoped_connection, execution_opt)
    
                # Create session
                sess = self.session_class(bind=scoped_connection)
                session_registry[tenant_id] = sess
                return sess
    
        ...
        # Other methods removed for brevity
    
    
    SessionCreator = tenant_scoped_session()
    
    
    # Usage
    sess_1 = SessionCreator(1)

    Then we just have a few other things like flush flushes all branched connections.

    I'm aware it's not ideal, so I started looking at 1.4/2.0 compatible ways to achieve this.

  18. modified the milestones: 2.0, 2.0beta on Oct 11, 2022
  19. added
    duplicate
    on Oct 11, 2022
  20. zzzeek commented on Oct 14, 2022

    @zzzeek
    Member

    adding identity_token to ORM execute state is part of #7837

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    duplicatehorizontal shardingormquestionuse case

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions