diff --git a/BTCPayServer/Extensions.cs b/BTCPayServer/Extensions.cs index 52f4b54d5..eb4ad0f44 100644 --- a/BTCPayServer/Extensions.cs +++ b/BTCPayServer/Extensions.cs @@ -4,6 +4,7 @@ using System.Globalization; using System.Linq; using System.Net; using System.Net.WebSockets; +using System.Reflection; using System.Security.Claims; using System.Text; using System.Threading; @@ -449,5 +450,21 @@ namespace BTCPayServer }; return controller.View("PostRedirect", redirectVm); } + + public static string ToSql(this IQueryable query) where TEntity : class + { + var enumerator = query.Provider.Execute>(query.Expression).GetEnumerator(); + var relationalCommandCache = enumerator.Private("_relationalCommandCache"); + var selectExpression = relationalCommandCache.Private("_selectExpression"); + var factory = relationalCommandCache.Private("_querySqlGeneratorFactory"); + + var sqlGenerator = factory.Create(); + var command = sqlGenerator.GetCommand(selectExpression); + + string sql = command.CommandText; + return sql; + } + private static object Private(this object obj, string privateField) => obj?.GetType().GetField(privateField, BindingFlags.Instance | BindingFlags.NonPublic)?.GetValue(obj); + private static T Private(this object obj, string privateField) => (T)obj?.GetType().GetField(privateField, BindingFlags.Instance | BindingFlags.NonPublic)?.GetValue(obj); } } diff --git a/BTCPayServer/Services/Invoices/InvoiceRepository.cs b/BTCPayServer/Services/Invoices/InvoiceRepository.cs index 042d46644..32b81f693 100644 --- a/BTCPayServer/Services/Invoices/InvoiceRepository.cs +++ b/BTCPayServer/Services/Invoices/InvoiceRepository.cs @@ -527,7 +527,9 @@ retry: private IQueryable GetInvoiceQuery(ApplicationDbContext context, InvoiceQuery queryObject) { - IQueryable query = context.Invoices; + IQueryable query = queryObject.UserId is null + ? context.Invoices + : context.UserStore.Where(u => u.ApplicationUserId == queryObject.UserId).SelectMany(c => c.StoreData.Invoices); if (!queryObject.IncludeArchived) { @@ -546,11 +548,6 @@ retry: query = query.Where(i => stores.Contains(i.StoreDataId)); } - if (queryObject.UserId != null) - { - query = query.Where(i => i.StoreData.UserStores.Any(u => u.ApplicationUserId == queryObject.UserId)); - } - if (!string.IsNullOrEmpty(queryObject.TextSearch)) { var ids = new HashSet(SearchInvoice(queryObject.TextSearch)).ToArray(); @@ -605,7 +602,6 @@ retry: if (queryObject.Count != null) query = query.Take(queryObject.Count.Value); - return query; } @@ -628,7 +624,6 @@ retry: query = query.Include(o => o.HistoricalAddressInvoices).Include(o => o.AddressInvoices); if (queryObject.IncludeEvents) query = query.Include(o => o.Events); - var data = await query.ToArrayAsync().ConfigureAwait(false); return data.Select(ToEntity).ToArray(); }