private Task <T> load <T, TId>(TId id) where T : class where TId : notnull { var storage = _parent.StorageFor <T>(); if (storage is IDocumentStorage <T, TId> s) { var handler = new LoadByIdHandler <T, TId>(s, id); return(AddItem(handler)); } throw new DocumentIdTypeMismatchException(storage, typeof(TId)); }
public async Task <IEventStream <TDoc> > FetchForWriting(DocumentSessionBase session, TId id, long expectedStartingVersion, CancellationToken cancellation = default) { await _identityStrategy.EnsureAggregateStorageExists <TDoc>(session, cancellation).ConfigureAwait(false); await session.Database.EnsureStorageExistsAsync(typeof(TDoc), cancellation).ConfigureAwait(false); var command = _identityStrategy.BuildCommandForReadingVersionForStream(id, false); var builder = new CommandBuilder(command); builder.Append(";"); var handler = new LoadByIdHandler <TDoc, TId>(_storage, id); handler.ConfigureCommand(builder, session); long version = 0; try { using var reader = await session.ExecuteReaderAsync(builder.Compile(), cancellation).ConfigureAwait(false); if (await reader.ReadAsync(cancellation).ConfigureAwait(false)) { version = await reader.GetFieldValueAsync <long>(0, cancellation).ConfigureAwait(false); } if (expectedStartingVersion != version) { throw new ConcurrencyException( $"Expected the existing version to be {expectedStartingVersion}, but was {version}", typeof(TDoc), id); } await reader.NextResultAsync(cancellation).ConfigureAwait(false); var document = await handler.HandleAsync(reader, session, cancellation).ConfigureAwait(false); return(version == 0 ? _identityStrategy.StartStream <TDoc>(document, session, id, cancellation) : _identityStrategy.AppendToStream <TDoc>(document, session, id, version, cancellation)); } catch (Exception e) { if (e.Message.Contains(MartenCommandException.MaybeLockedRowsMessage)) { throw new StreamLockedException(id, e.InnerException); } throw; } }