Skip to content

Instantly share code, notes, and snippets.

@jokokko
Created August 8, 2016 07:17
Show Gist options
  • Save jokokko/4085f085eaef970ca87fea8337bb1927 to your computer and use it in GitHub Desktop.
Save jokokko/4085f085eaef970ca87fea8337bb1927 to your computer and use it in GitHub Desktop.
using System;
using System.Text;
namespace Marten.Services.Events
{
public class AssertEventStreamMaxEventId : IStorageOperation
{
private readonly Guid stream;
private readonly int expectedVersion;
private readonly string tableName;
public AssertEventStreamMaxEventId(Guid stream, int expectedVersion, string tableName)
{
this.stream = stream;
this.expectedVersion = expectedVersion;
this.tableName = tableName;
}
public string _sql;
void ICall.WriteToSql(StringBuilder builder)
{
builder.Append(_sql);
}
public void AddParameters(IBatchCommand batch)
{
// Parameterized queries won't work here: https://github.com/npgsql/npgsql/issues/331
_sql = $@"DO $$ BEGIN IF
(SELECT max(events.version)
FROM {tableName} AS events
WHERE events.stream_id = '{stream}') <> {expectedVersion} THEN
RAISE EXCEPTION 'Unexpected MAX(id) for event stream'; END IF; END; $$;";
}
public override string ToString()
{
return _sql;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment