skip to Main Content

I have a query such as:

select_query = [text(f) for f in fields]
with engine.connect() as conn:
    query = select(*select_query, MyTable.id).select_from(
        table(MyTable.__tablename__) ...

Everything works fine except when the field (inside select_query) is camelcase. Is there any function or directive to pass sqlalchemy so the camelcase fields do not break the select ?

2

Answers


  1. Chosen as BEST ANSWER

    @snakecharmerb's answer is correct, however I forgot to specify that my "fields" strings also contains the table ("table.myColumn"). So I had to do some lunatic scripting to fix my problem

        list_strings = [
            f.rsplit('.', 1)[0] + '.' + engine.dialect.identifier_preparer.quote(f.rsplit('.', 1)[1])
            for f in fields
        ]
        select_query: List[TextClause] = [text(f) for f in list_strings]
    

    This works, however, I recommend to anyone who can to switch to snake case for db fields


  2. You can get the behaviour that you want using the column construct (note the lower-case "c") rather than the text construct. Using column tells SQLAlchemy that it is dealing with a column name rather than some arbitrary SQL fragment, so it can assume that the name is correctly cased and quote accordingly.

    import sqlalchemy as sa
    ...
    select_query = [sa.column(f) for f in fields] 
    ...
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search