Skip to content

Commit 1336de9

Browse files
committed
Using the tenant id as part of FetchForWriting/Latest when using async projections
1 parent 01c4349 commit 1336de9

File tree

1 file changed

+21
-2
lines changed

1 file changed

+21
-2
lines changed

src/Marten/Events/Fetching/FetchAsyncPlan.cs

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
using Marten.Internal.Storage;
1212
using Marten.Linq.QueryHandlers;
1313
using Marten.Schema;
14+
using Marten.Storage;
1415
using Npgsql;
1516
using Weasel.Core;
1617
using Weasel.Postgresql;
@@ -73,8 +74,18 @@ public FetchAsyncPlan(EventGraph events, IEventIdentityStrategy<TId> identityStr
7374
_storage = storage;
7475
_aggregator = _events.Options.Projections.AggregatorFor<TDoc>();
7576

76-
_versionSelectionSql =
77-
$" left outer join {storage.TableName.QualifiedName} as a on d.stream_id = a.id where (a.mt_version is NULL or d.version > a.mt_version) and d.stream_id = ";
77+
if (_events.TenancyStyle == TenancyStyle.Single)
78+
{
79+
_versionSelectionSql =
80+
$" left outer join {storage.TableName.QualifiedName} as a on d.stream_id = a.id where (a.mt_version is NULL or d.version > a.mt_version) and d.stream_id = ";
81+
}
82+
else
83+
{
84+
_versionSelectionSql =
85+
$" left outer join {storage.TableName.QualifiedName} as a on d.stream_id = a.id and d.tenant_id = a.tenant_id where (a.mt_version is NULL or d.version > a.mt_version) and d.stream_id = ";
86+
}
87+
88+
7889
}
7990

8091
public async Task<IEventStream<TDoc>> FetchForWriting(DocumentSessionBase session, TId id, bool forUpdate, CancellationToken cancellation = default)
@@ -177,6 +188,14 @@ private void writeEventFetchStatement(TId id,
177188
builder.Append(_initialSql);
178189
builder.Append(_versionSelectionSql);
179190
builder.AppendParameter(id);
191+
192+
// You must do this for performance even if the stream ids were
193+
// magically unique across tenants
194+
if (_events.TenancyStyle == TenancyStyle.Conjoined)
195+
{
196+
builder.Append(" and d.tenant_id = ");
197+
builder.AppendParameter(builder.TenantId);
198+
}
180199
}
181200

182201
public async Task<IEventStream<TDoc>> FetchForWriting(DocumentSessionBase session, TId id, long expectedStartingVersion,

0 commit comments

Comments
 (0)