protected Predicate FromQueryPredicate(QueryPredicate queryPredicate)
        {
            switch (queryPredicate)
            {
                case QueryPredicate.EQUAL_TO:
                    return Predicate.EQUAL_TO;
                case QueryPredicate.GREATER_THAN:
                    return Predicate.GREATER_THAN;
                case QueryPredicate.GREATER_THAN_EQUAL_TO:
                    return Predicate.GREATER_THAN_EQUAL_TO;
                case QueryPredicate.IS_NOT_NULL:
                    return Predicate.IS_NOT_NULL;
                case QueryPredicate.IS_NULL:
                    return Predicate.IS_NULL;
                case QueryPredicate.LESS_THAN:
                    return Predicate.LESS_THAN;
                case QueryPredicate.LESS_THAN_EQUAL_TO:
                    return Predicate.LESS_THAN_EQUAL_TO;
                case QueryPredicate.LIKE:
                    return Predicate.LIKE;
                case QueryPredicate.NOT_EQUAL_TO:
                    return Predicate.NOT_EQUAL_TO;
            }

            System.Diagnostics.Debug.Assert(false); // this should never happen
            return Predicate.LIKE;
        }
 public CumulativeRecordPermission(string id, Type entityType, UserRecordPermission initialPermissions, ActivityGrant grant)
 {
     Id = id;
       EntityType = entityType;
       RecordPermission = initialPermissions;
       SourceGrants.Add(grant);
       if(grant.Filter != null) {
     FilterPredicate = grant.Filter.EntityFilter.GetPredicate(entityType);
     QueryPredicate = grant.Filter.QueryFilter.GetPredicate(entityType);
       }
       HasFilter = (FilterPredicate != null);
 }
        public IQueryable<TElement> CreateQuery<TElement>(Expression expression)
        {
            if (typeof(TElement) != typeof(T))
            {
                throw new ArgumentException("Only " + typeof(T).FullName + " objects are supported");
            }

            bool isMethodCallExpression = expression is MethodCallExpression;

            if (!isMethodCallExpression)
            {
                return new ClientQueryableCollection<TElement>(this as ClientQueryProvider<TElement>, expression);
            }

            var cmd = this.Command as QueryCommand<TElement>;
            MethodCallExpression mc = expression as MethodCallExpression;
            switch (mc.Method.Name)
            {
                case "Where":
                    if (mc.Arguments[1] is UnaryExpression where)
                    {
                        var t = where.Operand as Expression<Func<TElement, bool>>;
                        var queryPredicate = new QueryPredicate<TElement>(t);
                        if (cmd != null && cmd.QueryParameters is IPredicateQueryable queryParameters)
                        {
                            queryParameters.Where.Add(queryPredicate.ToString());
                        }
                    }

                    break;
                case "Take":
                    if (mc.Arguments[1] is ConstantExpression limit)
                    {
                        if (cmd != null && cmd.QueryParameters is IPageable queryParameters)
                        {
                            queryParameters.Limit = (int)limit.Value;
                        }
                    }

                    break;
                case "Skip":
                    if (mc.Arguments[1] is ConstantExpression offset)
                    {
                        if (cmd != null && cmd.QueryParameters is IPageable queryParameters)
                        {
                            queryParameters.Offset = (int)offset.Value;
                        }
                    }

                    break;
                case "OrderBy":
                case "ThenBy":
                case "OrderByDescending":
                case "ThenByDescending":
                    if (mc.Arguments[1] is UnaryExpression sort)
                    {
                        if (cmd != null && cmd.QueryParameters is ISortable queryParameters)
                        {
                            if (mc.Method.Name.StartsWith("OrderBy", StringComparison.Ordinal))
                            {
                                queryParameters.Sort.Clear();
                            }

                            var direction = SortDirection.Ascending;
                            if (mc.Method.Name.EndsWith("Descending", StringComparison.Ordinal))
                            {
                                direction = SortDirection.Descending;
                            }

                            var render = sort.Operand.RenderSort();
                            queryParameters.Sort.Add(new Sort<T>(render, direction).ToString());
                        }
                    }

                    break;
                case "Expand":
                    if (mc.Arguments[1] is UnaryExpression expand)
                    {
                        if (cmd != null && cmd.QueryParameters is IExpandable queryParameters)
                        {
                            queryParameters.Expand.Add(new Expansion<TElement>(expand.Operand).ToString());
                        }
                    }

                    break;
                default:
                    break;
            }

            return new ClientQueryableCollection<TElement>(this as ClientQueryProvider<TElement>, expression);
        }
Exemple #4
0
        private void PopulateJoinDependantsList(IList<QueryPredicate> list, Expression joinGraph)
        {
            if (joinGraph is JoinExpression) {
                JoinExpression joinExp = (JoinExpression) joinGraph;

                // Populate parents first
                PopulateJoinDependantsList(list, joinExp.Left);
                PopulateJoinDependantsList(list, joinExp.Right);

                // Is this an outer join?
                JoinType joinType = joinExp.JoinType;
                if (joinType == JoinType.Outer ||
                    joinType == JoinType.OuterLeft ||
                    joinType == JoinType.OuterRight) {
                    // The outer table
                    if (joinType != JoinType.OuterLeft)
                        throw new ApplicationException("Unsupported join type " + joinType);

                    // Make a list of tables that are dependants on the right side
                    // (the outer join).
                    List<TableName> rightDependancy = new List<TableName>();
                    List<Expression> rightDependancyExps = new List<Expression>();
                    PopulateSourceList(rightDependancy, rightDependancyExps, joinExp.Right);

                    // Yes, so get the filter term
                    Expression filter = joinExp.Filter;

                    // Make a list of dependants on the expression itself
                    List<QueryPredicate> dependants = new List<QueryPredicate>();

                    // If filter_op is not null
                    if (filter != null) {
                        // Simplify the filter expression and create a predicate list
                        Expression simplifiedFilter = SimplifyTerm(filter);
                        PopulateDependantsList(dependants, simplifiedFilter);

                        // Any predicates that have no dependancy on the right dependency of
                        // the outer join we move to the main filter clause
                        for (int j = dependants.Count - 1; j >= 0; j--) {
                            QueryPredicate exp = dependants[j];
                            // If this predicate not dependant on any sources on the right
                            // tree, we simply shift it to the main filter clause.
                            if (!exp.IsDependantOnAny(rightDependancy)) {
                                MergeWithDependantList(exp, list);
                                dependants.RemoveAt(j);
                            } else {
                                // Set the right dependancy info in the predicate
                                exp.right_dependancy = rightDependancy;
                                exp.right_exclusive = true;
                                exp.JoinType = joinType;
                            }
                        }
                    }

                    // filter_op is null, so dependants size will be 0 so it'll just add
                    // a default expression dependant to the list for this join

                    // If there are no dependants, we create a default dependant term for
                    // this outer join, so that we correctly markup this outer join
                    // expression.
                    if (dependants.Count == 0) {
                        QueryPredicate exprDep = new QueryPredicate(new FetchStaticExpression(new SqlObject(true)), new List<TableName>());
                        exprDep.right_dependancy = rightDependancy;
                        exprDep.right_exclusive = true;
                        exprDep.JoinType = joinType;
                        list.Add(exprDep);
                    } else {
                        // The final QueryPredicate are expressions that reference the
                        // outer table in the join filter

                        // Merge them all together,
                        QueryPredicate exprDep = dependants[0];
                        for (int i = 1; i < dependants.Count; ++i) {
                            QueryPredicate next_expr = dependants[i];
                            exprDep.Merge(next_expr);
                        }
                        list.Add(exprDep);
                    }
                }

            } else if (joinGraph is AliasTableNameExpression) {
                // Terminating condition
            } else {
                throw new ApplicationException("Unexpected operation");
            }
        }
 partial void OnGeneratedPredicateWithRsn(QueryPredicate queryPredicate, IQueryable <Entities.InvoicesEntity> leftHandQueryable, SortedSet <QueryParameter> parameters, ref IQueryable <Entities.InvoicesEntity> resultingQueryable);
Exemple #6
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DataFieldMatchExpression"/> class.
 /// </summary>
 /// <param name="leftField">Left field.</param>
 /// <param name="rightField">Right field.</param>
 /// <param name="predicate">Predicate.</param>
 internal DataFieldMatchExpression(DataFieldInfo leftField, DataFieldInfo rightField, QueryPredicate predicate)
 {
     this.leftField  = leftField;
     this.rightField = rightField;
     this.predicate  = predicate;
 }
Exemple #7
0
        private void PopulateDependantsList(IList<QueryPredicate> list, Expression filter)
        {
            // Split by AND
            List<Expression> unionTerms = new List<Expression>();
            SplitByFunction(unionTerms, filter, "@and_sql");
            // Discover the tables each term is dependant on
            foreach (Expression expression in unionTerms) {
                List<TableName> tables = new List<TableName>();
                PopulateDependantTablesForExpression(tables, expression, sourceList);

                // Create an QueryPredicate object
                QueryPredicate exprDep = new QueryPredicate(expression, tables);

                // Merge it with the list or add to the end if we can't merge it with
                // an existing entry
                MergeWithDependantList(exprDep, list);
            }
        }
Exemple #8
0
 /// <summary>
 /// Hack the query
 /// </summary>
 public bool HackQuery(QueryBuilder builder, SqlStatement sqlStatement, SqlStatement whereClause, Type tmodel, PropertyInfo property, string queryPrefix, QueryPredicate predicate, object values, IEnumerable <TableMapping> scopedTables, params KeyValuePair <string, object>[] queryFilter)
 {
     if (typeof(SecurityUser) == tmodel && property.Name == nameof(SecurityUser.UserEntity))
     {
         var userkey         = TableMapping.Get(typeof(DbUserEntity)).GetColumn(nameof(DbUserEntity.SecurityUserKey), false);
         var personSubSelect = builder.CreateQuery <UserEntity>(queryFilter.Select(p => new KeyValuePair <String, Object>(p.Key.Replace("userEntity.", ""), p.Value)), null, userkey);
         var userIdKey       = TableMapping.Get(typeof(DbSecurityUser)).PrimaryKey.FirstOrDefault();
         whereClause.And($"{userIdKey.Name} IN (").Append(personSubSelect).Append(")");
         return(true);
     }
     return(false);
 }
 internal QueryData(QueryData queryData)
 {
     _selectedValue = queryData._selectedValue;
     _predicate = queryData._predicate;
 }
        protected override IQueryable <Entities.InventoryItemSummaryEntity> GeneratePredicate(QueryPredicate queryPredicate, IQueryable <Entities.InventoryItemSummaryEntity> leftHandQueryable = null)
        {
            InventoryItemSummaryQueryStrategy queryStrategy = GetNullQueryStrategy();
            SortedSet <QueryParameter>        parameters    = queryPredicate.Parameters;

            IQueryable <Entities.InventoryItemSummaryEntity> resultingQueryable = null;

            if (queryPredicate.Name == GetFunctionName <Guid>(queryStrategy.WithRsn))
            {
                OnGeneratePredicateWithRsn(queryPredicate, leftHandQueryable, parameters, ref resultingQueryable);
                GeneratePredicateWithRsn(parameters, leftHandQueryable, ref resultingQueryable);
                OnGeneratedPredicateWithRsn(queryPredicate, leftHandQueryable, parameters, ref resultingQueryable);
                return(resultingQueryable);
            }

            resultingQueryable
                = GeneratePredicateWithPermissionScopeAny <ISingleSignOnToken>(queryPredicate, leftHandQueryable)
                  ?? GeneratePredicateWithPermissionScopeUser <ISingleSignOnToken>(queryPredicate, leftHandQueryable)
                  ?? GeneratePredicateWithPermissionScopeCompany <ISingleSignOnToken>(queryPredicate, leftHandQueryable)
                  ?? GeneratePredicateWithPermissionScopeCompanyAndUser <ISingleSignOnToken>(queryPredicate, leftHandQueryable);

            if (resultingQueryable != null)
            {
                return(resultingQueryable);
            }

            throw new InvalidOperationException("No known predicate could be generated.");
        }
        /// <summary>
        /// Query hack for creation time
        /// </summary>
        public bool HackQuery(QueryBuilder builder, SqlStatement sqlStatement, SqlStatement whereClause, Type tmodel, PropertyInfo property, string queryPrefix, QueryPredicate predicate, object values, IEnumerable <TableMapping> scopedTables, params KeyValuePair <String, object>[] queryFilter)
        {
            if (property.Name == nameof(IBaseEntityData.CreationTime) && typeof(IVersionedEntity).IsAssignableFrom(tmodel)) // filter by first creation time
            {
                var ormMap          = scopedTables.SelectMany(o => o.Columns);
                var replacesVersion = ormMap.FirstOrDefault(o => o.SourceProperty.Name == nameof(IDbVersionedData.ReplacesVersionKey));
                // Find the join Column
                var joinCol = replacesVersion.Table.Columns.FirstOrDefault(o => o.ForeignKey?.Table == scopedTables.Last().OrmType);

                whereClause.And($"EXISTS (SELECT crt{replacesVersion.Table.TableName}.{joinCol.Name} FROM {replacesVersion.Table.TableName} AS crt{replacesVersion.Table.TableName} WHERE crt{replacesVersion.Table.TableName}.{joinCol.Name} = {queryPrefix}{replacesVersion.Table.TableName}.{joinCol.Name} AND crt{replacesVersion.Table.TableName}.{replacesVersion.Name} IS NULL ");
                whereClause.And(builder.CreateWhereCondition(tmodel, predicate.Path, values, "crt", scopedTables.ToList()));
                whereClause.Append(")");
                return(true);
            }
            return(false);
        }
Exemple #12
0
 private AggregateHavingExpression SingleParam(QueryPredicate predicate, object value)
 {
     return(SingleParam(predicate, value, false));
 }
 partial void OnGeneratePredicateWithOrderId(QueryPredicate queryPredicate, IQueryable <Entities.OrderEntity> leftHandQueryable, SortedSet <QueryParameter> parameters, ref IQueryable <Entities.OrderEntity> resultingQueryable);
        public bool HackQuery(QueryBuilder builder, SqlStatement sqlStatement, SqlStatement whereClause, Type tmodel, PropertyInfo property, string queryPrefix, QueryPredicate predicate, object values, IEnumerable <TableMapping> scopedTables)
        {
            if (property.Name == "RcptTo" && property.PropertyType.StripGeneric() == typeof(SecurityUser))
            {
                if (predicate.SubPath == "userName")
                {
                    if (!(values is IList))
                    {
                        values = new List <Object>()
                        {
                            values
                        }
                    }
                    ;

                    var    lValues = values as IList;
                    var    secRepo = ApplicationServiceContext.Current.GetService <ISecurityRepositoryService>();
                    Guid[] vals    = lValues.OfType <String>().Select(u => secRepo.GetUser(u)?.Key).OfType <Guid>().ToArray();
                    whereClause.And($"rcptTo IN ({String.Join(",", vals.Select(o => $"X'{BitConverter.ToString(((Guid)o).ToByteArray()).Replace("-", "")}'").ToArray())})");
                    return(true);
                }
                else
                {
                    throw new InvalidOperationException("Cannot map this expression");
                }
            }
            return(false);
        }
    }
 internal QueryData(QueryData queryData)
 {
     _selectedValue = queryData._selectedValue;
     _predicate     = queryData._predicate;
 }
 public QueryData(string selectedValue, QueryPredicate predicate)
 {
     _selectedValue = selectedValue;
     _predicate     = predicate;
 }
Exemple #17
0
        /// <summary>
        /// Hack the particular query
        /// </summary>
        public bool HackQuery(QueryBuilder builder, SqlStatement sqlStatement, SqlStatement whereClause, Type tmodel, PropertyInfo property, String queryPrefix, QueryPredicate predicate, object values, IEnumerable <TableMapping> scopedTables)
        {
            // Hack mnemonic queries
            if (typeof(Concept).GetTypeInfo().IsAssignableFrom(property.PropertyType.GetTypeInfo()) && predicate.SubPath == "mnemonic")
            {
                // Has this already been joined?
                var mapType = property.DeclaringType;
                if (mapType.GetTypeInfo().IsAbstract)
                {
                    mapType = tmodel;
                }
                var declType    = TableMapping.Get(this.m_mapper.MapModelType(mapType));
                var keyProperty = property.PropertyType == typeof(Guid) ? property : mapType.GetRuntimeProperty(property.Name + "Key");
                var declProp    = declType.GetColumn(this.m_mapper.MapModelProperty(mapType, declType.OrmType, keyProperty));
                if (declProp.ForeignKey == null)
                {
                    return(false);                             // No FK link
                }
                var    tblMap       = TableMapping.Get(this.m_mapper.MapModelType(property.PropertyType));
                var    fkTbl        = TableMapping.Get(declProp.ForeignKey.Table);
                string directFkName = $"{queryPrefix}{fkTbl.TableName}";

                // We have to join to the FK table
                if (!declProp.IsAlwaysJoin)
                {
                    var fkColumn = fkTbl.GetColumn(declProp.ForeignKey.Column);
                    sqlStatement.Append($" INNER JOIN {fkTbl.TableName} AS {directFkName}_{declProp.Name} ON ({queryPrefix}{declType.TableName}.{declProp.Name} = {directFkName}_{declProp.Name}.{fkColumn.Name})");
                    directFkName += $"_{declProp.Name}";
                }

                // We aren't yet joined to our table, we need to join to our table though!!!!
                if (declProp.ForeignKey.Table != tblMap.OrmType)
                {
                    var fkKeyColumn = fkTbl.Columns.FirstOrDefault(o => o.ForeignKey?.Table == tblMap.OrmType && o.Name == tblMap.PrimaryKey.First().Name) ??
                                      tblMap.Columns.FirstOrDefault(o => o.ForeignKey?.Table == fkTbl.OrmType && o.Name == fkTbl.PrimaryKey.First().Name);
                    if (fkKeyColumn == null)
                    {
                        return(false);                     // couldn't find the FK link
                    }
                    // Now we want to filter our FK
                    var tblName = $"{queryPrefix}{declProp.Name}_{tblMap.TableName}";
                    sqlStatement.Append($" INNER JOIN {tblMap.TableName} AS {tblName} ON ({directFkName}.{fkKeyColumn.Name} = {tblName}.{fkKeyColumn.Name})");

                    // Append the where clause
                    whereClause.And(builder.CreateWhereCondition(property.PropertyType, predicate.SubPath, values, $"{queryPrefix}{declProp.Name}_", new List <TableMapping>()
                    {
                        tblMap
                    }, tblName));
                }
                else
                {
                    // Append the where clause
                    whereClause.And(builder.CreateWhereCondition(property.PropertyType, predicate.SubPath, values, $"{queryPrefix}{declProp.Name}_", new List <TableMapping>()
                    {
                        tblMap
                    }, $"{directFkName}"));
                }
                return(true);
            }
            else
            {
                return(false);
            }
        }
Exemple #18
0
            public bool HasEqualDependants(QueryPredicate dep)
            {
                // False if the sizes different
                int sz = dependant_on.Count;
                if (sz != dep.dependant_on.Count)
                    return false;

                // Equal sizes
                for (int i = 0; i < sz; ++i) {
                    if (!dep.IsDependantOn(dependant_on[i])) {
                        // False if the given list doesn't contain this item.
                        return false;
                    }
                }
                // Match
                return true;
            }
 public static CheckByQueryCommand <T> SetWhere <T>(this CheckByQueryCommand <T> command, QueryPredicate <T> queryPredicate)
     where T : Resource <T>, ICheckable <T>
 {
     return(command.SetWhere(queryPredicate.ToString()));
 }
 public QueryData(string selectedValue, QueryPredicate predicate)
 {
     _selectedValue = selectedValue;
     _predicate = predicate;
 }
Exemple #21
0
        /// <summary>
        /// Hack query builder based on clause
        /// </summary>
        public bool HackQuery(QueryBuilder builder, SqlStatement sqlStatement, SqlStatement whereClause, Type tmodel, PropertyInfo property, string queryPrefix, QueryPredicate predicate, object values, IEnumerable <TableMapping> scopedTables, params KeyValuePair <String, object>[] queryFilter)
        {
            string columnName = String.Empty;
            Type   scanType   = null;

            // Filter values
            if (typeof(Concept).IsAssignableFrom(property.PropertyType) && predicate.SubPath == "mnemonic")
            {
                Regex removeRegex = null;
                if (predicate.Path == "participationRole" && property.DeclaringType == typeof(ActParticipation))
                {
                    columnName = "rol_cd_id";
                    scanType   = typeof(ActParticipationKey);
                    // We want to remove the inner join for cd_tbl
                    removeRegex = new Regex(@"INNER\sJOIN\scd_tbl\s.*\(.*?rol_cd_id.*");
                }
                else if (predicate.Path == "relationshipType" && property.DeclaringType == typeof(EntityRelationship))
                {
                    columnName  = "rel_typ_cd_id";
                    scanType    = typeof(EntityRelationshipTypeKeys);
                    removeRegex = new Regex(@"INNER\sJOIN\scd_tbl\s.*\(.*?rel_typ_cd_id.*");
                }
                else if (predicate.Path == "relationshipType" && property.DeclaringType == typeof(ActRelationship))
                {
                    columnName  = "rel_typ_cd_id";
                    scanType    = typeof(ActRelationshipTypeKeys);
                    removeRegex = new Regex(@"INNER\sJOIN\scd_tbl\s.*\(.*?rel_typ_cd_id.*");
                }
                else
                {
                    return(false);
                }

                // Now we scan
                List <Object> qValues = new List <object>();
                if (values is IEnumerable)
                {
                    foreach (var i in values as IEnumerable)
                    {
                        var fieldInfo = scanType.GetRuntimeField(i.ToString());
                        if (fieldInfo == null)
                        {
                            return(false);
                        }
                        qValues.Add(fieldInfo.GetValue(null));
                    }
                }
                else
                {
                    var fieldInfo = scanType.GetRuntimeField(values.ToString());
                    if (fieldInfo == null)
                    {
                        return(false);
                    }
                    qValues.Add(fieldInfo.GetValue(null));
                }

                // Now add to query
                whereClause.And($"{columnName} IN ({String.Join(",", qValues.Select(o=>$"'{o}'").ToArray())})");

                // Remove the inner join
                var          remStack = new Stack <SqlStatement>();
                SqlStatement last;
                while (sqlStatement.RemoveLast(out last))
                {
                    var m = removeRegex.Match(last.SQL);
                    if (m.Success)
                    {
                        // The last thing we added was the
                        if (m.Index == 0 && m.Length == last.SQL.Length)
                        {
                            remStack.Pop();
                        }
                        else
                        {
                            sqlStatement.Append(last.SQL.Remove(m.Index, m.Length), last.Arguments.ToArray());
                        }
                        break;
                    }
                    else
                    {
                        remStack.Push(last);
                    }
                }
                while (remStack.Count > 0)
                {
                    sqlStatement.Append(remStack.Pop());
                }
                return(true);
            }
            else
            {
                return(false);
            }
        }
        /// <summary>
        /// Hack the query
        /// </summary>
        public bool HackQuery(QueryBuilder builder, SqlStatement sqlStatement, SqlStatement whereClause, Type tmodel, PropertyInfo property, string queryPrefix, QueryPredicate predicate, object values, IEnumerable <TableMapping> scopedTables, params KeyValuePair <String, object>[] queryFilter)
        {
            String cmpTblType = String.Empty, valTblType = String.Empty, keyName = String.Empty;
            Type   guardType = null, componentType = null;

            // We can attempt to hack the address
            if (typeof(EntityAddress).IsAssignableFrom(tmodel))
            {
                cmpTblType    = "ent_addr_cmp_tbl";
                valTblType    = "ent_addr_cmp_val_tbl";
                guardType     = typeof(AddressComponentKeys);
                componentType = typeof(EntityAddressComponent);
                keyName       = "addr_id";
            }
            else if (typeof(EntityName).IsAssignableFrom(tmodel))
            {
                cmpTblType    = "ent_name_cmp_tbl";
                valTblType    = "phon_val_tbl";
                guardType     = typeof(NameComponentKeys);
                componentType = typeof(EntityNameComponent);
                keyName       = "name_id";
            }
            else
            {
                return(false);
            }

            // Not applicable for us if
            //  - Not a name or address
            //  - Predicate is not component.value
            //  - There is already other where clause stuff
            if (guardType == null ||
                predicate.Path != "component" ||
                predicate.SubPath != "value" ||
                !String.IsNullOrEmpty(whereClause.SQL))
            {
                return(false);
            }

            // Pop the last statement off
            // var fromClause = sqlStatement.RemoveLast();

            var subQueryAlias = $"{queryPrefix}{scopedTables.First().TableName}";

            whereClause.And($" {subQueryAlias}.{keyName} IN (");

            foreach (var itm in queryFilter)
            {
                var    pred        = QueryPredicate.Parse(itm.Key);
                String guardFilter = String.Empty;

                // Do we have a guard for address?
                if (!String.IsNullOrEmpty(pred.Guard))
                {
                    // Translate Guards to UUIDs
                    var guards = pred.Guard.Split('|');
                    for (int i = 0; i < guards.Length; i++)
                    {
                        guards[i] = guardType.GetField(guards[i]).GetValue(null).ToString();
                    }
                    if (guards.Any(o => o == null))
                    {
                        return(false);
                    }

                    // Add to where clause
                    guardFilter = $"AND {queryPrefix}{cmpTblType}.typ_cd_id IN ({String.Join(",", guards.Select(o => $"'{o}'"))}) ";
                }

                // Filter on the component value
                var value = itm.Value;
                if (value is String)
                {
                    value = new List <Object>()
                    {
                        value
                    }
                }
                ;
                var qValues = value as List <Object>;

                // Filter based on type and prefix :)
                whereClause
                .Append($" SELECT {queryPrefix}{cmpTblType}.{keyName} ")
                .Append($" FROM {cmpTblType} AS {queryPrefix}{cmpTblType} ")
                .Append(" WHERE ")
                .Append($" val_seq_id IN (SELECT val_seq_id FROM {valTblType} WHERE ")
                .Append(builder.CreateSqlPredicate($"{valTblType}", "val", componentType.GetProperty("Value"), qValues))
                .Append(") ")
                .Append(guardFilter)
                .Append(" INTERSECT ");
            }
            whereClause.RemoveLast();
            whereClause.Append($") ");
            whereClause.And($"{subQueryAlias}.obslt_vrsn_seq_id IS NULL ");

            return(true);
        }
    }
Exemple #23
0
            public void Merge(QueryPredicate dep)
            {
                // Assert the join types are equal
                if (joinTypeSet && dep.joinTypeSet &&
                    !join_type.Equals(dep.join_type))
                    throw new ApplicationException("Incorrect join type for merge.");

                if ((!joinTypeSet && dep.joinTypeSet) ||
                    (joinTypeSet && !dep.joinTypeSet))
                    throw new ApplicationException("Incorrect join type for merge.");

                // We simply wrap the expressions around an 'and'
                FunctionExpression andFun = new FunctionExpression("@and_sql");
                andFun.Parameters.Add(expression);
                andFun.Parameters.Add(dep.expression);
                expression = andFun;
                // Merge the dependants set
                foreach (TableName tname in dep.dependant_on) {
                    if (!dependant_on.Contains(tname)) {
                        dependant_on.Add(tname);
                    }
                }
            }
        /// <summary>
        /// Hack the query
        /// </summary>
        public bool HackQuery(QueryBuilder builder, SqlStatement sqlStatement, SqlStatement whereClause, Type tmodel, PropertyInfo property, string queryPrefix, QueryPredicate predicate, object values, IEnumerable <TableMapping> scopedTables, params KeyValuePair <String, object>[] queryFilter)
        {
            String cmpTblType = String.Empty, valTblType = String.Empty, keyName = String.Empty;
            Type   guardType = null, componentType = null;

            // We can attempt to hack the address
            if (typeof(EntityAddress).IsAssignableFrom(tmodel))
            {
                cmpTblType    = "ent_addr_cmp_tbl";
                valTblType    = "ent_addr_cmp_val_tbl";
                guardType     = typeof(AddressComponentKeys);
                componentType = typeof(EntityAddressComponent);
                keyName       = "addr_id";
            }
            else if (typeof(EntityName).IsAssignableFrom(tmodel))
            {
                cmpTblType    = "ent_name_cmp_tbl";
                valTblType    = "phon_val_tbl";
                guardType     = typeof(NameComponentKeys);
                componentType = typeof(EntityNameComponent);
                keyName       = "name_id";
            }
            else
            {
                return(false);
            }

            // Not applicable for us if
            //  - Not a name or address
            //  - Predicate is not component.value
            //  - There is already other where clause stuff
            if (guardType == null ||
                predicate.Path != "component" ||
                predicate.SubPath != "value" ||
                !String.IsNullOrEmpty(whereClause.SQL))
            {
                return(false);
            }

            whereClause.And($" {keyName} IN (SELECT {keyName} FROM  {cmpTblType} AS {queryPrefix}{cmpTblType} ");
            // Filter through other name or address components which may be in the query at this query level
            List <String> componentTypeGuard = new List <String>();
            var           localChar          = 'a';
            int           vCount             = 0;

            foreach (var itm in queryFilter)
            {
                var    pred        = QueryPredicate.Parse(itm.Key);
                String guardFilter = String.Empty;

                // Do we have a guard for address?
                if (!String.IsNullOrEmpty(pred.Guard))
                {
                    // Translate Guards to UUIDs
                    var guards = pred.Guard.Split('|');
                    for (int i = 0; i < guards.Length; i++)
                    {
                        guards[i] = guardType.GetField(guards[i]).GetValue(null).ToString();
                    }
                    if (guards.Any(o => o == null))
                    {
                        return(false);
                    }

                    // Add to where clause
                    componentTypeGuard.AddRange(guards);
                    guardFilter = $"AND {queryPrefix}{cmpTblType}.typ_cd_id IN ({String.Join(",", guards.Select(o => $"'{o}'"))})";
                }

                // Filter on the component value
                var value = itm.Value;
                if (value is String)
                {
                    value = new List <Object>()
                    {
                        value
                    }
                }
                ;
                var qValues = value as List <Object>;
                vCount++;


                whereClause.Append($"LEFT JOIN (SELECT val_seq_id FROM {valTblType} AS {queryPrefix}{valTblType} WHERE ");
                whereClause.Append(builder.CreateSqlPredicate($"{queryPrefix}{valTblType}", "val", componentType.GetProperty("Value"), qValues));
                whereClause.Append($") AS {queryPrefix}{valTblType}_{localChar} ON ({queryPrefix}{valTblType}_{localChar++}.val_seq_id = {queryPrefix}{cmpTblType}.val_seq_id {guardFilter})");
            }

            whereClause.Append($" WHERE ");
            if (componentTypeGuard.Count > 0)
            {
                whereClause.Append($"{queryPrefix}{cmpTblType}.typ_cd_id IN ({String.Join(",", componentTypeGuard.Select(o => $"'{o}'"))}) AND ");
            }
            whereClause.Append("(");
            // Ensure that the left joined objects exist
            for (char s = 'a'; s < localChar; s++)
            {
                whereClause.Append($" {queryPrefix}{valTblType}_{s}.val_seq_id IS NOT NULL ").Append("OR");
            }
            whereClause.RemoveLast();
            whereClause.Append($") GROUP BY {keyName} HAVING COUNT(DISTINCT {queryPrefix}{cmpTblType}.cmp_id) >= {vCount})");

            return(true);
        }
    }
Exemple #25
0
        private void MergeWithDependantList(QueryPredicate exprDep, IList<QueryPredicate> list)
        {
            bool merged = false;
            // If we should even bother trying to merge this
            bool merge_attempt = exprDep.dependant_on.Count > 1 &&
                                 exprDep.expression is FunctionExpression &&
                                 IsSimpleEquivalence(((FunctionExpression) exprDep.expression).Name);
            if (merge_attempt) {
                // Merge this expression into the list
                int sz = list.Count;
                for (int i = 0; i < sz && !merged; ++i) {
                    QueryPredicate targetExp = list[i];
                    // If the set of dependants is equal and all the terms are equi
                    // predicates, then we can simply combine the terms.
                    // We do not combine single source terms letting the planner schedule
                    // filter terms as it sees best fit.
                    if (targetExp.right_dependancy == null &&
                        exprDep.HasEqualDependants(targetExp)) {
                        Expression expr = targetExp.expression;
                        // Only merge if the expression is an equivalence function
                        if (expr is FunctionExpression &&
                            IsSimpleEquivalence(((FunctionExpression)expr).Name)) {
                            // Yes, so merge and break
                            targetExp.Merge(exprDep);
                            // Simplify
                            targetExp.expression = SimplifyTerm(targetExp.expression);

                            merged = true;
                            break;
                        }
                    }
                }
            }
            // If we didn't merge, add to list
            if (!merged) {
                list.Add(exprDep);
            }
        }
Exemple #26
0
 /// <summary>
 /// Raises a <see cref="NotImplementedException"/> as it's currently not needed.
 /// </summary>
 protected override IQueryable <TData> GeneratePredicate(QueryPredicate queryPredicate, IQueryable <TData> leftHandQueryable = null)
 {
     throw new NotImplementedException();
 }