问题
Intro: I'm writing web interface with SQLAlchemy reflection that supports multiple databases. It turns out that authors of application defined postgresql with lowercase tables/columns, eg. job.jobstatus while sqlite has mixed case, eg Job.JobStatus. I'm using DeclarativeReflectedBase from examples to combine reflection and declarative style.
The issue: Configure SQLAlchemy to work with tables/columns case insensitive with reflection
I have done so far:
- I have changed DeclarativeReflectedBase.prepare() method to pass quote=False into Table.__init__
What is left to be solved:
- relationship definitions still has to obey case when configuring joins, like primaryjoin="Job.JobStatus==Status.JobStatus".
- configure __tablename__ based on engine type
The question: Are my assumptions correct or is there more straightforward way? Maybe I could tell reflection to reflect everything lowercase and all problems are gone.
回答1:
you'd probably want to look into defining a ".key" on each Column that's in lower case, that way you can refer to columns as lower case within application code. You should use the column_reflect event (See http://docs.sqlalchemy.org/en/latest/core/events.html#schema-events) to define this key as a lower case version of the .name.
then, when you reflect the table, I'd just do something like this:
def reflect_table(name, engine):
if engine.dialect.name == 'postgresql':
name = name.lower()
return Table(name, autoload=True, autoload_with=engine)
my_table = reflect_table("MyTable", engine)
I think that might cover it.
来源:https://stackoverflow.com/questions/9383837/sqlalchemy-reflection-different-backends-and-table-column-case-insensitivity