Get Started With Postgres

View Source

Installation

We recommend reading up on postgresql if you haven't.

mix igniter.install ash_postgres

Adding AshPostgres to your resources

You can add AshPostgres to a resource with mix ash.patch.extend Your.Resource.Name postgres. For example:

mix ash.patch.extend Helpdesk.Support.Ticket postgres
mix ash.patch.extend Helpdesk.Support.Representative postgres

Create the database and tables

First, we'll create the database with mix ash.setup.

Then we will generate database migrations. This is one of the many ways that AshPostgres can save time and reduce complexity.

For example:

mix ash.codegen add_tickets_and_representatives

If you are unfamiliar with database migrations, it is a good idea to get a rough idea of what they are and how they work. See the links at the bottom of this guide for more. A rough overview of how migrations work is that each time you need to make changes to your database, they are saved as small, reproducible scripts that can be applied in order. This is necessary both for clean deploys as well as working with multiple developers making changes to the structure of a single database.

Typically, you need to write these by hand. AshPostgres, however, will store snapshots each time you run the command to generate migrations and will figure out what migrations need to be created.

You should always look at the generated migrations to ensure that they look correct. Do so now by looking at the generated file in priv/repo/migrations.

Finally, we will create the local database and apply the generated migrations:

mix ash.setup

Try it out

This is based on the Get Started guide. If you haven't already, you should read that first.

And now we're ready to try it out! Run the following in iex:

Lets create some data. We'll make a representative and give them some open and some closed tickets.

require Ash.Query

representative = (
  Helpdesk.Support.Representative
  |> Ash.Changeset.for_create(:create, %{name: "Joe Armstrong"})
  |> Ash.create!()
)

for i <- 0..5 do
  ticket =
    Helpdesk.Support.Ticket
    |> Ash.Changeset.for_create(:open, %{subject: "Issue #{i}"})
    |> Ash.create!()
    |> Ash.Changeset.for_update(:assign, %{representative_id: representative.id})
    |> Ash.update!()

  if rem(i, 2) == 0 do
    ticket
    |> Ash.Changeset.for_update(:close)
    |> Ash.update!()
  end
end

And now we can read that data. You should see some debug logs that show the sql queries AshPostgres is generating.

require Ash.Query

# Show the tickets where the subject contains "2"
Helpdesk.Support.Ticket
|> Ash.Query.filter(contains(subject, "2"))
|> Ash.read!()
require Ash.Query

# Show the tickets that are closed and their subject does not contain "4"
Helpdesk.Support.Ticket
|> Ash.Query.filter(status == :closed and not(contains(subject, "4")))
|> Ash.read!()

And, naturally, now that we are storing this in postgres, this database is persisted even if we stop/start our application. The nice thing, however, is that this was the exact same code that we ran against our resources when they were backed by ETS.

Aggregates

Lets add some aggregates to our representatives resource. Aggregates are a tool to include grouped up data about relationships. You can read more about them in the Aggregates guide.

Here we will add an aggregate to easily query how many tickets are assigned to a representative, and how many of those tickets are open/closed.

# in lib/helpdesk/support/representative.ex

  aggregates do
    # The first argument here is the name of the aggregate
    # The second is the relationship
    count :total_tickets, :tickets

    count :open_tickets, :tickets do
      # Here we add a filter over the data that we are aggregating
      filter expr(status == :open)
    end

    count :closed_tickets, :tickets do
      filter expr(status == :closed)
    end
  end

Aggregates are powerful because they will be translated to SQL, and can be used in filters and sorts. For example:

# in iex

require Ash.Query

Helpdesk.Support.Representative
|> Ash.Query.filter(closed_tickets < 4)
|> Ash.Query.sort(closed_tickets: :desc)
|> Ash.read!()

You can also load individual aggregates on demand after queries have already been run, and minimal SQL will be issued to run the aggregate.

# in iex

require Ash.Query

representatives = Helpdesk.Support.read!(Helpdesk.Support.Representative)

Ash.load!(representatives, :open_tickets)

Calculations

Calculations can be pushed down into SQL in the same way. Calculations are similar to aggregates, except they work on individual records. They can, however, refer to aggregates on the resource, which opens up powerful possibilities with very simple code.

For example, we can determine the percentage of tickets that are open:

# in lib/helpdesk/support/representative.ex

  calculations do
    calculate :percent_open, :float, expr(open_tickets / total_tickets)
  end

Calculations can be loaded and used in the same way as aggregates.

require Ash.Query

Helpdesk.Support.Representative
|> Ash.Query.filter(percent_open > 0.25)
|> Ash.Query.sort(:percent_open)
|> Ash.Query.load(:percent_open)
|> Ash.read!()

Rich Configuration Options

Take a look at the DSL documentation for more information on what you can configure. You can add check constraints, configure the behavior of foreign keys, use postgres schemas with Ash's multitenancy feature, and more!

What next?

  • Check out the data layer docs: AshPostgres.DataLayer

  • Ecto's documentation. AshPostgres (and much of Ash itself) is made possible by the amazing Ecto. If you find yourself looking for escape hatches when using Ash or ways to work directly with your database, you will want to know how Ecto works. Ash and AshPostgres intentionally do not hide Ecto, and in fact encourages its use whenever you need an escape hatch.

  • Postgres' documentation. Although AshPostgres makes things a lot easier, you should understand the basics of postgres and SQL.

  • Ecto's Migration documentation read more about migrations. Even with the ash_postgres migration generator, you will very likely need to modify your own migrations some day.