VALUES clause in SQLAlchemy

后端 未结 6 836
北海茫月
北海茫月 2020-12-01 17:26

Is there a way to build a Query object in SQLAlchemy which will be the equivalent of:

SELECT * FROM (VALUES (1, 2, 3)) AS sq;

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-01 17:43

    Not the best solution but it worked for me:

    import sqlalchemy as sa
    
    query = sa.select(['*']).select_from(sa.text("(VALUES (1,2,3)) as sq"))
    connection.execute(query).fetchall()
    

    Output: [(1, 2, 3)]

    PS: VALUES with the aliased columns example:

    import sqlalchemy as sa
    
    query_cte = (
        sa.select([sa.column('age'), sa.column('name')])
            .select_from(sa.text("(VALUES (22, 'Bob'), (30, 'Julia')) as t (age, name)"))
    ).cte()
    query_name = sa.select([query_cte.c.name])
    connection.execute(query_name).fetchall()
    

    Output: [('Bob',), ('Julia',)]

    WARNING: This solution is good for simple values. Be careful with the special symbols or words, they should be properly escaped.

提交回复
热议问题