vendredi 26 février 2021

Why doesn't SQLAlchemy reflect tables in non-public schema?

I have a PostgreSQL database, which has had all objects in public schema. Used SQLAlchemy to succesfully connect to it and reflect objects from it.

Now I needed to create a separate schema schema2 in the same database. I assigned to new user all rights in that schema, checked that I can connect from command line with psql and do things in it.

But SQLAlchemy doesn't see any tables in the schema, when I try to use the same method to reflect its tables -- despite trying various ways to specify schema!

This is what worked for initial connection to public schema:

from sqlalchemy.ext.automap import automap_base
from sqlalchemy import create_engine
from sqlalchemy import Table, Integer, String, Text,  Column, ForeignKey

Base=automap_base()
sql_conn='postgres://my_user@/foo'
engine=create_engine(sql_conn)

Base.prepare(engine, reflect=True)

Then I could use Base.classes.* for tables and I didn't need to create Table classes on my own.

Now, this same works for this new user for public schema as well.

But whenever I somehow try to pass the schema2 to reflect tables from schema2, I always get empty Base.classes.*

I tried all the solutions in SQLAlchemy support of Postgres Schemas but I don't get anything at all reflected!

I tried:

  • making user's default schema schema2 via SQL means: ALTER new_user SET search_path=schema2;

  • tried to pass schema in engine.connect via engine options

  • tried to set schema in MetaData and use that, as per SQLAlchemy docs:

Doing:

meta=MetaData(bind=engine,schema='schema2')
meta.reflect()

does work, as I can see all the tables correctly in meta.tables afterwards.

However, when I try to get Base.classes working as per SQLAlchemy automapper docs, the Base.classes don't get populated:

from sqlalchemy.ext.automap import automap_base
from sqlalchemy import create_engine
from sqlalchemy import Table, Integer, String, Text,  Column, ForeignKey, MetaData

sql_conn='postgres://new_user@/foo'
engine=create_engine(sql_conn)
meta=MetaData(bind=engine,schema='schema2') 
Base=automap_base(metadata=meta)
Base.prepare(engine, reflect=True)

Base.classes is empty...

I am now stumped. Any ideas?

PS. I am working on newest SQLAlchemy available (1.3) under pip for Python2.7, Ubuntu 18.04LTS.





Aucun commentaire:

Enregistrer un commentaire