SQLAlchemy, reflection, different backends and table/column case insensitivity

▼魔方 西西 提交于 2021-02-19 07:53:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!