  Developing high-performance applications that interact with databases is a
difficult task, as developers need to understand both the details of the
language in which their applications are written in, and also the intricacies
of the relational model. One popular solution to this problem is the use of
object-relational mapping (ORM) libraries that provide transparent access to
the database using the same language that the application is written in.
Unfortunately, using such frameworks can easily lead to applications with poor
performance because developers often end up implementing relational operations
in application code, and doing so usually does not take advantage of the
optimized implementations of relational operations, efficient query plans, or
push down of predicates that database systems provide. In this paper we present
QBS, an algorithm that automatically identifies fragments of application logic
that can be pushed into SQL queries. The QBS algorithm works by automatically
synthesizing invariants and postconditions for the original code fragment. The
postconditions and invariants are expressed using a theory of ordered relations
that allows us to reason precisely about the contents and order of the records
produced even by complex code fragments that compute joins and aggregates. The
theory is close in expressiveness to SQL, so the synthesized postconditions can
be readily translated to SQL queries. Using 40 code fragments extracted from
over 120k lines of open-source code written using the Java Hibernate ORM, we
demonstrate that our approach can convert a variety of imperative constructs
into relational specifications.
