Skip to content
Advertisement

With sqlalchemy one() function can more than one row be returned from the database engine?

From the documentation:

Return exactly one result or raise an exception.

This is from the function call. What I am wondering is that if the database engine is running somewhere else with communication via tcp (for example), can the machine running the SQLAlchemy application ever receive more than one result?

I would assume this would be independent of DB but if this isn’t the case my question is for hana DB.

Advertisement

Answer

Behind the scenes Query.one() uses a “fetch one” approach, but that is not the whole story. Whether or not your client first buffers the entire query result depends on your driver in use and the DBMS – for example if it supports server side cursors or not.

Also, SQLAlchemy Query deduplicates single ORM entity results, such as

session.query(MyModel).one()

In order to do that it has to keep on reading the result set until it either finds a non-unique result, in which case it raises an exception, or there are no more results. One might wonder when could there even be such duplicates, and an answer to that is “when using joins”:

session.query(MyModel).join(MyModelChild).one()

The end result is that it has to read the entire result set, or up to first non-unique result, if using the ORM and the Query API, or Result.scalar_one() in the 2.0 style API.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement