0

I have an SQL query that inserts a row into a table. One of the columns is assigned a value returned from sub-query that aggregates multiple values using string_agg. How can this be written using SQLAlchemy ORM?

The postgres query

INSERT INTO blobs (_id, data) VALUES (nextval('blobs_id_seq'),
  (SELECT string_agg(blobs.data, NULL ORDER BY blobs._id DESC) 
    FROM blobs where blobs._id IN (1,2) ) );

The table ORM

    class Blob(Base):
      __tablename__ = 'blobs'
      _id = Column(Integer, Sequence('blobs_id_seq'), primary_key=True, unique=True)
     data = Column(LargeBinary)

    Base.metadata.create_all(engine)

    db = Session(engine)
    db.add(Blob(data=b'aa'))
    db.add(Blob(data=b'bb'))
    db.add(Blob(data=b'cc'))
    db.commit()

Invalid ORM insert

    # Should yield a "Blob" with data = b"bbaa"
    db.add(Blob(data=db.query(func.string_agg(Blob.data, None))
      .filter( Blob._id.in_([1, 2]) )
      .order_by( Blob._id.desc() ) ))

1 Answer 1

0

It turns out there is a dialect specific helper aggregate_order_by that renders a query that outputs the expected results.

db.add(Blob(data=db.query(func.string_agg(Blob.data,
    aggregate_order_by(None, Blob._id.desc())))
  .filter( Blob._id.in_([1, 2]) )))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.