What does Ecto DB Alias do?

This code is not explained in the Programming Ecto book,

alias MusicDB.{Repo, Artist}

I know that the code produces a list of [MusicDB.Repo, MusicDB.Artist] but what does this actually do for Ecto programming?

It doesn’t really have anything to do with ecto itself, but rather plain elixir: https://hexdocs.pm/elixir/Kernel.SpecialForms.html#alias/2

8 Likes

Like @LostKobrakai said this is plain Elixir not Ecto. In Elixir Module names can have dots . to create a namespace or hierarchy. So if you examine the file structure in the MusicDB sample code you’ll notice that in lib/music_db there’s a bunch of modules prefixed with the name MusicDB like this

MusicDB.Artist
MusicDB.Track
MusicDB.Repo

So the modules Artist, Track, Repo are all namespaced under MusicDB. And when you need to refer to these modules instead of typing MusicDB.Artist you can use the alias macro to save yourself some typing and shorten your code like this.

alias MusicDB.Artist

Now instead of typing MusicDB.Artist you can just type Artist

When you need to refer to multiple modules under the same namespace you can write your alias like this.

alias MusicDB.{Repo, Artist}

So in the Programming Ecto book when you open up iex if you don’t use alias MuscDB.{Repo, Artist} you would have to type it like this.

MusicDB.Repo.insert(%MusicDB.Artist{name: "Dizzy Gillespie"})

So using an alias can save you a lot of typing especially in iex.

2 Likes

a little tip is to put the alias etc in the .iex.exs file - then it’s available in iex

https://hexdocs.pm/iex/IEx.html#module-the-iex-exs-file

eg mine looks like this:

import Ecto.Query
import Ecto.Changeset
alias Phoenix.Presence

alias MyApp.{
  Repo,
  User,
  Booking,
  Event,
  Meeting,
  Subscription
}
5 Likes