Packages
eventstore
0.6.2
1.4.8
1.4.7
1.4.6
1.4.4
1.4.3
1.4.2
1.4.1
1.4.0
1.3.2
1.3.1
1.3.0
1.2.3
1.2.2
1.2.1
1.2.0
1.1.0
1.0.3
1.0.2
1.0.1
1.0.0
1.0.0-rc.0
0.17.0
0.16.2
0.16.1
0.16.0
0.15.1
0.15.0
0.14.0
0.14.0-rc.0
0.13.2
0.13.1
0.13.0
0.12.1
0.12.0
0.11.0
0.11.0-rc.0
0.10.1
0.10.0
0.9.0
0.8.1
0.8.0
0.7.4
0.7.3
0.7.2
0.7.1
0.7.0
0.6.2
0.6.1
0.6.0
0.5.2
0.5.1
0.5.0
0.4.3
0.4.2
0.4.1
0.4.0
0.3.0
0.2.1
0.2.0
0.1.0
0.0.5
0.0.4
0.0.3
0.0.2
0.0.1
Event store using PostgreSQL for persistence.
Current section
Files
Jump to
Current section
Files
lib/event_store/storage/stream.ex
defmodule EventStore.Storage.Stream do
@moduledoc """
Streams are an abstraction around a stream of events for a given stream identity
"""
require Logger
alias EventStore.Sql.Statements
alias EventStore.Storage.{QueryLatestEventId,QueryLatestStreamVersion,QueryStreamInfo,Reader}
def create_stream(conn, stream_uuid) do
_ = Logger.debug(fn -> "attempting to create stream \"#{stream_uuid}\"" end)
conn
|> Postgrex.query(Statements.create_stream, [stream_uuid])
|> handle_create_response(stream_uuid)
end
def read_stream_forward(conn, stream_uuid, start_version, count \\ nil) do
execute_with_stream_id(conn, stream_uuid, fn stream_id ->
Reader.read_forward(conn, stream_id, start_version, count)
end)
end
def read_all_streams_forward(conn, start_event_id, count \\ nil) do
Reader.read_all_forward(conn, start_event_id, count)
end
def latest_event_id(conn) do
QueryLatestEventId.execute(conn)
end
def stream_info(conn, stream_uuid) do
QueryStreamInfo.execute(conn, stream_uuid)
end
def latest_stream_version(conn, stream_uuid) do
execute_with_stream_id(conn, stream_uuid, fn stream_id ->
QueryLatestStreamVersion.execute(conn, stream_id)
end)
end
defp execute_with_stream_id(conn, stream_uuid, execute_fn) do
case lookup_stream_id(conn, stream_uuid) do
{:ok, stream_id} -> execute_fn.(stream_id)
response -> response
end
end
defp handle_create_response({:ok, %Postgrex.Result{rows: [[stream_id]]}}, stream_uuid) do
_ = Logger.debug(fn -> "created stream \"#{stream_uuid}\" (id: #{stream_id})" end)
{:ok, stream_id}
end
defp handle_create_response({:error, %Postgrex.Error{postgres: %{code: :unique_violation}}}, stream_uuid) do
_ = Logger.warn(fn -> "failed to create stream \"#{stream_uuid}\", already exists" end)
{:error, :stream_exists}
end
defp handle_create_response({:error, error}, stream_uuid) do
_ = Logger.warn(fn -> "failed to create stream \"#{stream_uuid}\"" end)
{:error, error}
end
defp lookup_stream_id(conn, stream_uuid) do
conn
|> Postgrex.query(Statements.query_stream_id, [stream_uuid])
|> handle_lookup_response(stream_uuid)
end
defp handle_lookup_response({:ok, %Postgrex.Result{num_rows: 0}}, stream_uuid) do
_ = Logger.warn(fn -> "attempted to access unknown stream \"#{stream_uuid}\"" end)
{:error, :stream_not_found}
end
defp handle_lookup_response({:ok, %Postgrex.Result{rows: [[stream_id]]}}, _) do
{:ok, stream_id}
end
end