Create a Makefile
, see the erlang.mk getting started guide.
PROJECT = example1
DEPS = epgsql
include erlang.mk
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.
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.
- Pooling of pg connection
- Implement select and insert(sanitize inputs) into pg
- Implement notice to client via web sockets