示例#1
0
        public async Task LongCountPredicateAsync([DataSources] string context)
        {
            var query = CompiledQuery.Compile <IDataContext, int, CancellationToken, Task <long> >((db, id, token) =>
                                                                                                   db.GetTable <AsyncDataTable>().LongCountAsync(c => c.Id == id, token));

            using (var db = GetDataContext(context))
                using (db.CreateLocalTable(GenerateData()))
                {
                    var result = await query(db, 2, CancellationToken.None);

                    Assert.AreEqual(1, result);
                }
        }
示例#2
0
        public async Task SumAsyncDouble([IncludeDataSources(true, TestProvName.AllSQLite)] string context)
        {
            var query = CompiledQuery.Compile <IDataContext, int, CancellationToken, Task <double> >((db, id, token) =>
                                                                                                     db.GetTable <AsyncDataTable>().Where(c => c.Id < id).Select(c => (double)c.Id).SumAsync(token));

            using (var db = GetDataContext(context))
                using (db.CreateLocalTable(GenerateData()))
                {
                    var result = await query(db, 5, CancellationToken.None);

                    Assert.AreEqual(10, result);
                }
        }
示例#3
0
        public async Task ContainsAsync([IncludeDataSources(true, TestProvName.AllSQLite)] string context)
        {
            var query = CompiledQuery.Compile <IDataContext, int, CancellationToken, Task <bool> >((db, id, token) =>
                                                                                                   db.GetTable <AsyncDataTable>().Select(c => c.Id).ContainsAsync(id, token));

            using (var db = GetDataContext(context))
                using (db.CreateLocalTable(GenerateData()))
                {
                    var result = await query(db, 2, CancellationToken.None);

                    Assert.IsTrue(result);
                }
        }
示例#4
0
        public async Task MaxSelectorAsync([DataSources] string context)
        {
            var query = CompiledQuery.Compile <IDataContext, int, CancellationToken, Task <int> >((db, id, token) =>
                                                                                                  db.GetTable <AsyncDataTable>().Where(c => c.Id > id).MaxAsync(c => c.Id, token));

            using (var db = GetDataContext(context))
                using (db.CreateLocalTable(GenerateData()))
                {
                    var result = await query(db, 2, CancellationToken.None);

                    Assert.AreEqual(10, result);
                }
        }
示例#5
0
		// Jeff Lanning ([email protected]): Added overload for OPath support
		public IDataReader GetDataReader(Type entityType, CommandInfo commandInfo, CompiledQuery query, object[] parameterValues) {
			IDbConnection conn = null;
			try {
				conn = ProviderFactory.GetConnection(this.connection, this.provider);
				IDbCommand cmd = CreateDbCommand(Guid.NewGuid(), entityType, commandInfo, conn, query, parameterValues);
				cmd.Connection.Open();
				return cmd.ExecuteReader(CommandBehavior.CloseConnection);
			}
			catch {
				if( conn != null ) conn.Close();
				throw;
			}
		}
示例#6
0
        public void ParamTest1()
        {
            var query = CompiledQuery.Compile <ITestDataContext, int, IEnumerable <Child> >((db, id) =>
                                                                                            from c in db.Child
                                                                                            where c.ParentID == id
                                                                                            select new Child
            {
                ParentID = id,
                ChildID  = c.ChildID
            });

            ForEachProvider(db => Assert.AreEqual(2, query(db, 2).ToList().Count()));
        }
示例#7
0
        public void Contains4([DataSources] string context)
        {
            var arr = new[] { 1, 2 };

            using (var data = GetDataContext(context))
                AreEqual(
                    from p in Parent
                    where arr.Contains(p.ParentID)
                    select p,
                    CompiledQuery.Compile <ITestDataContext, IQueryable <Parent> >(db =>
                                                                                   from p in db.Parent
                                                                                   where arr.Contains(p.ParentID)
                                                                                   select p)(data));
        }
示例#8
0
        public void ParamTest1(string context)
        {
            var query = CompiledQuery.Compile <ITestDataContext, int, IEnumerable <Child> >((db, id) =>
                                                                                            from c in db.Child
                                                                                            where c.ParentID == id
                                                                                            select new Child
            {
                ParentID = id,
                ChildID  = c.ChildID
            });

            using (var db = GetDataContext(context))
                Assert.AreEqual(2, query(db, 2).ToList().Count());
        }
示例#9
0
        public void Contains3(string context)
        {
            var n = 2;

            using (var data = GetDataContext(context))
                AreEqual(
                    from p in Parent
                    where new[] { 1, n }.Contains(p.ParentID)
                    select p,
                    CompiledQuery.Compile <ITestDataContext, IQueryable <Parent> >(db =>
                                                                                   from p in db.Parent
                                                                                   where new[] { 1, n }.Contains(p.ParentID)
                                                                                   select p)(data));
        }
示例#10
0
        public static Delegate Compile(LambdaExpression query)
        {
            CompiledQuery cq     = new CompiledQuery(query);
            Type          dt     = query.Type;
            MethodInfo    method = dt.GetMethod("Invoke", BindingFlags.Instance | BindingFlags.Public);

            ParameterInfo[]       parameters = method.GetParameters();
            ParameterExpression[] pexprs     = parameters.Select(p => Expression.Parameter(p.ParameterType, p.Name)).ToArray();
            var              args            = Expression.NewArrayInit(typeof(object), pexprs.Select(p => Expression.Convert(p, typeof(object))).ToArray());
            Expression       body            = Expression.Convert(Expression.Call(Expression.Constant(cq), "Invoke", Type.EmptyTypes, args), method.ReturnType);
            LambdaExpression e = Expression.Lambda(dt, body, pexprs);

            return(e.Compile());
        }
示例#11
0
        public void Setup()
        {
            _result = new QueryResult()
            {
                Schema     = SalesOrderHeader.SchemaTable,
                Names      = SalesOrderHeader.Names,
                FieldTypes = SalesOrderHeader.FieldTypes,
                DbTypes    = SalesOrderHeader.DbTypes,
                Data       = Enumerable.Range(0, 31465).Select(_ => SalesOrderHeader.SampleRow).ToArray()
                             //Data       = Enumerable.Range(0, 100).Select(_ => SalesOrderHeader.SampleRow).ToArray()
            };

            _compiled = CompiledQuery.Compile((Db db) => db.SalesOrderHeader);
        }
示例#12
0
        public void Contains4()
        {
            var arr = new[] { 1, 2 };

            var expected =
                from p in Parent
                where arr.Contains(p.ParentID)
                select p;

            ForEachProvider(data => AreEqual(expected, CompiledQuery.Compile <ITestDataContext, IQueryable <Parent> >(db =>
                                                                                                                      from p in db.Parent
                                                                                                                      where arr.Contains(p.ParentID)
                                                                                                                      select p)(data)));
        }
示例#13
0
                public Expression GetGroupJoin(GroupJoinContext context)
                {
                    // Convert outer condition.
                    //
                    var outerParam = Expression.Parameter(context.OuterKeyLambda.Body.Type, "o");
                    var outerKey   = context.OuterKeyLambda.GetBody(context.Lambda.Parameters[0]);

                    outerKey = context.Builder.BuildExpression(context, outerKey, false);

                    // Convert inner condition.
                    //
                    var parameters = context.Builder.CurrentSqlParameters
                                     .Select((p, i) => new { p, i })
                                     .ToDictionary(_ => _.p.Expression, _ => _.i);
                    var paramArray = Expression.Parameter(typeof(object[]), "ps");

                    var innerKey = context.InnerKeyLambda.Body.Transform(e =>
                    {
                        if (parameters.TryGetValue(e, out var idx))
                        {
                            return(Expression.Convert(
                                       Expression.ArrayIndex(paramArray, Expression.Constant(idx)),
                                       e.Type));
                        }

                        return(e);
                    });

                    // Item reader.
                    //
                    var expr = Expression.Call(
                        null,
                        MemberHelper.MethodOf(() => Queryable.Where(null, (Expression <Func <TElement, bool> >)null !)),
                        context._innerExpression,
                        Expression.Lambda <Func <TElement, bool> >(
                            ExpressionBuilder.Equal(context.Builder.MappingSchema, innerKey, outerParam),
                            new[] { context.InnerKeyLambda.Parameters[0] }));

                    var lambda = Expression.Lambda <Func <IDataContext, TKey, object?[]?, IQueryable <TElement> > >(
                        Expression.Convert(expr, typeof(IQueryable <TElement>)),
                        Expression.Parameter(typeof(IDataContext), "ctx"),
                        outerParam,
                        paramArray);

                    var itemReader = CompiledQuery.Compile(lambda);

                    return(Expression.Call(
                               null,
                               MemberHelper.MethodOf(() => GetGrouping(null !, null !, default !, null !)),
示例#14
0
        protected void btnCompQuery_Click(object sender, EventArgs e)
        {
            //Compiled Query, szybsze
            var compliedQuery = CompiledQuery.Compile(
                (SampleDataContext dataContext, int EmpID) =>
                (from s in dataContext.EmployeesLINQ
                 where s.ID == EmpID
                 select s).Single());

            using (SampleDataContext dbContext = new SampleDataContext())
            {
                EmployeesLINQ emp = compliedQuery(dbContext, 1);
                Response.Write("<script>alert('Employee with ID 1 is " + emp.FirstName + "')</script>");
            }
        }
        private static void ExecuteQueryLoop(AWEntities oContext, AWL2SDataContext dContext, List <decimal> resultList, QueryType qType, int LoopCount)
        {
            var compQuery = CompiledQuery.Compile <AWEntities, IQueryable <AWCustomer> >
                                ((AWEntities ctx ) =>
                                from c in ctx.AWCustomers select c);


            for (int j = 0; j < LoopCount; j++)
            {
                var sw2 = new System.Diagnostics.Stopwatch();
                sw2.Start();
                //------------using compiled query
                // var customers = compQuery.Invoke(context);

                //iterating is about the same time as tolist
                switch (qType)
                {
                case QueryType.L2E:
                    // oContext = new AWEntities();
                    oContext.AWCustomers.MergeOption = MergeOption.OverwriteChanges;
                    var customers = (from c in oContext.AWCustomers select c).ToList();
                    break;

                case QueryType.EntityObject:
                    //  oContext = new AWEntities();
                    oContext.AWCustomers.MergeOption = MergeOption.OverwriteChanges;
                    var oqCusts = oContext.CreateQuery <AWCustomer>("AWCustomers").ToList();
                    break;

                case QueryType.L2S:
                    var l2SCusts = (from c in dContext.L2SCustomers select c).ToList();
                    break;

                case QueryType.CompiledL2E:
                    var compCusts = compQuery.Invoke(oContext).ToList();

                    break;

                case QueryType.DataReader:
                    break;

                default:
                    throw new ArgumentOutOfRangeException("qType");
                }
                sw2.Stop();
                resultList.Add(sw2.ElapsedMilliseconds);
            }
        }
示例#16
0
        public int GetTotalRegistros(string search)
        {
            try
            {
                var query = Dbset.Where(x => x.NOME.Contains(search) ||
                                        x.SITUACAO.Contains(search) ||
                                        x.DISPONIVEL.Contains(search)).Count();

                var _object = CompiledQuery.Compile <ObjectContext, int>(ctx => query);
                return(_object.Invoke(((IObjectContextAdapter)Entities).ObjectContext));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        internal QueryExecutionContext(CompiledQuery query)
        {
            Transaction transaction = Transaction.RunningTransaction;

            CompiledQuery   = query;
            Errors          = query.Errors;
            QueryParameters = new Dictionary <string, (object?, bool)>();
            foreach (Parameter item in query.ConstantValues)
            {
                QueryParameters.Add(item.Name, (transaction.PersistenceProviderFactory.ConvertToStoredType(item.Type !, item.Value), true));
            }
            foreach (Parameter item in query.DefaultValues)
            {
                QueryParameters.Add(item.Name, (transaction.PersistenceProviderFactory.ConvertToStoredType(item.Type !, item.Value), false));
            }
        }
示例#18
0
        /// <summary>
        /// Queries employees that have provided ZIP code in address with a compiled query.
        /// </summary>
        /// <param name="cache">Cache.</param>
        private static void CompiledQueryExample(ICache <EmployeeKey, Employee> cache)
        {
            const int zip = 94109;

            // Compile cache query to eliminate LINQ overhead on multiple runs.
            Func <int, IQueryCursor <ICacheEntry <EmployeeKey, Employee> > > qry =
                CompiledQuery.Compile((int z) => cache.AsCacheQueryable().Where(emp => emp.Value.Address.Zip == z));

            Console.WriteLine();
            Console.WriteLine(">>> Employees with zipcode using compiled query " + zip + ":");

            foreach (ICacheEntry <EmployeeKey, Employee> entry in qry(zip))
            {
                Console.WriteLine(">>>    " + entry.Value);
            }
        }
示例#19
0
        public void CheckLeftJoin2()
        {
            var expected =
                from p in Parent
                join ch in Child on p.ParentID equals ch.ParentID into lj1
                from ch in lj1.DefaultIfEmpty()
                where ch != null
                select p;

            ForEachProvider(data => AreEqual(expected, CompiledQuery.Compile <ITestDataContext, IQueryable <Parent> >(db =>
                                                                                                                      from p in db.Parent
                                                                                                                      join ch in db.Child on p.ParentID equals ch.ParentID into lj1
                                                                                                                      from ch in lj1.DefaultIfEmpty()
                                                                                                                      where null != ch
                                                                                                                      select p)(data)));
        }
        private static string LinqToEntitiesTest()
        {
            var compQuery = CompiledQuery.Compile <AWEntities,
                                                   IQueryable <AWCustomer> >((AWEntities ctx) =>
                                                                             from cust in ctx.AWCustomers select cust);


            var     resultList  = new List <decimal>();
            decimal testresults = 0;
            var     sw          = new System.Diagnostics.Stopwatch();
            var     sw2         = new System.Diagnostics.Stopwatch();

            for (int i = 0; i < 2; i++)
            {
                sw.Reset();
                sw.Start();

                resultList.Clear();
                var context = new AWEntities(); //<--been moving this in and out of the next for loop
                for (int j = 0; j < 100; j++)
                {
                    //sw2.Reset();
                    //sw2.Start();


                    //------------using compiled query
                    // var customers = compQuery.Invoke(context);

                    //iterating is about the same time as tolist
                    var customers = (from c in context.AWCustomers select c).ToList();
                    // sw2.Stop();
                    //resultList.Add(sw2.ElapsedMilliseconds);
                }
                //Console.WriteLine("l2e query 1:{0}", resultList[0]);
                //        Console.WriteLine("l2e query 2:{0}", resultList[1]);
                //        Console.WriteLine("l2e query 3:{0}", resultList[2]);
                //        Console.WriteLine("total {0}", resultList.Sum());
                //        Console.ReadKey();

                sw.Stop();
                testresults = sw.ElapsedMilliseconds;
            }

            Console.WriteLine("LINQ to Entities: {0}ms", testresults);
            Console.ReadKey();
            return(String.Format("LINQ to Entities: {0}ms", testresults));
        }
示例#21
0
        public bool GetSingleColumnParam(Stopwatch watch, int repeatCount, int takeCount)
        {
            var query = CompiledQuery.Compile((TestContext db, int id, int p) =>
                                              db.Narrows.Where(t => t.ID == id && t.Field1 == p).Select(t => t.ID).First());

            watch.Start();

            using (var db = new TestContext())
                for (var i = 0; i < repeatCount; i++)
                {
                    query(db, 1, 2);
                }

            watch.Stop();

            return(true);
        }
示例#22
0
        public bool GetSingleColumnSlow(Stopwatch watch, int repeatCount, int takeCount)
        {
            var query = CompiledQuery.Compile((TestContext db) =>
                                              db.Narrows.Where(t => t.ID == 1).Select(t => t.ID).First());

            watch.Start();

            for (var i = 0; i < repeatCount; i++)
            {
                using (var db = new TestContext())
                    query(db);
            }

            watch.Stop();

            return(true);
        }
示例#23
0
        public void CompiledQuery_with_contains_does_not_hold_reference_to_context_Test(out WeakReference wr)
        {
            using (var context = CreateCompiledQueryContext())
            {
                wr = new WeakReference(context);

                Expression <Func <CompiledQueryContext, string, string, IEnumerable <CompiledQueryBlog> > > expression =
                    (ctx, fake, prm) =>
                    (from b in ctx.Blogs
                     where b.Title.Contains(prm)
                     select b);

                var cq     = CompiledQuery.Compile(expression);
                var query  = cq(context, "What-everrrr", "Foo");
                var result = query.ToList();
            }
        }
示例#24
0
 public void CheckLeftJoin2(string context)
 {
     using (var data = GetDataContext(context))
         AreEqual(
             from p in Parent
             join ch in Child on p.ParentID equals ch.ParentID into lj1
             from ch in lj1.DefaultIfEmpty()
             where ch != null
             select p
             ,
             CompiledQuery.Compile <ITestDataContext, IQueryable <Parent> >(db =>
                                                                            from p in db.Parent
                                                                            join ch in db.Child on p.ParentID equals ch.ParentID into lj1
                                                                            from ch in lj1.DefaultIfEmpty()
                                                                            where null != ch
                                                                            select p)(data));
 }
示例#25
0
        public bool GetSingleColumnFast(Stopwatch watch, int repeatCount, int takeCount)
        {
            var query = CompiledQuery.Compile((L2DBContext db) =>
                                              db.Narrows.Where(t => t.ID == 1).Select(t => t.ID).First());

            watch.Start();

            using (var db = new L2DBContext(TrackChanges))
                for (var i = 0; i < repeatCount; i++)
                {
                    query(db);
                }

            watch.Stop();

            return(true);
        }
示例#26
0
        public async Task <bool> GetSingleColumnFastAsync(Stopwatch watch, int repeatCount, int takeCount)
        {
            var query = CompiledQuery.Compile((L2DBContext db) =>
                                              db.Narrows.Where(t => t.ID == 1).Select(t => t.ID).FirstAsync(default(CancellationToken)));

            watch.Start();

            using (var db = new L2DBContext(TrackChanges))
                for (var i = 0; i < repeatCount; i++)
                {
                    await query(db);
                }

            watch.Stop();

            return(true);
        }
示例#27
0
        public bool ComplicatedLinqSlow(Stopwatch watch, int repeatCount, int takeCount, int nRows)
        {
            var query = CompiledQuery.Compile((BLTContext db, int top) =>
                                              (
                                                  from n in db.NarrowLongs
                                                  join w in db.WideLongs on n.Field1 equals w.Field1
                                                  where
                                                  n.ID >= 0 && n.ID <= nRows &&
                                                  !new[] { 0, 20, 50, 187635 }.Contains(w.Field1)
                                                  select new
            {
                n.ID,
                w.Field1
            }
                                              )
                                              .Union
                                              (
                                                  from n in db.NarrowLongs
                                                  join w in db.WideLongs on n.Field1 equals w.Field1
                                                  where
                                                  n.ID >= 0 && n.ID <= nRows &&
                                                  !new[] { 0, 240, 500, 18635 }.Contains(w.Field1)
                                                  select new
            {
                n.ID,
                w.Field1
            }
                                              )
                                              .OrderByDescending(n1 => n1.Field1)
                                              .Skip(1000)
                                              .Take(top));

            watch.Start();

            for (var i = 0; i < repeatCount; i++)
            {
                using (var db = new BLTContext())
                    foreach (var item in query(db, takeCount))
                    {
                    }
            }

            watch.Stop();

            return(true);
        }
示例#28
0
        public void Setup()
        {
            _cn = new MockDbConnection(new QueryResult()
            {
                Return = 1
            }, ConnectionState.Open);
            _db = new DataConnection(SQLiteTools.GetDataProvider(ProviderName.SQLiteMS), _cn);

            _compiledInsert = CompiledQuery.Compile <DataConnection, string, string, string, decimal, decimal, int>((ctx, key, value1, value2, value3, value4) =>
                                                                                                                    ctx.GetTable <TESTTABLE>()
                                                                                                                    .Value(i => i.COLUMN1, key)
                                                                                                                    .Value(i => i.COLUMN2, value1)
                                                                                                                    .Value(i => i.COLUMN12, value2)
                                                                                                                    .Value(i => i.COLUMN15, value3)
                                                                                                                    .Value(i => i.COLUMN16, value4)
                                                                                                                    .Insert());
        }
示例#29
0
        public void Setup()
        {
            _context = new TestDataContext(_connectionString.FormattedConnectionString);
            _context.DeferredLoadingEnabled = false;

            _findWhereTestIntIs = CompiledQuery.Compile <TestDataContext, int, IEnumerable <TestEntity> >
                                  (
                (context, testInt) => context.TestEntities
                .Where <TestEntity>(t => t.TestInt == testInt)
                                  );

            _find = CompiledQuery.Compile <TestDataContext, int, TestEntity>
                    (
                (context, id) => context.TestEntities
                .SingleOrDefault(t => t.Id == id)
                    );
        }
        public IEnumerable <EV_INSCRICAO> GetInscricaoPaginacao(string order, int offset, int limit)
        {
            var skip = (offset - 1) * limit < 0 ? 0 : (offset - 1) * limit;

            if (order == "asc")
            {
                var query   = Dbset.Include("EV_EVENTO").Include("EV_CLIENTE").OrderBy(x => x.CRIADO);
                var _object = CompiledQuery.Compile <ObjectContext, IQueryable <EV_INSCRICAO> >(ctx => query.Skip(skip).Take(limit));
                return(_object.Invoke(((IObjectContextAdapter)Entities).ObjectContext).ToList());
            }
            else
            {
                var query   = Dbset.Include("EV_EVENTO").Include("EV_CLIENTE").OrderByDescending(x => x.CRIADO);
                var _object = CompiledQuery.Compile <ObjectContext, IQueryable <EV_INSCRICAO> >(ctx => query.Skip(skip).Take(limit));
                return(_object.Invoke(((IObjectContextAdapter)Entities).ObjectContext).ToList());
            }
        }
示例#31
0
        /// <summary>
        /// Queries employees that have specific salary with a compiled query.
        /// </summary>
        /// <param name="cache">Cache.</param>
        private static void CompiledQueryExample(ICache <int, Employee> cache)
        {
            const int minSalary = 10000;

            var cache0 = cache.AsCacheQueryable();

            // Compile cache query to eliminate LINQ overhead on multiple runs.
            Func <int, IQueryCursor <ICacheEntry <int, Employee> > > qry =
                CompiledQuery.Compile((int ms) => cache0.Where(emp => emp.Value.Salary > ms));

            Console.WriteLine();
            Console.WriteLine($">>> Employees with salary > {minSalary} using compiled query:");

            foreach (var entry in qry(minSalary))
            {
                Console.WriteLine(">>>    " + entry.Value);
            }
        }
示例#32
0
		// Jeff Lanning ([email protected]): Added overload for OPath support
		public DataSet GetDataSet(Type entityType, CommandInfo commandInfo, CompiledQuery query, object[] parameterValues) {
			using (IDbConnection conn = ProviderFactory.GetConnection(this.connection, this.provider))
			{
				IDbCommand cmd = CreateDbCommand(Guid.NewGuid(), entityType, commandInfo, conn, query, parameterValues);
				IDbDataAdapter adapter = ProviderFactory.GetAdapter(cmd, this.provider);
				DataSet dataSet = new DataSet("WilsonORMapper");
				adapter.Fill(dataSet);				
				return dataSet;
			}
		}
示例#33
0
		private IDbCommand CreateDbCommand(Guid transactionId, Type entityType, CommandInfo commandInfo, IDbConnection conn, CompiledQuery query, object[] parameterValues) {
			IDbCommand cmd = conn.CreateCommand();
			cmd.CommandText = query.SqlQuery;
			cmd.CommandType = CommandType.Text;
			if (this.supportsTimeout) {
				cmd.CommandTimeout = (query.baseQuery != null) ? query.baseQuery.CommandTimeout : this.commandTimeout;
			}

			// build the parameter array (use the ordinals to get them in the correct order)
			Parameter[] parameters = new Parameter[query.parameterCount];
			if (parameterValues != null) {
				if (parameterValues.Length != parameters.Length) {
					throw new Exception("Number of parameters in the expression does not match number of values provided.");
				}
				
				for (int i = 0; i < parameters.Length; i++) {
					OPathParameter p = query.parameterTable[i];
					parameters[p.Ordinal] = new Parameter(p.Name, parameterValues[i], null);
				}
			}
			else // use the parameters in the base query (if any)
			{
				//note: the compiler will only allow an exact number of parameters in the base query... or none at all.
				for (int i = 0; i < parameters.Length; i++) {
					OPathParameter p = query.parameterTable[i];
					parameters[p.Ordinal] = new Parameter(p.Name, p.Value, null);
				}
			}

			// add the parameters to the command
			for (int i = 0; i < parameters.Length; i++) {
				cmd.Parameters.Add(this.GetParameter(cmd, parameters[i]));
			}
	
			this.InterceptCommand(transactionId, entityType, commandInfo, cmd);
			return cmd;
		}
示例#34
0
        public override ICompiledQuery Compile(IParsedQuery parsed) {
            CompiledQuery serializedQuery = new CompiledQuery() {
                Children = parsed.Children.Select(this.Compile).Where(child => child != null).ToList(),
                Root = parsed.Root,
                Methods = parsed.Methods,
                Skip = parsed.Skip,
                Limit = parsed.Limit
            };

            List<String> compiled = new List<String>() {
                parsed.Methods.FirstOrDefault()
            };

            if (parsed.Root is Merge) {
                ICompiledQuery save = serializedQuery.Children.FirstOrDefault(child => child.Root is Save);
                ICompiledQuery modify = serializedQuery.Children.FirstOrDefault(child => child.Root is Modify);

                if (save != null && modify != null) {
                    compiled.Add("INTO");
                    compiled.Add(save.Collections.FirstOrDefault());
                    compiled.Add("SET");
                    compiled.Add(save.Assignments.FirstOrDefault());
                    //compiled.Add("ON DUPLICATE KEY UPDATE");
                    //compiled.Add(modify.Assignments.FirstOrDefault());
                }
            }
            else if (parsed.Root is Index) {
                Primary primary = parsed.Root.FirstOrDefault(attribute => attribute is Primary) as Primary;
                Unique unique = parsed.Root.FirstOrDefault(attribute => attribute is Unique) as Unique;

                if (primary == null) {
                    // UNIQUE INDEX `Score_UNIQUE` (`Score` ASC)
                    if (unique != null) {
                        compiled.Add("UNIQUE INDEX");

                        if (parsed.Root.Any(attribute => attribute is IfNotExists)) {
                            compiled.Add("IF NOT EXISTS");
                        }

                        // todo move the name element to a modifier?
                        compiled.Add(String.Format("`{0}`", ((Index)parsed.Root).Name));
                    }
                    // INDEX `Name_INDEX` (`Name` ASC)
                    else {
                        compiled.Add("INDEX");

                        if (parsed.Root.Any(attribute => attribute is IfNotExists)) {
                            compiled.Add("IF NOT EXISTS");
                        }

                        // todo move the name element to a modifier?
                        compiled.Add(String.Format("`{0}`", ((Index)parsed.Root).Name));
                    }

                    compiled.Add("ON");

                    if (parsed.Collections.Any() == true) {
                        serializedQuery.Collections.Add(String.Join(", ", parsed.Collections));
                        compiled.Add(serializedQuery.Collections.FirstOrDefault());
                    }

                    if (parsed.Sortings.Any() == true) {
                        serializedQuery.Sortings.Add(String.Join(", ", parsed.Sortings));
                        compiled.Add(String.Format("({0})", serializedQuery.Sortings.FirstOrDefault()));
                    }
                }
                else {
                    // SQLite does not support adding primary indexes after a table has been created.
                    serializedQuery = null;
                }
            }
            else if (parsed.Root is Alter) {
                if (parsed.Collections.Any() == true) {
                    compiled.Add("TABLE");

                    serializedQuery.Collections.Add(String.Join(", ", parsed.Collections));
                    compiled.Add(serializedQuery.Collections.FirstOrDefault());
                }

                compiled.Add(String.Join(", ", serializedQuery.Children.Where(child => child.Root is Create || child.Root is Drop).SelectMany(child => child.Compiled)));
            }
            else if (parsed.Root is Find) {
                serializedQuery.Fields = new List<String>(parsed.Fields);
                compiled.Add(parsed.Fields.Any() == true ? String.Join(", ", parsed.Fields) : "*");

                if (parsed.Collections.Any() == true) {
                    serializedQuery.Collections.Add(String.Join(", ", parsed.Collections));
                    compiled.Add("FROM");
                    compiled.Add(serializedQuery.Collections.FirstOrDefault());
                }

                if (parsed.Conditions.Any() == true) {
                    serializedQuery.Conditions.Add(String.Join(" AND ", parsed.Conditions));
                    compiled.Add("WHERE");
                    compiled.Add(serializedQuery.Conditions.FirstOrDefault());
                }

                if (parsed.Sortings.Any() == true) {
                    serializedQuery.Sortings.Add(String.Join(", ", parsed.Sortings));
                    compiled.Add("ORDER BY");
                    compiled.Add(serializedQuery.Sortings.FirstOrDefault());
                }

                if (parsed.Limit != null) {
                    compiled.Add("LIMIT");
                    compiled.Add(parsed.Limit.Value.ToString(CultureInfo.InvariantCulture));
                }

                if (parsed.Skip != null) {
                    compiled.Add("OFFSET");
                    compiled.Add(parsed.Skip.Value.ToString(CultureInfo.InvariantCulture));
                }
            }
            else if (parsed.Root is Create) {
                if (parsed.Databases.Any() == true) {
                    serializedQuery.Databases.Add(parsed.Databases.FirstOrDefault());
                    compiled = new List<String> {
                        "ATTACH",
                        "DATABASE",
                        serializedQuery.Databases.FirstOrDefault()
                    };
                }
                else if (parsed.Collections.Any() == true) {
                    compiled.Add("TABLE");

                    if (parsed.Root.Any(modifier => modifier is IfNotExists) == true) {
                        compiled.Add("IF NOT EXISTS");
                    }

                    compiled.Add(parsed.Collections.FirstOrDefault());

                    // parsed.Indices will only hae primary keys generated. Autoincrement primary keys mut be inline.
                    if (parsed.Indices.Any() == true && parsed.Root.DescendantsAndSelf<AutoIncrement>().Any() == false) {
                        List<String> fieldsIndicesCombination = new List<String>(parsed.Fields);
                        fieldsIndicesCombination.AddRange(parsed.Indices);

                        serializedQuery.Indices.Add(String.Join(", ", fieldsIndicesCombination.ToArray()));

                        compiled.Add(String.Format("({0})", serializedQuery.Indices.FirstOrDefault()));
                    }
                    else {
                        compiled.Add(String.Format("({0})", String.Join(", ", parsed.Fields.ToArray())));
                    }
                }
                else if (parsed.Fields.Any() == true) {
                    compiled.Add("COLUMN");

                    compiled.Add(String.Join(", ", parsed.Fields.ToArray()));
                }
            }
            else if (parsed.Root is Save) {
                if (parsed.Collections.Any() == true) {
                    compiled.Add("INTO");
                    serializedQuery.Collections.Add(parsed.Collections.FirstOrDefault());
                    compiled.Add(serializedQuery.Collections.FirstOrDefault());
                }

                if (parsed.Fields.Any() == true) {
                    serializedQuery.Fields.Add(String.Join(", ", parsed.Fields));
                    compiled.Add(String.Format("({0})", serializedQuery.Fields.FirstOrDefault()));
                }

                compiled.Add("VALUES");

                if (parsed.Values.Any() == true) {
                    serializedQuery.Values.Add(String.Join(", ", parsed.Values));
                    compiled.Add(String.Format("({0})", serializedQuery.Values.FirstOrDefault()));
                }

                if (parsed.Assignments.Any() == true) {
                    serializedQuery.Assignments.Add(String.Join(", ", parsed.Assignments));
                }
            }
            else if (parsed.Root is Modify) {
                if (parsed.Collections.Any() == true) {
                    serializedQuery.Collections.Add(String.Join(", ", parsed.Collections));
                    compiled.Add(serializedQuery.Collections.FirstOrDefault());
                }

                if (parsed.Assignments.Any() == true) {
                    serializedQuery.Assignments.Add(String.Join(", ", parsed.Assignments));
                    compiled.Add("SET");
                    compiled.Add(serializedQuery.Assignments.FirstOrDefault());
                }

                if (parsed.Conditions.Any() == true) {
                    serializedQuery.Conditions.Add(String.Join(" AND ", parsed.Conditions));
                    compiled.Add("WHERE");
                    compiled.Add(serializedQuery.Conditions.FirstOrDefault());
                }
            }
            else if (parsed.Root is Remove) {
                if (parsed.Collections.Any() == true) {
                    serializedQuery.Collections.Add(String.Join(", ", parsed.Collections));
                    compiled.Add("FROM");
                    compiled.Add(serializedQuery.Collections.FirstOrDefault());
                }

                if (parsed.Conditions.Any() == true) {
                    serializedQuery.Conditions.Add(String.Join(" AND ", parsed.Conditions));
                    compiled.Add("WHERE");
                    compiled.Add(serializedQuery.Conditions.FirstOrDefault());
                }
            }
            else if (parsed.Root is Drop) {
                if (parsed.Databases.Any() == true) {
                    serializedQuery.Databases.Add(parsed.Databases.FirstOrDefault());
                    compiled = new List<String> {
                        "DETACH",
                        "DATABASE",
                        serializedQuery.Databases.FirstOrDefault()
                    };
                }
                else if (parsed.Collections.Any() == true) {
                    compiled.Add("TABLE");
                    serializedQuery.Collections.Add(parsed.Collections.FirstOrDefault());
                    compiled.Add(serializedQuery.Collections.FirstOrDefault());
                }
                else if (parsed.Fields.Any() == true) {
                    compiled.Add("COLUMN");

                    compiled.Add(String.Join(", ", parsed.Fields.ToArray()));
                }
            }

            if (serializedQuery != null) serializedQuery.Compiled.Add(String.Join(" ", compiled));

            return serializedQuery;
        }