protected AbstractSortByFirstComparableAttribute(MediaItemAspectMetadata.AttributeSpecification attr)
 {
     _attr = attr;
 }
 public QueryAttribute(MediaItemAspectMetadata.AttributeSpecification attr)
 {
     _attr = attr;
 }
Exemple #3
0
 public FilterByAlbumCompilationCriterion(MediaItemAspectMetadata.AttributeSpecification attributeType)
     : base(attributeType)
 {
     _necessaryMIATypeIds = Consts.NECESSARY_ALBUM_MIAS;
 }
 /// <summary>
 /// Creates a table query of the external table of an attribute of cardinality <see cref="Cardinality.ManyToOne"/>.
 /// </summary>
 /// <param name="miaManagement">MIA management instance.</param>
 /// <param name="spec">Attribute type of cardinality <see cref="Cardinality.ManyToOne"/> whose table should be requested.</param>
 /// <returns>Table query for the table of the given attribute type.</returns>
 public static TableQueryData CreateTableQueryOfMTOTable(MIA_Management miaManagement,
                                                         MediaItemAspectMetadata.AttributeSpecification spec)
 {
     return(new TableQueryData(miaManagement.GetMIACollectionAttributeTableName(spec)));
 }
Exemple #5
0
 public BetweenFilter(MediaItemAspectMetadata.AttributeSpecification attributeType,
                      object value1, object value2) : base(attributeType)
 {
     _value1 = value1;
     _value2 = value2;
 }
Exemple #6
0
 public FilterByContentGroupCriterion(MediaItemAspectMetadata.AttributeSpecification attributeType)
     : base(attributeType)
 {
 }
 public static string SerializeAttributeTypeReference(MediaItemAspectMetadata.AttributeSpecification attributeType)
 {
     return(attributeType.ParentMIAM.AspectId + ":" + attributeType.AttributeName);
 }
 protected AbstractSortByComparableObjectAttribute(string displayName, MediaItemAspectMetadata.AttributeSpecification sortAttr)
 {
     _displayName = displayName;
     _sortAttr    = sortAttr;
 }
Exemple #9
0
 public InFilter(MediaItemAspectMetadata.AttributeSpecification attributeType,
                 IEnumerable <object> values) : base(attributeType)
 {
     _values = new List <object>(values);
 }
        protected virtual void CompileStatementParts(MIA_Management miaManagement, IFilter filter, IFilter subqueryFilter, Namespace ns, BindVarNamespace bvNamespace,
                                                     ICollection <MediaItemAspectMetadata> requiredMIATypes, string outerMIIDJoinVariable, ICollection <TableJoin> tableJoins,
                                                     IList <object> resultParts, IList <BindVar> resultBindVars)
        {
            if (filter == null)
            {
                return;
            }

            MediaItemIdFilter mediaItemIdFilter = filter as MediaItemIdFilter;

            if (mediaItemIdFilter != null)
            {
                ICollection <Guid> mediaItemIds = mediaItemIdFilter.MediaItemIds;
                if (mediaItemIds.Count == 0)
                {
                    resultParts.Add("1 = 2");
                }
                else
                {
                    if (mediaItemIds.Count == 1)
                    {
                        resultParts.Add(outerMIIDJoinVariable);
                        BindVar bindVar = new BindVar(bvNamespace.CreateNewBindVarName("V"), mediaItemIds.First(), typeof(Guid));
                        resultParts.Add(" = @" + bindVar.Name);
                        resultBindVars.Add(bindVar);
                    }
                    else
                    {
                        bool first = true;
                        ICollection <string> clusterExpressions = new List <string>();
                        foreach (IList <Guid> mediaItemIdsCluster in CollectionUtils.Cluster(mediaItemIds, MAX_IN_VALUES_SIZE))
                        {
                            IList <string> bindVarRefs = new List <string>(MAX_IN_VALUES_SIZE);
                            foreach (Guid mediaItemId in mediaItemIdsCluster)
                            {
                                BindVar bindVar = new BindVar(bvNamespace.CreateNewBindVarName("V"), mediaItemId, typeof(Guid));
                                bindVarRefs.Add("@" + bindVar.Name);
                                resultBindVars.Add(bindVar);
                            }
                            if (!first)
                            {
                                resultParts.Add(" OR ");
                            }
                            first = false;
                            resultParts.Add(outerMIIDJoinVariable);
                            resultParts.Add(" IN (" + StringUtils.Join(", ", bindVarRefs) + ")");
                        }
                        resultParts.Add(StringUtils.Join(" OR ", clusterExpressions));
                    }
                }
                return;
            }

            BooleanCombinationFilter boolFilter = filter as BooleanCombinationFilter;

            if (boolFilter != null && boolFilter.Operator == BooleanOperator.And && boolFilter.Operands.Count > 1 && boolFilter.Operands.ToList().All(x => x is IAttributeFilter))
            {
                ICollection <IFilter> remainingOperands = new List <IFilter>();

                // Special case to do multiple MIA boolean logic first
                IDictionary <Guid, ICollection <IAttributeFilter> > multiGroups = new Dictionary <Guid, ICollection <IAttributeFilter> >();
                foreach (IAttributeFilter operand in boolFilter.Operands)
                {
                    MultipleMediaItemAspectMetadata mmiam = operand.AttributeType.ParentMIAM as MultipleMediaItemAspectMetadata;
                    if (mmiam != null)
                    {
                        Guid key = operand.AttributeType.ParentMIAM.AspectId;
                        if (!multiGroups.ContainsKey(key))
                        {
                            multiGroups[key] = new List <IAttributeFilter>();
                        }
                        multiGroups[key].Add(operand);
                    }
                    else
                    {
                        remainingOperands.Add(operand);
                    }
                }

                if (multiGroups.Keys.Count > 0)
                {
                    bool firstGroup = true;
                    foreach (ICollection <IAttributeFilter> filterGroup in multiGroups.Values)
                    {
                        if (firstGroup)
                        {
                            firstGroup = false;
                        }
                        else
                        {
                            resultParts.Add(" AND ");
                        }

                        bool firstItem = true;
                        foreach (IAttributeFilter filterItem in filterGroup)
                        {
                            MediaItemAspectMetadata.AttributeSpecification attributeType = filterItem.AttributeType;
                            if (firstItem)
                            {
                                resultParts.Add(outerMIIDJoinVariable);
                                resultParts.Add(" IN(");
                                resultParts.Add("SELECT ");
                                resultParts.Add(MIA_Management.MIA_MEDIA_ITEM_ID_COL_NAME);
                                resultParts.Add(" FROM ");
                                resultParts.Add(miaManagement.GetMIATableName(attributeType.ParentMIAM));
                                resultParts.Add(" WHERE ");

                                firstItem = false;
                            }
                            else
                            {
                                resultParts.Add(" AND ");
                            }
                            //Empty filter needs to be handled differently to other IAttribute filters
                            if (filterItem is EmptyFilter)
                            {
                                resultParts.Add(miaManagement.GetMIAAttributeColumnName(attributeType));
                                resultParts.Add(" IS NULL");
                            }
                            else
                            {
                                BuildAttributeFilterExpression(filterItem, miaManagement.GetMIAAttributeColumnName(attributeType), bvNamespace, resultParts, resultBindVars);
                            }
                        }
                        resultParts.Add(")");
                    }

                    // Process remaining operands ?
                    if (remainingOperands.Count == 0)
                    {
                        return;
                    }

                    resultParts.Add(" AND ");
                    boolFilter.Operands = remainingOperands;
                }
            }
            if (boolFilter != null)
            {
                int         numOperands  = boolFilter.Operands.Count;
                IEnumerator enumOperands = boolFilter.Operands.GetEnumerator();
                if (!enumOperands.MoveNext())
                {
                    return;
                }
                if (numOperands > 1)
                {
                    resultParts.Add("(");
                }
                CompileStatementParts(miaManagement, (IFilter)enumOperands.Current, subqueryFilter, ns, bvNamespace,
                                      requiredMIATypes, outerMIIDJoinVariable, tableJoins, resultParts, resultBindVars);
                while (enumOperands.MoveNext())
                {
                    switch (boolFilter.Operator)
                    {
                    case BooleanOperator.And:
                        resultParts.Add(" AND ");
                        break;

                    case BooleanOperator.Or:
                        resultParts.Add(" OR ");
                        break;

                    default:
                        throw new NotImplementedException(string.Format(
                                                              "Boolean filter operator '{0}' isn't supported by the media library", boolFilter.Operator));
                    }
                    CompileStatementParts(miaManagement, (IFilter)enumOperands.Current, subqueryFilter, ns, bvNamespace,
                                          requiredMIATypes, outerMIIDJoinVariable, tableJoins, resultParts, resultBindVars);
                }
                if (numOperands > 1)
                {
                    resultParts.Add(")");
                }
                return;
            }

            NotFilter notFilter = filter as NotFilter;

            if (notFilter != null)
            {
                resultParts.Add("NOT (");
                CompileStatementParts(miaManagement, notFilter.InnerFilter, subqueryFilter, ns, bvNamespace,
                                      requiredMIATypes, outerMIIDJoinVariable, tableJoins, resultParts, resultBindVars);
                resultParts.Add(")");
                return;
            }

            FalseFilter falseFilter = filter as FalseFilter;

            if (falseFilter != null)
            {
                resultParts.Add("1 = 2");
                return;
            }

            // Must be done before checking IAttributeFilter - EmptyFilter is also an IAttributeFilter but must be
            // compiled in a different way
            EmptyFilter emptyFilter = filter as EmptyFilter;

            if (emptyFilter != null)
            {
                MediaItemAspectMetadata.AttributeSpecification attributeType = emptyFilter.AttributeType;
                requiredMIATypes.Add(attributeType.ParentMIAM);
                Cardinality cardinality = attributeType.Cardinality;
                if (cardinality == Cardinality.Inline || cardinality == Cardinality.ManyToOne)
                {
                    resultParts.Add(new QueryAttribute(attributeType));
                    resultParts.Add(" IS NULL"); // MTO attributes are joined with left outer joins and thus can also be checked for NULL
                }
                else if (cardinality == Cardinality.OneToMany)
                {
                    resultParts.Add("NOT EXISTS(");
                    resultParts.Add("SELECT V.");
                    resultParts.Add(MIA_Management.MIA_MEDIA_ITEM_ID_COL_NAME);
                    resultParts.Add(" FROM ");
                    resultParts.Add(miaManagement.GetMIACollectionAttributeTableName(attributeType));
                    resultParts.Add(" V WHERE V.");
                    resultParts.Add(MIA_Management.MIA_MEDIA_ITEM_ID_COL_NAME);
                    resultParts.Add("=");
                    resultParts.Add(outerMIIDJoinVariable);
                    resultParts.Add(")");
                }
                else if (cardinality == Cardinality.ManyToMany)
                {
                    resultParts.Add("NOT EXISTS(");
                    resultParts.Add("SELECT NM.");
                    resultParts.Add(MIA_Management.MIA_MEDIA_ITEM_ID_COL_NAME);
                    resultParts.Add(" FROM ");
                    resultParts.Add(miaManagement.GetMIACollectionAttributeNMTableName(attributeType));
                    resultParts.Add(" NM INNER JOIN ");
                    resultParts.Add(miaManagement.GetMIACollectionAttributeTableName(attributeType));
                    resultParts.Add(" V ON NM.");
                    resultParts.Add(MIA_Management.FOREIGN_COLL_ATTR_ID_COL_NAME);
                    resultParts.Add(" = V.");
                    resultParts.Add(MIA_Management.FOREIGN_COLL_ATTR_ID_COL_NAME);
                    resultParts.Add(" WHERE NM.");
                    resultParts.Add(MIA_Management.MIA_MEDIA_ITEM_ID_COL_NAME);
                    resultParts.Add("=");
                    resultParts.Add(outerMIIDJoinVariable);
                    resultParts.Add(")");
                }
                return;
            }

            // Must be done before checking IAttributeFilter - EmptyUserDataFilter is also an IAttributeFilter but must be
            // compiled in a different way
            EmptyUserDataFilter emptyUserDataFilter = filter as EmptyUserDataFilter;

            if (emptyUserDataFilter != null)
            {
                BindVar userIdVar = new BindVar(bvNamespace.CreateNewBindVarName("V"), emptyUserDataFilter.UserProfileId, typeof(Guid));

                resultParts.Add("NOT EXISTS(");
                resultParts.Add("SELECT ");
                resultParts.Add(MIA_Management.MIA_MEDIA_ITEM_ID_COL_NAME);
                resultParts.Add(" FROM ");
                resultParts.Add(UserProfileDataManagement_SubSchema.USER_MEDIA_ITEM_DATA_TABLE_NAME);
                resultParts.Add(" WHERE ");
                resultParts.Add(UserProfileDataManagement_SubSchema.USER_PROFILE_ID_COL_NAME);
                resultParts.Add(" = @" + userIdVar.Name);
                resultBindVars.Add(userIdVar);
                resultParts.Add(" AND ");
                resultParts.Add(UserProfileDataManagement_SubSchema.USER_DATA_KEY_COL_NAME);
                resultParts.Add(" = '");
                resultParts.Add(emptyUserDataFilter.UserDataKey);
                resultParts.Add("' AND ");
                resultParts.Add(UserProfileDataManagement_SubSchema.USER_DATA_VALUE_COL_NAME);
                resultParts.Add(" IS NOT NULL ");
                resultParts.Add(" AND ");
                resultParts.Add(MIA_Management.MIA_MEDIA_ITEM_ID_COL_NAME);
                resultParts.Add("=");
                resultParts.Add(outerMIIDJoinVariable);
                resultParts.Add(")");

                return;
            }

            AbstractRelationshipFilter relationshipFilter = filter as AbstractRelationshipFilter;

            if (relationshipFilter != null)
            {
                resultParts.Add(outerMIIDJoinVariable);
                resultParts.Add(" IN(");
                BuildRelationshipSubquery(relationshipFilter, subqueryFilter, miaManagement, bvNamespace, resultParts, resultBindVars);
                resultParts.Add(")");
                return;
            }

            RelationalUserDataFilter relationalUserDataFilter = filter as RelationalUserDataFilter;

            if (relationalUserDataFilter != null)
            {
                BindVar userIdVar = new BindVar(bvNamespace.CreateNewBindVarName("V"), relationalUserDataFilter.UserProfileId, typeof(Guid));
                BindVar bindVar   = new BindVar(bvNamespace.CreateNewBindVarName("V"), relationalUserDataFilter.FilterValue, typeof(string));

                resultParts.Add(outerMIIDJoinVariable);
                resultParts.Add(" IN(");
                resultParts.Add("SELECT ");
                resultParts.Add(MIA_Management.MIA_MEDIA_ITEM_ID_COL_NAME);
                resultParts.Add(" FROM ");
                resultParts.Add(UserProfileDataManagement_SubSchema.USER_MEDIA_ITEM_DATA_TABLE_NAME);
                resultParts.Add(" WHERE ");
                resultParts.Add(UserProfileDataManagement_SubSchema.USER_PROFILE_ID_COL_NAME);
                resultParts.Add(" = @" + userIdVar.Name);
                resultBindVars.Add(userIdVar);
                resultParts.Add(" AND ");
                resultParts.Add(UserProfileDataManagement_SubSchema.USER_DATA_KEY_COL_NAME);
                resultParts.Add(" = '");
                resultParts.Add(relationalUserDataFilter.UserDataKey);
                resultParts.Add("' AND ");
                resultParts.Add(UserProfileDataManagement_SubSchema.USER_DATA_VALUE_COL_NAME);
                switch (relationalUserDataFilter.Operator)
                {
                case RelationalOperator.EQ:
                    resultParts.Add(" = ");
                    break;

                case RelationalOperator.NEQ:
                    resultParts.Add(" <> ");
                    break;

                case RelationalOperator.LT:
                    resultParts.Add(" < ");
                    break;

                case RelationalOperator.LE:
                    resultParts.Add(" <= ");
                    break;

                case RelationalOperator.GT:
                    resultParts.Add(" > ");
                    break;

                case RelationalOperator.GE:
                    resultParts.Add(" >= ");
                    break;

                default:
                    throw new NotImplementedException(string.Format(
                                                          "Relational user data filter operator '{0}' isn't supported by the media library", relationalUserDataFilter.Operator));
                }
                resultParts.Add("@" + bindVar.Name);
                resultBindVars.Add(bindVar);
                resultParts.Add(")");
                return;
            }

            IAttributeFilter attributeFilter = filter as IAttributeFilter;

            if (attributeFilter != null)
            {
                MediaItemAspectMetadata.AttributeSpecification attributeType = attributeFilter.AttributeType;
                if (attributeType.ParentMIAM is MultipleMediaItemAspectMetadata)
                {
                    resultParts.Add(outerMIIDJoinVariable);
                    resultParts.Add(" IN(");
                    resultParts.Add("SELECT ");
                    resultParts.Add(MIA_Management.MIA_MEDIA_ITEM_ID_COL_NAME);
                    resultParts.Add(" FROM ");
                    resultParts.Add(miaManagement.GetMIATableName(attributeType.ParentMIAM));
                    resultParts.Add(" WHERE ");
                    BuildAttributeFilterExpression(attributeFilter, miaManagement.GetMIAAttributeColumnName(attributeType), bvNamespace, resultParts, resultBindVars);
                    resultParts.Add(")");

                    return;
                }

                // For attribute filters, we have to create different kinds of expressions, depending on the
                // cardinality of the attribute to be filtered.
                // For Inline and MTO attributes, we simply create
                //
                // QA [Operator] [Comparison-Value]
                //
                // for OTM attributes, we create
                //
                // INNER JOIN [OTM-Value-Table] V ON V.MEDIA_ITEM_ID=[Outer-Join-Variable-Placeholder]
                // WHERE [...] and V.VALUE [Operator] [Comparison-Value])
                //
                // for MTM attributes, we create
                //
                // INNER JOIN [MTM-NM-Table] NM ON NM.MEDIA_ITEM_ID=[Outer-Join-Variable-Placeholder]
                // INNER JOIN [MTM-Value-Table] V ON NM.ID = V.ID
                // WHERE [...] AND V.VALUE [Operator] [Comparison-Value])

                requiredMIATypes.Add(attributeType.ParentMIAM);
                Cardinality cardinality = attributeType.Cardinality;
                if (cardinality == Cardinality.Inline || cardinality == Cardinality.ManyToOne)
                {
                    BuildAttributeFilterExpression(attributeFilter, new QueryAttribute(attributeType), bvNamespace,
                                                   resultParts, resultBindVars);
                }
                else if (cardinality == Cardinality.OneToMany)
                {
                    string joinTable = miaManagement.GetMIACollectionAttributeTableName(attributeType);
                    string attrName;
                    if (!_innerJoinedTables.TryGetValue(joinTable, out attrName))
                    {
                        TableQueryData tqd = new TableQueryData(joinTable);

                        tableJoins.Add(new TableJoin("LEFT OUTER JOIN", tqd,
                                                     new RequestedAttribute(tqd, MIA_Management.MIA_MEDIA_ITEM_ID_COL_NAME), outerMIIDJoinVariable));
                        attrName = new RequestedAttribute(tqd, MIA_Management.COLL_ATTR_VALUE_COL_NAME).GetQualifiedName(ns);
                        _innerJoinedTables.Add(joinTable, attrName);
                    }
                    BuildAttributeFilterExpression(attributeFilter, attrName, bvNamespace, resultParts, resultBindVars);
                }
                else if (cardinality == Cardinality.ManyToMany)
                {
                    string miaCollectionAttributeNMTableName = miaManagement.GetMIACollectionAttributeNMTableName(attributeType);
                    string attrName;
                    if (!_innerJoinedTables.TryGetValue(miaCollectionAttributeNMTableName, out attrName))
                    {
                        TableQueryData tqdMiaCollectionAttributeNMTable = new TableQueryData(miaCollectionAttributeNMTableName);

                        tableJoins.Add(new TableJoin("LEFT OUTER JOIN", tqdMiaCollectionAttributeNMTable,
                                                     new RequestedAttribute(tqdMiaCollectionAttributeNMTable, MIA_Management.MIA_MEDIA_ITEM_ID_COL_NAME), outerMIIDJoinVariable));

                        TableQueryData tqdMiaCollectionAttributeTable = new TableQueryData(miaManagement.GetMIACollectionAttributeTableName(attributeType));

                        tableJoins.Add(new TableJoin("LEFT OUTER JOIN", tqdMiaCollectionAttributeTable,
                                                     new RequestedAttribute(tqdMiaCollectionAttributeNMTable, MIA_Management.FOREIGN_COLL_ATTR_ID_COL_NAME),
                                                     new RequestedAttribute(tqdMiaCollectionAttributeTable, MIA_Management.FOREIGN_COLL_ATTR_ID_COL_NAME)));
                        attrName = tqdMiaCollectionAttributeTable.GetAlias(ns) + "." + MIA_Management.COLL_ATTR_VALUE_COL_NAME;
                        _innerJoinedTables.Add(miaCollectionAttributeNMTableName, attrName);
                    }
                    BuildAttributeFilterExpression(attributeFilter, attrName, bvNamespace, resultParts, resultBindVars);
                }
                return;
            }
            throw new InvalidDataException("Filter type '{0}' isn't supported by the media library", filter.GetType().Name);
        }
Exemple #11
0
 public LanguageFilterCriterion(MediaItemAspectMetadata.AttributeSpecification attributeType)
     : base(attributeType)
 {
 }
Exemple #12
0
 public FilterByMovieCertificationCriterion(MediaItemAspectMetadata.AttributeSpecification attributeType)
     : base(attributeType)
 {
 }
 public SortInformation(MediaItemAspectMetadata.AttributeSpecification attributeType, SortDirection sortDirection)
 {
   _attributeType = attributeType;
   _sortDirection = sortDirection;
 }
Exemple #14
0
 protected AbstractAttributeFilter(MediaItemAspectMetadata.AttributeSpecification attributeType)
 {
     _attributeType = attributeType;
 }
Exemple #15
0
 public void RegisterMediaItemAspectRoleHierarchyChildCountAttribute(Guid childRole, Guid parentRole, MediaItemAspectMetadata parentMiaType, MediaItemAspectMetadata.AttributeSpecification childCountAttribute, bool includeVirtual)
 {
 }
Exemple #16
0
 public EmptyFilter(MediaItemAspectMetadata.AttributeSpecification attributeType) : base(attributeType)
 {
 }
 public SimpleMLFilterCriterion(MediaItemAspectMetadata.AttributeSpecification keyAttributeType, MediaItemAspectMetadata.AttributeSpecification valueAttributeType, IEnumerable <Guid> necessaryMIATypeIds)
 {
     _keyAttributeType    = keyAttributeType;
     _valueAttributeType  = valueAttributeType;
     _necessaryMIATypeIds = necessaryMIATypeIds;
 }
 public ChildAggregateAttributeSortInformation(Guid parentRole, Guid childRole, MediaItemAspectMetadata.AttributeSpecification childAttributeType, AggregateFunction aggregateFunction, SortDirection sortDirection)
 {
     _aggregateFunction  = aggregateFunction;
     _childAttributeType = childAttributeType;
     _sortDirection      = sortDirection;
     _parentRole         = parentRole;
     _childRole          = childRole;
 }
Exemple #19
0
        protected void CompileStatementParts(MIA_Management miaManagement, IFilter filter, Namespace ns, BindVarNamespace bvNamespace,
                                             ICollection <MediaItemAspectMetadata> requiredMIATypes, string outerMIIDJoinVariable, ICollection <TableJoin> tableJoins,
                                             IList <object> resultParts, IList <BindVar> resultBindVars)
        {
            if (filter == null)
            {
                return;
            }

            MediaItemIdFilter mediaItemIdFilter = filter as MediaItemIdFilter;

            if (mediaItemIdFilter != null)
            {
                ICollection <Guid> mediaItemIds = mediaItemIdFilter.MediaItemIds;
                if (mediaItemIds.Count == 0)
                {
                    resultParts.Add("1 = 2");
                }
                else
                {
                    if (mediaItemIds.Count == 1)
                    {
                        resultParts.Add(outerMIIDJoinVariable);
                        BindVar bindVar = new BindVar(bvNamespace.CreateNewBindVarName("V"), mediaItemIds.First(), typeof(Guid));
                        resultParts.Add(" = @" + bindVar.Name);
                        resultBindVars.Add(bindVar);
                    }
                    else
                    {
                        bool first = true;
                        ICollection <string> clusterExpressions = new List <string>();
                        foreach (IList <Guid> mediaItemIdsCluster in CollectionUtils.Cluster(mediaItemIds, MAX_IN_VALUES_SIZE))
                        {
                            IList <string> bindVarRefs = new List <string>(MAX_IN_VALUES_SIZE);
                            foreach (Guid mediaItemId in mediaItemIdsCluster)
                            {
                                BindVar bindVar = new BindVar(bvNamespace.CreateNewBindVarName("V"), mediaItemId, typeof(Guid));
                                bindVarRefs.Add("@" + bindVar.Name);
                                resultBindVars.Add(bindVar);
                            }
                            if (!first)
                            {
                                resultParts.Add(" OR ");
                            }
                            first = false;
                            resultParts.Add(outerMIIDJoinVariable);
                            resultParts.Add(" IN (" + StringUtils.Join(", ", bindVarRefs) + ")");
                        }
                        resultParts.Add(StringUtils.Join(" OR ", clusterExpressions));
                    }
                }
                return;
            }

            BooleanCombinationFilter boolFilter = filter as BooleanCombinationFilter;

            if (boolFilter != null)
            {
                int         numOperands  = boolFilter.Operands.Count;
                IEnumerator enumOperands = boolFilter.Operands.GetEnumerator();
                if (!enumOperands.MoveNext())
                {
                    return;
                }
                if (numOperands > 1)
                {
                    resultParts.Add("(");
                }
                CompileStatementParts(miaManagement, (IFilter)enumOperands.Current, ns, bvNamespace,
                                      requiredMIATypes, outerMIIDJoinVariable, tableJoins, resultParts, resultBindVars);
                while (enumOperands.MoveNext())
                {
                    switch (boolFilter.Operator)
                    {
                    case BooleanOperator.And:
                        resultParts.Add(" AND ");
                        break;

                    case BooleanOperator.Or:
                        resultParts.Add(" OR ");
                        break;

                    default:
                        throw new NotImplementedException(string.Format(
                                                              "Boolean filter operator '{0}' isn't supported by the media library", boolFilter.Operator));
                    }
                    CompileStatementParts(miaManagement, (IFilter)enumOperands.Current, ns, bvNamespace,
                                          requiredMIATypes, outerMIIDJoinVariable, tableJoins, resultParts, resultBindVars);
                }
                if (numOperands > 1)
                {
                    resultParts.Add(")");
                }
                return;
            }

            NotFilter notFilter = filter as NotFilter;

            if (notFilter != null)
            {
                resultParts.Add("NOT (");
                CompileStatementParts(miaManagement, notFilter.InnerFilter, ns, bvNamespace,
                                      requiredMIATypes, outerMIIDJoinVariable, tableJoins, resultParts, resultBindVars);
                resultParts.Add(")");
                return;
            }

            FalseFilter falseFilter = filter as FalseFilter;

            if (falseFilter != null)
            {
                resultParts.Add("1 = 2");
                return;
            }

            // Must be done before checking IAttributeFilter - EmptyFilter is also an IAttributeFilter but must be
            // compiled in a different way
            EmptyFilter emptyFilter = filter as EmptyFilter;

            if (emptyFilter != null)
            {
                MediaItemAspectMetadata.AttributeSpecification attributeType = emptyFilter.AttributeType;
                requiredMIATypes.Add(attributeType.ParentMIAM);
                Cardinality cardinality = attributeType.Cardinality;
                if (cardinality == Cardinality.Inline || cardinality == Cardinality.ManyToOne)
                {
                    resultParts.Add(new QueryAttribute(attributeType));
                    resultParts.Add(" IS NULL"); // MTO attributes are joined with left outer joins and thus can also be checked for NULL
                }
                else if (cardinality == Cardinality.OneToMany)
                {
                    resultParts.Add("NOT EXISTS(");
                    resultParts.Add("SELECT V.");
                    resultParts.Add(MIA_Management.MIA_MEDIA_ITEM_ID_COL_NAME);
                    resultParts.Add(" FROM ");
                    resultParts.Add(miaManagement.GetMIACollectionAttributeTableName(attributeType));
                    resultParts.Add(" V WHERE V.");
                    resultParts.Add(MIA_Management.MIA_MEDIA_ITEM_ID_COL_NAME);
                    resultParts.Add("=");
                    resultParts.Add(outerMIIDJoinVariable);
                    resultParts.Add(")");
                }
                else if (cardinality == Cardinality.ManyToMany)
                {
                    resultParts.Add("NOT EXISTS(");
                    resultParts.Add("SELECT NM.");
                    resultParts.Add(MIA_Management.MIA_MEDIA_ITEM_ID_COL_NAME);
                    resultParts.Add(" FROM ");
                    resultParts.Add(miaManagement.GetMIACollectionAttributeNMTableName(attributeType));
                    resultParts.Add(" NM INNER JOIN ");
                    resultParts.Add(miaManagement.GetMIACollectionAttributeTableName(attributeType));
                    resultParts.Add(" V ON NM.");
                    resultParts.Add(MIA_Management.FOREIGN_COLL_ATTR_ID_COL_NAME);
                    resultParts.Add(" = V.");
                    resultParts.Add(MIA_Management.FOREIGN_COLL_ATTR_ID_COL_NAME);
                    resultParts.Add(" WHERE NM.");
                    resultParts.Add(MIA_Management.MIA_MEDIA_ITEM_ID_COL_NAME);
                    resultParts.Add("=");
                    resultParts.Add(outerMIIDJoinVariable);
                    resultParts.Add(")");
                }
                return;
            }

            IAttributeFilter attributeFilter = filter as IAttributeFilter;

            if (attributeFilter != null)
            {
                // For attribute filters, we have to create different kinds of expressions, depending on the
                // cardinality of the attribute to be filtered.
                // For Inline and MTO attributes, we simply create
                //
                // QA [Operator] [Comparison-Value]
                //
                // for OTM attributes, we create
                //
                // INNER JOIN [OTM-Value-Table] V ON V.MEDIA_ITEM_ID=[Outer-Join-Variable-Placeholder]
                // WHERE [...] and V.VALUE [Operator] [Comparison-Value])
                //
                // for MTM attributes, we create
                //
                // INNER JOIN [MTM-NM-Table] NM ON NM.MEDIA_ITEM_ID=[Outer-Join-Variable-Placeholder]
                // INNER JOIN [MTM-Value-Table] V ON NM.ID = V.ID
                // WHERE [...] AND V.VALUE [Operator] [Comparison-Value])

                MediaItemAspectMetadata.AttributeSpecification attributeType = attributeFilter.AttributeType;
                requiredMIATypes.Add(attributeType.ParentMIAM);
                Cardinality cardinality = attributeType.Cardinality;
                if (cardinality == Cardinality.Inline || cardinality == Cardinality.ManyToOne)
                {
                    BuildAttributeFilterExpression(attributeFilter, new QueryAttribute(attributeType), bvNamespace,
                                                   resultParts, resultBindVars);
                }
                else if (cardinality == Cardinality.OneToMany)
                {
                    string joinTable = miaManagement.GetMIACollectionAttributeTableName(attributeType);
                    string attrName;
                    if (!_innerJoinedTables.TryGetValue(joinTable, out attrName))
                    {
                        TableQueryData tqd = new TableQueryData(joinTable);

                        tableJoins.Add(new TableJoin("LEFT OUTER JOIN", tqd,
                                                     new RequestedAttribute(tqd, MIA_Management.MIA_MEDIA_ITEM_ID_COL_NAME), outerMIIDJoinVariable));
                        attrName = new RequestedAttribute(tqd, MIA_Management.COLL_ATTR_VALUE_COL_NAME).GetQualifiedName(ns);
                        _innerJoinedTables.Add(joinTable, attrName);
                    }
                    BuildAttributeFilterExpression(attributeFilter, attrName, bvNamespace, resultParts, resultBindVars);
                }
                else if (cardinality == Cardinality.ManyToMany)
                {
                    string miaCollectionAttributeNMTableName = miaManagement.GetMIACollectionAttributeNMTableName(attributeType);
                    string attrName;
                    if (!_innerJoinedTables.TryGetValue(miaCollectionAttributeNMTableName, out attrName))
                    {
                        TableQueryData tqdMiaCollectionAttributeNMTable = new TableQueryData(miaCollectionAttributeNMTableName);

                        tableJoins.Add(new TableJoin("LEFT OUTER JOIN", tqdMiaCollectionAttributeNMTable,
                                                     new RequestedAttribute(tqdMiaCollectionAttributeNMTable, MIA_Management.MIA_MEDIA_ITEM_ID_COL_NAME), outerMIIDJoinVariable));

                        TableQueryData tqdMiaCollectionAttributeTable = new TableQueryData(miaManagement.GetMIACollectionAttributeTableName(attributeType));

                        tableJoins.Add(new TableJoin("LEFT OUTER JOIN", tqdMiaCollectionAttributeTable,
                                                     new RequestedAttribute(tqdMiaCollectionAttributeNMTable, MIA_Management.FOREIGN_COLL_ATTR_ID_COL_NAME),
                                                     new RequestedAttribute(tqdMiaCollectionAttributeTable, MIA_Management.FOREIGN_COLL_ATTR_ID_COL_NAME)));
                        attrName = tqdMiaCollectionAttributeTable.GetAlias(ns) + "." + MIA_Management.COLL_ATTR_VALUE_COL_NAME;
                        _innerJoinedTables.Add(miaCollectionAttributeNMTableName, attrName);
                    }
                    BuildAttributeFilterExpression(attributeFilter, attrName, bvNamespace, resultParts, resultBindVars);
                }
                return;
            }
            throw new InvalidDataException("Filter type '{0}' isn't supported by the media library", filter.GetType().Name);
        }
Exemple #20
0
        private static void ChangeAttribute(IList <IFilter> filters, MediaItemAspectMetadata.AttributeSpecification from, MediaItemAspectMetadata.AttributeSpecification to)
        {
            foreach (IFilter filter in filters)
            {
                AbstractAttributeFilter af = filter as AbstractAttributeFilter;
                if (af != null && af.AttributeType == from)
                {
                    af.AttributeType = to;
                }

                BooleanCombinationFilter bcf = filter as BooleanCombinationFilter;
                if (bcf != null)
                {
                    ChangeAttribute(bcf.Operands.ToList(), from, to);
                }
            }
        }
Exemple #21
0
 public FilterByDiscNumberCriterion(MediaItemAspectMetadata.AttributeSpecification attributeType)
     : base(attributeType)
 {
 }
Exemple #22
0
        const string PROPERTY_CREATION_TEMPLATE_CONTROL = "{0} = new SProperty(typeof({1}));"; // Strong references allowed for Controls, but not for models

        #endregion

        /// <summary>
        /// Creates a class that exposes <see cref="MediaItemAspectMetadata.AttributeSpecification"/> as properties that can be used from xaml.
        /// This helper can create different class styles, depending on <paramref name="createAsControl"/>:
        /// <para>
        /// <c>false</c>: Create a standalone class using WProperty as property type (for models)
        /// <c>true</c>:  Create a class that derives from Control using SProperty as property type. This class can be used as custom control.
        /// </para>
        /// </summary>
        /// <param name="aspectType">MediaAspect type.</param>
        /// <param name="classNamespace">Namespace of generated class.</param>
        /// <param name="createAsControl">Create a control (see remarks on class).</param>
        /// <param name="exposeNullable">Internal value types are exposed as C# Nullable.</param>
        /// <returns>Source code of created class.</returns>
        public string BuildCodeTemplate(Type aspectType, string classNamespace, bool createAsControl, bool exposeNullable)
        {
            MediaItemAspectMetadata metadata = GetMetadata(aspectType);

            _createAsControl = createAsControl;
            _exposeNullable  = exposeNullable;
            string baseClass  = _createAsControl ? ": Control" : "";
            string aspectName = aspectType.Name;
            IDictionary <string, MediaItemAspectMetadata.AttributeSpecification> attributeSpecifications = metadata.AttributeSpecifications;

            foreach (KeyValuePair <string, MediaItemAspectMetadata.AttributeSpecification> attributeSpecification in attributeSpecifications)
            {
                MediaItemAspectMetadata.AttributeSpecification spec = attributeSpecification.Value;
                string attrName = attributeSpecification.Key;
                Type   attrType = spec.AttributeType;

                CreateProperty(attrName, attrType, spec.IsCollectionAttribute);
            }

            #region Copyright

            // Copyright
            _copyright.Add(@"/*
    Copyright (C) 2007-2014 Team MediaPortal
    http://www.team-mediaportal.com

    This file is part of MediaPortal 2

    MediaPortal 2 is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    MediaPortal 2 is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with MediaPortal 2. If not, see <http://www.gnu.org/licenses/>.
*/");
            #endregion

            #region Headers

            // Usings
            _usings.Add("using System;");
            _usings.Add("using System.Collections.Generic;");
            _usings.Add("using MediaPortal.Common.General;");
            _usings.Add("using MediaPortal.Common.MediaManagement;");
            _usings.Add("using MediaPortal.Common.MediaManagement.DefaultItemAspects;");
            if (_createAsControl)
            {
                _usings.Add("using MediaPortal.UI.SkinEngine.Controls.Visuals;");
            }

            // Constants
            _consts.Add("public static readonly ICollection<string> EMPTY_STRING_COLLECTION = new List<string>().AsReadOnly();");

            // Common properties
            CreateProperty("MediaItem", typeof(MediaItem));
            _propertyCreation.Add("_mediaItemProperty.Attach(MediaItemChanged);");

            #endregion

            // Construct source file
            StringBuilder result = new StringBuilder();

            AppendRegion(result, "Copyright (C) 2007-2014 Team MediaPortal", _copyright, false);

            AppendRegion(result, null, _usings, false);

            result.AppendLine();
            result.AppendLine();
            result.AppendFormat("namespace {0}\r\n{{\r\n", classNamespace); // Begin of namespace

            result.AppendLine("/// <summary>");
            result.AppendFormat("/// {0}Wrapper wraps the contents of <see cref=\"{0}\"/> into properties that can be bound from xaml controls.\r\n", aspectName);
            result.AppendLine("/// Note: this code was automatically created by the MediaItemAspectModelBuilder helper tool under Resources folder.");
            result.AppendLine("/// </summary>");                                                // Begin of class
            result.AppendFormat("public class {0}Wrapper{1}\r\n{{\r\n", aspectName, baseClass); // Begin of class

            AppendRegion(result, "Constants", _consts, false);
            AppendRegion(result, "Fields", _fields, false);
            AppendRegion(result, "Properties", _properties);

            List <string> ctors = new List <string> {
                string.Format("public {0}Wrapper()\r\n{{\r\n  {1}\r\n}}", aspectName, string.Join("\r\n  ", _propertyCreation.ToArray()))
            };
            AppendRegion(result, "Constructor", ctors);

            _members.Add(@"private void MediaItemChanged(AbstractProperty property, object oldvalue)
{
  Init(MediaItem);
}");

            CreateMembers(aspectType, _members);
            AppendRegion(result, "Members", _members);

            result.AppendLine("}");     // End of class
            result.AppendLine("\r\n}"); // End of namespace

            return(result.ToString());
        }
        protected int CompareAttributes(MediaItem x, MediaItemAspect aspectX, MediaItemAspectMetadata.AttributeSpecification attrX, MediaItem y, MediaItemAspect aspectY, MediaItemAspectMetadata.AttributeSpecification attrY)
        {
            string firstValueX = null;
            string firstValueY = null;

            if (attrX.IsCollectionAttribute)
            {
                IEnumerable <string> collectionX = aspectX.GetCollectionAttribute <string>(attrX);
                if (collectionX != null)
                {
                    List <string> valuesX = new List <string>(collectionX);
                    if (_preSortAttributes)
                    {
                        valuesX.Sort();
                    }
                    firstValueX = valuesX.FirstOrDefault();
                }
            }
            else
            {
                IList <MultipleMediaItemAspect> aspectsX;
                MultipleMediaItemAspectMetadata metadata = attrX.ParentMIAM as MultipleMediaItemAspectMetadata;
                if (metadata != null && MediaItemAspect.TryGetAspects(x.Aspects, metadata, out aspectsX))
                {
                    List <string> valuesX = new List <string>();
                    foreach (MultipleMediaItemAspect aspect in aspectsX)
                    {
                        if (!string.IsNullOrEmpty(aspect.GetAttributeValue <string>(attrX)))
                        {
                            valuesX.Add(aspect.GetAttributeValue <string>(attrX));
                        }
                    }
                    if (valuesX.Count > 0)
                    {
                        if (_preSortAttributes)
                        {
                            valuesX.Sort();
                        }
                        firstValueX = valuesX.FirstOrDefault();
                    }
                }
            }

            if (attrY.IsCollectionAttribute)
            {
                IEnumerable <string> collectionY = aspectY.GetCollectionAttribute <string>(attrY);
                if (collectionY != null)
                {
                    List <string> valuesY = new List <string>(collectionY);
                    if (_preSortAttributes)
                    {
                        valuesY.Sort();
                    }
                    firstValueY = valuesY.FirstOrDefault();
                }
            }
            else
            {
                IList <MultipleMediaItemAspect> aspectsY;
                MultipleMediaItemAspectMetadata metadata = attrY.ParentMIAM as MultipleMediaItemAspectMetadata;
                if (metadata != null && MediaItemAspect.TryGetAspects(y.Aspects, metadata, out aspectsY))
                {
                    List <string> valuesY = new List <string>();
                    foreach (MultipleMediaItemAspect aspect in aspectsY)
                    {
                        if (!string.IsNullOrEmpty(aspect.GetAttributeValue <string>(attrY)))
                        {
                            valuesY.Add(aspect.GetAttributeValue <string>(attrY));
                        }
                    }
                    if (valuesY.Count > 0)
                    {
                        if (_preSortAttributes)
                        {
                            valuesY.Sort();
                        }
                        firstValueY = valuesY.FirstOrDefault();
                    }
                }
            }
            return(ObjectUtils.Compare(firstValueX, firstValueY));
        }
 public LikeFilter(MediaItemAspectMetadata.AttributeSpecification attributeType,
                   string expression, char?escapeChar, bool caseSensitive) : base(attributeType, expression, escapeChar)
 {
     _caseSensitive = caseSensitive;
 }
Exemple #25
0
        protected void RequestSimpleAttribute(QueryAttribute queryAttribute,
                                              IDictionary <object, TableQueryData> tableQueries, IList <TableJoin> tableJoins, string miaJoinType,
                                              IDictionary <QueryAttribute, RequestedAttribute> requestedAttributes,
                                              IDictionary <MediaItemAspectMetadata, TableQueryData> miaTypeTableQueries,
                                              RequestedAttribute miaIdAttribute, out RequestedAttribute requestedAttribute)
        {
            if (requestedAttributes.TryGetValue(queryAttribute, out requestedAttribute))
            {
                // Already requested
                return;
            }
            MediaItemAspectMetadata.AttributeSpecification spec = queryAttribute.Attr;
            MediaItemAspectMetadata miaType = spec.ParentMIAM;
            TableQueryData          tqd;

            switch (spec.Cardinality)
            {
            case Cardinality.Inline:
                // For Inline queries, we request the Inline attribute's column name at the MIA main table, which gets joined
                // with the MIA ID
                if (!tableQueries.TryGetValue(miaType, out tqd))
                {
                    tqd = tableQueries[miaType] = TableQueryData.CreateTableQueryOfMIATable(_miaManagement, miaType);
                    if (miaTypeTableQueries != null)
                    {
                        miaTypeTableQueries.Add(miaType, tqd);
                    }
                    tableJoins.Add(new TableJoin(miaJoinType, tqd, miaIdAttribute,
                                                 new RequestedAttribute(tqd, MIA_Management.MIA_MEDIA_ITEM_ID_COL_NAME)));
                }
                requestedAttribute = new RequestedAttribute(tqd, _miaManagement.GetMIAAttributeColumnName(queryAttribute.Attr));
                break;

            case Cardinality.ManyToOne:
                // For MTO queries, we request both the MIA main table and the MTO table
                TableQueryData miaTqd;
                if (!tableQueries.TryGetValue(miaType, out miaTqd))
                {
                    miaTqd = tableQueries[miaType] = TableQueryData.CreateTableQueryOfMIATable(_miaManagement, miaType);
                    if (miaTypeTableQueries != null)
                    {
                        miaTypeTableQueries.Add(miaType, miaTqd);
                    }
                    // Add MIA main table to list of table joins
                    tableJoins.Add(new TableJoin(miaJoinType, miaTqd, miaIdAttribute,
                                                 new RequestedAttribute(miaTqd, MIA_Management.MIA_MEDIA_ITEM_ID_COL_NAME)));
                }
                if (!tableQueries.TryGetValue(spec, out tqd))
                {
                    tqd = tableQueries[spec] = TableQueryData.CreateTableQueryOfMTOTable(_miaManagement, spec);
                    // We must use left outer joins for MTO value tables, because if the value is null, the association FK is null
                    tableJoins.Add(new TableJoin("LEFT OUTER JOIN", tqd,
                                                 new RequestedAttribute(miaTqd, _miaManagement.GetMIAAttributeColumnName(queryAttribute.Attr)),
                                                 new RequestedAttribute(tqd, MIA_Management.FOREIGN_COLL_ATTR_ID_COL_NAME)));
                }
                requestedAttribute = new RequestedAttribute(tqd, MIA_Management.COLL_ATTR_VALUE_COL_NAME);
                break;

            default:
                throw new IllegalCallException("Attributes of cardinality '{0}' cannot be queried via the {1}", spec.Cardinality, GetType().Name);
            }
            requestedAttributes.Add(queryAttribute, requestedAttribute);
        }
 public LikeFilter(MediaItemAspectMetadata.AttributeSpecification attributeType,
                   string expression, char?escapeChar) : this(attributeType, expression, escapeChar, true)
 {
 }
        protected void GenerateSqlStatement(bool groupByValues,
                                            IDictionary <MediaItemAspectMetadata, string> miamAliases,
                                            out string mediaItemIdOrGroupSizeAlias,
                                            out IDictionary <QueryAttribute, string> attributeAliases,
                                            out string statementStr, out IList <BindVar> bindVars)
        {
            Namespace        ns          = new Namespace();
            BindVarNamespace bvNamespace = new BindVarNamespace();

            // Contains a mapping of each queried (=selected or filtered) attribute to its request attribute instance
            // data (which holds its requested query table instance)
            IDictionary <QueryAttribute, RequestedAttribute> requestedAttributes = new Dictionary <QueryAttribute, RequestedAttribute>();

            attributeAliases = new Dictionary <QueryAttribute, string>();

            // Contains a list of qualified attribute names for all select attributes - needed for GROUP BY-expressions
            ICollection <string> qualifiedGroupByAliases = new List <string>();

            // Contains a list of compiled select attribute declarations. We need this in a separate list (in contrast to using
            // the selectAttributes list together with the compiledAttributes map) because it might be the case that
            // an attribute is requested twice. In that rare case, we need a new alias name for it.
            IList <string> selectAttributeDeclarations = new List <string>();

            // Dictionary containing as key the requested MIAM instance OR attribute specification of cardinality MTO,
            // mapped to the table query data to request its contents.
            IDictionary <object, TableQueryData> tableQueries = new Dictionary <object, TableQueryData>();

            // Contains the same tables as the tableQueries variable, but in order and enriched with table join data
            IList <TableJoin> tableJoins = new List <TableJoin>();

            // Contains all table query data for MIA type tables
            IDictionary <MediaItemAspectMetadata, TableQueryData> miaTypeTableQueries = new Dictionary <MediaItemAspectMetadata, TableQueryData>();

            // Albert, 2012-01-29: Optimized query, don't join with media items table, if we have necessary requested MIAs. In that case,
            // we can use one of their media item ids.
            //// First create the request table query data for the MIA main table and the request attribute for the MIA ID.
            //// We'll need the requested attribute as join attribute soon.
            //TableQueryData miaTableQuery = new TableQueryData(MediaLibrary_SubSchema.MEDIA_ITEMS_TABLE_NAME);
            //RequestedAttribute miaIdAttribute = new RequestedAttribute(miaTableQuery, MediaLibrary_SubSchema.MEDIA_ITEMS_ITEM_ID_COL_NAME);

            RequestedAttribute miaIdAttribute = null; // Lazy initialized below

            // Contains CompiledSortInformation instances for each sort information instance
            IList <CompiledSortInformation> compiledSortInformation = null;

            List <BindVar> sqlVars = new List <BindVar>();

            // Ensure that the tables for all necessary MIAs are requested first (INNER JOIN)
            foreach (MediaItemAspectMetadata miaType in _necessaryRequestedMIAs)
            {
                if (miaType.IsTransientAspect)
                {
                    continue;
                }
                if (tableQueries.ContainsKey(miaType))
                {
                    // We only come here if miaType was already queried as necessary MIA, so optimize redundant entry
                    continue;
                }

                TableQueryData tqd = tableQueries[miaType] = TableQueryData.CreateTableQueryOfMIATable(_miaManagement, miaType);
                miaTypeTableQueries.Add(miaType, tqd);
                RequestedAttribute ra;
                // The first table join has invalid join attributes because miaIdAttribute is still null - but only the join table attribute is necessary
                // for the the first table - see below
                tableJoins.Add(new TableJoin("INNER JOIN", tqd,
                                             ra = new RequestedAttribute(tqd, MIA_Management.MIA_MEDIA_ITEM_ID_COL_NAME), miaIdAttribute));
                if (miaIdAttribute == null)
                {
                    miaIdAttribute = ra;
                }
            }

            if (miaIdAttribute == null)
            {                                                                           // If we didn't request any necessary MIA types, we have to add an artificial table for the miaIdAttribute
                TableQueryData miaTableQuery = new TableQueryData(MediaLibrary_SubSchema.MEDIA_ITEMS_TABLE_NAME);
                tableJoins.Add(new TableJoin("INNER JOIN", miaTableQuery, null, null)); // First table join has invalid join attributes - not needed for first table
                miaIdAttribute = new RequestedAttribute(miaTableQuery, MediaLibrary_SubSchema.MEDIA_ITEMS_ITEM_ID_COL_NAME);
            }

            // Ensure that the tables for all optional MIAs are requested first (LEFT OUTER JOIN)
            // That is necessary to make empty optional MIA types available in the result
            foreach (MediaItemAspectMetadata miaType in _optionalRequestedMIAs)
            {
                if (miaType.IsTransientAspect)
                {
                    continue;
                }
                if (tableQueries.ContainsKey(miaType))
                {
                    // We only come here if miaType was already queried as necessary or optional MIA, so optimize redundant entry
                    continue;
                }
                TableQueryData tqd = tableQueries[miaType] = TableQueryData.CreateTableQueryOfMIATable(_miaManagement, miaType);
                miaTypeTableQueries.Add(miaType, tqd);
                tableJoins.Add(new TableJoin("LEFT OUTER JOIN", tqd,
                                             new RequestedAttribute(tqd, MIA_Management.MIA_MEDIA_ITEM_ID_COL_NAME), miaIdAttribute));
            }

            // Build table query data for each selected Inline and MTO attribute
            // + select query attribute
            // + add alias to selectAttributeDeclarations
            foreach (QueryAttribute attr in _selectAttributes)
            {
                if (attr.Attr.ParentMIAM.IsTransientAspect)
                {
                    continue;
                }
                RequestedAttribute ra;
                RequestSimpleAttribute(attr, tableQueries, tableJoins, "LEFT OUTER JOIN", requestedAttributes, miaTypeTableQueries,
                                       miaIdAttribute, out ra);
                string alias;
                selectAttributeDeclarations.Add(_selectProjectionFunction == null ?
                                                ra.GetDeclarationWithAlias(ns, out alias) :
                                                ra.GetDeclarationWithAlias(ns, _selectProjectionFunction, out alias));
                attributeAliases.Add(attr, alias);
                qualifiedGroupByAliases.Add(ra.GetAlias(ns));
            }

            CompiledFilter compiledFilter = CreateCompiledFilter(ns, bvNamespace, miaIdAttribute.GetQualifiedName(ns), tableJoins);

            // Build table query data for each Inline attribute which is part of a filter
            // + compile query attribute
            foreach (QueryAttribute attr in compiledFilter.RequiredAttributes)
            {
                if (attr.Attr.ParentMIAM.IsTransientAspect)
                {
                    continue;
                }
                if (attr.Attr.Cardinality != Cardinality.Inline && attr.Attr.Cardinality != Cardinality.ManyToOne)
                {
                    continue;
                }
                // Tables of Inline and MTO attributes, which are part of a filter, are joined with main table
                RequestedAttribute ra;
                RequestSimpleAttribute(attr, tableQueries, tableJoins, "LEFT OUTER JOIN", requestedAttributes,
                                       miaTypeTableQueries, miaIdAttribute, out ra);
            }
            // Build table query data for each sort attribute
            if (_sortInformation != null)
            {
                compiledSortInformation = new List <CompiledSortInformation>();
                BindVar userVar = null;
                foreach (ISortInformation sortInformation in _sortInformation)
                {
                    AttributeSortInformation attributeSort = sortInformation as AttributeSortInformation;
                    if (attributeSort != null)
                    {
                        if (attributeSort.AttributeType.ParentMIAM.IsTransientAspect)
                        {
                            continue;
                        }
                        MediaItemAspectMetadata.AttributeSpecification attr = attributeSort.AttributeType;
                        if (attr.Cardinality != Cardinality.Inline && attr.Cardinality != Cardinality.ManyToOne)
                        {
                            // Sorting can only be done for Inline and MTO attributes
                            continue;
                        }
                        RequestedAttribute ra;
                        RequestSimpleAttribute(new QueryAttribute(attr), tableQueries, tableJoins, "LEFT OUTER JOIN", requestedAttributes,
                                               miaTypeTableQueries, miaIdAttribute, out ra);
                        compiledSortInformation.Add(new CompiledSortInformation(ra, attributeSort.Direction));
                        continue;
                    }

                    DataSortInformation dataSort = sortInformation as DataSortInformation;
                    if (dataSort != null && _userProfileId.HasValue)
                    {
                        TableQueryData     tqd = new TableQueryData(UserProfileDataManagement.UserProfileDataManagement_SubSchema.USER_MEDIA_ITEM_DATA_TABLE_NAME);
                        RequestedAttribute ra  = new RequestedAttribute(tqd, UserProfileDataManagement.UserProfileDataManagement_SubSchema.USER_DATA_VALUE_COL_NAME);
                        compiledSortInformation.Add(new CompiledSortInformation(ra, dataSort.Direction));

                        if (userVar == null)
                        {
                            userVar = new BindVar("UID", _userProfileId.Value, typeof(Guid));
                            sqlVars.Add(userVar);
                        }
                        TableJoin join = new TableJoin("LEFT OUTER JOIN", tqd, new RequestedAttribute(tqd, UserProfileDataManagement.UserProfileDataManagement_SubSchema.USER_PROFILE_ID_COL_NAME), "@" + userVar.Name);
                        join.AddCondition(new RequestedAttribute(tqd, MIA_Management.MIA_MEDIA_ITEM_ID_COL_NAME), miaIdAttribute);
                        join.AddCondition(new RequestedAttribute(tqd, UserProfileDataManagement.UserProfileDataManagement_SubSchema.USER_DATA_KEY_COL_NAME), $"'{dataSort.UserDataKey}'");
                        tableJoins.Add(join);
                    }
                }
            }
            StringBuilder result = new StringBuilder("SELECT ");

            string groupClause = StringUtils.Join(", ", qualifiedGroupByAliases.Select(alias => "V." + alias));

            if (groupByValues)
            {
                mediaItemIdOrGroupSizeAlias = "C";
                // Create an additional COUNT expression for the MEDIA_ITEMS.MEDIA_ITEM_ID in the GROUP BY-statement
                result.Append("COUNT(V.C) ");
                result.Append(mediaItemIdOrGroupSizeAlias);
                if (!string.IsNullOrWhiteSpace(groupClause))
                {
                    result.Append(", ");
                    result.Append(groupClause);
                }
                result.Append(" FROM (");
                result.Append("SELECT DISTINCT ");
                result.Append(miaIdAttribute.GetQualifiedName(ns));
                result.Append(" C");
            }
            else
            {
                // Append plain attribute MEDIA_ITEMS.MEDIA_ITEM_ID if no GROUP BY-statement is requested
                result.Append(miaIdAttribute.GetDeclarationWithAlias(ns, out mediaItemIdOrGroupSizeAlias));

                // System attributes: Necessary to evaluate if a requested MIA is present for the media item
                foreach (KeyValuePair <MediaItemAspectMetadata, TableQueryData> kvp in miaTypeTableQueries)
                {
                    result.Append(", ");
                    string miamColumn = kvp.Value.GetAlias(ns) + "." + MIA_Management.MIA_MEDIA_ITEM_ID_COL_NAME;
                    result.Append(miamColumn);
                    string miamAlias = ns.GetOrCreate(miamColumn, "A");
                    result.Append(" ");
                    result.Append(miamAlias);
                    if (miamAlias != null)
                    {
                        miamAliases.Add(kvp.Key, miamAlias);
                    }
                }
            }

            // Selected attributes
            foreach (string selectAttr in selectAttributeDeclarations)
            {
                result.Append(", ");
                result.Append(selectAttr);
            }

            string whereStr = compiledFilter.CreateSqlFilterCondition(ns, requestedAttributes, out bindVars);

            foreach (BindVar bv in sqlVars)
            {
                bindVars.Add(bv);
            }

            result.Append(" FROM ");

            bool firstJoinTable = true;

            // Other joined tables
            foreach (TableJoin tableJoin in tableJoins)
            {
                if (firstJoinTable)
                {
                    result.Append(tableJoin.JoinedTable.GetDeclarationWithAlias(ns));
                    firstJoinTable = false;
                }
                else
                {
                    result.Append(tableJoin.GetJoinDeclaration(ns));
                }
                result.Append(' ');
            }

            if (!string.IsNullOrEmpty(whereStr))
            {
                result.Append(" WHERE ");
                result.Append(whereStr);
            }
            if (groupByValues)
            {
                result.Append(") V");
                if (qualifiedGroupByAliases.Count > 0)
                {
                    result.Append(" GROUP BY ");
                    result.Append(groupClause);
                }
            }
            else
            {
                if (compiledSortInformation != null && compiledSortInformation.Count > 0)
                {
                    IEnumerable <string> sortCriteria = compiledSortInformation.Select(csi => csi.GetSortDeclaration(ns));
                    result.Append(" ORDER BY ");
                    result.Append(StringUtils.Join(", ", sortCriteria));
                }
            }
            statementStr = result.ToString();
        }
Exemple #28
0
 public SortInformation(MediaItemAspectMetadata.AttributeSpecification attributeType, SortDirection sortDirection)
 {
     _attributeType = attributeType;
     _sortDirection = sortDirection;
 }
Exemple #29
0
 protected AbstractExpressionFilter(MediaItemAspectMetadata.AttributeSpecification attributeType,
                                    string expression, char?escapeChar) : base(attributeType)
 {
     _expression = expression;
     _escapeChar = escapeChar;
 }
 public SimpleMLFilterCriterion(MediaItemAspectMetadata.AttributeSpecification attributeType)
 {
     _valueAttributeType = attributeType;
 }
 protected AbstractAttributeFilter(MediaItemAspectMetadata.AttributeSpecification attributeType)
 {
   _attributeType = attributeType;
 }
 public async Task<Tuple<HomogenousMap, HomogenousMap>> GetKeyValueGroupsAsync(MediaItemAspectMetadata.AttributeSpecification keyAttributeType, MediaItemAspectMetadata.AttributeSpecification valueAttributeType,
   IFilter selectAttributeFilter, ProjectionFunction projectionFunction, IEnumerable<Guid> necessaryMIATypes, IFilter filter, bool onlyOnline, bool includeVirtual)
 {
   CpAction action = GetAction("X_MediaPortal_GetKeyValueGroups");
   string projectionFunctionStr = SerializeProjectionFunction(projectionFunction);
   string onlineStateStr = SerializeOnlineState(onlyOnline);
   IList<object> inParameters = new List<object>
   {
     MarshallingHelper.SerializeGuid(keyAttributeType.ParentMIAM.AspectId),
     keyAttributeType.AttributeName,
     MarshallingHelper.SerializeGuid(valueAttributeType.ParentMIAM.AspectId),
     valueAttributeType.AttributeName,
     selectAttributeFilter,
     projectionFunctionStr,
     MarshallingHelper.SerializeGuidEnumerationToCsv(necessaryMIATypes),
     filter,
     onlineStateStr,
     includeVirtual,
   };
   IList<object> outParameters = await action.InvokeAsync(inParameters);
   return new Tuple<HomogenousMap, HomogenousMap>((HomogenousMap)outParameters[0], (HomogenousMap)outParameters[1]);
 }