Current section

Files

Jump to
gleam_mongo src mongo@client.erl
Raw

src/mongo@client.erl

-module(mongo@client).
-compile(no_auto_import).
-export([connect/2, db/2, collection/2, execute/2]).
-export_type([connection/0, database/0, collection/0]).
-opaque connection() :: {connection, tcp:socket()}.
-opaque database() :: {database, connection(), binary()}.
-type collection() :: {collection, database(), binary()}.
-spec connect(binary(), integer()) -> {ok, connection()} | {error, nil}.
connect(Ip, Port) ->
case tcp:connect(Ip, Port) of
{ok, Socket} ->
{ok, {connection, Socket}};
{error, nil} ->
{error, nil}
end.
-spec db(connection(), binary()) -> database().
db(Connection, Name) ->
{database, Connection, Name}.
-spec collection(database(), binary()) -> collection().
collection(Db, Name) ->
{collection, Db, Name}.
-spec execute(collection(), bson@types:value()) -> {ok,
list({binary(),
bson@types:value()})} |
{error, nil}.
execute(Collection, Cmd) ->
{document, Body@1} = case Cmd of
{document, Body} -> {document, Body};
_try ->
erlang:error(#{gleam_error => assert,
message => <<"Assertion pattern match failed"/utf8>>,
value => _try,
module => <<"mongo/client"/utf8>>,
function => <<"execute"/utf8>>,
line => 37})
end,
Cmd@1 = [{<<"$db"/utf8>>,
{str, erlang:element(3, erlang:element(2, Collection))}} |
Body@1],
Encoded = bson:encode(Cmd@1),
Size = gleam@bit_string:byte_size(Encoded) + 21,
Packet = begin
_pipe = [<<Size:32/little, 0:32, 0:32, 2013:32/little, 0:32, 0>>,
Encoded],
gleam@bit_string:concat(_pipe)
end,
case begin
_pipe@1 = erlang:element(
2,
erlang:element(2, erlang:element(2, Collection))
),
tcp:send(_pipe@1, Packet)
end of
ok ->
case begin
_pipe@2 = erlang:element(
2,
erlang:element(2, erlang:element(2, Collection))
),
tcp:'receive'(_pipe@2)
end of
{ok, Response} ->
<<_@1:168, Rest/bitstring>> = Response,
case bson:decode(Rest) of
{ok, Result} ->
{ok, Result};
{error, nil} ->
{error, nil}
end;
{error, nil} ->
{error, nil}
end;
_@2 ->
{error, nil}
end.