Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sqlalchemy JSONB jsonb_to_recordset

i.m trying to convert sql statement to sqlalchemy ORM statement (expressions on jsonB) but in sqlalchemy i cannot find hot to use JSONB jsonb_to_recordset function

Here my expression in SQL (work perfectly)

select title, items.name, items.exist_data, items.found
        from loaninformation,jsonb_to_recordset(loaninformation.general_info) 
                                                as items(name text, exist_data text, found bool)
        where title='r12' and items.name='Investor';

In sqlalchemy with text i did it (it works)

s = text("""select title, items.name, items.exist_data, items.found
                                        from loaninformation,jsonb_to_recordset(loaninformation.general_info)
                                                as items(name text, exist_data text, found bool)
                                                    where title=:title and items.name=:investor_name;""")

In sqlalchemy ORM i try code below (but code is incorrect)

 query = session.query(items.name, items.exist_data, items.found sqlalchemy.func.jsonb_to_recordset(LoanInformation.general_info).\
            label("items"(name text, exist_data text, found bool))
    query = query.filter(and_(LoanInformation.title=='r12', LoanInformation.items.name=='Investor'))

How can i do it in sqlalchemy ORM?

like image 812
dmitriy_one Avatar asked Mar 19 '26 10:03

dmitriy_one


1 Answers

In SQLAlchemy 1.4 you can build the query without having to resort to using text:

from sqlalchemy import func, column, Text, Boolean

items = func.jsonb_to_recordset(LoanInformation.general_info).\ 
    table_valued(
        column("name", Text),
        column("exist_data", Text),
        column("found", Boolean)).\
    render_derived(with_types=True)

query = session.query(
        LoanInformation.title,
        items.c.name,
        items.c.exist_data,
        items.c.found).\
    filter(LoanInformation.title == 'r12',
           items.c.name == 'Investor')
like image 141
Ilja Everilä Avatar answered Mar 21 '26 23:03

Ilja Everilä



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!