private DbCommandTree MakeCommandTree() { DbCommandTree dbCommandTree = (DbCommandTree)null; if (this._commandTreeSetByUser != null) { dbCommandTree = this._commandTreeSetByUser; } else if (CommandType.Text == this.CommandType) { if (!string.IsNullOrEmpty(this._esqlCommandText)) { dbCommandTree = CqlQuery.Compile(this._esqlCommandText, (Perspective) new ModelPerspective(this._connection.GetMetadataWorkspace()), (ParserOptions)null, this.GetParameterTypeUsage().Select <KeyValuePair <string, TypeUsage>, DbParameterReferenceExpression>((Func <KeyValuePair <string, TypeUsage>, DbParameterReferenceExpression>)(paramInfo => paramInfo.Value.Parameter(paramInfo.Key)))).CommandTree; } else { if (this._isCommandDefinitionBased) { throw new InvalidOperationException(Strings.EntityClient_CannotReprepareCommandDefinitionBasedCommand); } throw new InvalidOperationException(Strings.EntityClient_NoCommandText); } } else if (CommandType.StoredProcedure == this.CommandType) { dbCommandTree = (DbCommandTree) new DbFunctionCommandTree(this.Connection.GetMetadataWorkspace(), DataSpace.CSpace, this.DetermineFunctionImport(), (TypeUsage)null, (IEnumerable <KeyValuePair <string, TypeUsage> >) this.GetParameterTypeUsage()); } return(dbCommandTree); }
internal static DbExpression CompileFunctionView( string viewDef, StorageMappingItemCollection mappingItemCollection, ParserOptions.CompilationMode compilationMode, IEnumerable <DbParameterReferenceExpression> parameters) { DebugCheck.NotEmpty(viewDef); DebugCheck.NotNull(mappingItemCollection); Perspective perspective = new TargetPerspective(mappingItemCollection.Workspace); var parserOptions = new ParserOptions(); parserOptions.ParserCompilationMode = compilationMode; // Parameters have to be accessible in the body as regular scope variables, not as command parameters. // Hence compile view as lambda with parameters as lambda vars, then invoke the lambda specifying // command parameters as values of the lambda vars. var functionBody = CqlQuery.CompileQueryCommandLambda( viewDef, perspective, parserOptions, null /* parameters */, parameters.Select(pInfo => pInfo.ResultType.Variable(pInfo.ParameterName))); Debug.Assert(functionBody != null, "functionBody != null"); DbExpression expr = functionBody.Invoke(parameters); return(expr); }
/// <summary> /// Compiles eSQL <paramref name="functionDefinition" /> and returns <see cref="DbLambda" />. /// Guarantees type match of lambda variables and <paramref name="functionParameters" />. /// Passes thru all excepions coming from <see cref="CqlQuery" />. /// </summary> internal static DbLambda CompileFunctionDefinition( string functionDefinition, IList <FunctionParameter> functionParameters, EdmItemCollection edmItemCollection) { DebugCheck.NotNull(functionParameters); DebugCheck.NotNull(edmItemCollection); var workspace = new MetadataWorkspace(); workspace.RegisterItemCollection(edmItemCollection); Perspective perspective = new ModelPerspective(workspace); // Since we compile lambda expression and generate variables from the function parameter definitions, // the returned DbLambda will contain variable types that match function parameter types. var functionBody = CqlQuery.CompileQueryCommandLambda( functionDefinition, perspective, null /* use default parser options */, null /* parameters */, functionParameters.Select(pInfo => pInfo.TypeUsage.Variable(pInfo.Name))); Debug.Assert(functionBody != null, "functionBody != null"); return(functionBody); }
private void TryDiscover() { try { // system.local contains release_version which current usage. // system.peers contains old versions, we only need current release version. IConnection connection = _cluster.GetConnection(); var obsLocalPeer = new CqlQuery <DiscoveredPeer>(connection, ConsistencyLevel.ONE, ExecutionFlags.None, "select data_center,rack,tokens,release_version from system.local", _peerFactory); obsLocalPeer.Subscribe(x => { Notify(connection.Endpoint, x.Datacenter, x.Rack, x.Tokens, x.release_version, x.release_version); var obsPeers = new CqlQuery <DiscoveredPeer>(connection, ConsistencyLevel.ONE, ExecutionFlags.None, "select rpc_address,data_center,rack,tokens,release_version from system.peers", _peerFactory); obsPeers.Subscribe(p => Notify(p.RpcAddress, p.Datacenter, p.Rack, p.Tokens, p.release_version, x.release_version), ex => _logger.Error("SystemPeersDiscoveryService failed with error {0}", ex)); }, ex => _logger.Error("SystemPeersDiscoveryService failed with error {0}", ex)); } catch (Exception ex) { _logger.Error("SystemPeersDiscoveryService failed with error {0}", ex); } }
private static CqlQuery <T> AddSort <T>(CqlQuery <T> query, Sort sort) { var propertyType = typeof(T).GetProperty(sort.Path).PropertyType; return(GenericMethod.Invoke(() => AddSort <T, object>(query, sort), new[] { typeof(T), typeof(object) }, new[] { typeof(T), propertyType })); }
private static CqlQuery <T> BuildReadQuery <T>(CqlQuery <T> query, Condition[] filters) { if (!filters.Any() || filters.Any(x => x.Operator != ObjectFieldFilterOperator.Equals)) { throw new InvalidOperationException("Invalid filters for read query"); } return(BuildQuery(query, filters)); }
/// <summary> /// Ensures we have the command tree, either the user passed us the tree, or an eSQL statement that we need to parse /// </summary> private void MakeCommandTree() { // We must have a connection before we come here Debug.Assert(this._connection != null); // Do the work only if we don't have a command tree yet if (this._preparedCommandTree == null) { DbCommandTree resultTree = null; if (this._commandTreeSetByUser != null) { resultTree = this._commandTreeSetByUser; } else if (CommandType.Text == CommandType) { if (!string.IsNullOrEmpty(this._esqlCommandText)) { // The perspective to be used for the query compilation Perspective perspective = (Perspective) new ModelPerspective(_connection.GetMetadataWorkspace()); // get a dictionary of names and typeusage from entity parameter collection Dictionary <string, TypeUsage> queryParams = GetParameterTypeUsage(); resultTree = CqlQuery.Compile( this._esqlCommandText, perspective, null /*parser option - use default*/, queryParams.Select(paramInfo => paramInfo.Value.Parameter(paramInfo.Key))).CommandTree; } else { // We have no command text, no command tree, so throw an exception if (this._isCommandDefinitionBased) { // This command was based on a prepared command definition and has no command text, // so reprepare is not possible. To create a new command with different parameters // requires creating a new entity command definition and calling it's CreateCommand method. throw EntityUtil.InvalidOperation(System.Data.Entity.Strings.EntityClient_CannotReprepareCommandDefinitionBasedCommand); } else { throw EntityUtil.InvalidOperation(System.Data.Entity.Strings.EntityClient_NoCommandText); } } } else if (CommandType.StoredProcedure == CommandType) { // get a dictionary of names and typeusage from entity parameter collection IEnumerable <KeyValuePair <string, TypeUsage> > queryParams = GetParameterTypeUsage(); EdmFunction function = DetermineFunctionImport(); resultTree = new DbFunctionCommandTree(this.Connection.GetMetadataWorkspace(), DataSpace.CSpace, function, null, queryParams); } // After everything is good and succeeded, assign the result to our field this._preparedCommandTree = resultTree; } }
internal static DbLambda CompileFunctionDefinition( string functionDefinition, IList <FunctionParameter> functionParameters, EdmItemCollection edmItemCollection) { ModelPerspective modelPerspective = new ModelPerspective(new MetadataWorkspace((Func <EdmItemCollection>)(() => edmItemCollection), (Func <StoreItemCollection>)(() => (StoreItemCollection)null), (Func <StorageMappingItemCollection>)(() => (StorageMappingItemCollection)null))); return(CqlQuery.CompileQueryCommandLambda(functionDefinition, (Perspective)modelPerspective, (ParserOptions)null, (IEnumerable <DbParameterReferenceExpression>)null, functionParameters.Select <FunctionParameter, DbVariableReferenceExpression>((Func <FunctionParameter, DbVariableReferenceExpression>)(pInfo => pInfo.TypeUsage.Variable(pInfo.Name))))); }
public void LinqWhere_AppendMultipleTimes() { int userId = 1; int date = 2; long time = 3; MappingConfiguration config = new MappingConfiguration(); config.MapperFactory.PocoDataFactory.AddDefinitionDefault(typeof(TestTable), () => LinqAttributeBasedTypeDefinition.DetermineAttributes(typeof(TestTable))); Table <TestTable> table = new Table <TestTable>(_session, config); table.CreateIfNotExists(); table.Insert(new TestTable { UserId = 1, Date = 2, TimeColumn = 1 }).Execute(); table.Insert(new TestTable { UserId = 1, Date = 2, TimeColumn = 2 }).Execute(); table.Insert(new TestTable { UserId = 1, Date = 2, TimeColumn = 3 }).Execute(); table.Insert(new TestTable { UserId = 1, Date = 2, TimeColumn = 4 }).Execute(); table.Insert(new TestTable { UserId = 1, Date = 2, TimeColumn = 5 }).Execute(); CqlQuery <TestTable> query1Actual = table.Where(i => i.UserId == userId && i.Date == date); CqlQuery <TestTable> query2Actual = query1Actual.Where(i => i.TimeColumn >= time); query2Actual = query2Actual.OrderBy(i => i.TimeColumn); // ascending CqlQuery <TestTable> query3Actual = query1Actual.Where(i => i.TimeColumn <= time); query3Actual = query3Actual.OrderByDescending(i => i.TimeColumn); string query1Expected = "SELECT \"user\", \"date\", \"time\" FROM \"test1\" WHERE \"user\" = ? AND \"date\" = ? ALLOW FILTERING"; string query2Expected = "SELECT \"user\", \"date\", \"time\" FROM \"test1\" WHERE \"user\" = ? AND \"date\" = ? AND \"time\" >= ? ORDER BY \"time\" ALLOW FILTERING"; string query3Expected = "SELECT \"user\", \"date\", \"time\" FROM \"test1\" WHERE \"user\" = ? AND \"date\" = ? AND \"time\" <= ? ORDER BY \"time\" DESC ALLOW FILTERING"; Assert.AreEqual(query1Expected, query1Actual.ToString()); Assert.AreEqual(query2Expected, query2Actual.ToString()); Assert.AreEqual(query3Expected, query3Actual.ToString()); List <TestTable> result2Actual = query2Actual.Execute().ToList(); List <TestTable> result3Actual = query3Actual.Execute().ToList(); Assert.AreEqual(3, result2Actual.First().TimeColumn); Assert.AreEqual(5, result2Actual.Last().TimeColumn); Assert.AreEqual(3, result3Actual.First().TimeColumn); Assert.AreEqual(1, result3Actual.Last().TimeColumn); }
public static CqlQuery <T> BuildQuery <T>(CqlQuery <T> query, Condition[] filters, Sort[] sorts) { query = BuildQuery(query, filters); foreach (var sort in sorts) { query = AddSort(query, sort); } return(query); }
public IEnumerable <T> ExecuteQuery <T>(CqlQuery <T> query) { if (query != null) { return(query.Execute()); } else { return(null); } }
internal static DbCommandTree CompileView( string viewDef, StorageMappingItemCollection mappingItemCollection, ParserOptions.CompilationMode compilationMode) { Perspective perspective = (Perspective) new TargetPerspective(mappingItemCollection.Workspace); return(CqlQuery.Compile(viewDef, perspective, new ParserOptions() { ParserCompilationMode = compilationMode }, (IEnumerable <DbParameterReferenceExpression>)null).CommandTree); }
// <summary> // Ensures we have the command tree, either the user passed us the tree, or an eSQL statement that we need to parse // </summary> private DbCommandTree MakeCommandTree() { // We must have a connection before we come here Debug.Assert(_connection != null); DbCommandTree resultTree = null; if (_commandTreeSetByUser != null) { resultTree = _commandTreeSetByUser; } else if (CommandType.Text == CommandType) { if (!string.IsNullOrEmpty(_esqlCommandText)) { // The perspective to be used for the query compilation Perspective perspective = new ModelPerspective(_connection.GetMetadataWorkspace()); // get a dictionary of names and typeusage from entity parameter collection var queryParams = GetParameterTypeUsage(); resultTree = CqlQuery.Compile( _esqlCommandText, perspective, null /*parser option - use default*/, queryParams.Select(paramInfo => paramInfo.Value.Parameter(paramInfo.Key))).CommandTree; } else { // We have no command text, no command tree, so throw an exception if (_isCommandDefinitionBased) { // This command was based on a prepared command definition and has no command text, // so reprepare is not possible. To create a new command with different parameters // requires creating a new entity command definition and calling it's CreateCommand method. throw new InvalidOperationException(Strings.EntityClient_CannotReprepareCommandDefinitionBasedCommand); } else { throw new InvalidOperationException(Strings.EntityClient_NoCommandText); } } } else if (CommandType.StoredProcedure == CommandType) { // get a dictionary of names and typeusage from entity parameter collection IEnumerable <KeyValuePair <string, TypeUsage> > queryParams = GetParameterTypeUsage(); var function = DetermineFunctionImport(); resultTree = new DbFunctionCommandTree(Connection.GetMetadataWorkspace(), DataSpace.CSpace, function, null, queryParams); } return(resultTree); }
internal static DbExpression CompileFunctionView( string viewDef, StorageMappingItemCollection mappingItemCollection, ParserOptions.CompilationMode compilationMode, IEnumerable <DbParameterReferenceExpression> parameters) { Perspective perspective = (Perspective) new TargetPerspective(mappingItemCollection.Workspace); return((DbExpression)CqlQuery.CompileQueryCommandLambda(viewDef, perspective, new ParserOptions() { ParserCompilationMode = compilationMode }, (IEnumerable <DbParameterReferenceExpression>)null, parameters.Select <DbParameterReferenceExpression, DbVariableReferenceExpression>((Func <DbParameterReferenceExpression, DbVariableReferenceExpression>)(pInfo => pInfo.ResultType.Variable(pInfo.ParameterName)))).Invoke((IEnumerable <DbExpression>)parameters)); }
//https://datastax-oss.atlassian.net/browse/CSHARP-43 //LINQ query with multiple "where" generate wrong cql and it is failed to execute public void Bug_CSHARP_43() { int userId = 1; int date = 2; int time = 3; Table <TestTable> table = Session.GetTable <TestTable>(); table.CreateIfNotExists(); table.Insert(new TestTable { UserId = 1, Date = 2, Token = 1 }).Execute(); table.Insert(new TestTable { UserId = 1, Date = 2, Token = 2 }).Execute(); table.Insert(new TestTable { UserId = 1, Date = 2, Token = 3 }).Execute(); table.Insert(new TestTable { UserId = 1, Date = 2, Token = 4 }).Execute(); table.Insert(new TestTable { UserId = 1, Date = 2, Token = 5 }).Execute(); CqlQuery <TestTable> query = table.Where(i => i.UserId == userId && i.Date == date); CqlQuery <TestTable> query2 = query.Where(i => i.Token >= time); query2 = query2.OrderBy(i => i.Token); CqlQuery <TestTable> query3 = query.Where(i => i.Token <= time); query3 = query3.OrderByDescending(i => i.Token); Assert.AreEqual("SELECT * FROM \"test1\" WHERE \"user\" = 1 AND \"date\" = 2 ALLOW FILTERING", query.ToString()); Assert.AreEqual("SELECT * FROM \"test1\" WHERE \"user\" = 1 AND \"date\" = 2 AND \"time\" >= 3 ORDER BY \"time\" ASC ALLOW FILTERING", query2.ToString()); Assert.AreEqual("SELECT * FROM \"test1\" WHERE \"user\" = 1 AND \"date\" = 2 AND \"time\" <= 3 ORDER BY \"time\" DESC ALLOW FILTERING", query3.ToString()); List <TestTable> result2 = query2.Execute().ToList(); List <TestTable> result3 = query3.Execute().ToList(); Assert.AreEqual(3, result2.First().Token); Assert.AreEqual(5, result2.Last().Token); Assert.AreEqual(3, result3.First().Token); Assert.AreEqual(1, result3.Last().Token); }
public async Task <object> Handle(DesignHub hub, InvokeArgs args) { var modelId = args.GetString(); var modelNode = hub.DesignTree.FindModelNode(ModelType.Entity, ulong.Parse(modelId)); if (modelNode == null) { throw new Exception($"Cannot find EntityModel: {modelId}"); } var model = (EntityModel)modelNode.Model; if (model.StoreOptions == null) { throw new Exception("DTO can't load data."); } if (model.PersistentState == PersistentState.Detached) { //TODO:考虑根据设计时模型生成一条伪记录给前端 throw new Exception("EntityModel is new, can't load data."); } if (model.SysStoreOptions != null) { #if FUTURE var q = new TableScan(model.Id); var res = await q.Take(20).ToListAsync(); if (res == null || res.Count == 0) { throw new Exception("no record"); //TODO: 同上 } return(res); #endif } if (model.SqlStoreOptions != null) { var q = new SqlQuery(model.Id); return(await q.Take(20).ToListAsync()); } if (model.CqlStoreOptions != null) { var q = new CqlQuery(model.Id) { Limit = 20 }; return(await q.ToListAsync()); } throw new NotSupportedException(); }
/// <summary> /// Executes the specified expression. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="expression">The expression.</param> /// <returns></returns> TResult IQueryProvider.Execute <TResult>(Expression expression) { if (!typeof(TResult).IsAssignableFrom(typeof(ICqlRow))) { throw new CassandraException("'TElement' must inherit from IFluentBaseColumnFamily"); } if (expression.NodeType == ExpressionType.Call) { expression = ((MethodCallExpression)expression).Arguments[0]; } var result = new CqlQuery(expression, this); return((TResult)Enumerable.FirstOrDefault(result)); }
internal DbExpression Parse() { if (_queryExpression != null) { return(_queryExpression); } List <DbParameterReferenceExpression> parameters = null; if (Parameters != null) { parameters = new List <DbParameterReferenceExpression>(Parameters.Count); foreach (var parameter in Parameters) { var typeUsage = parameter.TypeUsage; if (null == typeUsage) { // Since ObjectParameters do not allow users to specify 'facets', make // sure that the parameter TypeUsage is not populated with the provider // default facet values. ObjectContext.Perspective.TryGetTypeByName( parameter.MappableType.FullNameWithNesting(), false /* bIgnoreCase */, out typeUsage); } Debug.Assert(typeUsage != null, "typeUsage != null"); parameters.Add(typeUsage.Parameter(parameter.Name)); } } var lambda = CqlQuery.CompileQueryCommandLambda( _queryText, // Command Text ObjectContext.Perspective, // Perspective null, // Parser options - null indicates 'use default' parameters, // Parameters null // Variables ); Debug.Assert(lambda.Variables == null || lambda.Variables.Count == 0, "lambda.Variables must be empty"); return(lambda.Body); }
static internal DbCommandTree CompileView( string viewDef, StorageMappingItemCollection mappingItemCollection, ParserOptions.CompilationMode compilationMode) { Debug.Assert(!String.IsNullOrEmpty(viewDef), "!String.IsNullOrEmpty(viewDef)"); Debug.Assert(mappingItemCollection != null, "mappingItemCollection != null"); Perspective perspective = new TargetPerspective(mappingItemCollection.Workspace); ParserOptions parserOptions = new ParserOptions(); parserOptions.ParserCompilationMode = compilationMode; DbCommandTree expr = CqlQuery.Compile(viewDef, perspective, parserOptions, null).CommandTree; Debug.Assert(expr != null, "Compile returned empty tree?"); return(expr); }
internal static DbCommandTree CompileView( string viewDef, StorageMappingItemCollection mappingItemCollection, ParserOptions.CompilationMode compilationMode) { DebugCheck.NotEmpty(viewDef); DebugCheck.NotNull(mappingItemCollection); Perspective perspective = new TargetPerspective(mappingItemCollection.Workspace); var parserOptions = new ParserOptions(); parserOptions.ParserCompilationMode = compilationMode; var expr = CqlQuery.Compile(viewDef, perspective, parserOptions, null).CommandTree; Debug.Assert(expr != null, "Compile returned empty tree?"); return(expr); }
public async Task <int?> Count(Filter[] filters, int?limit) { CqlQuery <T> query = table; if (filters.Any()) { query = query.Where(BuildPredicate(filters)); } if (limit.HasValue) { query = query.Take(limit.Value); } var count = await query.Count().ExecuteAsync().ConfigureAwait(false); return((int)count); }
public override Void Execute() { Debug.Write(CqlQuery.ToString(), "query"); byte[] query = CqlQuery; bool isCqlQueryCompressed = query.Length > 200 && Session.ConnectionBuilder.CompressCqlQueries; // it doesn't make sense to compress queryies that are really small if (isCqlQueryCompressed) { query = Helper.ZlibCompress(query); } var result = Session.GetClient().execute_cql_query( query, isCqlQueryCompressed ? Apache.Cassandra.Compression.GZIP : Apache.Cassandra.Compression.NONE ); return(new Void()); }
private void TryDiscover() { try { IConnection connection = _cluster.GetConnection(); var obsLocalPeer = new CqlQuery <DiscoveredPeer>(connection, ConsistencyLevel.ONE, ExecutionFlags.None, "select data_center,rack,tokens from system.local", _peerFactory); obsLocalPeer.Subscribe(x => Notify(connection.Endpoint, x.Datacenter, x.Rack, x.Tokens), ex => _logger.Error("SystemPeersDiscoveryService failed with error {0}", ex)); var obsPeers = new CqlQuery <DiscoveredPeer>(connection, ConsistencyLevel.ONE, ExecutionFlags.None, "select rpc_address,data_center,rack,tokens from system.peers", _peerFactory); obsPeers.Subscribe(x => Notify(x.RpcAddress, x.Datacenter, x.Rack, x.Tokens), ex => _logger.Error("SystemPeersDiscoveryService failed with error {0}", ex)); } catch (Exception ex) { _logger.Error("SystemPeersDiscoveryService failed with error {0}", ex); } }
public override IEnumerable <ICqlRow> Execute() { Debug.Write(CqlQuery.ToString(), "query"); byte[] query = CqlQuery; bool isCqlQueryCompressed = query.Length > 200 && Session.ConnectionBuilder.CompressCqlQueries; // it doesn't make sense to compress queries that are really small if (isCqlQueryCompressed) { query = Helper.ZlibCompress(query); } if (CqlVersion == null) { CqlVersion = Session.ConnectionBuilder.CqlVersion; } var client = Session.GetClient(); var result = (CqlResult)null; if (CqlVersion == FluentCassandra.Connections.CqlVersion.Cql || client.describe_version() < RpcApiVersion.Cassandra120) { result = client.execute_cql_query( query, isCqlQueryCompressed ? Apache.Cassandra.Compression.GZIP : Apache.Cassandra.Compression.NONE); } else if (CqlVersion == FluentCassandra.Connections.CqlVersion.Cql3) { result = client.execute_cql3_query( query, isCqlQueryCompressed ? Apache.Cassandra.Compression.GZIP : Apache.Cassandra.Compression.NONE, Session.ReadConsistency); } else { throw new FluentCassandraException(CqlVersion + " is not a valid CQL version."); } return(GetRows(result)); }
public async Task <object[]> Search(Filter[] filters, Sort[] sorts, int @from, int count) { CqlQuery <T> query = table; if (filters.Any()) { query = query.Where(BuildPredicate(filters)); } foreach (var sort in sorts) { query = sort.Direction == ObjectFilterSortOrder.Ascending ? query.OrderBy(BuildSort(sort)) : query.OrderByDescending(BuildSort(sort)); } // (p.vostretsov, 28.03.2020): В Cql нельзя сделать Skip var results = await query.Take(from + count).ExecuteAsync().ConfigureAwait(false); return(results.Skip(from).Take(count).Cast <object>().ToArray()); }
public IQuery <T> Execute <T>(string cql, object dataSource, PartitionKey partitionKey) { if (null != dataSource) { throw new ArgumentException("Binary protocol v2 is not implemented"); } // grab a connection BigInteger? token = partitionKey == null ? null : _cluster.Partitioner.ComputeToken(partitionKey); IConnection connection = _cluster.GetConnection(token); // define execution context ConsistencyLevel cl = _consistencyLevel ?? connection.DefaultConsistencyLevel; ExecutionFlags executionFlags = _executionFlags ?? connection.DefaultExecutionFlags; // out to spit out results IDataMapper factoryOut = _factoryOut.Create <T>(); IQuery <T> query = new CqlQuery <T>(connection, cl, executionFlags, cql, factoryOut); return(query); }
public void LinqInsert_Batch_Test() { Table <Movie> nerdMoviesTable = new Table <Movie>(_session, new MappingConfiguration()); Batch batch = _session.CreateBatch(); Movie movie1 = Movie.GetRandomMovie(); Movie movie2 = Movie.GetRandomMovie(); movie1.Director = "Joss Whedon"; var movies = new List <Movie> { movie1, movie2, }; batch.Append(from m in movies select nerdMoviesTable.Insert(m)); Task taskSaveMovies = Task.Factory.FromAsync(batch.BeginExecute, batch.EndExecute, null); taskSaveMovies.Wait(); Task taskSelectStartMovies = Task <IEnumerable <Movie> > .Factory.FromAsync( nerdMoviesTable.BeginExecute, nerdMoviesTable.EndExecute, null). ContinueWith(res => Movie.DisplayMovies(res.Result)); taskSelectStartMovies.Wait(); CqlQuery <Movie> selectAllFromWhere = from m in nerdMoviesTable where m.Director == movie1.Director select m; Task taskselectAllFromWhere = Task <IEnumerable <Movie> > .Factory.FromAsync(selectAllFromWhere.BeginExecute, selectAllFromWhere.EndExecute, null). ContinueWith(res => Movie.DisplayMovies(res.Result)); taskselectAllFromWhere.Wait(); Task <List <Movie> > taskselectAllFromWhereWithFuture = Task <IEnumerable <Movie> > . Factory.FromAsync(selectAllFromWhere.BeginExecute, selectAllFromWhere.EndExecute, null). ContinueWith(a => a.Result.ToList()); Movie.DisplayMovies(taskselectAllFromWhereWithFuture.Result); }
internal DbExpression Parse() { if (this._queryExpression != null) { return(this._queryExpression); } List <DbParameterReferenceExpression> referenceExpressionList = (List <DbParameterReferenceExpression>)null; if (this.Parameters != null) { referenceExpressionList = new List <DbParameterReferenceExpression>(this.Parameters.Count); foreach (ObjectParameter parameter in this.Parameters) { TypeUsage typeUsage = parameter.TypeUsage; if (typeUsage == null) { this.ObjectContext.Perspective.TryGetTypeByName(parameter.MappableType.FullNameWithNesting(), false, out typeUsage); } referenceExpressionList.Add(typeUsage.Parameter(parameter.Name)); } } return(CqlQuery.CompileQueryCommandLambda(this._queryText, (Perspective)this.ObjectContext.Perspective, (ParserOptions)null, (IEnumerable <DbParameterReferenceExpression>)referenceExpressionList, (IEnumerable <DbVariableReferenceExpression>)null).Body); }
private void TryDiscover() { try { IConnection connection = _cluster.GetConnection(); var obsLocalPeer = new CqlQuery<DiscoveredPeer>(connection, ConsistencyLevel.ONE, ExecutionFlags.None, "select data_center,rack,tokens from system.local", _peerFactory); obsLocalPeer.Subscribe(x => Notify(connection.Endpoint, x.Datacenter, x.Rack, x.Tokens), ex => _logger.Error("SystemPeersDiscoveryService failed with error {0}", ex)); var obsPeers = new CqlQuery<DiscoveredPeer>(connection, ConsistencyLevel.ONE, ExecutionFlags.None, "select rpc_address,data_center,rack,tokens from system.peers", _peerFactory); obsPeers.Subscribe(x => Notify(x.RpcAddress, x.Datacenter, x.Rack, x.Tokens), ex => _logger.Error("SystemPeersDiscoveryService failed with error {0}", ex)); } catch (Exception ex) { _logger.Error("SystemPeersDiscoveryService failed with error {0}", ex); } }
public static CqlQuery <T> BuildQuery <T>(CqlQuery <T> query, Condition[] filters) { return(filters.Any() ? query.Where(CriterionHelper.BuildPredicate <T>(filters, CqlObjectParser.Parse)) : query); }
private static CqlQuery <T> AddSort <T, TProperty>(CqlQuery <T> query, Sort sort) { return(sort.SortOrder == ObjectFilterSortOrder.Ascending ? query.OrderBy(CriterionHelper.BuildSort <T, TProperty>(sort)) : query.OrderByDescending(CriterionHelper.BuildSort <T, TProperty>(sort))); }