Exemple #1
0
        /// <summary>
        /// Sets up the key columns for the schema.
        /// </summary>
        /// <param name="schema"></param>
        private void SetupKeyColumns(SqlSchema schema)
        {
            if (schema == null)
            {
                throw new ArgumentNullException("schema");
            }

            //	declare	@TableName varchar(128)
            //	select @TableName = 'dbttmtourinformation'
            //
            //	select  c.COLUMN_NAME
            //	from    INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk ,
            //		INFORMATION_SCHEMA.KEY_COLUMN_USAGE c
            //	where   pk.TABLE_NAME = @TableName
            //	and	CONSTRAINT_TYPE = 'PRIMARY KEY'
            //	and	c.TABLE_NAME = pk.TABLE_NAME
            //	and	c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME

            foreach (SqlTable table in schema.Tables)
            {
                // statement...
                SqlStatement statement = new SqlStatement(@"select c.COLUMN_NAME ColumnName from INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk, 
						INFORMATION_SCHEMA.KEY_COLUMN_USAGE c where pk.TABLE_NAME = @p0 and CONSTRAINT_TYPE = 'PRIMARY KEY'
						and c.TABLE_NAME = pk.TABLE_NAME	and c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME"                            , CommandType.Text,
                                                          new object[] { table.NativeName }, this.Dialect);

                // get...
                DataTable columns = this.ExecuteDataTable(statement);
                foreach (DataRow column in columns.Rows)
                {
                    // column...
                    string    columnName   = (string)column["ColumnName"];
                    SqlColumn schemaColumn = table.Columns[columnName];
                    if (schemaColumn != null)
                    {
                        schemaColumn.Flags |= EntityFieldFlags.Key;
                    }
                }

                // go again, this time with this to find the auto increment columns...
                //SELECT column_name, COLUMNPROPERTY(OBJECT_ID('actions'),column_name,'IsIdentity') as IsIdentity
                //	FROM information_schema.columns
                //	WHERE table_name='actions'
                statement = new SqlStatement(@"SELECT column_name ColumnName, COLUMNPROPERTY(OBJECT_ID(@p0),column_name,'IsIdentity') as IsIdentity,
				ORDINAL_POSITION Ordinal FROM information_schema.columns	WHERE table_name=@p0"                    , new object[] { table.NativeName }, this.Dialect);
                columns   = this.ExecuteDataTable(statement);
                foreach (DataRow column in columns.Rows)
                {
                    // get...
                    string    columnName   = (string)column["ColumnName"];
                    SqlColumn schemaColumn = table.Columns[columnName];

                    int  ordinal    = Convert.ToInt32(column["Ordinal"]);
                    bool isIdentity = Convert.ToBoolean(column["IsIdentity"]);
                    if (schemaColumn != null && isIdentity)
                    {
                        schemaColumn.Flags |= EntityFieldFlags.AutoIncrement;
                    }

                    if (schemaColumn != null)
                    {
                        schemaColumn.Ordinal = ordinal;
                    }
                }

                // Sort them
                table.Columns.SortByOrdinal();
            }
        }
Exemple #2
0
        /// <summary>
        /// Adds indexes to the schema.
        /// </summary>
        /// <param name="schema"></param>
        private void AddIndexesToSchema(SqlSchema schema)
        {
            if (schema == null)
            {
                throw new ArgumentNullException("schema");
            }

            foreach (SqlTable table in schema.Tables)
            {
                // create...
                SqlStatement statement = new SqlStatement("sp_MShelpindex", this.Dialect);
                statement.CommandType = CommandType.StoredProcedure;
                statement.Parameters.Add(new SqlStatementParameter("tablename", DbType.String, table.NativeName));
                statement.Parameters.Add(new SqlStatementParameter("indexname", DbType.String, DBNull.Value));
                statement.Parameters.Add(new SqlStatementParameter("flags", DbType.Int32, 1));

                // exec...
                DataTable indexes = this.ExecuteDataTable(statement);
                if (indexes == null)
                {
                    throw new InvalidOperationException("indexes is null.");
                }

                // walk...
                foreach (DataRow indexRow in indexes.Rows)
                {
                    // If we have a primary key
                    if ((((int)indexRow["status"]) & 2048) != 0)
                    {
                        continue;
                    }

                    // get the columns...
                    ArrayList columnNames = new ArrayList();
                    for (int index = 1; index <= 16; index++)
                    {
                        // name...
                        string indexColumnName = "indcol" + index.ToString();
                        if (indexRow.IsNull(indexColumnName) == false)
                        {
                            columnNames.Add(indexRow[indexColumnName]);
                        }
                    }

                    // any?
                    if (columnNames.Count > 0)
                    {
                        // create a new index...
                        SqlIndex index = new SqlIndex((string)indexRow["name"]);
                        table.Indexes.Add(index);

                        // mbr - 04-10-2007 - set owner...
                        index.SetSchema(schema);

                        // unique values?
                        int flags = (int)indexRow["status"];
                        if ((flags & 2) == 2)
                        {
                            index.HasUniqueValues = true;
                        }

                        // setup the columns...
                        foreach (string columnName in columnNames)
                        {
                            // find...
                            SqlColumn column = table.Columns[columnName];
                            if (column == null)
                            {
                                throw new InvalidOperationException(string.Format("Column '{0}' not found on table '{1}'.", column.NativeName, table.NativeName));
                            }

                            // add...
                            index.Columns.Add(column);
                        }

                        // mbr - 2011-11-02 we also need to do included columns...
                        AddIncludedColumns(table, index);
                    }
                }
            }
        }
Exemple #3
0
 /// <summary>
 /// Appends the column name for a field constraint.
 /// </summary>
 /// <param name="context"></param>
 /// <param name="statement"></param>
 /// <param name="builder"></param>
 /// <param name="field"></param>
 public virtual void AppendColumnNameForEntityFieldFilterConstraint(FilterConstraintAppendContext context,
                                                                    EntityFieldFilterConstraint constraint, SqlStatement statement, StringBuilder builder, EntityField field)
 {
     // defer...
     this.AddExtendedPropertyToSelectStatement(context.Creator, statement, builder, field);
 }
Exemple #4
0
 /// <summary>
 /// Append SQL to select the extended properties from the extended table for the entity
 /// </summary>
 /// <param name="statement"></param>
 /// <param name="builder"></param>
 /// <param name="field"></param>
 public abstract void AddExtendedPropertyToSelectStatement(SqlStatementCreator creator, SqlStatement statement, StringBuilder builder,
                                                           EntityField field);
Exemple #5
0
        /// <summary>
        /// Appends joins to the query.
        /// </summary>
        protected internal virtual void AppendJoin(SqlStatement statement, StringBuilder builder)
        {
            if (statement == null)
            {
                throw new ArgumentNullException("statement");
            }
            if (builder == null)
            {
                throw new ArgumentNullException("builder");
            }

            // create...
            if (this.Type == JoinType.InnerJoin)
            {
                builder.Append("INNER JOIN");
            }
            else if (this.Type == JoinType.LeftOuterJoin)
            {
                builder.Append("LEFT OUTER JOIN");
            }
            else if (this.Type == JoinType.RightOuterJoin)
            {
                builder.Append("RIGHT OUTER JOIN");
            }
            else
            {
                throw new NotSupportedException(string.Format("Join type '{0}' not supported.", this.Type));
            }
            builder.Append(" ");

            if (this.UseAlias)
            {
                builder.Append(statement.Dialect.FormatTableName(this.TargetEntityType.NativeName, this.Alias));
            }
            else
            {
                builder.Append(statement.Dialect.FormatTableName(this.TargetEntityType.NativeName));
            }

            builder.Append(" ON ");

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

            // target...
            EntityField[] targetKeyFields = this.TargetKeyFields;
            if (targetKeyFields == null)
            {
                throw new InvalidOperationException("targetKeyFields is null.");
            }
            if (sourceFields.Length != targetKeyFields.Length)
            {
                throw new InvalidOperationException(string.Format("Length mismatch for 'keyFields' and 'targetKeyFields': {0} cf {1}.", sourceFields.Length, targetKeyFields.Length));
            }

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

                // format...
                if (this.HasSourceAlias)
                {
                    builder.Append(statement.Dialect.FormatColumnName(sourceFields[index], this.SourceAlias));
                }
                else
                {
                    builder.Append(statement.Dialect.FormatColumnName(sourceFields[index], true));
                }
                builder.Append("=");

                if (this.UseAlias)
                {
                    builder.Append(statement.Dialect.FormatColumnName(targetKeyFields[index], this.Alias));
                }
                else
                {
                    builder.Append(statement.Dialect.FormatColumnName(targetKeyFields[index], true));
                }
            }
        }
Exemple #6
0
 /// <summary>
 /// Appends joins to the statement.
 /// </summary>
 /// <param name="statement"></param>
 /// <param name="builder"></param>
 public abstract void AppendJoinsToSelectStatement(SqlStatement statement, StringBuilder builder);
Exemple #7
0
        /// <summary>
        /// Executes key values for the filter.
        /// </summary>
        /// <param name="connection"></param>
        /// <returns></returns>
        // mbr - 26-11-2007 - for c7 - created this overload that accepts a connection.
        internal object[][] ExecuteKeyValues(IConnection connection)
        {
            // check...
            if (EntityType == null)
            {
                throw new InvalidOperationException("EntityType is null.");
            }

            // before?
            EntityField[] before = null;
            if (this.Fields.Count > 0)
            {
                before = this.Fields.ToArray();
            }

            try
            {
                // replace the fields...
                this.Fields.Clear();
                this.Fields.AddRange(this.EntityType.GetKeyFields());
                if (this.Fields.Count == 0)
                {
                    throw new InvalidOperationException(string.Format("'{0}' does not have any key fields.", this.EntityType));
                }

                // sql...
                SqlStatement sql = this.GetStatement();
                if (sql == null)
                {
                    throw new InvalidOperationException("sql is null.");
                }

                // mbr - 26-11-2007 - connection...
                bool disposeConnectionOnFinish = false;
                if (connection == null)
                {
                    // get...
                    connection = Database.CreateConnection(sql);
                    if (connection == null)
                    {
                        throw new InvalidOperationException("connection is null.");
                    }

                    // flag...
                    disposeConnectionOnFinish = true;
                }

                // run it...
                try
                {
                    // are we the right type?
                    if (!(connection is Connection))
                    {
                        throw new NotSupportedException(string.Format("Cannot handle '{0}'.", connection.GetType()));
                    }

                    // make sure we can open it...
                    ((Connection)connection).EnsureNativeConnectionOpen();

                    // command...
                    var command = connection.CreateCommand(sql);
                    try
                    {
                        using (IDataReader reader = command.ExecuteReader())
                        {
                            // walk...
                            ArrayList results = new ArrayList();
                            while (reader.Read())
                            {
                                object[] keys = new object[this.Fields.Count];
                                reader.GetValues(keys);

                                // add...
                                results.Add(keys);
                            }

                            // return...
                            return((object[][])results.ToArray(typeof(object[])));
                        }
                    }
                    catch (Exception ex)
                    {
                        throw ((Connection)connection).CreateCommandException("Failed to execute key values.", command, ex, null);
                    }
                    //finally
                    //{
                    //    if(command != null)
                    //    {
                    //        command.Dispose();
                    //        command = null;
                    //    }
                    //}
                }
                finally
                {
                    // mbr - 26-11-2007 - do we need to kill off the connection?
                    if (disposeConnectionOnFinish)
                    {
                        connection.Dispose();
                        connection = null;
                    }
                }
            }
            finally
            {
                // put it all back togehter...
                this.Fields.Clear();
                if (before != null)
                {
                    this.Fields.AddRange(before);
                }
            }
        }
        /// <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 });
        }
Exemple #9
0
 /// <summary>
 /// Adds constraints to the statement.
 /// </summary>
 /// <param name="statement"></param>
 /// <param name="builder"></param>
 // mbr - 25-09-2007 - made protected internal
 //		protected virtual void AppendConstraints(SqlStatement statement, StringBuilder builder)
 protected internal virtual void AppendConstraints(SqlStatement statement, StringBuilder builder)
 {
     // no-op...
 }
Exemple #10
0
        /// <summary>
        /// Creates a statement.
        /// </summary>
        /// <returns></returns>
        public override SqlStatement GetStatement()
        {
            if (EntityType == null)
            {
                throw new ArgumentNullException("EntityType");
            }

            // mbr - 16-10-2005 - changed so that inheriting classes can override default field inclusion behaviour...
            EntityField[] fields = this.ResolveFieldsForSelect();
            if (fields == null)
            {
                throw new ArgumentNullException("fields");
            }
            if (fields.Length == 0)
            {
                throw new InvalidOperationException("No fields selected.");
            }

            // create a statement...
            if (Dialect == null)
            {
                throw new ArgumentNullException("Dialect");
            }
            SqlStatement statement = new SqlStatement(this.EntityType, this.Dialect);

            if (this.TimeoutSeconds > 0)
            {
                statement.TimeoutSeconds = this.TimeoutSeconds;
            }

            // set...
            statement.SetOriginalCreator(this);

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

            // set up the basic select text...
            StringBuilder builder = new StringBuilder();

            builder.Append(statement.Dialect.SelectKeyword);

            // mbr - 2010-03-03 - added...
            if (this.Distinct)
            {
                builder.Append(" ");
                builder.Append(statement.Dialect.DistinctKeyword);
            }

            // top...
            if (this.Top > 0 && statement.Dialect.TopAtTop)
            {
                builder.Append(" ");
                builder.Append(statement.Dialect.FormatTop(this.Top));
            }

            // fields...
            builder.Append(" ");
            for (int index = 0; index < fields.Length; index++)
            {
                // add...
                if (index > 0)
                {
                    builder.Append(statement.Dialect.IdentifierSeparator);
                }

                // field...
                EntityField field = fields[index];
                if (field.IsExtendedProperty)
                {
                    // mbr - 25-09-2007 - provider...
                    //					AppendExtendedPropertyStatement(statement, builder, field);
                    if (Database.ExtensibilityProvider == null)
                    {
                        throw new InvalidOperationException("Database.ExtensibilityProvider is null.");
                    }
                    Database.ExtensibilityProvider.AddExtendedPropertyToSelectStatement(this, statement, builder, field);
                }
                else
                {
                    // mbr - 2008-09-11 - changed for MySQL support...
                    //					builder.Append(statement.Dialect.FormatColumnName(field, this.UseFullyQualifiedNames));
                    builder.Append(statement.Dialect.FormatColumnNameForSelect(field, this.UseFullyQualifiedNames));

                    // mbr - 10-10-2007 - case 875 - do nothing if we don't have a join...
                    if (field.EntityType == this.EntityType)
                    {
                        statement.SelectMap.MapFields.Add(new SelectMapField(field, index));
                    }
                    else
                    {
                        // find it!
                        SqlJoin found = null;
                        foreach (SqlJoin join in this.Joins)
                        {
                            if (join.TargetEntityType == field.EntityType)
                            {
                                found = join;
                                break;
                            }
                        }

                        // found?
                        if (found == null)
                        {
                            throw new InvalidOperationException(string.Format("Could not find a join for field '{0}'.", field));
                        }

                        // set...
                        statement.SelectMap.MapFields.Add(new SelectMapField(field, index, found));
                    }
                }
            }

            this.AppendIndent(builder);
            builder.Append(statement.Dialect.FromKeyword);
            builder.Append(" ");
            builder.Append(statement.Dialect.FormatTableName(this.EntityType.NativeName));

            if (this.HasForcedIndex)
            {
                builder.Append(" ");
                builder.Append(statement.Dialect.GetForceIndexDirective(this.ForcedIndex));
            }

            // mbr - 25-09-2007 - joins...
            this.AppendJoins(statement, builder);

            // get the contraints...
            StringBuilder constraints = new StringBuilder();

            this.AppendConstraints(statement, constraints);

            // trim...
            string useConstraints = constraints.ToString().Trim();

            //// mbr - 13-10-2005 - rejigged to handle partitioning...
            //// mbr - 08-03-2006 - added supports...
            // mbr - 2014-11-30 - removes partitioning...
            //if(!(this.IgnorePartitioning) && this.EntityType.SupportsPartitioning)
            //{
            //    // get the strategy....
            //    PartitioningStrategy strategy = this.EntityType.PartitioningStrategy;
            //    if(strategy == null)
            //        throw new InvalidOperationException("strategy is null.");

            //    // get the partition SQL...
            //    // mbr - 04-09-2007 - 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 - a zero-length string might be ok...
            //    if(useConstraints.Length == 0 && !(strategy.IsZeroLengthIdSetOk))
            //        throw new InvalidOperationException("'useConstraints' is zero-length.");
            //}

            // mbr - 2010-03-10 - added a method to allow us to change the statement before it is executed...
            if (Database.StatementCallback != null)
            {
                useConstraints = Database.StatementCallback.ReplaceContraints(statement, this, useConstraints);
            }

            // do we have constraints?
            if (useConstraints.Length > 0)
            {
                // just add the constraints...
                this.AppendIndent(builder);
                builder.Append(this.Dialect.WhereKeyword);
                builder.Append(" ");
                builder.Append(useConstraints);
            }

            // mbr - 2010-03-08 - if not distinct...
            ///if (this.SortOrder.Count > 0)
            //if ((!(this.Distinct) || this.ForceSortOnDistinct) && this.SortOrder.Count > 0)
            // mbr - 2016-08-17 -- no idea why this was like this...
            if (this.SortOrder.Count > 0)
            {
                // append...
                this.AppendIndent(builder);
                builder.Append(statement.Dialect.OrderByKeyword);
                builder.Append(" ");

                // add...
                for (int index = 0; index < this.SortOrder.Count; index++)
                {
                    if (index > 0)
                    {
                        builder.Append(statement.Dialect.IdentifierSeparator);
                    }

                    // spec...
                    SortSpecification specification = this.SortOrder[index];

                    // mbr - 10-10-2007 - case 875 - fixed to qualify...
                    //					builder.Append(statement.Dialect.FormatNativeName(specification.Field.NativeName));

                    if (specification.Field != null)
                    {
                        builder.Append(statement.Dialect.FormatColumnName(specification.Field, this.UseFullyQualifiedNames));
                    }
                    else
                    {
                        builder.Append(specification.FreeSort);
                    }

                    // direction?
                    builder.Append(" ");
                    builder.Append(statement.Dialect.GetSortDirectionKeyword(specification.Direction));
                }
            }

            // top...
            if (this.Top > 0 && !(statement.Dialect.TopAtTop))
            {
                this.AppendIndent(builder);
                builder.Append(statement.Dialect.FormatTop(this.Top));
            }

            if (this.SignalRecompile)
            {
                builder.Append(" OPTION(RECOMPILE)");
            }

            // setup...
            statement.CommandText = builder.ToString();
            statement.CommandType = CommandType.Text;

            // extras...
            statement.Parameters.AddRange(this.ExtraParameters);

            // return...
            return(statement);
        }
Exemple #11
0
 internal CommandCreatedEventArgs(IConnection connection, SqlStatement statement, IDbCommand command)
 {
     this.Connection = connection;
     this.Statement  = statement;
     this.Command    = command;
 }
Exemple #12
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 });
        }
Exemple #13
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 });
        }