inspection does not update mapper schema when schema assigned to declarative during runtime

4 views
Skip to first unread message

Peter Lai

unread,
Jul 2, 2020, 12:23:24 PM7/2/20
to sqlalchemy
It appears that if during runtime I assign a schema to declarative, then `inspect()` it, the resulting Selectable does not have the schema assigned to it:

in model.py:

from sqlalchemy import Column, String, DateTime
from sqlalchemy.ext.declarative import declarative_base


Base = declarative_base()


class MyClass(Base):
    __tablename__
= 'mytable'


    username
= Column(String(128), primary_key=True)


    
in run.py:

from sqlalchemy import create_engine, inspect

from model import MyClass

engine
= sqlalchemy.create_engine(...)

MyClass.schema = 'notme'

# I just want to do a manual select on the table not use a session

mytable
= inspect(MyClass).local_table

result
= engine.execute(mytable.select().first())

#This fails because for the given connection the select table must be qualified under schema 'notme'

#The solution seems to be to assign schema to the Selectable itself, not the declarative:

mytable
.schema = 'notme'



Is this an expected behavior?


Mike Bayer

unread,
Jul 2, 2020, 3:01:09 PM7/2/20
to noreply-spamdigest via sqlalchemy
yes, there is no significance to an attribute named "schema" on a declarative class.  to set the schema name for a table on the declarative class, __table_args__ must be used as documented at https://docs.sqlalchemy.org/en/13/orm/extensions/declarative/table_config.html?highlight=__table_args__

additionally it's not a good idea to change ".schema" on an already created Table object as the table will be mis-classified within its owning MetaData collection and it will also not work properly with statement caching.








--
SQLAlchemy -
The Python SQL Toolkit and Object Relational Mapper
 
 
To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description.
---
You received this message because you are subscribed to the Google Groups "sqlalchemy" group.
To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+...@googlegroups.com.

Reply all
Reply to author
Forward
0 new messages