Пример #1
0
 public static CypherExtensionContext Create(ICypherFluentQuery query)
 {
     return(new CypherExtensionContext
     {
         JsonContractResolver = query.Query.JsonContractResolver
     });
 }
Пример #2
0
        protected DataResult <T> Read(ICypherFluentQuery <T> query)
        {
            if (HasCustomReader)
            {
                return(Read(query, Map));
            }

            try
            {
                var result = query.ResultsAsync.Result;

                var value    = result.SingleOrDefault();
                var rowCount = value == null ? 0 : 1;

                return(CreateDataResult(query.Query.QueryText, rowCount,
                                        value, DataResultType.Success, Success, Success));
            }
            catch (DbException exception)
            {
                return(CreateDataResult(query.Query.QueryText, 0, default(T), DataResultType.UnknownError,
                                        FriendlyReadMessage, InternalReadMessage, null, exception));
            }
            catch (InvalidOperationException exception)
            {
                return(CreateDataResult(query.Query.QueryText, 0, default(T), DataResultType.UnknownError,
                                        "We got a few more results than expected just then, and Curio doesn't know how to deal with the extra ones. We've woken up the developers and they'll get it working ASAP.",
                                        "An operation was performed that usually only returns a single record, but multiple records were returned.", null, exception));
            }
        }
Пример #3
0
        public static ICypherFluentQuery AppendWhereClause <TSearchHeadEnum>(
            ICypherFluentQuery q
            , List <SearchPredicate <TSearchHeadEnum> > predicates
            , Func <SearchTerm <TSearchHeadEnum>, string> termToWhereText
            , bool whereAdded = false)
            where TSearchHeadEnum : struct, IConvertible
        {
            var firstWhereAdded = whereAdded;

            foreach (var predicate in predicates)
            {
                var whereText = PredicateToWhereText(predicate, termToWhereText);

                if (!firstWhereAdded)
                {
                    q = q.Where(whereText);
                    firstWhereAdded = true;
                }
                else
                {
                    q = q.AndWhere(whereText);
                }
            }

            return(q);
        }
Пример #4
0
        private static ICypherFluentQuery CommonCreate <T>(
            this ICypherFluentQuery query
            , T entity
            , CreateOptions options
            , Func <string, string> getFinalCql) where T : class
        {
            if (options == null)
            {
                options = new CreateOptions();
            }

            var createProperties      = GetCreateProperties(entity);
            var identifier            = entity.EntityParamKey(options.Identifier);
            var intermediateCreateCql = GetMatchWithParam(identifier, entity.EntityLabel(), createProperties.Count > 0 ? identifier : "");

            var createCql = getFinalCql(intermediateCreateCql);

            var dynamicOptions = new CreateDynamicOptions {
                IgnoreNulls = true
            };                                                                    // working around some buug where null properties are blowing up. don't care on create.
            var cutdownEntity = entity.CreateDynamic(createProperties, dynamicOptions);

            query = query.Create(createCql);

            if (createProperties.Count > 0)
            {
                query = query.WithParam(identifier, cutdownEntity);
            }

            return(query);
        }
        protected ICypherFluentQuery AddRoles(ICypherFluentQuery query, IList <IdentityRole> roles, string userId)
        {
            if (roles == null || roles.Count == 0)
            {
                return(query);
            }

            for (var i = 0; i < roles.Count; i++)
            {
                var roleVar     = $"r{i}";
                var userRoleVar = $"ur{i}";
                query = query
                        .With("u")
                        .Match(p => p.Pattern <IdentityRole>(roleVar)
                               .Constrain(r => r.NormalizedName == roles[i].NormalizedName))
                        .Merge(p => p.Pattern <TUser, IdentityUser_Role, IdentityRole>("u", userRoleVar, roleVar)
                               .Constrain(null,
                                          ur => ur.RoleId == CypherVariables.Get <IdentityRole>(roleVar).Id&& ur.UserId == userId,
                                          null))
                        .OnCreate()
                        .Set <IdentityUser_Role>(ur => ur.CreatedOn == new Occurrence(), userRoleVar);
            }

            return(query);
        }
Пример #6
0
        protected AnnotatedQuery(ICypherFluentQuery query, AnnotatedQuery previous) : base(query)
        {
            if (VbCompareReplacerType == null)
            {
                var neo4jClientAssembly = typeof(ICypherFluentQuery).GetTypeInfo().Assembly;
                VbCompareReplacerType = neo4jClientAssembly.GetType("Neo4jClient.Cypher.VbCompareReplacer");
            }

            if (previous == null)
            {
                QueryContext = CypherUtilities.GetQueryContext(query);

                CamelCaseProperties = (bool)query.GetType().GetField("CamelCaseProperties",
                                                                     BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public).GetValue(query);
                FunctionVisitor = new FunctionExpressionVisitor(QueryContext);
            }
            else
            {
                QueryContext = previous.QueryContext;
                QueryContext.CurrentQueryWriter   = QueryWriterGetter(query);
                QueryContext.CurrentBuildStrategy = QueryContext.BuildStrategyGetter(query);

                CamelCaseProperties = previous.CamelCaseProperties;
                var funcsVisitor = previous.FunctionVisitor;
                funcsVisitor.QueryContext = QueryContext;
                FunctionVisitor           = funcsVisitor;
            }

            var context = QueryContext?.AnnotationsContext ?? previous?.AnnotationsContext;

            if (context != null)
            {
                AnnotationsContext = context;
            }
        }
Пример #7
0
        internal static ICypherFluentQuery <TResult> SharedProjectionQuery <TResult>
            (this ICypherFluentQuery query, LambdaExpression expression, string clause,
            bool isOutputQuery,
            bool applyResultMode = true, bool applyResultFormat = true)
        {
            var queryContext = CypherUtilities.GetQueryContext(query);

            queryContext.CurrentBuildStrategy = queryContext.CurrentBuildStrategy ?? PropertiesBuildStrategy.WithParams;
            var funcVisitor = new FunctionExpressionVisitor(queryContext);
            var result      = ExpressionUtilities.BuildProjectionQueryExpression
                                  (expression, queryContext, funcVisitor, isOutputQuery, out var mode, out var format);

            return(Mutate <TResult>(query, w =>
            {
                if (applyResultMode)
                {
                    w.ResultMode = mode;
                }

                if (applyResultFormat)
                {
                    w.ResultFormat = format;
                }

                w.AppendClause(clause + " " + result);
            }));
        }
 public static CypherExtensionContext Create(ICypherFluentQuery query)
 {
     return new CypherExtensionContext
     {
         JsonContractResolver = query.Query.JsonContractResolver
     };
 }
Пример #9
0
        private RelationshipCheckResponse Check(ICypherFluentQuery q, IRelationshipCheckRequest request)
        {
            q = q.With("ID(e) as nodeId, count(rel) as relationshipCount");

            switch (request.ThresholdType)
            {
                case RelationshipThresholdType.ReturnIfGreaterThan:
                    q = q.Where($"relationshipCount > {request.Threshold}");
                    break;

                case RelationshipThresholdType.ReturnIfNotExact:
                    q = q.Where($"relationshipCount <> {request.Threshold}");
                    break;
                case RelationshipThresholdType.ReturnIfEqual:
                    q = q.Where($"relationshipCount = {request.Threshold}");
                    break;

                default:
                    throw new Exception("<INSERT PR HERE>");
            }

            var responses = q.Return((nodeId, relationshipCount) =>
            new Violation
            {
                NodeId = nodeId.As<long>()
            });

            var response = new RelationshipCheckResponse();
            response.Request = request;
            response.Violations.AddRange(responses.Results.ToList());
            return response;
        }
Пример #10
0
        public static ICypherFluentQuery MatchQuerry(this ICypherFluentQuery cypher, string varialbeName, BaseNode node)
        {
            if (node is Person)
            {
                return(cypher.MatchQuerry(varialbeName, (Person)node));
            }
            if (node is Commit)
            {
                return(cypher.MatchQuerry(varialbeName, (Commit)node));
            }
            if (node is File)
            {
                return(cypher.MatchQuerry(varialbeName, (File)node));
            }
            if (node is AstElement)
            {
                return(cypher.MatchQuerry(varialbeName, (AstElement)node));
            }

            if (node is AstElementDeleted)
            {
                return(cypher.MatchQuerry(varialbeName, (AstElementDeleted)node));
            }

            string matchClause = "(" + varialbeName + ":" + node.GetType().Name + ")";

            if (node.Id > 0)
            {
                return(cypher.Match(matchClause).Where(varialbeName + ".Id=" + node.Id));
            }

            throw new NotImplementedException("Needs a specialices MatchQuery for " + node.GetType().Name);
        }
Пример #11
0
 public static ICypherFluentQuery MatchRelationship <T>(
     this ICypherFluentQuery query
     , T relationship
     , MatchRelationshipOptions options) where T : BaseRelationship
 {
     return(MatchRelationshipWorker(query, relationship, options, (fluentQuery, s) => fluentQuery.Match(s)));
 }
Пример #12
0
        public static string GetFormattedDebugText(this ICypherFluentQuery query)
        {
            // write once, read never!
            var regex = new Regex("\\\"([^(\\\")\"]+)\\\":", RegexOptions.Multiline);

            return(regex.Replace(query.Query.DebugQueryText, "$1:"));
        }
Пример #13
0
        public async Task <IEnumerable <GroupDTO> > GetGroupsPage(string filters, string userFilter, string orderBy, bool descending, int from, int to)
        {
            var a = _client.Cypher
                    .Match("(g:Group), (s:Student), (ow)-[:OWNER]-(g)")
                    .Where(userFilter);

            if (!string.IsNullOrEmpty(filters))
            {
                a = a.AndWhere(filters);
            }

            a = a.With("g, {Id: ID(ow), Student: ow} as st");

            ICypherFluentQuery <GroupDTO> ret = a.Return((g, st) => new GroupDTO
            {
                Id      = Return.As <int>("ID(g)"),
                Group   = Return.As <Group>("g"),
                Student = st.As <StudentDTO>()
            });

            if (descending)
            {
                ret = ret.OrderByDescending(orderBy);
            }
            else
            {
                ret = ret.OrderBy(orderBy);
            }

            return(await ret.Skip(from).Limit(to).ResultsAsync);
        }
Пример #14
0
        public static ICypherFluentQuery MatchRelationship <T>(this ICypherFluentQuery query, T relationship, List <CypherProperty> matchOverride = null) where T : BaseRelationship
        {
            var options = new MatchRelationshipOptions();

            options.MatchOverride = matchOverride;
            return(MatchRelationship(query, relationship, options));
        }
Пример #15
0
        public static ICypherFluentQuery MatchQuerry(this ICypherFluentQuery cypher, string varialbeName, Commit node)
        {
            string matchClause = "(" + varialbeName + ":" + node.GetType().Name + ")";
            string whereClause = varialbeName + "." + nameof(node.Sha) + "=\"" + node.Sha + "\"";

            return(cypher.Match(matchClause).Where(whereClause));
        }
 internal static ICypherFluentQuery MergeKey(this ICypherFluentQuery q, IKey key, string valueLabel)
 {
     if (key is ActorKey)
     {
         return(q
                .Merge($"({valueLabel}:Actor:CanJoin {{ key: {{{valueLabel}Key}}, name: {{{valueLabel}Name}} }})")
                .WithParam($"{valueLabel}Key", key.Key)
                .WithParam($"{valueLabel}Name", key.Name));
     }
     if (key is ThingKey)
     {
         return(q
                .Merge($"({valueLabel}:Thing:CanBeGranted {{ key: {{{valueLabel}Key}}, name: {{{valueLabel}Name}} }})")
                .WithParam($"{valueLabel}Key", key.Key)
                .WithParam($"{valueLabel}Name", key.Name));
     }
     if (key is NodeKey)
     {
         return(q
                .Merge($"({valueLabel}:Node:CanBeJoined:CanJoin {{ key: {{{valueLabel}Key}}, name: {{{valueLabel}Name}} }})")
                .WithParam($"{valueLabel}Key", key.Key)
                .WithParam($"{valueLabel}Name", key.Name));
     }
     else
     {
         throw new NotImplementedException();
     }
 }
Пример #17
0
        public ICypherFluentQuery Create(ICypherFluentQuery fluentQuery, bool merge = false)
        
        {

            fluentQuery.Create(NodeWithAlias());//.ExecuteWithoutResults();
            return fluentQuery;
        }
 public PathBuilder(ICypherFluentQuery query, IPathExtent path,
                    string pathVariable, AnnotationsContext context)
     : this(query, context)
 {
     Path         = path;
     PathVariable = pathVariable;
 }
Пример #19
0
 public TransportationRepository(IGraphClientBuilder graphClientBuilder, ILoggingService loggingService)
 {
     _graphClientFunc   = graphClientBuilder.GetGraphClient();
     _cypherFluentQuery = new CypherFluentQuery(_graphClientFunc);
     _repositoryPolicy  = Policy.Handle <Exception>().WaitAndRetryAsync(5, retryAttempt =>
                                                                        TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)),
                                                                        (exception, span) => { loggingService.LogMessage(exception.ToString()); });
 }
Пример #20
0
        public static ICypherFluentQuery CreateRelationship <T>(this ICypherFluentQuery query, T entity, CreateOptions options = null) where T : BaseRelationship
        {
            Func <string, string> getFinalCql = intermediateCql => GetRelationshipCql(entity.FromKey, intermediateCql, entity.ToKey);

            query = CommonCreate(query, entity, options, getFinalCql);

            return(query);
        }
 public PathBuilder(ICypherFluentQuery query,
                    Expression <Func <IPathBuilder, IPathExtent> > expression,
                    AnnotationsContext context = null)
     : this(query, context)
 {
     Path         = expression?.Compile().Invoke(this);
     PathVariable = expression?.Parameters[0].Name;
 }
Пример #22
0
        public static ICypherFluentQuery CreateEntity <T>(this ICypherFluentQuery query, T entity, CreateOptions options) where T : class
        {
            Func <string, string> getFinalCql = intermediateCql => WithPrePostWrap(intermediateCql, options);

            query = CommonCreate(query, entity, options, getFinalCql);

            return(query);
        }
 public static CypherExtensionContext Create(ICypherFluentQuery query)
 {
     return new CypherExtensionContext()
     {
         //TODO: Once other pull request is in for camel casing, pass whatever is set
         //JsonContractResolver = query.Query.JsonContractResolver
     };
 }
Пример #24
0
 public static ICypherFluentQuery OptionalMatchEntity <T>(this ICypherFluentQuery query, T entity, MatchOptions options = null)
     where T : class
 {
     if (options == null)
     {
         options = new MatchOptions();
     }
     return(MatchWorker(query, entity, options, (q, s) => q.OptionalMatch(s)));
 }
Пример #25
0
        public static ICypherFluentQuery MergeEntity <T>(this ICypherFluentQuery query, T entity, string paramKey = null, List <CypherProperty> mergeOverride = null, List <CypherProperty> onMatchOverride = null, List <CypherProperty> onCreateOverride = null, string preCql = "", string postCql = "") where T : class
        {
            paramKey = entity.EntityParamKey(paramKey);
            var context = CypherExtensionContext.Create(query);
            var cypher1 = entity.ToCypherString <T, CypherMergeAttribute>(context, paramKey, mergeOverride);
            var cql     = string.Format("{0}({1}){2}", preCql, cypher1, postCql);

            return(query.CommonMerge(entity, paramKey, cql, mergeOverride, onMatchOverride, onCreateOverride));
        }
Пример #26
0
        private ICypherFluentQuery AddLockout(ICypherFluentQuery query, LockoutInfo lockoutInfo)
        {
            if (lockoutInfo == null)
                return query;

            query = query.With("u")
                .Create($"(u)-[:{Relationship.IsLockedOut}]->(:{LockoutInfo.Label} {{lockoutParam}})")
                .WithParam("lockoutParam", lockoutInfo);
            return query;
        }
Пример #27
0
        public new ICypherFluentQuery Create(ICypherFluentQuery fluentQuery, bool merge = false)
        {



            return base.Create(fluentQuery, merge);



        }
Пример #28
0
        /// <summary>
        ///     Erstellt eine neue Gipfelgruppe in einer Gegend
        /// </summary>
        /// <param name="area"></param>
        /// <param name="summitGroup"></param>
        public SummitGroup Create(Area area, SummitGroup summitGroup)
        {
            ICypherFluentQuery query = GraphClient.Cypher
                                       .Match("".Area("a"))
                                       .Where((Area a) => a.Id == area.Id)
                                       .Create("a".Has().SummitGroupWithParam())
                                       .WithParam("summitGroup", summitGroup);

            return(query.Return(sg => sg.As <SummitGroup>()).Results.First());
        }
Пример #29
0
        public static ICypherFluentQuery MergeRelationship <T>(this ICypherFluentQuery query, T entity, List <CypherProperty> mergeOverride = null, List <CypherProperty> onMatchOverride = null, List <CypherProperty> onCreateOverride = null) where T : BaseRelationship
        {
            //Eaxctly the same as a merge entity except the cql is different
            var cql = GetRelationshipCql(
                entity.FromKey
                , entity.ToCypherString <T, CypherMergeAttribute>(CypherExtensionContext.Create(query), entity.Key, mergeOverride)
                , entity.ToKey);

            return(query.CommonMerge(entity, entity.Key, cql, mergeOverride, onMatchOverride, onCreateOverride));
        }
Пример #30
0
        /// <summary>
        /// Matches the source and target nodes of the <paramref name="TVector"/>.
        /// </summary>
        /// <typeparam name="TVector"></typeparam>
        /// <param name="query"></param>
        /// <param name="from"></param>
        /// <param name="to"></param>
        /// <param name="sourceGuid"></param>
        /// <param name="targetGuid"></param>
        /// <returns></returns>
        public static ICypherFluentQuery Match <TVector>(this ICypherFluentQuery query, string from, string to, Guid sourceGuid, Guid targetGuid) where TVector : Vector
        {
            var vectorType = Common.Unpack <TVector>();

            query = query.Match(
                "(" + from + ":" + Common.NodeLabel(vectorType.Source) + " { Guid: {sourceGuid} })",
                "(" + to + ":" + Common.NodeLabel(vectorType.Target) + " { Guid: {targetGuid} })")
                    .WithParams(new { sourceGuid, targetGuid });
            return(query);
        }
Пример #31
0
        /// <summary>
        ///     Erstellt einen neuen Logeintrag einer Variation
        /// </summary>
        public LogEntry Create(Variation variation, LogEntry logEntry)
        {
            ICypherFluentQuery query = GraphClient.Cypher
                                       .Match("".Variation("v"))
                                       .Where((Variation v) => v.Id == variation.Id)
                                       .Create("".Node("v").Has().LogEntryWithParam())
                                       .WithParam("logEntry", logEntry);

            return(query.Return(le => le.As <LogEntry>()).Results.First());
        }
Пример #32
0
        /// <summary>
        ///     Erstellt einen neuen Schwierigkeitsgrad in einer Skala
        /// </summary>
        public DifficultyLevel Create(DifficultyLevelScale difficultyLevelScale, DifficultyLevel difficultyLevel)
        {
            ICypherFluentQuery query = GraphClient.Cypher
                                       .Match("".DifficultyLevelScale("dls"))
                                       .Where((DifficultyLevelScale dls) => dls.Id == difficultyLevelScale.Id)
                                       .Create("dls".Has().DifficultyLevelWithParam())
                                       .WithParam("difficultyLevel", difficultyLevel);

            return(query.Return(dl => dl.As <DifficultyLevel>()).Results.First());
        }
Пример #33
0
        public static ICypherFluentQuery Where(this ICypherFluentQuery query, string matchText, bool onlyLive = false)
        {
            if (!onlyLive)
            {
                return(query.Where(matchText));
            }

            return(query
                   .Where(matchText)
                   .AndWhere(string.Format("p.title in [{0}]", string.Join(", ", PathwaysConfigurationManager.GetLivePathwaysElements().Select(p => string.Format("'{0}'", p.Title))))));
        }
Пример #34
0
 public static ICypherFluentQuery OptionalMatchRelationship <T>(
     this ICypherFluentQuery query
     , T relationship
     , MatchRelationshipOptions options = null) where T : BaseRelationship
 {
     if (options == null)
     {
         options = new MatchRelationshipOptions();
     }
     return(MatchRelationshipWorker(query, relationship, options, (fluentQuery, s) => fluentQuery.OptionalMatch(s)));
 }
Пример #35
0
        public static ICypherFluentQuery CreateEntity <T>(this ICypherFluentQuery query, T entity, string identifier = null, List <CypherProperty> onCreateOverride = null, string preCql = "", string postCql = "") where T : class
        {
            var options = new CreateOptions();

            options.PostCql        = postCql;
            options.PreCql         = preCql;
            options.Identifier     = identifier;
            options.CreateOverride = onCreateOverride;

            return(CreateEntity(query, entity, options));
        }
        public void Execute(ICypherFluentQuery cypher)
        {

            ProcessStacks();

            foreach (var query in _queryStack)
            {

                if (query.QueryType == QueryTypeEnum.Match)
                {
                    cypher = cypher.Match(query.QueryString);
                    continue;
                }
                if (query.QueryType == QueryTypeEnum.OptionalMatch)
                {
                    cypher = cypher.OptionalMatch(query.QueryString);
                    continue;
                }

                if (query.QueryType == QueryTypeEnum.Where)
                {
                    cypher = cypher.Where(query.QueryString);
                    continue;
                }

                if (query.QueryType == QueryTypeEnum.Create)
                {
                    cypher = cypher.Create(query.QueryString);
                    continue;
                }

                if (query.QueryType == QueryTypeEnum.Merge)
                {
                    cypher = cypher.Merge(query.QueryString);
                    continue;
                }

                if (query.QueryType == QueryTypeEnum.Delete)
                {
                    cypher = cypher.Delete(query.QueryString);
                    continue;
                }

                if (query.QueryType == QueryTypeEnum.With)
                {
                    cypher = cypher.With(query.QueryString);
                    continue;
                }

            }

            cypher.ExecuteWithoutResults();
        }