Organize The Application Core and Boundary

Let's learn how to write queries for Phoenix LiveView.

In the previous lessons, we didn’t need to execute more complex queries than the CRUD-supporting ones provided by generated code. Our survey feature is a bit different, however. To support the survey functionality, we’ll need to execute some custom queries. In this lesson, we’ll learn how to compose and execute complex database queries with Ecto, and we’ll see how this work fits into the organized core and boundary layers of an application. Then, we’ll be ready to use our custom queries in the survey LiveView.

Ecto query composition, as we already know, is certain and predictable. It belongs in our application’s core. But where exactly in the core should we put code that dynamically constructs complex queries?

Queries are a little bit like functions. It’s fine to express short ones in-line, much like anonymous functions, within the scope of a module like a context. However, it is important to provide a first-class function to express and name more complex queries. These functions belong in their very own dedicated query builder modules in the application core. Before we build any such modules, however, let’s discuss the queries that our survey feature will need to use.

We will need the following individual queries to support the survey feature:

  • The demographic section of our survey will need a query to return the demographic for a given user.
  • The rating section of the survey will rely on a query to return all products with preloaded ratings for a given user.

Let’s begin with the first query.

Get hands-on with 1200+ tech skills courses.