|
| 1 | +(erlang-epgsql)= |
| 2 | + |
| 3 | +# Erlang epgsql |
| 4 | + |
| 5 | +:::{div} sd-text-muted |
| 6 | +Connect to CrateDB from Erlang using epgsql. |
| 7 | +::: |
| 8 | + |
| 9 | +:::{rubric} About |
| 10 | +::: |
| 11 | + |
| 12 | +[epgsql] is the designated Erlang PostgreSQL client library. |
| 13 | + |
| 14 | +:::{rubric} Synopsis |
| 15 | +::: |
| 16 | + |
| 17 | +`rebar.config` |
| 18 | +```erlang |
| 19 | +{deps, |
| 20 | + [ |
| 21 | + {epgsql, ".*", {git, "https://github.com/epgsql/epgsql.git", {tag, "4.8.0"}}} |
| 22 | + ]}. |
| 23 | +``` |
| 24 | +`epgsql_example.erl` |
| 25 | +```erlang |
| 26 | +-module(epgsql_example). |
| 27 | +-export([start/0]). |
| 28 | + |
| 29 | +start() -> |
| 30 | + {ok, C} = epgsql:connect(#{ |
| 31 | + host => "localhost", |
| 32 | + username => "crate", |
| 33 | + password => "crate", |
| 34 | + database => "doc", |
| 35 | + port => 5432, |
| 36 | + timeout => 4000 |
| 37 | + }), |
| 38 | + {ok, _, Result} = epgsql:squery(C, "SELECT mountain, height FROM sys.summits ORDER BY height DESC LIMIT 3"), |
| 39 | + io:fwrite("~p~n", [Result]), |
| 40 | + ok = epgsql:close(C), |
| 41 | + init:stop(). |
| 42 | +``` |
| 43 | + |
| 44 | +:::{rubric} SSL connection |
| 45 | +::: |
| 46 | + |
| 47 | +Start the Erlang [SSL application] first, |
| 48 | +use the `ssl` and `ssl_opts` arguments on `epgsql:connect`, and |
| 49 | +replace username, password, and hostname with values matching |
| 50 | +your environment. |
| 51 | + |
| 52 | +Also use this variant to connect to CrateDB Cloud. |
| 53 | +```erlang |
| 54 | +start() -> |
| 55 | + ssl:start(), |
| 56 | + {ok, C} = epgsql:connect(#{ |
| 57 | + host => "testcluster.cratedb.net", |
| 58 | + username => "admin", |
| 59 | + password => "password", |
| 60 | + database => "doc", |
| 61 | + port => 5432, |
| 62 | + ssl => true, |
| 63 | + ssl_opts => [{verify, verify_none}], |
| 64 | + timeout => 4000 |
| 65 | + }), |
| 66 | +``` |
| 67 | + |
| 68 | +:::{rubric} Example |
| 69 | +::: |
| 70 | + |
| 71 | +Create the files `rebar.config` and `epgsql_example.erl` including the synopsis code shared above. |
| 72 | + |
| 73 | +:::{include} ../_cratedb.md |
| 74 | +::: |
| 75 | +```shell |
| 76 | +rebar3 compile |
| 77 | +erlc epgsql_example.erl |
| 78 | +rebar3 shell --eval 'epgsql_example:start().' |
| 79 | +``` |
| 80 | + |
| 81 | + |
| 82 | +[epgsql]: https://github.com/epgsql/epgsql |
| 83 | +[SSL application]: https://www.erlang.org/docs/28/apps/ssl/ssl_app.html |
0 commit comments