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() ) ))