public List <KeyOpValue> GetUpdateColumns()
        {
            var builder = new UpdateStatementBuilder(new FromClause("theName"));

            this.FindUpdateColumns(builder);
            return(builder.Values);
        }
        public override SqlStatement GetUpdateStatement(object obj, Condition iwc)
        {
            var sb = new UpdateStatementBuilder(Context.Info.From);

            Context.Handler.SetValuesForUpdate(sb, obj);
            var lv = (int)Context.Info.LockVersion.GetValue(obj);

            sb.Where.Conditions = iwc && (CK.K[Context.Info.LockVersion.Name] == lv);
            bool find = false;

            foreach (var kv in sb.Values)
            {
                if (kv.Key == Context.Info.LockVersion.Name)
                {
                    kv.Value = lv + 1;
                    find     = true;
                    break;
                }
            }
            if (!find)
            {
                sb.Values.Add(new KeyOpValue(Context.Info.LockVersion.Name, lv + 1, KvOpertation.None));
            }
            return(sb.ToSqlStatement(Context));
        }
Example #3
0
        public string GetSql(Action <IUpdateStatementBuilder <T> > action, Action <IRestrictable <T> > restriction, List <object> parameters)
        {
            var builder = new UpdateStatementBuilder <T>();

            action(builder);
            if (builder.HasNoStatements())
            {
                throw new UpdateByQueryException("Can not update without update statements. Please add SET statements");
            }

            var properties = builder.GetEnumerable().ToArray();

            if (properties.Any(x => x.Property.ReadOnly))
            {
                throw new UpdateByQueryException("Update by query columns contained at least one read only column");
            }

            var columns = properties
                          .Select(x => x.GetSql(_map, parameters)).ToArray();

            var restrictable = new Restrictable <T>();

            restriction(restrictable);

            var where = restrictable.BuildRestrictionsIncludeWhere(parameters, _map.Dialect);

            return(string.Format("UPDATE {0} SET {1}{2};", _map.TableName, string.Join(", ", columns), where));
        }
Example #4
0
        public virtual SqlStatement GetUpdateStatement(object obj, Condition iwc)
        {
            var isv = new UpdateStatementBuilder(this.Context.Info.From);

            this.Context.Handler.SetValuesForUpdate(isv, obj);
            isv.Where.Conditions = iwc;
            return(isv.ToSqlStatement(this.Context));
        }
Example #5
0
        public override SqlStatement GetDeleteStatement(Condition iwc)
        {
            var sb = new UpdateStatementBuilder(Context.Info.From);

            sb.Values.Add(new KeyOpValue(_columnName, true, KvOpertation.None));
            sb.Where.Conditions = iwc && _colExp;
            return(sb.ToSqlStatement(Context));
        }
Example #6
0
 private IUpdatable <T> Operate(string key, object value, KvOpertation op)
 {
     if (_updater == null)
     {
         _updater = new UpdateStatementBuilder(_ctx.Info.From);
     }
     _updater.Values.Add(new KeyOpValue(key, value, op));
     return(this);
 }
Example #7
0
        public void TestUpdatedOn()
        {
            var dc = new DataProvider("SQLite");
            var sb = new UpdateStatementBuilder(new FromClause("user"));

            sb.Values.Add(new KeyOpValue("UpdatedOn", null, KvOpertation.Now));
            SqlStatement sql = sb.ToSqlStatement(dc.Dialect, null);

            Assert.AreEqual("UPDATE [user] SET [UpdatedOn]=DATETIME(CURRENT_TIMESTAMP, 'localtime') ;\n", sql.SqlCommandText);
        }
Example #8
0
        public void ConstructorShouldHoldQueryableReference()
        {
            // Arrange
            IQueryable <TestClass> queryable = new List <TestClass>().AsQueryable();

            // Act
            var statementBuilder = new UpdateStatementBuilder <TestClass>(queryable);

            // Assert
            Assert.Same(queryable, statementBuilder.Queryable);
        }
Example #9
0
        public virtual SqlStatement GetUpdateStatement(Condition iwc, object obj)
        {
            var isv = new UpdateStatementBuilder(this.Context.Info.From);

            foreach (var property in obj.GetType().GetProperties())
            {
                isv.Values.Add(new KeyOpValue(property.Name, property.GetValue(obj, null), KvOpertation.None));
            }
            isv.Where.Conditions = iwc;
            return(isv.ToSqlStatement(this.Context));
        }
Example #10
0
 public override void AddColumn(ModelContext ctx, string columnName, object o)
 {
     base.AddColumn(ctx, columnName, null);
     if (o != null)
     {
         var stm = new UpdateStatementBuilder(ctx.Info.From);
         stm.Values.Add(new KeyOpValue(columnName, o, KvOpertation.None));
         var sql = stm.ToSqlStatement(ctx);
         ctx.Provider.ExecuteNonQuery(sql);
     }
 }
Example #11
0
        public void AppendMemberAssignmentThrowsArgumentNullExceptionWhenExpressionIsNull()
        {
            // Arrange
            IQueryable <TestClass> queryable = new List <TestClass>().AsQueryable();

            var statementBuilder = new UpdateStatementBuilder <TestClass>(queryable);

            // Act and Assert
            Assert.Throws <ArgumentNullException>(
                () => statementBuilder.AppendMemberAssignment(null)
                );
        }
Example #12
0
        public override void ProcessBelongsTo(UpdateStatementBuilder builder, MemberHandler m, object fk)
        {
            object v;

            if (_LoadedColumns.TryGetValue(m.Name, out v))
            {
                if (NotEqual(v, fk))
                {
                    base.ProcessBelongsTo(builder, m, fk);
                }
            }
        }
Example #13
0
        public override void ProcessSimpleMember(UpdateStatementBuilder builder, MemberHandler m, object n)
        {
            object v;

            if (_LoadedColumns.TryGetValue(m.Name, out v))
            {
                if (NotEqual(v, n))
                {
                    base.ProcessSimpleMember(builder, m, n);
                }
            }
        }
        private IStatementBuildProvider CreateProvider()
        {
            var selectStatementBuilder = new SelectStatementBuilder();
            var insertStatementBuilder = new InsertStatementBuilder();
            var updateStatementBuilder = new UpdateStatementBuilder();
            var conditionBuilder       = new ConditionBuilder();

            return(new SqlStatementBuildProvider(selectStatementBuilder,
                                                 insertStatementBuilder,
                                                 updateStatementBuilder,
                                                 conditionBuilder));
        }
Example #15
0
        public override void ProcessLazyLoad(UpdateStatementBuilder builder, MemberHandler m, object value, Type type)
        {
            object v;

            if (_LoadedColumns.TryGetValue(m.Name, out v))
            {
                if (!NotEqual(value, v))
                {
                    return;
                }
            }
            base.ProcessLazyLoad(builder, m, value, type);
        }
Example #16
0
        public bool FindUpdateColumns(DbObjectSmartUpdate model, UpdateStatementBuilder builder)
        {
            var autoList = new List <KeyOpValue> ();

            foreach (var m in model.Context.Info.Members)
            {
                if (m.Is.DbGenerate || m.Is.HasOne || m.Is.HasMany ||
                    m.Is.HasAndBelongsToMany || m.Is.CreatedOn || m.Is.Key)
                {
                    continue;
                }
                if (m.Is.Count)
                {
                    autoList.Add(new KeyOpValue(m.Name, 1, KvOpertation.Add));
                    continue;
                }
                if (m.Is.UpdatedOn || m.Is.SavedOn)
                {
                    autoList.Add(new KeyOpValue(m.Name, null, KvOpertation.Now));
                    continue;
                }
                if (m.Is.SimpleField)
                {
                    object n = m.GetValue(model);
                    ProcessSimpleMember(builder, m, n);
                }
                else if (m.Is.LazyLoad)
                {
                    var ll = (ILazyLoading)m.GetValue(model);
                    if (ll.IsLoaded)
                    {
                        var value = ll.Read();
                        var type  = m.MemberType.GetGenericArguments() [0];
                        ProcessLazyLoad(builder, m, value, type);
                    }
                }
                else if (m.Is.BelongsTo)
                {
                    var bt = (IBelongsTo)m.GetValue(model);
                    var fk = bt.ForeignKey;
                    ProcessBelongsTo(builder, m, fk);
                }
            }
            if (builder.Values.Count > 0)
            {
                builder.Values.AddRange(autoList);
                return(true);
            }
            return(false);
        }
Example #17
0
        public static int Update <T>(this UpdateStatementBuilder <T> updateBuilder) where T : class
        {
            IQueryable <T> queryable = updateBuilder.Queryable;

            // Resolve Service
            var serviceFactory = new ServiceFactory <T>(queryable);
            var commandService = serviceFactory.CreateCommandService();

            // Create & Execute Query
            var query = new UpdateStatement <T>(
                updateBuilder.Assignements,
                IQueryableHelper.GetQueryPredicate(queryable)
                );

            return(commandService.Update(query));
        }
Example #18
0
        public void AppendMemberAssignmentThrowsArgumentExceptionWhenMemberIsNotOfTheRightType()
        {
            // Arrange
            IQueryable <TestClass> queryable = new List <TestClass>().AsQueryable();

            var statementBuilder = new UpdateStatementBuilder <TestClass>(queryable);

            MemberAssignment assignment
                = Expression.Bind(
                      typeof(OtherClass).GetProperty(nameof(OtherClass.Id)),
                      Expression.Constant(3)
                      );

            // Act and Assert
            Assert.Throws <ArgumentException>(
                () => statementBuilder.AppendMemberAssignment(assignment)
                );
        }
Example #19
0
        public virtual SqlStatement GetUpdateStatement(object obj, Condition iwc)
        {
            var isv = new UpdateStatementBuilder(this.Context.Info.From);
            var o   = obj as DbObjectSmartUpdate;

            if (o != null)
            {
                if (!o.FindUpdateColumns(isv))
                {
                    return(null);
                }
            }
            else
            {
                this.Context.Handler.SetValuesForUpdate(isv, obj);
            }
            isv.Where.Conditions = iwc;
            return(isv.ToSqlStatement(this.Context));
        }
Example #20
0
        public void AppendMemberAssignmentThrowsInvalidOperationExceptionOnDuplicateMemberAssignement()
        {
            // Arrange
            IQueryable <TestClass> queryable = new List <TestClass>().AsQueryable();

            var statementBuilder = new UpdateStatementBuilder <TestClass>(queryable);

            MemberAssignment assignment
                = Expression.Bind(
                      typeof(TestClass).GetProperty(nameof(TestClass.Id)),
                      Expression.Constant(3)
                      );

            // Act and Assert
            statementBuilder.AppendMemberAssignment(assignment);
            Assert.Throws <InvalidOperationException>(
                () => statementBuilder.AppendMemberAssignment(assignment)
                );
        }
Example #21
0
        public static int Update <T>(this IQueryable <T> queryable, Expression <Func <T, T> > constructorExpression) where T : class
        {
            // Check & Cast parameters
            Check.NotNull(queryable, nameof(queryable));

            MemberInitExpression memberInit
                = constructorExpression.Body as MemberInitExpression
                  ?? throw new ArgumentException(nameof(constructorExpression), $"The body of the expression must be of type\"{typeof(MemberInitExpression).Name}\".");

            // Create statement
            var statementBuilder = new UpdateStatementBuilder <T>(queryable);

            foreach (MemberAssignment assignement in memberInit.Bindings)
            {
                statementBuilder.AppendMemberAssignment(assignement);
            }

            // Act
            return(Update <T>(statementBuilder));
        }
Example #22
0
        public void AppendMemberAssignmentShouldAppendAssignment()
        {
            // Arrange
            IQueryable <TestClass> queryable = new List <TestClass>().AsQueryable();

            var statementBuilder = new UpdateStatementBuilder <TestClass>(queryable);

            MemberAssignment assignment
                = Expression.Bind(
                      typeof(TestClass).GetProperty(nameof(TestClass.Id)),
                      Expression.Constant(3)
                      );

            // Act
            statementBuilder.AppendMemberAssignment(assignment);

            // Assert
            Assert.Single(statementBuilder.Assignements);
            Assert.Same(assignment, statementBuilder.Assignements.First());
        }
Example #23
0
        private int ProcessHasManyAndHasOne(IDbObject obj)
        {
            var result = 0;

            foreach (var member in Info.RelationMembers)
            {
                if (member.Is.HasMany || member.Is.HasOne)
                {
                    var t    = member.MemberInfo.MemberType.GetGenericArguments()[0];
                    var ctx0 = ModelContext.GetInstance(t);
                    ctx0.Operator.Fixer.TryFix();
                    var sb  = new UpdateStatementBuilder(ctx0.Info.From);
                    var key = ctx0.Info.GetBelongsTo(Info.HandleType).Name;
                    sb.Values.Add(new KeyOpValue(key, null, KvOpertation.None));
                    sb.Where.Conditions = CK.K[key] == Handler.GetKeyValue(obj);
                    var sql = sb.ToSqlStatement(ctx0);
                    result += ctx0.Provider.ExecuteNonQuery(sql);
                }
            }
            return(result);
        }
Example #24
0
        public IRelationalCommand Build <TEntity>(SqlStatementKind statementKind, IEntityModel model, TEntity entity, IEntityMapping entityMapping)
        {
            switch (statementKind)
            {
            case SqlStatementKind.CreateTable:

                ISqlStatementBuilder <CreateTableStatement> statementBuilder = new CreateTableStatementBuilder(model, entityMapping);

                ISqlStatement statement = statementBuilder.BuildStatement();

                return(new RelationalCommand(statement.GetText(), null));

            case SqlStatementKind.Insert:

                ISqlStatementBuilder <InsertStatement> insertStatementBuilder = new InsertStatementBuilder(entity, entityMapping);
                InsertStatement insertStatement = insertStatementBuilder.BuildStatement();

                return(new RelationalCommand(insertStatement.GetText(), insertStatement.Parameters));

            case SqlStatementKind.Update:

                ISqlStatementBuilder <UpdateStatement> updateStatementBuilder = new UpdateStatementBuilder(entity, entityMapping);
                UpdateStatement updateStatement = updateStatementBuilder.BuildStatement();

                return(new RelationalCommand(updateStatement.GetText(), updateStatement.Parameters));

            case SqlStatementKind.Delete:

                ISqlStatementBuilder <DeleteStatement> deleteStatementBuilder = new DeleteStatementBuilder(entity, entityMapping);
                DeleteStatement deleteStatement = deleteStatementBuilder.BuildStatement();

                return(new RelationalCommand(deleteStatement.GetText(), deleteStatement.Parameters));

            default:

                throw new NotImplementedException();
            }
        }
Example #25
0
        public void SetValueShouldAppendAssignment()
        {
            // Arrange
            IQueryable <TestClass> queryable = new List <TestClass>().AsQueryable();

            var statementBuilder = new UpdateStatementBuilder <TestClass>(queryable);

            // Act
            statementBuilder.SetValue(s => s.Id, 3);

            // Assert
            Assert.Single(statementBuilder.Assignements);

            MemberAssignment assignment = statementBuilder.Assignements.Single();

            Assert.Same(typeof(TestClass).GetProperty(nameof(TestClass.Id)), assignment.Member);
            Assert.IsAssignableFrom <ConstantExpression>(assignment.Expression);

            var constantExpression = assignment.Expression as ConstantExpression;

            Assert.IsType <int>(constantExpression.Value);
            Assert.Equal(3, constantExpression.Value);
        }
Example #26
0
        public void SetValueShouldAppendIncreaseAssignment()
        {
            // Arrange
            IQueryable <TestClass> queryable = new List <TestClass>().AsQueryable();

            var statementBuilder = new UpdateStatementBuilder <TestClass>(queryable);

            PropertyInfo propertyToAssign = typeof(TestClass).GetProperty(nameof(TestClass.Id));

            // Act
            statementBuilder.SetValue(s => s.Id, s => s.Id + 3);

            // Assert
            Assert.Single(statementBuilder.Assignements);

            MemberAssignment assignment = statementBuilder.Assignements.Single();

            Assert.Same(propertyToAssign, assignment.Member);
            Assert.IsAssignableFrom <BinaryExpression>(assignment.Expression);

            var binaryExpression = assignment.Expression as BinaryExpression;

            Assert.IsAssignableFrom <MemberExpression>(binaryExpression.Left);
            Assert.IsAssignableFrom <ConstantExpression>(binaryExpression.Right);

            var memberExpression = binaryExpression.Left as MemberExpression;

            Assert.Same(propertyToAssign, memberExpression.Member);

            Assert.Equal(ExpressionType.Add, binaryExpression.NodeType);

            var constantExpression = binaryExpression.Right as ConstantExpression;

            Assert.IsType <int>(constantExpression.Value);
            Assert.Equal(3, constantExpression.Value);
        }
Example #27
0
 internal protected bool FindUpdateColumns(UpdateStatementBuilder builder)
 {
     return(_updateHelper.FindUpdateColumns(this, builder));
 }
Example #28
0
 public virtual void ProcessBelongsTo(UpdateStatementBuilder builder, MemberHandler m, object fk)
 {
     builder.Values.Add(new KeyOpValue(m.Name, fk, fk == null ? typeof(long) : fk.GetType()));
 }
Example #29
0
 public virtual void ProcessLazyLoad(UpdateStatementBuilder builder, MemberHandler m, object value, Type type)
 {
     builder.Values.Add(new KeyOpValue(m.Name, value, type));
 }
Example #30
0
 public virtual void ProcessSimpleMember(UpdateStatementBuilder builder, MemberHandler m, object n)
 {
     builder.Values.Add(new KeyOpValue(m.Name, n, m.MemberType));
 }