Skip to content

Instantly share code, notes, and snippets.

@Morabaraba
Created August 27, 2016 22:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Morabaraba/abe8e054039ea76a74e44e1408c0b774 to your computer and use it in GitHub Desktop.
Save Morabaraba/abe8e054039ea76a74e44e1408c0b774 to your computer and use it in GitHub Desktop.
Basic erlang.mk and epgsql

PostgreSQL + Erlang

erlang.mk

Create a Makefile, see the erlang.mk getting started guide.

PROJECT = example1
DEPS = epgsql
include erlang.mk

repl

Start your PostgreSQL Server and open up your erl repl(read–eval–print loop) by typing make run in your terminal. Make sure epgsql is loaded by running.

m(epgsql).

if it loads successfully you will see the module's information. To connect to our database run.

{ok, Connection} = epgsql:connect("<hostname>", "<username>", "<password>", [{database, "<dbname>"}]).

This will return a connection that we can then use to interact with the database. Create a table by running the following Simple Query.

{ok, [], []} = epgsql:squery(Connection, 
    "CREATE TABLE IF NOT EXISTS event (_id TEXT PRIMARY KEY, at TIMESTAMP, meta JSONB);").

Now to insert data into our database run.

{ok, 1} = epgsql:squery(Connection, 
    "INSERT INTO event (_id, at, meta) VALUES ('postgres+erlang+rocks', now(), '{\"learning\": \"Welcome to Erlang and PostgreSQL.\"}'::JSONB);").

This returns {ok, N}, where N is the number of rows inserted. Lets go head and add two more items into our database.

{ok, 2} = epgsql:squery(Connection, "INSERT INTO event (_id, at, meta) VALUES ('blank meta', now(), NULL), ('blank meta', now(), '{}') ;").

In order to query our database we can also use a Simple Query.

{ok, Cols, Rows} =  epgsql:squery(Connection, "SELECT * FROM event;").

This will return all the data in the row as binary data. In order to get data returned typed correctly we need to use an extended query:

{ok, Cols, Rows} =  epgsql:equery(Connection, "SELECT * FROM event;").

That's how you can connect to and get data in and out of a Postgres database using Erlang.

Now lets close the connection by running

epgsql:close(Connection).

Original article by Reza Nikoopour can be found here.

Cowboy web sockets

We will wrap our queries around cowboy web socket handlers.

To get up and running with cowboy web sockets look at the example

I git cloned cowboy

git clone git@github.com:ninenines/cowboy.git

and make run the example.

TODO

  • Pooling of pg connection
  • Implement select and insert(sanitize inputs) into pg
  • Implement notice to client via web sockets
⇐ [Introduction]
[frameworks] ⇒

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment