Beispiel #1
0
	    public Query(QueryType type, long token, ReqlAst term, OptArgs globalOptions)
		{
			this.Type = type;
			this.Token = token;
			this.Term = term;
			this.GlobalOptions = globalOptions;
		}
 Task <Response> IConnection.RunUnsafeAsync(ReqlAst term, object globalOpts, CancellationToken cancelToken)
 {
     if (this.shutdownSignal.IsCancellationRequested)
     {
         throw new ReqlDriverError("HostPool is shutdown.");
     }
     return(poolingStrategy.RunUnsafeAsync(term, globalOpts, cancelToken));
 }
        void IConnection.RunNoReply(ReqlAst term, object globalOpts)
        {
            var opts = OptArgs.FromAnonType(globalOpts);

            SetDefaultDb(opts);
            opts.With("noreply", true);
            SendQueryNoReply(Query.Start(NewToken(), term, opts));
        }
Beispiel #4
0
 /// <summary>
 /// Prepares the query by setting the default DB if it doesn't exist.
 /// </summary>
 protected Query PrepareQuery(ReqlAst term, OptArgs globalOpts) {
     SetDefaultDb(globalOpts);
     Query q = Query.Start(NewToken(), term, globalOpts);
     if (globalOpts?.ContainsKey("noreply") == true) {
         throw new ReqlDriverError("Don't provide the noreply option as an optarg. Use `.RunNoReply` instead of `.Run`");
     }
     return q;
 }
 void IConnection.RunNoReply(ReqlAst term, object globalOpts)
 {
     if (this.shutdownSignal.IsCancellationRequested)
     {
         throw new ReqlDriverError("HostPool is shutdown.");
     }
     poolingStrategy.RunNoReply(term, globalOpts);
 }
Beispiel #6
0
        public override async Task <string> RunResultAsRawJson(ReqlAst term, object globalOpts, CancellationToken cancelToken)
        {
            HostEntry host = GetRoundRobin();

            try {
                return(await host.conn.RunResultAsRawJson(term, globalOpts, cancelToken).ConfigureAwait(false));
            }
            catch (Exception e) when(ExceptionIs.NetworkError(e))
            {
                host.MarkFailed();
                throw;
            }
        }
Beispiel #7
0
        public override void RunNoReply(ReqlAst term, object globalOpts)
        {
            HostEntry host = GetRoundRobin();

            try
            {
                host.conn.RunNoReply(term, globalOpts);
            }
            catch (Exception e) when(ExceptionIs.NetworkError(e))
            {
                host.MarkFailed();
                throw;
            }
        }
        protected RethinkQueryable <T> GetQueryable <T>(string table, ReqlAst expected)
        {
            var executor = new TestRethinkQueryExecutor(RethinkDB.R.Table(table), Connection, reql =>
            {
                QueriesAreTheSame(expected, reql);
            });

            return(new RethinkQueryable <T>(
                       new DefaultQueryProvider(
                           typeof(RethinkQueryable <>),
                           QueryParser.CreateDefault(),
                           executor)
                       ));
        }
        private void QueriesAreTheSame(ReqlAst expected, ReqlAst actual)
        {
            var buildMethod = typeof(ReqlAst).GetMethod("Build", BindingFlags.Instance | BindingFlags.NonPublic);

            var expectedJson = ((JArray)buildMethod.Invoke(expected, new object[0])).ToString(Formatting.None);
            var actualJson   = ((JArray)buildMethod.Invoke(actual, new object[0])).ToString(Formatting.None);

            var removeIdsRegex = new Regex(@"\[\d+\]");

            var expectedParsed = removeIdsRegex.Replace(ParseReql(expectedJson), "");
            var actualParsed   = removeIdsRegex.Replace(ParseReql(actualJson), "");

            Assert.AreEqual(expectedParsed, actualParsed);
        }
        public override void RunNoReply(ReqlAst term, object globalOpts)
        {
            HostEntry host = GetEpsilonGreedy();

            try
            {
                var start = DateTime.Now.Ticks;
                host.conn.RunNoReply(term, globalOpts);
                var end = DateTime.Now.Ticks;
                MarkSuccess(host, start, end);
            }
            catch (Exception e) when(ExceptionIs.NetworkError(e))
            {
                host.MarkFailed();
                throw;
            }
        }
        public bool IsAppropriate( ReqlAst reql, Expression expression, Type resultType )
        {
            var subQueryExpression = expression as SubQueryExpression;
            if( subQueryExpression == null )
                return false;

            var type = subQueryExpression.QueryModel.MainFromClause.FromExpression.Type;

            if( type.GetTypeInfo().IsGenericType
                && type.GetGenericTypeDefinition() == typeof( IGrouping<,> ) )
            {
                if( subQueryExpression.QueryModel.ResultOperators[0] is AnyResultOperator )
                    return true;
                throw new NotImplementedException( "This filter is not supported for GroupBy" );
            }

            return false;
        }
        public override async Task <Cursor <T> > RunCursorAsync <T>(ReqlAst term, object globalOpts, CancellationToken cancelToken)
        {
            HostEntry host = GetEpsilonGreedy();

            try
            {
                var start  = DateTime.Now.Ticks;
                var result = await host.conn.RunCursorAsync <T>(term, globalOpts, cancelToken).ConfigureAwait(false);

                var end = DateTime.Now.Ticks;
                MarkSuccess(host, start, end);
                return(result);
            }
            catch (Exception e) when(ExceptionIs.NetworkError(e))
            {
                host.MarkFailed();
                throw;
            }
        }
        public bool IsAppropriate(ReqlAst reql, Expression expression, Type resultType)
        {
            var binaryExpression = expression as BinaryExpression;

            if (!(reql is Table) || binaryExpression?.NodeType != ExpressionType.Equal)
            {
                return(false);
            }

            var left = binaryExpression.Left as MemberExpression;

            if (left != null)
            {
                return(IsIndex(left));
            }

            var right = binaryExpression.Right as MemberExpression;

            return(right != null && IsIndex(right));
        }
        public bool IsAppropriate(ReqlAst reql, Expression expression, Type resultType)
        {
            var subQueryExpression = expression as SubQueryExpression;

            if (subQueryExpression == null)
            {
                return(false);
            }

            var type = subQueryExpression.QueryModel.MainFromClause.FromExpression.Type;

            if (type.GetTypeInfo().IsGenericType &&
                type.GetGenericTypeDefinition() == typeof(IGrouping <,>))
            {
                if (subQueryExpression.QueryModel.ResultOperators[0] is AnyResultOperator)
                {
                    return(true);
                }
                throw new NotImplementedException("This filter is not supported for GroupBy");
            }

            return(false);
        }
Beispiel #15
0
		public static Query Start(long token, ReqlAst term, OptArgs globalOptions)
		{
			return new Query(QueryType.START, token, term, globalOptions);
		}
        Task <Cursor <T> > IConnection.RunCursorAsync <T>(ReqlAst term, object globalOpts, CancellationToken cancelToken)
        {
            Query q = PrepareQuery(term, OptArgs.FromAnonType(globalOpts));

            return(RunQueryCursorAsync <T>(q, cancelToken));
        }
Beispiel #17
0
 Task<Response> IConnection.RunUnsafeAsync(ReqlAst term, object globalOpts, CancellationToken cancelToken)
 {
     Query q = PrepareQuery(term, OptArgs.FromAnonType(globalOpts));
     return SendQuery(q, cancelToken, awaitResponse: true);
 }
 public abstract Task <Cursor <T> > RunCursorAsync <T>(ReqlAst term, object globalOpts, CancellationToken cancelToken);
 public abstract Task <T> RunResultAsync <T>(ReqlAst term, object globalOpts, CancellationToken cancelToken);
Beispiel #20
0
 Task<T> IConnection.RunResultAsync<T>(ReqlAst term, object globalOpts, CancellationToken cancelToken) {
     Query q = PrepareQuery(term, OptArgs.FromAnonType(globalOpts));
     return RunQueryResultAsync<T>(q, cancelToken);
 }
 public virtual ErrorBuilder SetTerm(Query query)
 {
     this.Term = query.Term;
     return(this);
 }
		public virtual ErrorBuilder SetTerm(Query query)
		{
			this.Term = query.Term;
			return this;
		}
 public abstract void RunNoReply(ReqlAst term, object globalOpts);
 public bool IsAppropriate(ReqlAst reql, Expression expression, Type resultType) => true;
 public bool IsAppropriate( ReqlAst reql, Expression expression, Type resultType ) => true;
 protected override void ProcessQuery( ReqlAst query )
 {
     validate( query );
 }
 public abstract Task <Response> RunUnsafeAsync(ReqlAst term, object globalOpts, CancellationToken cancelToken);
 public abstract Task <dynamic> RunAsync <T>(ReqlAst term, object globalOpts, CancellationToken cancelToken);
Beispiel #29
0
 protected virtual void ProcessQuery(ReqlAst query)
 {
 }
Beispiel #30
0
 protected override void ProcessQuery(ReqlAst query)
 {
     validate(query);
 }
Beispiel #31
0
    public static RethinkQueryStatus RethinkConnect(DatabaseCache cache, string connectionString, bool syncLocalChanges = true, bool filterGalaxyData = true)
    {
        // Add Unity.Mathematics serialization support to RethinkDB Driver
        //Converter.Serializer.Converters.Add(new MathJsonConverter());
        JsonConvert.DefaultSettings = () => new JsonSerializerSettings
        {
            Converters = new List <JsonConverter>
            {
                new MathJsonConverter(),
                Converter.DateTimeConverter,
                Converter.BinaryConverter,
                Converter.GroupingConverter,
                Converter.PocoExprConverter
            }
        };

        var connection = R.Connection().Hostname(connectionString).Port(RethinkDBConstants.DefaultPort).Timeout(60).Connect();

        Debug.Log("Connected to RethinkDB");

        if (syncLocalChanges)
        {
            // When entries are changed locally, push the changes to RethinkDB
            cache.OnDataUpdateLocal += async entry =>
            {
                var table  = entry.GetType().GetCustomAttribute <RethinkTableAttribute>()?.TableName ?? "Other";
                var result = await R
                             .Db("Aetheria")
                             .Table(table)
                             .Get(entry.ID)
                             .Replace(entry)
                             .RunAsync(connection);

                Debug.Log($"Uploaded entry to RethinkDB: {entry.ID} result: {result}");
            };

            cache.OnDataInsertLocal += async entry =>
            {
                var table  = entry.GetType().GetCustomAttribute <RethinkTableAttribute>()?.TableName ?? "Other";
                var result = await R
                             .Db("Aetheria")
                             .Table(table)
                             .Insert(entry)
                             .RunAsync(connection);

                Debug.Log($"Inserted entry to RethinkDB: {entry.ID} result: {result}");
            };

            cache.OnDataDeleteLocal += async entry =>
            {
                var table  = entry.GetType().GetCustomAttribute <RethinkTableAttribute>()?.TableName ?? "Other";
                var result = await R
                             .Db("Aetheria")
                             .Table(table)
                             .Get(entry.ID)
                             .Delete()
                             .RunAsync(connection);

                Debug.Log($"Deleted entry from RethinkDB: {entry.ID} result: {result}");
            };
        }

        var status = new RethinkQueryStatus();

        // Get all item data from RethinkDB
        Task.Run(async() =>
        {
            status.ItemsEntries = R
                                  .Db("Aetheria")
                                  .Table("Items")
                                  .Count().RunAtom <int>(connection);

            var result = await R
                         .Db("Aetheria")
                         .Table("Items")
                         .RunCursorAsync <DatabaseEntry>(connection);
            while (await result.MoveNextAsync())
            {
                var entry = result.Current;
                //Debug.Log($"Received Items entry from RethinkDB: {entry.GetType()} {(entry as INamedEntry)?.EntryName ?? ""}:{entry.ID}");
                cache.Add(entry, true);
                status.RetrievedItems++;
            }
        }).WrapErrors();

        // Get globaldata and all galaxy map layer data from RethinkDB
        Task.Run(async() =>
        {
            ReqlAst operation = R
                                .Db("Aetheria")
                                .Table("Galaxy");
            if (filterGalaxyData)
            {
                var filter = ((Table)operation).Filter(o =>
                                                       o["$type"] == typeof(GalaxyMapLayerData).Name ||
                                                       o["$type"] == typeof(GlobalData).Name ||
                                                       o["$type"] == typeof(MegaCorporation).Name);
                status.GalaxyEntries = filter.Count().RunAtom <int>(connection);
                operation            = filter;
            }
            else
            {
                status.GalaxyEntries = ((Table)operation).Count().RunAtom <int>(connection);
            }

            var result = await operation
                         .RunCursorAsync <DatabaseEntry>(connection);
            while (await result.MoveNextAsync())
            {
                var entry = result.Current;
                //Debug.Log($"Received Galaxy entry from RethinkDB: {entry.GetType()} {(entry as INamedEntry)?.EntryName ?? ""}:{entry.ID}");
                cache.Add(entry, true);
                status.RetrievedItems++;
            }
        }).WrapErrors();

        // Subscribe to changes from RethinkDB
        Task.Run(async() =>
        {
            var result = await R
                         .Db("Aetheria")
                         .Table("Items")
                         .Changes()
                         .RunChangesAsync <DatabaseEntry>(connection);
            while (await result.MoveNextAsync())
            {
                var change = result.Current;
                if (change.OldValue == null)
                {
                    Debug.Log($"Received change from RethinkDB (Entry Created): {change.NewValue.ID}");
                }
                else if (change.NewValue == null)
                {
                    Debug.Log($"Received change from RethinkDB (Entry Deleted): {change.OldValue.ID}");
                }
                else
                {
                    Debug.Log($"Received change from RethinkDB: {change.NewValue.ID}");
                }
                cache.Add(change.NewValue, true);
            }
        }).WrapErrors();

        Observable.Timer(DateTimeOffset.Now, TimeSpan.FromSeconds(60)).Subscribe(_ =>
        {
            Debug.Log(R.Now().Run <DateTime>(connection).ToString() as string);
        });

        return(status);
    }