Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/AppCoreNet.EventStore.SqlServer/SqlServerEventStore.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Licensed under the MIT license.
// Licensed under the MIT license.
// Copyright (c) The AppCore .NET project.

using System;
Expand Down Expand Up @@ -62,6 +62,7 @@ public async Task WriteAsync(
StreamId = streamId,
ExpectedPosition = state.Value,
Events = events,
LockResource = _options.ApplicationName + "-WriteEvents",
};

Model.WriteEventsResult result =
Expand Down
12 changes: 10 additions & 2 deletions src/AppCoreNet.EventStore.SqlServer/WriteEventsStoredProcedure.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Licensed under the MIT license.
// Licensed under the MIT license.
// Copyright (c) The AppCore .NET project.

using System;
Expand All @@ -24,6 +24,8 @@ internal sealed class WriteEventsSqlStoredProcedure : SqlStoredProcedure<Model.W

required public IEnumerable<object> Events { get; init; }

required public string LockResource { get; init; }

public WriteEventsSqlStoredProcedure(DbContext dbContext, string? schema, IEventStoreSerializer serializer)
: base(dbContext, $"[{SchemaUtils.GetEventStoreSchema(schema)}].{ProcedureName}")
{
Expand Down Expand Up @@ -51,16 +53,21 @@ public static IEnumerable<string> GetCreateScripts(string? schema)
CREATE PROCEDURE [{schema}].{ProcedureName} (
@{nameof(StreamId)} NVARCHAR({Constants.StreamIdMaxLength}),
@{nameof(ExpectedPosition)} BIGINT,
@{nameof(Events)} [{schema}].[{nameof(Model.EventTableType)}] READONLY
@{nameof(Events)} [{schema}].[{nameof(Model.EventTableType)}] READONLY,
@{nameof(LockResource)} NVARCHAR(max)
)
AS
BEGIN
DECLARE @StreamKey AS INT;
DECLARE @StreamSequence AS BIGINT;
DECLARE @StreamIndex AS BIGINT;
DECLARE @LockResult AS INT;

IF @{nameof(StreamId)} is NULL RAISERROR('The value for parameter ''{nameof(StreamId)}'' must not be NULL', 16, 1)

EXEC @LockResult = sp_getapplock @Resource = @{nameof(LockResource)}, @LockMode = 'Exclusive';
IF @LockResult < 0 RAISERROR('Event write lock could not be acquired', 16, 1)

SELECT
@StreamKey = Id,
@StreamSequence = [{nameof(Model.EventStream.Sequence)}],
Expand Down Expand Up @@ -192,6 +199,7 @@ protected override SqlParameter[] GetParameters()
TypeName = $"[{_schema}].[{nameof(Model.EventTableType)}]",
Value = CreateEventDataTable(),
},
new SqlParameter($"@{nameof(LockResource)}", LockResource)
];
}
}
Loading