| | | 1 | | #pragma warning disable RS0030 // Do not use banned APIs |
| | | 2 | | |
| | | 3 | | using System; |
| | | 4 | | using System.Collections.Concurrent; |
| | | 5 | | using System.Collections.Generic; |
| | | 6 | | using System.Linq; |
| | | 7 | | using System.Linq.Expressions; |
| | | 8 | | using System.Reflection; |
| | | 9 | | using Jellyfin.Database.Implementations.Entities; |
| | | 10 | | using Microsoft.EntityFrameworkCore; |
| | | 11 | | |
| | | 12 | | namespace Jellyfin.Database.Implementations; |
| | | 13 | | |
| | | 14 | | /// <summary> |
| | | 15 | | /// Contains a number of query related extensions. |
| | | 16 | | /// </summary> |
| | | 17 | | public static class JellyfinQueryHelperExtensions |
| | | 18 | | { |
| | 2 | 19 | | private static readonly MethodInfo _containsMethodGenericCache = typeof(Enumerable).GetMethods(BindingFlags.Public | |
| | 2 | 20 | | private static readonly MethodInfo _efParameterInstruction = typeof(EF).GetMethod(nameof(EF.Parameter), BindingFlags |
| | 2 | 21 | | private static readonly ConcurrentDictionary<Type, MethodInfo> _containsQueryCache = new(); |
| | | 22 | | |
| | | 23 | | /// <summary> |
| | | 24 | | /// Builds an optimised query checking one property against a list of values while maintaining an optimal query. |
| | | 25 | | /// </summary> |
| | | 26 | | /// <typeparam name="TEntity">The entity.</typeparam> |
| | | 27 | | /// <typeparam name="TProperty">The property type to compare.</typeparam> |
| | | 28 | | /// <param name="query">The source query.</param> |
| | | 29 | | /// <param name="oneOf">The list of items to check.</param> |
| | | 30 | | /// <param name="property">Property expression.</param> |
| | | 31 | | /// <returns>A Query.</returns> |
| | | 32 | | public static IQueryable<TEntity> WhereOneOrMany<TEntity, TProperty>(this IQueryable<TEntity> query, IList<TProperty |
| | | 33 | | { |
| | 490 | 34 | | return query.Where(OneOrManyExpressionBuilder(oneOf, property)); |
| | | 35 | | } |
| | | 36 | | |
| | | 37 | | /// <summary> |
| | | 38 | | /// Builds a query that checks referenced ItemValues for a cross BaseItem lookup. |
| | | 39 | | /// </summary> |
| | | 40 | | /// <param name="baseQuery">The source query.</param> |
| | | 41 | | /// <param name="context">The database context.</param> |
| | | 42 | | /// <param name="itemValueType">The type of item value to reference.</param> |
| | | 43 | | /// <param name="referenceIds">The list of BaseItem ids to check matches.</param> |
| | | 44 | | /// <param name="invert">If set an exclusion check is performed instead.</param> |
| | | 45 | | /// <returns>A Query.</returns> |
| | | 46 | | public static IQueryable<BaseItemEntity> WhereReferencedItem( |
| | | 47 | | this IQueryable<BaseItemEntity> baseQuery, |
| | | 48 | | JellyfinDbContext context, |
| | | 49 | | ItemValueType itemValueType, |
| | | 50 | | IList<Guid> referenceIds, |
| | | 51 | | bool invert = false) |
| | | 52 | | { |
| | 0 | 53 | | return baseQuery.Where(ReferencedItemFilterExpressionBuilder(context, itemValueType, referenceIds, invert)); |
| | | 54 | | } |
| | | 55 | | |
| | | 56 | | /// <summary> |
| | | 57 | | /// Builds a query that checks referenced ItemValues for a cross BaseItem lookup. |
| | | 58 | | /// </summary> |
| | | 59 | | /// <param name="baseQuery">The source query.</param> |
| | | 60 | | /// <param name="context">The database context.</param> |
| | | 61 | | /// <param name="itemValueTypes">The type of item value to reference.</param> |
| | | 62 | | /// <param name="referenceIds">The list of BaseItem ids to check matches.</param> |
| | | 63 | | /// <param name="invert">If set an exclusion check is performed instead.</param> |
| | | 64 | | /// <returns>A Query.</returns> |
| | | 65 | | public static IQueryable<BaseItemEntity> WhereReferencedItemMultipleTypes( |
| | | 66 | | this IQueryable<BaseItemEntity> baseQuery, |
| | | 67 | | JellyfinDbContext context, |
| | | 68 | | IList<ItemValueType> itemValueTypes, |
| | | 69 | | IList<Guid> referenceIds, |
| | | 70 | | bool invert = false) |
| | | 71 | | { |
| | 0 | 72 | | var itemFilter = OneOrManyExpressionBuilder<BaseItemEntity, Guid>(referenceIds, f => f.Id); |
| | 0 | 73 | | var typeFilter = OneOrManyExpressionBuilder<ItemValueMap, ItemValueType>(itemValueTypes, m => m.ItemValue.Type); |
| | | 74 | | |
| | | 75 | | // Flat sub-selects + Contains instead of a nested correlated .Any(...Any(...)). |
| | 0 | 76 | | var referencedCleanValues = context.BaseItems |
| | 0 | 77 | | .Where(itemFilter) |
| | 0 | 78 | | .Select(e => e.CleanName); |
| | | 79 | | |
| | 0 | 80 | | var matchingItemIds = context.ItemValuesMap |
| | 0 | 81 | | .Where(typeFilter) |
| | 0 | 82 | | .Where(m => referencedCleanValues.Contains(m.ItemValue.CleanValue)) |
| | 0 | 83 | | .Select(m => m.ItemId); |
| | | 84 | | |
| | 0 | 85 | | if (invert) |
| | | 86 | | { |
| | 0 | 87 | | return baseQuery.Where(e => !matchingItemIds.Contains(e.Id)); |
| | | 88 | | } |
| | | 89 | | |
| | 0 | 90 | | return baseQuery.Where(e => matchingItemIds.Contains(e.Id)); |
| | | 91 | | } |
| | | 92 | | |
| | | 93 | | /// <summary> |
| | | 94 | | /// Builds a query expression that checks referenced ItemValues for a cross BaseItem lookup. |
| | | 95 | | /// </summary> |
| | | 96 | | /// <param name="context">The database context.</param> |
| | | 97 | | /// <param name="itemValueType">The type of item value to reference.</param> |
| | | 98 | | /// <param name="referenceIds">The list of BaseItem ids to check matches.</param> |
| | | 99 | | /// <param name="invert">If set an exclusion check is performed instead.</param> |
| | | 100 | | /// <returns>A Query.</returns> |
| | | 101 | | public static Expression<Func<BaseItemEntity, bool>> ReferencedItemFilterExpressionBuilder( |
| | | 102 | | this JellyfinDbContext context, |
| | | 103 | | ItemValueType itemValueType, |
| | | 104 | | IList<Guid> referenceIds, |
| | | 105 | | bool invert = false) |
| | | 106 | | { |
| | | 107 | | // Well genre/artist/album etc items do not actually set the ItemValue of thier specitic types so we cannot matc |
| | | 108 | | /* |
| | | 109 | | "(guid in (select itemid from ItemValues where CleanValue = (select CleanName from TypedBaseItems where guid=@Ge |
| | | 110 | | */ |
| | | 111 | | |
| | 0 | 112 | | var itemFilter = OneOrManyExpressionBuilder<BaseItemEntity, Guid>(referenceIds, f => f.Id); |
| | | 113 | | |
| | | 114 | | // Flat sub-selects + Contains instead of a nested correlated .Any(...Any(...)). |
| | 0 | 115 | | var referencedCleanValues = context.BaseItems |
| | 0 | 116 | | .Where(itemFilter) |
| | 0 | 117 | | .Select(e => e.CleanName); |
| | | 118 | | |
| | 0 | 119 | | var matchingItemIds = context.ItemValuesMap |
| | 0 | 120 | | .Where(m => m.ItemValue.Type == itemValueType && referencedCleanValues.Contains(m.ItemValue.CleanValue)) |
| | 0 | 121 | | .Select(m => m.ItemId); |
| | | 122 | | |
| | 0 | 123 | | if (invert) |
| | | 124 | | { |
| | 0 | 125 | | return item => !matchingItemIds.Contains(item.Id); |
| | | 126 | | } |
| | | 127 | | |
| | 0 | 128 | | return item => matchingItemIds.Contains(item.Id); |
| | | 129 | | } |
| | | 130 | | |
| | | 131 | | /// <summary> |
| | | 132 | | /// Filters items that match any of the specified (provider name, value) pairs. |
| | | 133 | | /// </summary> |
| | | 134 | | /// <param name="baseQuery">The source query.</param> |
| | | 135 | | /// <param name="providerIds">Dictionary mapping provider names to arrays of values to match.</param> |
| | | 136 | | /// <returns>A filtered query.</returns> |
| | | 137 | | public static IQueryable<BaseItemEntity> WhereHasAnyProviderIds( |
| | | 138 | | this IQueryable<BaseItemEntity> baseQuery, |
| | | 139 | | IReadOnlyDictionary<string, string[]> providerIds) |
| | | 140 | | { |
| | 0 | 141 | | var providerKeys = providerIds |
| | 0 | 142 | | .SelectMany(kvp => kvp.Value.Select(v => $"{kvp.Key}:{v}")) |
| | 0 | 143 | | .ToList(); |
| | | 144 | | |
| | 0 | 145 | | if (providerKeys.Count == 0) |
| | | 146 | | { |
| | 0 | 147 | | return baseQuery; |
| | | 148 | | } |
| | | 149 | | |
| | 0 | 150 | | return baseQuery.Where(e => e.Provider!.Any(p => providerKeys.Contains(p.ProviderId + ":" + p.ProviderValue))); |
| | | 151 | | } |
| | | 152 | | |
| | | 153 | | /// <summary> |
| | | 154 | | /// Filters items that have any of the specified providers. Empty/null values match any value for that provider. |
| | | 155 | | /// </summary> |
| | | 156 | | /// <param name="baseQuery">The source query.</param> |
| | | 157 | | /// <param name="providerIds">Dictionary mapping provider names to optional values.</param> |
| | | 158 | | /// <returns>A filtered query.</returns> |
| | | 159 | | public static IQueryable<BaseItemEntity> WhereHasAnyProviderId( |
| | | 160 | | this IQueryable<BaseItemEntity> baseQuery, |
| | | 161 | | IReadOnlyDictionary<string, string> providerIds) |
| | | 162 | | { |
| | 0 | 163 | | var existenceOnly = providerIds |
| | 0 | 164 | | .Where(e => string.IsNullOrEmpty(e.Value)) |
| | 0 | 165 | | .Select(e => e.Key) |
| | 0 | 166 | | .ToList(); |
| | | 167 | | |
| | 0 | 168 | | var specificValues = providerIds |
| | 0 | 169 | | .Where(e => !string.IsNullOrEmpty(e.Value)) |
| | 0 | 170 | | .Select(e => $"{e.Key}:{e.Value}") |
| | 0 | 171 | | .ToList(); |
| | | 172 | | |
| | 0 | 173 | | if (existenceOnly.Count == 0 && specificValues.Count == 0) |
| | | 174 | | { |
| | 0 | 175 | | return baseQuery; |
| | | 176 | | } |
| | | 177 | | |
| | 0 | 178 | | if (existenceOnly.Count == 0) |
| | | 179 | | { |
| | 0 | 180 | | return baseQuery.Where(e => e.Provider!.Any(p => |
| | 0 | 181 | | specificValues.Contains(p.ProviderId + ":" + p.ProviderValue))); |
| | | 182 | | } |
| | | 183 | | |
| | 0 | 184 | | if (specificValues.Count == 0) |
| | | 185 | | { |
| | 0 | 186 | | return baseQuery.Where(e => e.Provider!.Any(p => existenceOnly.Contains(p.ProviderId))); |
| | | 187 | | } |
| | | 188 | | |
| | | 189 | | // Single EXISTS over Provider with both predicates OR'd, instead of two separate subqueries. |
| | 0 | 190 | | return baseQuery.Where(e => e.Provider!.Any(p => |
| | 0 | 191 | | existenceOnly.Contains(p.ProviderId) || |
| | 0 | 192 | | specificValues.Contains(p.ProviderId + ":" + p.ProviderValue))); |
| | | 193 | | } |
| | | 194 | | |
| | | 195 | | /// <summary> |
| | | 196 | | /// Excludes items that match any of the specified (provider name, value) pairs. |
| | | 197 | | /// </summary> |
| | | 198 | | /// <param name="baseQuery">The source query.</param> |
| | | 199 | | /// <param name="providerIds">Dictionary mapping provider names to values to exclude.</param> |
| | | 200 | | /// <returns>A filtered query.</returns> |
| | | 201 | | public static IQueryable<BaseItemEntity> WhereExcludeProviderIds( |
| | | 202 | | this IQueryable<BaseItemEntity> baseQuery, |
| | | 203 | | IReadOnlyDictionary<string, string> providerIds) |
| | | 204 | | { |
| | 0 | 205 | | var excludeKeys = providerIds |
| | 0 | 206 | | .Select(e => $"{e.Key}:{e.Value}") |
| | 0 | 207 | | .ToList(); |
| | | 208 | | |
| | 0 | 209 | | if (excludeKeys.Count == 0) |
| | | 210 | | { |
| | 0 | 211 | | return baseQuery; |
| | | 212 | | } |
| | | 213 | | |
| | 0 | 214 | | return baseQuery.Where(e => e.Provider!.All(p => !excludeKeys.Contains(p.ProviderId + ":" + p.ProviderValue))); |
| | | 215 | | } |
| | | 216 | | |
| | | 217 | | /// <summary> |
| | | 218 | | /// Builds an optimised query expression checking one property against a list of values while maintaining an optimal |
| | | 219 | | /// </summary> |
| | | 220 | | /// <typeparam name="TEntity">The entity.</typeparam> |
| | | 221 | | /// <typeparam name="TProperty">The property type to compare.</typeparam> |
| | | 222 | | /// <param name="oneOf">The list of items to check.</param> |
| | | 223 | | /// <param name="property">Property expression.</param> |
| | | 224 | | /// <returns>A Query.</returns> |
| | | 225 | | public static Expression<Func<TEntity, bool>> OneOrManyExpressionBuilder<TEntity, TProperty>(this IList<TProperty> o |
| | | 226 | | { |
| | 535 | 227 | | var parameter = Expression.Parameter(typeof(TEntity), "item"); |
| | 535 | 228 | | property = ParameterReplacer.Replace<Func<TEntity, TProperty>, Func<TEntity, TProperty>>(property, property.Para |
| | 535 | 229 | | if (oneOf.Count == 1) |
| | | 230 | | { |
| | 441 | 231 | | var value = oneOf[0]; |
| | 441 | 232 | | if (typeof(TProperty).IsValueType) |
| | | 233 | | { |
| | 253 | 234 | | return Expression.Lambda<Func<TEntity, bool>>(Expression.Equal(property.Body, Expression.Constant(value) |
| | | 235 | | } |
| | | 236 | | else |
| | | 237 | | { |
| | 188 | 238 | | return Expression.Lambda<Func<TEntity, bool>>(Expression.ReferenceEqual(property.Body, Expression.Consta |
| | | 239 | | } |
| | | 240 | | } |
| | | 241 | | |
| | 94 | 242 | | var containsMethodInfo = _containsQueryCache.GetOrAdd(typeof(TProperty), static (key) => _containsMethodGenericC |
| | | 243 | | |
| | | 244 | | // Always wrap the collection in EF.Parameter so EF Core caches a single compiled plan and reuses it across call |
| | 94 | 245 | | return Expression.Lambda<Func<TEntity, bool>>( |
| | 94 | 246 | | Expression.Call( |
| | 94 | 247 | | null, |
| | 94 | 248 | | containsMethodInfo, |
| | 94 | 249 | | Expression.Call(null, _efParameterInstruction.MakeGenericMethod(oneOf.GetType()), Expression.Constant(on |
| | 94 | 250 | | property.Body), |
| | 94 | 251 | | parameter); |
| | | 252 | | } |
| | | 253 | | |
| | | 254 | | internal static class ParameterReplacer |
| | | 255 | | { |
| | | 256 | | // Produces an expression identical to 'expression' |
| | | 257 | | // except with 'source' parameter replaced with 'target' expression. |
| | | 258 | | internal static Expression<TOutput> Replace<TInput, TOutput>( |
| | | 259 | | Expression<TInput> expression, |
| | | 260 | | ParameterExpression source, |
| | | 261 | | ParameterExpression target) |
| | | 262 | | { |
| | 535 | 263 | | return new ParameterReplacerVisitor<TOutput>(source, target) |
| | 535 | 264 | | .VisitAndConvert(expression); |
| | | 265 | | } |
| | | 266 | | |
| | | 267 | | private sealed class ParameterReplacerVisitor<TOutput> : ExpressionVisitor |
| | | 268 | | { |
| | | 269 | | private readonly ParameterExpression _source; |
| | | 270 | | private readonly ParameterExpression _target; |
| | | 271 | | |
| | 535 | 272 | | public ParameterReplacerVisitor(ParameterExpression source, ParameterExpression target) |
| | | 273 | | { |
| | 535 | 274 | | _source = source; |
| | 535 | 275 | | _target = target; |
| | 535 | 276 | | } |
| | | 277 | | |
| | | 278 | | internal Expression<TOutput> VisitAndConvert<T>(Expression<T> root) |
| | | 279 | | { |
| | 535 | 280 | | return (Expression<TOutput>)VisitLambda(root); |
| | | 281 | | } |
| | | 282 | | |
| | | 283 | | protected override Expression VisitLambda<T>(Expression<T> node) |
| | | 284 | | { |
| | | 285 | | // Leave all parameters alone except the one we want to replace. |
| | 535 | 286 | | var parameters = node.Parameters.Select(p => p == _source ? _target : p); |
| | | 287 | | |
| | 535 | 288 | | return Expression.Lambda<TOutput>(Visit(node.Body), parameters); |
| | | 289 | | } |
| | | 290 | | |
| | | 291 | | protected override Expression VisitParameter(ParameterExpression node) |
| | | 292 | | { |
| | | 293 | | // Replace the source with the target, visit other params as usual. |
| | 535 | 294 | | return node == _source ? _target : base.VisitParameter(node); |
| | | 295 | | } |
| | | 296 | | } |
| | | 297 | | } |
| | | 298 | | } |