Repository navigation
Closed as not planned
Description
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) # TrueError
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
Metadata
Metadata
Assignees
Labels
duplicateThis issue or pull request already existshorizontal shardingormquestionissue where a "fix" on the SQLAlchemy side is unlikely, hence more of a usage questionuse casenot really a feature or a bug; can be support for new DB features or user use cases not anticipated
Activity
zzzeek commentedon Mar 21, 2022
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.
add note that schema translate not supported per object
zzzeek commentedon Mar 21, 2022
I've added a note to the documentation section at https://docs.sqlalchemy.org/en/14/core/connections.html?highlight=schema_translate_map#schema-translating, where it discusses ORM use at the bottom, to clarify this.
zzzeek commentedon Mar 21, 2022
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.
note that horizontal sharding supports multi schema translates
note that horizontal sharding supports multi schema translates
zzzeek commentedon Mar 21, 2022
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.
zzzeek commentedon Mar 22, 2022
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:
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.
3 remaining items
zzzeek commentedon Mar 23, 2022
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
[-]Session identity map doesn't differentiate on schema_translate_map[/-][+]add identity_token API to ormexecutestate[/+]zzzeek commentedon Mar 23, 2022
milestoning at 2.0 for visibility, this can be backported to 1.4 if it's just the single identity_token element on ORMExecuteContext
[-]add identity_token API to ormexecutestate[/-][+]add identity_token API to ormexecutecontext[/+]gricey432 commentedon Mar 23, 2022
No, full CRUD, I just showed SELECT as it was the simplest reproduction.
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 customsessionmaker.It creates one base connection per thread, then when asked for a Session for a
tenant_idit branches the base connection and sets the execution options on that. Then returns a Session for the configured connection. This achieves:Then we just have a few other things like
flushflushes all branched connections.I'm aware it's not ideal, so I started looking at 1.4/2.0 compatible ways to achieve this.
zzzeek commentedon Oct 14, 2022
adding identity_token to ORM execute state is part of #7837