示例#1
0
        /// <summary>
        /// Creates an Delete statement.
        /// </summary>
        /// <returns></returns>
        public override SqlStatement[] GetStatements(WorkUnitProcessingContext context)
        {
            if (EntityType == null)
            {
                throw new ArgumentNullException("EntityType");
            }
            if (Dialect == null)
            {
                throw new InvalidOperationException("Dialect is null.");
            }

            // create...
            SqlStatement statement = new SqlStatement(this.EntityType, this.Dialect);

            // sql...
            StringBuilder builder = new StringBuilder();
            EntityField   field   = null;

            field = GetExtendedFields()[0];             // This is the field being updated

            AppendInsertIntoExtendedTable(context, field, builder, statement);

            builder.Append(")");

            statement.CommandText = builder.ToString();
            return(new SqlStatement[] { statement });
        }
示例#2
0
        /// <summary>
        /// Creates a statement for this work unit.
        /// </summary>
        /// <param name="statements"></param>
        private SqlStatement CreateInsertStatement(WorkUnitProcessingContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            // check...
            if (EntityType == null)
            {
                throw new ArgumentNullException("EntityType");
            }

            // create...
            if (context.Connection == null)
            {
                throw new InvalidOperationException("context.Connection is null.");
            }
            if (context.Connection.Dialect == null)
            {
                throw new InvalidOperationException("context.Connection.Dialect is null.");
            }
            SqlStatement statement = new SqlStatement(this.EntityType, context.Connection.Dialect);

            // builder...
            StringBuilder builder = new StringBuilder();

            this.AppendInsertPortion(statement, builder);

            // set...
            statement.CommandText = builder.ToString();

            // return...
            return(statement);
        }
示例#3
0
        // mbr - 10-10-2007 - removed.
//		private SqlStatement GetSprocStatement(WorkUnitProcessingContext context)
//		{
//			// check...
//			if(EntityType == null)
//				throw new ArgumentNullException("EntityType");
//			if(Dialect == null)
//				throw new InvalidOperationException("Dialect is null.");
//
//			// create a statement...
//			SqlStatement statement = new SqlStatement(this.EntityType, this.Dialect);
//
//			// command text...
//			statement.CommandText = this.Dialect.FormatSprocName(SqlTable.SprocPrefix + "I" + this.EntityType.NativeName.Name);
//			statement.CommandType = CommandType.StoredProcedure;
//
//			// setup the parameters...
//			foreach(EntityField field in this.EntityType.Fields)
//			{
//				// create...
//				SqlStatementParameter parameter = this.CreateParameterForField(field, false, OnNotFound.ReturnNull);
//				statement.Parameters.Add(parameter);
//
//				// auto?
//				// mbr - 04-07-2007 - changed.
////				if(field.IsAutoIncrement())
//				if(field.IsAutoIncrement)
//					parameter.Direction = ParameterDirection.Output;
//			}
//
//			// return...
//			return statement;
//		}

        private SqlStatement GetAdhocStatement(WorkUnitProcessingContext context)
        {
            // check...
            if (EntityType == null)
            {
                throw new ArgumentNullException("EntityType");
            }
            if (Dialect == null)
            {
                throw new InvalidOperationException("Dialect is null.");
            }

            // create...
            SqlStatement statement = new SqlStatement(this.EntityType, this.Dialect);

            statement.OriginalWorkUnit = this;

            // command text...
            StringBuilder builder = new StringBuilder();

            this.AppendInsertPortion(statement, builder);
            if (context.Connection.SupportsMultiStatementQueries && context.Dialect.LastInsertedIdMode == LastInsertedIdMode.Scalar)
            {
                this.AppendSelectIdPortion(statement, builder);
            }

            // set...
            statement.CommandText = builder.ToString();

            // return...
            return(statement);
        }
示例#4
0
        /// <summary>
        /// Returns true if the extension row for the entity exists.
        /// </summary>
        /// <returns></returns>
        protected bool DoesExtendedRowExist(WorkUnitProcessingContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            // values...
            EntityField[] keyFields = this.EntityType.GetKeyFields();
            this.AssertKeyFields(keyFields);

            // values...
            object[] values = this.EntityType.Storage.GetKeyValues(this.Entity);
            if (values == null)
            {
                throw new InvalidOperationException("values is null.");
            }
            if (keyFields.Length != values.Length)
            {
                throw new InvalidOperationException(string.Format("Length mismatch for 'keyFields' and 'values': {0} cf {1}.", keyFields.Length, values.Length));
            }

            // sql...
            SqlStatement  sql     = new SqlStatement();
            StringBuilder builder = new StringBuilder();

            // builder...
            builder.Append("SELECT ");
            for (int index = 0; index < keyFields.Length; index++)
            {
                if (index > 0)
                {
                    builder.Append(", ");
                }
                builder.Append(sql.Dialect.FormatColumnName(
                                   ColumnPerFieldExtensibilityProvider.MangleIdColumnName(keyFields[index].NativeName)));
            }

            // from...
            builder.Append(" FROM ");
            builder.Append(sql.Dialect.FormatTableName(this.EntityType.NativeNameExtended));

            // values...
            this.AppendWhereClause(sql, builder, keyFields, values);

            // set...
            sql.CommandText = builder.ToString();

            // result...
            bool result = context.Connection.ExecuteExists(sql);

            return(result);
        }
        public override SqlStatement[] GetStatements(WorkUnitProcessingContext context)
        {
            // job one - find out if we have an item...
            bool exists = this.DoesExtendedRowExist(context);

            if (exists)
            {
                return(this.GetUpdateStatements(context));
            }
            else
            {
                return(this.GetInsertStatements(context));
            }
        }
示例#6
0
        /// <summary>
        /// Creates an Delete statement.
        /// </summary>
        /// <returns></returns>
        public override SqlStatement[] GetStatements(WorkUnitProcessingContext context)
        {
            if (EntityType == null)
            {
                throw new ArgumentNullException("EntityType");
            }
            if (Dialect == null)
            {
                throw new InvalidOperationException("Dialect is null.");
            }

            // create...
            SqlStatement  statement = new SqlStatement(this.EntityType, this.Dialect);
            StringBuilder builder   = new StringBuilder();

            // DELETE FROM ActivitesBFX WHERE
            builder.Append(statement.Dialect.DeleteFromKeyword);
            builder.Append(" ");
            // mbr - 08-12-2005 - changed...
            //			builder.Append(statement.Dialect.FormatNativeName(ExtendedPropertySettings.GetExtendedNativeNameForEntityType(EntityType)));
            builder.Append(statement.Dialect.FormatNativeName(this.EntityType.NativeNameExtended));
            builder.Append(" ");
            builder.Append(statement.Dialect.WhereKeyword);
            builder.Append(" ");
            AppendKeyFieldConstraints(builder, statement);

            // field name...
            if (FieldName == null)
            {
                throw new InvalidOperationException("'FieldName' is null.");
            }
            if (FieldName.Length == 0)
            {
                throw new InvalidOperationException("'FieldName' is zero-length.");
            }
            builder.Append(" AND ");
            builder.Append(statement.Dialect.FormatColumnName("Name"));
            builder.Append("=");
            builder.Append(statement.Dialect.FormatVariableNameForQueryText(statement.Parameters.Add(DbType.String, this.FieldName)));

            // set..
            statement.CommandText = builder.ToString();
            return(new SqlStatement[] { statement });
        }
示例#7
0
        /// <summary>
        /// Creates an Delete statement.
        /// </summary>
        /// <returns></returns>
        public override SqlStatement[] GetStatements(WorkUnitProcessingContext context)
        {
            if (EntityType == null)
            {
                throw new ArgumentNullException("EntityType");
            }

            // create...
            SqlStatement statement = new SqlStatement(this.EntityType, this.Dialect);

            // sql...
            StringBuilder builder = new StringBuilder();
            EntityField   field   = GetExtendedFields()[0];         // This is the field being updated

            // If we are doing an insert or update we must check to see if the field already exists
            builder.Append("IF ((");
            builder.Append(statement.Dialect.SelectKeyword);
            builder.Append(" COUNT(*) ");
            builder.Append(statement.Dialect.FromKeyword);
            builder.Append(" ");
            // mbr - 08-12-2005 - changed...
//			builder.Append(statement.Dialect.FormatNativeName(ExtendedPropertySettings.GetExtendedNativeNameForEntityType(EntityType)));
            builder.Append(statement.Dialect.FormatNativeName(this.EntityType.NativeNameExtended));
            builder.Append(" ");
            builder.Append(statement.Dialect.WhereKeyword);
            builder.Append(" ");

            AppendKeyFieldConstraints(builder, statement);
            AppendPropertyNameConstraint(field, builder, statement);

            builder.Append(" ) = 0)\r\n");

            base.AppendInsertIntoExtendedTable(context, field, builder, statement);

            builder.Append(")\r\n");
            builder.Append("ELSE\r\n");

            AppendUpdateExtendedTable(field, builder, statement);

            statement.CommandText = builder.ToString();
            return(new SqlStatement[] { statement });
        }
示例#8
0
        /// <summary>
        /// Processes the work unit.
        /// </summary>
        /// <param name="context"></param>
        public virtual void Process(WorkUnitProcessingContext context, ITimingBucket timings)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            // walk...
            SqlStatement[] statements = null;
            using (timings.GetTimer("GetStatements"))
                statements = this.GetStatements(context);

            using (timings.GetTimer("Execute"))
            {
                foreach (SqlStatement statement in statements)
                {
                    context.Connection.ExecuteNonQuery(statement);
                }
            }
        }
示例#9
0
        /// <summary>
        /// Executes the statement;
        /// </summary>
        /// <param name="context"></param>
        /// <param name="statement"></param>
        /// <returns></returns>
        private object[] Execute(WorkUnitProcessingContext context, SqlStatement statement)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (statement == null)
            {
                throw new ArgumentNullException("statement");
            }

            // check...
            if (context.Connection == null)
            {
                throw new InvalidOperationException("context.Connection is null.");
            }

            // run it...
            return(new object[] { context.Connection.ExecuteScalar(statement) });
        }
示例#10
0
        /// <summary>
        /// Creates a statement for this work unit.
        /// </summary>
        /// <param name="statements"></param>
        public override SqlStatement[] GetStatements(WorkUnitProcessingContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            //// check...
            //if (context.Connection == null)
            //    throw new InvalidOperationException("context.Connection is null.");
            //switch (context.Connection.SqlMode)
            //{
            //    case SqlMode.AdHoc:
            return(new SqlStatement[] { GetAdhocStatement(context) });

            // mbr - 10-10-2007 - removed.
            //				case SqlMode.Sprocs:
            //					return new SqlStatement[] { GetSprocStatement(context) };

            //    default:
            //        throw new NotSupportedException(string.Format("Cannot handle '{0}' ({1}).", context.Connection.SqlMode, context.Connection.SqlMode.GetType()));
            //}
        }
示例#11
0
        public override SqlStatement[] GetStatements(WorkUnitProcessingContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            // get...
            EntityField[] keyFields = this.EntityType.GetKeyFields();
            this.AssertKeyFields(keyFields);

            // key values...
            object[] keyValues = this.EntityType.Storage.GetKeyValues(this.Entity);
            if (keyValues == null)
            {
                throw new InvalidOperationException("keyValues is null.");
            }
            if (keyFields.Length != keyValues.Length)
            {
                throw new InvalidOperationException(string.Format("Length mismatch for 'keyFields' and 'keyValues': {0} cf {1}.", keyFields.Length, keyValues.Length));
            }

            // delete...
            SqlStatement  sql     = new SqlStatement();
            StringBuilder builder = new StringBuilder();

            // create...
            builder.Append("DELETE FROM ");
            builder.Append(sql.Dialect.FormatTableName(this.EntityType.NativeNameExtended));
            this.AppendWhereClause(sql, builder, keyFields, keyValues);

            // set...
            sql.CommandText = builder.ToString();

            // return...
            return(new SqlStatement[] { sql });
        }
示例#12
0
        /// <summary>
        /// Creates an Delete statement.
        /// </summary>
        /// <returns></returns>
        public override SqlStatement[] GetStatements(WorkUnitProcessingContext context)
        {
            // check...
            if (EntityType == null)
            {
                throw new ArgumentNullException("EntityType");
            }
            if (Dialect == null)
            {
                throw new InvalidOperationException("Dialect is null.");
            }

            // mbr - 25-04-2007 - added touched...
            TouchedValueCollection block = this.AddTouchedValueBlock();

            if (block == null)
            {
                throw new InvalidOperationException("block is null.");
            }

            // create...
            SqlStatement statement = new SqlStatement(this.EntityType, this.Dialect);

            statement.OriginalWorkUnit = this;

            // sql...
            StringBuilder builder = new StringBuilder();

            builder.Append(statement.Dialect.UpdateKeyword);
            builder.Append(" ");
            builder.Append(statement.Dialect.FormatNativeName(this.EntityType.NativeName));
            builder.Append(" ");
            builder.Append(statement.Dialect.SetKeyword);
            builder.Append(" ");

            // do the non-key fields...
            EntityField[] fields = this.GetNonAutoIncrementFields();
            if (fields.Length == 0)
            {
                throw new InvalidOperationException("Non-key fields are zero length.");
            }

            // walk...
            int fieldCount = 0;

            for (int index = 0; index < fields.Length; index++)
            {
                // create a parameter...
                SqlStatementParameter parameter = this.CreateParameterForField(fields[index]);
                statement.Parameters.Add(parameter);
                parameter.RelatedField = fields[index];

                // mbr - 25-04-2007 - added touched...
                object originalValue = null;
                if (this.Entity is Entity && ((Entity)this.Entity).GetOriginalValue(fields[index], ref originalValue))
                {
                    block.Add(new TouchedValue(fields[index], originalValue, parameter.Value));
                }

                // add...
                if (fieldCount > 0)
                {
                    builder.Append(",");
                }
                builder.Append(statement.Dialect.FormatNativeName(fields[index].NativeName));
                builder.Append("=");
                builder.Append(statement.Dialect.FormatVariableNameForQueryText(parameter.Name));

                fieldCount++;
            }

            // where...
            builder.Append(" ");
            builder.Append(statement.Dialect.WhereKeyword);
            builder.Append(" ");

            // key...
            fields = this.GetKeyFields();
            if (fields.Length == 0)
            {
                throw new InvalidOperationException("Key fields are zero length.");
            }

            // walk...
            StringBuilder constraints = new StringBuilder();

            for (int index = 0; index < fields.Length; index++)
            {
                // param...
                SqlStatementParameter parameter = this.CreateParameterForField(fields[index]);
                statement.Parameters.Add(parameter);
                parameter.RelatedField = fields[index];

                // add...
                if (index > 0)
                {
                    constraints.Append(" ");
                    constraints.Append(statement.Dialect.AndKeyword);
                    constraints.Append(" ");
                }
                constraints.Append(statement.Dialect.FormatNativeName(fields[index].NativeName));
                constraints.Append("=");
                constraints.Append(statement.Dialect.FormatVariableNameForQueryText(parameter.Name));
            }

            // mbr - 13-10-2005 - rejigged to handle partitioning...
            string useConstraints = constraints.ToString();

            //if(this.EntityType.SupportsPartitioning)
            //{
            //    // get the strategy....
            //    PartitioningStrategy strategy = this.EntityType.PartitioningStrategy;
            //    if(strategy == null)
            //        throw new InvalidOperationException("strategy is null.");

            //    // mbr - 04-09-2007 - for c7 - need to be able to skip the the constraint check...
            //    if(strategy.ConstrainUpdateQuery)
            //    {
            //        // get the partition SQL...  (yes, this is for read, not for write.  for write really means 'for insert'.)
            //        // mbr - 04-09-2007 - for c7 - removed 'forReading'.
            //        //				useConstraints = strategy.RebuildConstraints(statement, useConstraints, true);
            //        useConstraints = strategy.RebuildConstraints(statement, useConstraints);

            //        // we have to get something back...
            //        if(useConstraints == null)
            //            throw new InvalidOperationException("'useConstraints' is null.");

            //        // mbr - 04-09-2007 - for c7 - zero-length can be ok.
            //        if(useConstraints.Length == 0 && !(strategy.IsZeroLengthIdSetOk))
            //            throw new InvalidOperationException("'useConstraints' is zero-length.");
            //    }
            //}

            // append...
            builder.Append(useConstraints);

            // return...
            statement.CommandText = builder.ToString();
            return(new SqlStatement[] { statement });
        }
示例#13
0
 /// <summary>
 /// Gets the statement that will execute the unit.
 /// </summary>
 /// <param name="connection"></param>
 /// <returns></returns>
 public abstract SqlStatement[] GetStatements(WorkUnitProcessingContext context);
示例#14
0
 public override SqlStatement[] GetStatements(WorkUnitProcessingContext context)
 {
     return(this.GetInsertStatements(context));
 }
示例#15
0
        /// <summary>
        /// Append insert into extended table
        /// </summary>
        /// <param name="context"></param>
        /// <param name="extendedField"></param>
        /// <param name="builder"></param>
        /// <param name="statement"></param>
        protected void AppendInsertIntoExtendedTable(WorkUnitProcessingContext context, EntityField extendedField, StringBuilder builder, SqlStatement statement)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            EntityField[] keyFields = GetKeyFields();

            string propertyName          = AddPropertyNameParameter(extendedField, statement);
            string propertyNameParameter = FlatTableExtensibilityProvider.AddNameParameter(extendedField, statement);

            // Append the inssert statements
            builder.Append(statement.Dialect.InsertIntoKeyword);
            builder.Append(" ");
            // mbr - 08-12-2005 - changed...
//			builder.Append(statement.Dialect.FormatNativeName(ExtendedPropertySettings.GetExtendedNativeNameForEntityType(EntityType)));
            builder.Append(statement.Dialect.FormatNativeName(this.EntityType.NativeNameExtended));
            builder.Append(" (");
            builder.Append(statement.Dialect.FormatNativeName(FlatTableExtensibilityProvider.GetColumnNameForDbType(extendedField.DBType)));
            builder.Append(statement.Dialect.IdentifierSeparator);
            builder.Append(statement.Dialect.FormatNativeName(ExtendedPropertySettings.GetExtendedNativeNameForNameColumn()));

            for (int index = 0; index < keyFields.Length; index++)
            {
                builder.Append(statement.Dialect.IdentifierSeparator);
                builder.Append(statement.Dialect.FormatNativeName(keyFields[index].NativeName));
            }

            builder.Append(") ");
            builder.Append(statement.Dialect.ValuesKeyword);
            builder.Append(" (");

            // create the param...

            builder.Append(statement.Dialect.FormatVariableNameForQueryText(propertyName));
            builder.Append(statement.Dialect.IdentifierSeparator);
            builder.Append(statement.Dialect.FormatVariableNameForQueryText(propertyNameParameter));

            for (int index = 0; index < keyFields.Length; index++)
            {
                // create the param...
                SqlStatementParameter param = null;
                if (!statement.Parameters.Contains(keyFields[index].NativeName.Name))
                {
                    AddPropertyNameParameter(keyFields[index], statement);
                }

                // Get the parameter
                param = statement.Parameters[keyFields[index].Name];

                // We need to get the id of the field if it is auto generated from the context
                if (context.Bag.LastCreatedId != null)
                {
                    param.Value = context.Bag.LastCreatedId;
                }

                // add...
                builder.Append(statement.Dialect.IdentifierSeparator);
                builder.Append(statement.Dialect.FormatVariableNameForQueryText(param.Name));
            }
        }
示例#16
0
        /// <summary>
        /// Gets the statements to do an insert.
        /// </summary>
        /// <returns></returns>
        protected SqlStatement[] GetInsertStatements(WorkUnitProcessingContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            // check...
            if (EntityType == null)
            {
                throw new InvalidOperationException("EntityType is null.");
            }

            // keys...
            EntityField[] keyFields = this.EntityType.GetKeyFields();
            AssertKeyFields(keyFields);

            // key values...
            object[] keyValues = this.EntityType.Storage.GetKeyValues(this.Entity);
            if (keyValues == null)
            {
                throw new InvalidOperationException("keyValues is null.");
            }
            if (keyFields.Length != keyValues.Length)
            {
                throw new InvalidOperationException(string.Format("Length mismatch for 'keyFields' and 'keyValues': {0} cf {1}.", keyFields.Length, keyValues.Length));
            }

            // fields...
            EntityField[] fields = this.GetFields();
            if (fields == null)
            {
                throw new InvalidOperationException("'fields' is null.");
            }
            if (fields.Length == 0)
            {
                throw new InvalidOperationException("'fields' is zero-length.");
            }

            // values...
            object[] values = this.GetValues();
            if (values == null)
            {
                throw new InvalidOperationException("values is null.");
            }
            if (fields.Length != values.Length)
            {
                throw new InvalidOperationException(string.Format("Length mismatch for 'fields' and 'values': {0} cf {1}.", fields.Length, values.Length));
            }

            // fields...
            ArrayList allFields = new ArrayList();

            allFields.AddRange(keyFields);
            allFields.AddRange(fields);

            // values...
            ArrayList allValues = new ArrayList();

            allValues.AddRange(keyValues);
            allValues.AddRange(values);

            // setup...
            SqlStatement  sql     = new SqlStatement();
            StringBuilder builder = new StringBuilder();

            // get...
            builder.Append(sql.Dialect.InsertIntoKeyword);
            builder.Append(" ");
            builder.Append(sql.Dialect.FormatTableName(this.EntityType.NativeNameExtended));
            builder.Append(" (");
            for (int index = 0; index < allFields.Count; index++)
            {
                if (index > 0)
                {
                    builder.Append(", ");
                }

                // field...
                EntityField field = (EntityField)allFields[index];

                // key?
                if (field.IsKey())
                {
                    builder.Append(sql.Dialect.FormatColumnName(ColumnPerFieldExtensibilityProvider.MangleIdColumnName(field.NativeName)));
                }
                else
                {
                    builder.Append(sql.Dialect.FormatColumnName(field.NativeName));
                }
            }
            builder.Append(") ");
            builder.Append(sql.Dialect.ValuesKeyword);
            builder.Append(" (");
            for (int index = 0; index < allFields.Count; index++)
            {
                if (index > 0)
                {
                    builder.Append(", ");
                }

                // value...
                object value = allValues[index];

                // mbr - 10-10-2007 - for c7 - before we wouldn't have had a reconciled value here, but now that the
                // reconciliation step has moved, we do.
                EntityField field = (EntityField)allFields[index];
//				if(field.IsKey())
//					value = context.Bag.LastCreatedId;
//				else if(value == null)
//					value = DBNull.Value;
                if (value == null)
                {
                    value = DBNull.Value;
                }

                // add...
                builder.Append(sql.Dialect.FormatVariableNameForQueryText(sql.Parameters.Add(field.DBType, value)));
            }
            builder.Append(")");

            // return...
            sql.CommandText = builder.ToString();
            return(new SqlStatement[] { sql });
        }
示例#17
0
        /// <summary>
        /// Processes the work unit.
        /// </summary>
        /// <param name="context"></param>
        public override void Process(WorkUnitProcessingContext context, ITimingBucket timings)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            // check...
            if (EntityType == null)
            {
                throw new ArgumentNullException("EntityType");
            }
            if (context.Connection == null)
            {
                throw new InvalidOperationException("context.Connection is null.");
            }

            // insert...
            SqlStatement[] statements = null;
            using (timings.GetTimer("GetStatements"))
            {
                statements = this.GetStatements(context);
                if (statements == null)
                {
                    throw new InvalidOperationException("'statements' is null.");
                }
                if (statements.Length == 0)
                {
                    throw new InvalidOperationException("'statements' is zero-length.");
                }
            }

            // get...
            SqlStatement statement = statements[0];

            if (statement == null)
            {
                throw new InvalidOperationException("statement is null.");
            }

            // run it...
            object[] result = null;

            // mbr - 27-10-2005 - if we're sproc mode, get the result differently...
            if (context.Connection.SqlMode == SqlMode.AdHoc)
            {
                if (context.Connection.SupportsMultiStatementQueries)
                {
                    // debug?
                    using (timings.GetTimer("SingletonExecute"))
                        result = this.Execute(context, statement);
                }
                else
                {
                    using (timings.GetTimer("MultipleExecutes"))
                    {
                        // run...
                        context.Connection.ExecuteNonQuery(statement);

                        // id...
                        if (context.Dialect.LastInsertedIdMode == LastInsertedIdMode.Scalar)
                        {
                            statement = this.CreateSelectIdStatement(context);
                            if (statement == null)
                            {
                                throw new InvalidOperationException("statement is null.");
                            }

                            // run...
                            result = new object[] { context.Connection.ExecuteScalar(statement) };
                        }
                        else if (context.Dialect.LastInsertedIdMode == LastInsertedIdMode.Parameter)
                        {
                            EntityField[] autos = this.GetAutoIncrementFields();
                            if (autos == null)
                            {
                                throw new InvalidOperationException("'autos' is null.");
                            }
                            if (autos.Length == 0)
                            {
                                throw new InvalidOperationException("'autos' is zero-length.");
                            }

                            SqlStatementParameter parameter = statement.Parameters[context.Dialect.LastInsertedIdVariableName];
                            if (parameter == null)
                            {
                                throw new InvalidOperationException("parameter is null.");
                            }

                            // run...
                            result = new object[] { parameter.Value };
                        }
                        else
                        {
                            throw new NotSupportedException(string.Format("Cannot handle {0}.", context.Dialect.LastInsertedIdMode));
                        }
                    }
                }
            }
            // mbr - 10-10-2007 - removed.
//			else if(context.Connection.SqlMode == SqlMode.Sprocs)
//			{
//				// run it...
//				context.Connection.ExecuteNonQuery(statement);
//
//				// get the return parameter...
//				EntityField[] autoFields = this.EntityType.GetAutoIncrementFields();
//				if(autoFields == null)
//					throw new InvalidOperationException("autoFields is null.");
//				if(autoFields.Length == 1)
//				{
//					// find it...
//					SqlStatementParameter parameter = statement.Parameters[autoFields[0].NativeName.Name];
//					if(parameter == null)
//						throw new InvalidOperationException("parameter is null.");
//
//					// return...
//					result = new object[] { parameter.Value };
//				}
//				else if(autoFields.Length > 1)
//					throw new NotSupportedException(string.Format("Tables with '{0}' auto-increment fields are not supported.", autoFields.Length));
//			}
            else
            {
                throw new NotSupportedException(string.Format("Cannot handle '{0}'.", context.Connection.SqlMode));
            }

            // set...
            using (timings.GetTimer("Passback"))
            {
                if (result != null)
                {
                    context.Bag.LastCreatedId = result[0];
                }
            }
        }
        /// <summary>
        /// Gets the statements to update data in the related table.
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private SqlStatement[] GetUpdateStatements(WorkUnitProcessingContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            // key fields...
            EntityField[] keyFields = this.EntityType.GetKeyFields();
            this.AssertKeyFields(keyFields);

            // key values...
            object[] keyValues = this.EntityType.Storage.GetKeyValues(this.Entity);
            if (keyValues == null)
            {
                throw new InvalidOperationException("keyValues is null.");
            }
            if (keyFields.Length != keyValues.Length)
            {
                throw new InvalidOperationException(string.Format("Length mismatch for 'keyFields' and 'keyValues': {0} cf {1}.", keyFields.Length, keyValues.Length));
            }

            // fields...
            EntityField[] fields = this.GetFields();
            if (fields == null)
            {
                throw new InvalidOperationException("'fields' is null.");
            }
            if (fields.Length == 0)
            {
                throw new InvalidOperationException("'fields' is zero-length.");
            }

            // values...
            object[] values = this.GetValues();
            if (values == null)
            {
                throw new InvalidOperationException("values is null.");
            }
            if (fields.Length != values.Length)
            {
                throw new InvalidOperationException(string.Format("Length mismatch for 'fields' and 'values': {0} cf {1}.", fields.Length, values.Length));
            }

            // sql...
            SqlStatement  sql     = new SqlStatement();
            StringBuilder builder = new StringBuilder();

            // update...
            builder.Append("UPDATE ");
            builder.Append(sql.Dialect.FormatTableName(this.EntityType.NativeNameExtended));
            builder.Append(" SET ");

            // values...
            for (int index = 0; index < fields.Length; index++)
            {
                if (index > 0)
                {
                    builder.Append(", ");
                }

                // add...
                builder.Append(sql.Dialect.FormatColumnName(fields[index].NativeName));
                builder.Append("=");

                // value...
                object value = values[index];
                if (value == null)
                {
                    value = DBNull.Value;
                }

                // add...
                builder.Append(sql.Dialect.FormatVariableNameForQueryText(sql.Parameters.Add(fields[index].DBType, value)));
            }

            // where...
            this.AppendWhereClause(sql, builder, keyFields, keyValues);

            // set...
            sql.CommandText = builder.ToString();

            // run...
            return(new SqlStatement[] { sql });
        }
示例#19
0
        /// <summary>
        /// Processes the given work units.
        /// </summary>
        /// <param name="units"></param>
        public void Process(WorkUnitCollection units, bool trace = false, IOperationItem operation = null, bool outsideTransaction = false, ITimingBucket timings = null)
        {
            if (units == null)
            {
                throw new ArgumentNullException("units");
            }
            if (units.Count == 0)
            {
                return;
            }

            // operation...
            if (timings == null)
            {
                timings = NullTimingBucket.Instance;
            }
            if (operation == null)
            {
                operation = NullOperationItem.Instance;
            }

            // mbr - 02-10-2007 - case 827 - notify outside...
            // mbr - 2014-11-30 - changed this to load up the statements...
            var touchedEts          = new List <EntityType>();
            var anyNeedsTransaction = units.Count > 1;
            var context             = new WorkUnitProcessingContext(timings);

            using (timings.GetTimer("Count"))
            {
                foreach (IWorkUnit unit in units)
                {
                    ISaveChangesNotification notification = unit.Entity as ISaveChangesNotification;
                    if (notification != null)
                    {
                        notification.BeforeSaveChangesOutTransaction(unit);
                    }

                    // add...
                    if (!(touchedEts.Contains(unit.EntityType)))
                    {
                        touchedEts.Add(unit.EntityType);
                    }

                    // add...
                    if (unit.NeedsTransaction && !(anyNeedsTransaction))
                    {
                        anyNeedsTransaction = true;
                    }
                }
            }

            // mbr - 26-11-2007 - get a manager for this thread...
            IWorkUnitTransactionManager manager = null;

            using (timings.GetTimer("Initialize manager"))
            {
                if (outsideTransaction)
                {
                    manager = new OutsideTransactionWorkUnitProcessorTransactionManager();
                }
                else
                {
                    //manager = WorkUnitProcessorTransactionManager.Current;

                    // mbr - 2014-11-30 - we only want to use transactions if we are in a tranaction. the old
                    // approach created a transaction just for single row inserts, which turned out created
                    // quite a slowdown...
                    if (anyNeedsTransaction)
                    {
                        manager = WorkUnitProcessorTransactionManager.Current;
                    }
                    else
                    {
                        manager = WorkUnitProcessorNullTransactionManager.Current;
                    }
                }
                if (manager == null)
                {
                    throw new InvalidOperationException("manager is null.");
                }

                // initialise the manager...
                manager.Initialize();
            }

            try
            {
                // mbr - 26-11-2007 - now done in the manager...
//				if(connection == null)
//					connection = Database.CreateConnection(units[0].EntityType.DatabaseName);

                // mbr - 26-11-2007 - don't do transactions here (the manager will do it)...
//				connection.BeginTransaction();
                try
                {
                    // reset the bag...
                    using (timings.GetTimer("Reset"))
                        context.ResetBag();

                    // run...
                    operation.ProgressMaximum = units.Count;
                    operation.ProgressValue   = 0;

                    // mbr - 06-09-2007 - for c7 - the "before" event can replace the work unit.  (done by changing the entity and regenerating.)
                    //foreach(IWorkUnit unit in units)
                    for (int index = 0; index < units.Count; index++)
                    {
                        using (var child = timings.GetChildBucket("Execute"))
                        {
                            // get a connection to use here...
                            IConnection connection = null;
                            using (child.GetTimer("Connect"))
                            {
                                connection = manager.GetConnection(units[index]);
                                if (connection == null)
                                {
                                    throw new InvalidOperationException("connection is null.");
                                }

                                // set...
                                context.SetConnection(connection);
                            }

                            // get the unit...
                            IWorkUnit unit = units[index];
                            try
                            {
                                if (trace)
                                {
                                    this.LogInfo(() => string.Format("Running unit '{0}'...", unit));
                                }

                                ISaveChangesNotification notification = unit.Entity as ISaveChangesNotification;
                                using (child.GetTimer("NotifyPre"))
                                {
                                    // before...
                                    if (notification != null)
                                    {
                                        // mbr - 02-10-2007 - case 827 - changed interface.
                                        //								IWorkUnit newUnit = notification.BeforeSaveChanges(unit);
                                        IWorkUnit newUnit = notification.BeforeSaveChangesInTransaction(unit, connection);

                                        // patch it..
                                        if (newUnit != unit)
                                        {
                                            units[index] = newUnit;
                                            unit         = newUnit;
                                        }
                                    }
                                }

                                // run it...
                                using (var childChild = child.GetChildBucket("Process"))
                                    unit.Process(context, childChild);

                                // set...
                                using (child.GetTimer("Results"))
                                    unit.SetResultsBag(context.Bag);

                                // mbr - 10-10-2007 - for c7 - do reconciliation here...
                                using (child.GetTimer("Reconcile"))
                                {
                                    WorkUnitCollection forReconciliation = new WorkUnitCollection();
                                    forReconciliation.Add(unit);
                                    unit.EntityType.Persistence.ReconcileWorkUnitProcessorResults(forReconciliation);
                                }

                                // mbr - 02-10-2007 - case 827 - call...
                                using (child.GetTimer("NotifyPost"))
                                {
                                    if (notification != null)
                                    {
                                        notification.AfterSaveChangesInTransaction(unit, connection);
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                throw new InvalidOperationException(string.Format(Cultures.Exceptions, "Failed when processing '{0}'.", unit), ex);
                            }

                            // next...
                            operation.IncrementProgress();
                        }
                    }

                    // mbr - 26-11-2007 - it's the manager that needs to commit...
//					connection.Commit();

                    using (timings.GetTimer("Commit"))
                        manager.Commit();
                }
                catch (Exception ex)
                {
                    // rollback...
                    try
                    {
                        // mbr - 26-11-2007 - it's the manager that needs to rollback...
//						connection.Rollback();
                        manager.Rollback(ex);
                    }
                    catch (Exception rollbackEx)
                    {
                        // mbr - 26-11-2007 - added.
                        if (this.Log.IsWarnEnabled)
                        {
                            this.Log.Warn("A further exception occurred whilst rolling back the transaction.", rollbackEx);
                        }
                    }

                    // throw...
                    throw new InvalidOperationException("Failed to process work units.", ex);
                }
            }
            finally
            {
                // mbr - 26-11-2007 - get the manager to tear down...
//				if(connection != null)
//					connection.Dispose();
                using (timings.GetTimer("Dispose"))
                    manager.Dispose();

                // mbr - 2010-04-19 - invalidate the caches...
                //EntityCache.Invalidate(touchedEts);

                // flag...
                foreach (IWorkUnit unit in units)
                {
                    ISaveChangesNotification notification = unit.Entity as ISaveChangesNotification;
                    if (notification != null)
                    {
                        notification.AfterSaveChangesOutTransaction(unit);
                    }
                }
            }
        }
示例#20
0
        /// <summary>
        /// Creates an Delete statement.
        /// </summary>
        /// <returns></returns>
        public override SqlStatement[] GetStatements(WorkUnitProcessingContext context)
        {
            // check...
            if (EntityType == null)
            {
                throw new ArgumentNullException("EntityType");
            }

            // create...
            SqlStatement statement = new SqlStatement(this.EntityType, this.Dialect);

            statement.OriginalWorkUnit = this;

            // sql...
            StringBuilder builder = new StringBuilder();

            builder.Append(statement.Dialect.DeleteFromKeyword);
            builder.Append(" ");
            builder.Append(statement.Dialect.FormatNativeName(this.EntityType.NativeName));
            builder.Append(" ");
            builder.Append(statement.Dialect.WhereKeyword);
            builder.Append(" ");

            // mbr - 13-10-2005 - rejigged to support partitioning...
            StringBuilder constraints = new StringBuilder();

            // key...
            EntityField[] fields = this.GetKeyFields();
            if (fields.Length == 0)
            {
                throw new InvalidOperationException("Key fields are zero length.");
            }

            // walk...
            for (int index = 0; index < fields.Length; index++)
            {
                // param...
                SqlStatementParameter parameter = this.CreateParameterForField(fields[index]);
                statement.Parameters.Add(parameter);

                // add...
                if (index > 0)
                {
                    constraints.Append(" ");
                    constraints.Append(statement.Dialect.AndKeyword);
                    constraints.Append(" ");
                }
                constraints.Append(statement.Dialect.FormatNativeName(fields[index].NativeName));
                constraints.Append("=");
                constraints.Append(statement.Dialect.FormatVariableNameForQueryText(parameter.Name));
            }

            // mbr - 13-10-2005 - rejigged to handle partitioning...
            string useConstraints = constraints.ToString();

            //if (this.EntityType.SupportsPartitioning)
            //{
            //    // get the strategy....
            //    PartitioningStrategy strategy = this.EntityType.PartitioningStrategy;
            //    if (strategy == null)
            //        throw new InvalidOperationException("strategy is null.");

            //    // mbr - 04-09-2007 - for c7 - can skip...
            //    if (strategy.ConstrianDeleteQuery)
            //    {
            //        // get the partition SQL...  (yes, this is for read, not for write.  for write really means 'for insert'.)
            //        // mbr - 04-09-2007 - for c7 - removed 'forReading'.
            //        //				useConstraints = strategy.RebuildConstraints(statement, useConstraints, true);
            //        useConstraints = strategy.RebuildConstraints(statement, useConstraints);

            //        // we have to get something back...
            //        if (useConstraints == null)
            //            throw new InvalidOperationException("'useConstraints' is null.");

            //        // mbr - 04-09-2007 - for c7 - zero length can be ok...
            //        if (useConstraints.Length == 0 && !(strategy.IsZeroLengthIdSetOk))
            //            throw new InvalidOperationException("'useConstraints' is zero-length.");
            //    }
            //}

            // append...
            builder.Append(useConstraints);

            // return...
            statement.CommandText = builder.ToString();
            return(new SqlStatement[] { statement });
        }