WesoviLabs
Sharing knowledge

Getting started with Elixir - Ecto

Jul 16, 2016

Purpose

The purpose of this article is sharing with other geeks my experience developing an application with Elixir. A few months ago I just did
some researches in coding with Erlang and to be honest I really enjoyed it writing the article First steps with Erlang, but this time I will go for a more real application which could provide me with some better feedback
about this functional programming language.

What’s Elixir?

Elixir is a dynamic, functional language designed for building scalable and maintainable applications and run over the Erlang Virtual Machine

What’s Ecto?

Ecto is a database wrapper that makes the life easier for Elixir developers who need to make use of database in their applications. Ecto works with Postgresql,
Mysql, MSSQL, SQLite3 and MongoDB.

In this tutotial we will be working with a Postgresql but we could do de same with any of the above databases.

Creating the project

By this point I assume you all have elixir installed on your computer. If not, you only need to got to the Elixir Siteand follow the installation steps.

Create the project

mix new -app <APP_NAME>

This will create some directories:

_build: This directory contains only compiled code and libraries.

config: Configuration for our application.

deps: Dependencies used by this application.

lib: The code of our project.

test: Unit testing for our application

mix.exs: In this file we define the dependencies and the application modules.

priv/repo: SQL scripts and Elixir migration scripts.

Adding dependencies

Since we are working with Postgresql we need to add the driver beside of the Ecto dependency.

So in the mix.exs file we add the below

...defapplicationdo[applications:[:logger,:postgrex,:ecto]]end

defpdepsdo[{:postgrex,">= 0.0.0"},{:ecto,"~> 2.0.0"}]end...

and to downlaod dependcy we run the command

mix deps.get

Configuring our database connection

First af all we create a Repo for our application. We create a new file in directory lib,

and then we edit file /config/config.exs to define the database driver connection. For this tutorial we assume
a postgresql instance run on port 3001 (we can make use of docker-compose.yml in docker directory)