Timo
Timo

Reputation: 5390

How to replace Postgres array elements using SQLAlchemy ORM?

Suppose we have a Postgres table with an integer array column xs:

create table mytable (
    id bigserial primary key,
    xs int[]
);

Using Postgres 9.4 and SQLAlchemy 1.0.14, I want to replace a single value (for example 123) in all of rows in xs column. What I have now is a raw SQL query that looks like

update mytable set xs = array_replace(xs, 123, 456) where 123 = any(xs)

The 123 = any(xs) is just to speed up query as otherwise we would replace all rows not regarding whether the interesting value is in the array or not.

How could I rewrite the above query using the SQLAlchemy ORM when I already have MyTable mapped?

Upvotes: 2

Views: 2327

Answers (1)

Ilja Everilä
Ilja Everilä

Reputation: 52929

Assuming you're using the correct postgresql.ARRAY type:

from sqlalchemy import  func

session.query(MyTable).\
    filter(MyTable.xs.any(123)).\
    update({MyTable.xs: func.array_replace(MyTable.xs, 123, 456)},
           synchronize_session=False)

Change the synchronization as necessary.

Upvotes: 4

Related Questions