Beispiel #1
0
 public NativeRowMap(Schema.Key key, Dictionary <String, Schema.Sort> equalitySorts, Schema.RowType keyRowType, Schema.RowType dataRowType) : base(keyRowType, dataRowType)
 {
     _key = key;
     _equalityComparer = new NativeRowMapEqualityComparer(this);
     _rows             = new Dictionary <NativeRow, NativeRow>(_equalityComparer);
     _equalitySorts    = equalitySorts;
 }
Beispiel #2
0
        protected override DataTable[] FillSchema
        (
            System.Data.DataSet dataSet,
            SchemaType schemaType,
            IDbCommand command,
            string srcTable,
            CommandBehavior behavior
        )
        {
            DataTable[]           tables = base.FillSchema(dataSet, schemaType, command, srcTable, behavior);
            IServerExpressionPlan plan   = ((DAECommand)command)._plan as IServerExpressionPlan;

            if (plan != null)
            {
                Schema.Key minimumKey = plan.TableVar.Keys.MinimumKey(true);
                foreach (DataTable table in tables)
                {
                    bool isPrimary;
                    table.Constraints.Clear();
                    foreach (Schema.Key key in plan.TableVar.Keys)
                    {
                        isPrimary = key == minimumKey;
                        table.Constraints.Add(key.Name, GetDataColumns(table, key), isPrimary);
                    }
                }
            }
            return(tables);
        }
Beispiel #3
0
 public NativeMap(IValueManager manager, Schema.TableVar tableVar, Schema.Key key, Dictionary <String, Schema.Sort> equalitySorts) : base()
 {
     TableVar      = tableVar;
     Key           = key;
     EqualitySorts = equalitySorts;
     Create(manager);
 }
Beispiel #4
0
        public override void DetermineDataType(Plan plan)
        {
            base.DetermineDataType(plan);

            if (_sequenceColumn != null)
            {
                Schema.TableVarColumn column =
                    Compiler.CompileIncludeColumnExpression
                    (
                        plan,
                        _sequenceColumn,
                        Keywords.Sequence,
                        plan.DataTypes.SystemInteger,
                        Schema.TableVarColumnType.Sequence
                    );
                DataType.Columns.Add(column.Column);
                TableVar.Columns.Add(column);
                _sequenceColumnIndex = TableVar.Columns.Count - 1;

                Schema.Key sequenceKey = new Schema.Key();
                sequenceKey.IsInherited = true;
                sequenceKey.Columns.Add(column);
                TableVar.Keys.Add(sequenceKey);
            }
        }
Beispiel #5
0
        private System.Data.DataColumn[] GetDataColumns(DataTable table, Schema.Key key)
        {
            System.Data.DataColumn[] dataColumns = new System.Data.DataColumn[key.Columns.Count];
            int i = 0;

            foreach (DAE.Schema.TableVarColumn column in key.Columns)
            {
                dataColumns[i++] = table.Columns[column.Name];
            }
            return(dataColumns);
        }
Beispiel #6
0
        private static string KeyValuesToString(Schema.Key key, Row row)
        {
            StringBuilder result = new StringBuilder();

            foreach (Schema.TableVarColumn column in key.Columns)
            {
                if (result.Length > 0)
                {
                    result.Append(", ");
                }
                result.Append(column.Column.Name + " := " + (row.HasValue(column.Column.Name) ? (string)row[column.Column.Name] : "<nil>"));
            }
            return("{ " + result.ToString() + " }");
        }
Beispiel #7
0
        protected override void InternalOpen()
        {
            _sourceTables = new Stack(Program.Stack.MaxStackDepth, Program.Stack.MaxCallDepth);
            _sourceTables.PushWindow(0);
            _parentRows = new Stack(Program.Stack.MaxStackDepth, Program.Stack.MaxCallDepth);
            _parentRows.PushWindow(0);
            PushSourceTable(null);
            _sourceRow = new Row(Manager, ((TableNode)Node.Nodes[0]).DataType.RowType);
            _tableType = new Schema.TableType();
            _tableVar  = new Schema.BaseTableVar(_tableType, Program.TempDevice);
            Schema.TableVarColumn newColumn;
            foreach (Schema.TableVarColumn column in Node.TableVar.Columns)
            {
                newColumn = (Schema.TableVarColumn)column.Copy();
                _tableType.Columns.Add(newColumn.Column);
                _tableVar.Columns.Add(newColumn);
            }

            if (Node.SequenceColumnIndex < 0)
            {
                newColumn = new Schema.TableVarColumn(new Schema.Column(Keywords.Sequence, Program.DataTypes.SystemInteger), Schema.TableVarColumnType.Stored);
                _tableType.Columns.Add(newColumn.Column);
                _tableVar.Columns.Add(newColumn);
                _sequenceColumnIndex = _tableVar.Columns.Count - 1;
            }
            else
            {
                _sequenceColumnIndex = Node.SequenceColumnIndex;
            }

            _targetRow = new Row(Manager, _tableType.RowType);
            Schema.Key key = new Schema.Key();
            key.Columns.Add(_tableVar.Columns[_sequenceColumnIndex]);
            _tableVar.Keys.Add(key);
            _buffer = new NativeTable(Manager, _tableVar);
            _scan   = new Scan(Manager, _buffer, _buffer.ClusteredIndex, ScanDirection.Forward, null, null);
            _scan.Open();
            _sequence = 0;
            _empty    = false;
            InternalNext();
            _empty = _scan.EOF();
            _scan.First();
        }
Beispiel #8
0
        public static Statement GenerateConditionedInsertStatement(Program program, TableNode sourceTable, TableNode targetTable, Expression targetExpression, bool insertOnly, string keyColumns)
        {
            // Produced statement looks similar to this:
            //	if not exists (<target> rename Target where <key column restriction>) then
            //		insert ASourceRow into <target>
            //	else
            //		update <target> rename Target set { <assignment list> } where <key column restriction>;

            string[] keyColumnNames = null;
            if (keyColumns == null)
            {
                // If no key columns are specified, default to a key from the target
                Schema.Key key = program.FindClusteringKey(targetTable.TableVar);
                keyColumnNames = new string[key.Columns.Count];
                for (int i = 0; i < key.Columns.Count; i++)
                {
                    keyColumnNames[i] = key.Columns[i].Name;
                }
            }
            else
            {
                // Parse and trim the key column names
                keyColumnNames = (keyColumns == "" ? new String[] { } : keyColumns.Split(new char[] { ',', ';' }));
                for (int i = 0; i < keyColumnNames.Length; i++)
                {
                    keyColumnNames[i] = keyColumnNames[i].Trim();
                }
            }

            // Compute the target restriction
            Expression targetCondition = null;

            foreach (string keyColumnName in keyColumnNames)
            {
                BinaryExpression comparison = new BinaryExpression(new IdentifierExpression(".Target." + keyColumnName), Instructions.Equal, new IdentifierExpression(".ASourceRow." + keyColumnName));
                if (targetCondition != null)
                {
                    targetCondition = new BinaryExpression(targetCondition, Instructions.And, comparison);
                }
                else
                {
                    targetCondition = comparison;
                }
            }

            // Construct the if ... then insert ... portion
            IfStatement ifStatement =
                new IfStatement
                (
                    new UnaryExpression
                    (
                        Instructions.Not,
                        new UnaryExpression
                        (
                            Instructions.Exists,
                            (targetCondition != null)
                                                                ? new RestrictExpression(new RenameAllExpression(targetExpression, "Target"), targetCondition)
                                                                : targetExpression
                        )
                    ),
                    GenerateInsertStatement(sourceTable, targetTable, targetExpression),
                    null
                );

            // If also doing updates, construct the else update ... portion
            if (!insertOnly)
            {
                UpdateStatement update = new UpdateStatement(new RenameAllExpression(targetExpression, "Target"));

                // Compute the assignments based on the target's columns
                foreach (Schema.Column column in targetTable.DataType.Columns)
                {
                    // If not a key column and it is in the source then add it as a restriction column
                    if ((Array.IndexOf(keyColumnNames, column.Name) < 0) && sourceTable.DataType.Columns.ContainsName(column.Name))
                    {
                        update.Columns.Add
                        (
                            new UpdateColumnExpression
                            (
                                new IdentifierExpression(".Target." + column.Name),
                                new IdentifierExpression(".ASourceRow." + column.Name)
                            )
                        );
                    }
                }

                if (update.Columns.Count > 0)
                {
                    update.Condition           = targetCondition;
                    ifStatement.FalseStatement = update;
                }
            }

            return(ifStatement);
        }
Beispiel #9
0
        public static string Copy(Program program, TableNode sourceTable, TableNode targetTable, GenerateStatementHandler generateStatement)
        {
            Statement targetStatement =
                generateStatement
                (
                    sourceTable,
                    targetTable,
                    (Expression)targetTable.EmitStatement(Alphora.Dataphor.DAE.Language.D4.EmitMode.ForCopy)
                );

            Schema.Key displaySourceKey = program.FindClusteringKey(sourceTable.TableVar);

            StringBuilder result = new StringBuilder();
            long          succeededUpdateCount          = 0;
            long          failedUpdateCount             = 0;
            bool          maxResultLengthMessageWritten = false;

            // Start a new process so that we don't mess with the transaction context of this one
            ProcessInfo info = new ProcessInfo(program.ServerProcess.ServerSession.SessionInfo);

            info.UseImplicitTransactions = false;
            IServerProcess targetProcess = ((IServerSession)program.ServerProcess.ServerSession).StartProcess(info);

            try
            {
                Program targetProgram = new Program((ServerProcess)targetProcess);
                targetProgram.Code = targetTable;
                targetProgram.Start(null);
                try
                {
                    // Have the target program use the main program's context
                    Stack oldTargetContext = targetProgram.SwitchContext(program.Stack);
                    try
                    {
                        info.DefaultIsolationLevel = IsolationLevel.Browse;
                        IServerProcess sourceProcess = ((IServerSession)program.ServerProcess.ServerSession).StartProcess(info);
                        try
                        {
                            Program sourceProgram = new Program((ServerProcess)sourceProcess);
                            sourceProgram.Code = sourceTable;
                            sourceProgram.Start(null);
                            try
                            {
                                // Have the source program use the main program's context
                                Stack oldSourceContext = sourceProgram.SwitchContext(program.Stack);
                                try
                                {
                                    ITable source = (ITable)sourceTable.Execute(sourceProgram);
                                    try
                                    {
                                        source.Open();

                                        // TODO: IBAS Project #26790 - allow cross-process row copies for streamed types
                                        // There is a MarshalRow call in the LocalProcess, would that solve this problem?
                                        using (Row row = new Row(targetProcess.ValueManager, sourceTable.DataType.CreateRowType()))
                                        {
                                            DataParams paramsValue = new DataParams();
                                            paramsValue.Add(new DataParam("ASourceRow", row.DataType, DAE.Language.Modifier.Const, row));

                                            IServerStatementPlan target = targetProcess.PrepareStatement(new D4TextEmitter().Emit(targetStatement), paramsValue);
                                            try
                                            {
                                                target.CheckCompiled();

                                                while (source.Next())
                                                {
                                                    row.ClearValues();
                                                    targetProcess.BeginTransaction(IsolationLevel.Isolated);
                                                    try
                                                    {
                                                        source.Select(row);
                                                        target.Execute(paramsValue);
                                                        targetProcess.CommitTransaction();
                                                        succeededUpdateCount++;
                                                    }
                                                    catch (Exception exception)
                                                    {
                                                        failedUpdateCount++;
                                                        targetProcess.RollbackTransaction();
                                                        if (result.Length < 100000)
                                                        {
                                                            result.Append(KeyValuesToString(displaySourceKey, row) + " - " + exception.Message + "\r\n");
                                                        }
                                                        else
                                                        {
                                                            if (!maxResultLengthMessageWritten)
                                                            {
                                                                result.Append(Strings.Get("MaxResultLengthExceeded"));
                                                                maxResultLengthMessageWritten = true;
                                                            }
                                                        }
                                                    }

                                                    // Yield in case our process is aborted.
                                                    program.CheckAborted();
                                                }
                                            }
                                            finally
                                            {
                                                targetProcess.UnprepareStatement(target);
                                            }
                                        }
                                    }
                                    finally
                                    {
                                        source.Close();
                                    }
                                }
                                finally
                                {
                                    sourceProgram.SwitchContext(oldSourceContext);                                      // Don't let the source program cleanup the main context
                                }
                            }
                            finally
                            {
                                sourceProgram.Stop(null);
                            }
                        }
                        finally
                        {
                            ((IServerSession)program.ServerProcess.ServerSession).StopProcess(sourceProcess);
                        }

                        result.AppendFormat(Strings.Get("Results"), succeededUpdateCount, failedUpdateCount);
                        return(result.ToString());
                    }
                    finally
                    {
                        targetProgram.SwitchContext(oldTargetContext);                          // Don't let the target program cleanup the main context
                    }
                }
                finally
                {
                    targetProgram.Stop(null);
                }
            }
            finally
            {
                ((IServerSession)program.ServerProcess.ServerSession).StopProcess(targetProcess);
            }
        }
Beispiel #10
0
 public Schema.Order OrderFromKey(Schema.Key key)
 {
     return(Compiler.OrderFromKey(Plan, key));
 }
Beispiel #11
0
        protected override void InternalDeleteRow(Schema.TableVar ATableVar, Row ARow)
        {
            using (SQLCommand LCommand = Connection.CreateCommand(false))
            {
                string LTableSchema = D4.MetaData.GetTag(ATableVar.MetaData, "Storage.Schema", Device.Schema);
                string LTableName   = Device.ToSQLIdentifier(ATableVar);
                if (LTableSchema != String.Empty)
                {
                    LTableName = String.Format("{0}.{1}", LTableSchema, LTableName);
                }
                if (Device.CommandTimeout >= 0)
                {
                    LCommand.CommandTimeout = Device.CommandTimeout;
                }
                LCommand.Statement   = LTableName;
                LCommand.CommandType = SQLCommandType.Table;
                LCommand.LockType    = SQLLockType.Pessimistic;
                SQLCursor LCursor = LCommand.Open(SQLCursorType.Dynamic, SQLIsolationLevel.Serializable);
                try
                {
                    SQLScalarType         LScalarType;
                    Schema.TableVarColumn LColumn;
                    Schema.Key            LKey = Program.FindClusteringKey(ATableVar);

                                        #if USESEEKTOUPDATE
                    object[] LKeyValues = new object[LKey.Columns.Count];
                    for (int LIndex = 0; LIndex < LKeyValues.Length; LIndex++)
                    {
                        LColumn            = ATableVar.Columns[LKey.Columns[LIndex].Name];
                        LScalarType        = (SQLScalarType)Device.DeviceScalarTypes[LColumn.DataType];
                        LKeyValues[LIndex] = ARow.HasValue(LColumn.Name) ? LScalarType.ParameterFromScalar(ARow[LColumn.Name]) : null;
                    }
                    if (!LCursor.FindKey(LKeyValues))
                    {
                        throw new RuntimeException(RuntimeException.Codes.OptimisticConcurrencyCheckRowNotFound);
                    }
                                        #else
                    StringBuilder            LFilter = new StringBuilder();
                    IADOFilterLiteralBuilder LBuilder;
                    for (int LIndex = 0; LIndex < LKey.Columns.Count; LIndex++)
                    {
                        LColumn     = ATableVar.Columns[LKey.Columns[LIndex].Name];
                        LScalarType = (SQLScalarType)Device.DeviceScalarTypes[LColumn.DataType];
                        LBuilder    = LScalarType as IADOFilterLiteralBuilder;
                        if (LBuilder == null)
                        {
                            throw new ConnectionException(ConnectionException.Codes.UnsupportedSearchableCall);
                        }

                        if (LIndex > 0)
                        {
                            LFilter.Append(" and ");
                        }

                        if (ARow.HasValue(LColumn.Name))
                        {
                            LFilter.AppendFormat("[{0}] = {1}", Device.ToSQLIdentifier(LColumn), LBuilder.ToLiteral((IScalar)ARow[LColumn.Name]));
                        }
                        else
                        {
                            throw new RuntimeException(RuntimeException.Codes.OptimisticConcurrencyCheckRowNotFound);
                        }
                    }

                    if (!LCursor.SetFilter(LFilter.ToString()))
                    {
                        throw new RuntimeException(RuntimeException.Codes.OptimisticConcurrencyCheckRowNotFound);
                    }
                                        #endif


                    LCursor.Delete();
                }
                finally
                {
                    LCommand.Close(LCursor);
                }
            }
        }
Beispiel #12
0
        public override void DetermineDataType(Plan plan)
        {
            DetermineModifiers(plan);
            Nodes[0]        = Compiler.EmitOrderNode(plan, SourceNode, new Schema.Order(_quotaOrder), true);
            _dataType       = new Schema.TableType();
            _tableVar       = new Schema.ResultTableVar(this);
            _tableVar.Owner = plan.User;
            _tableVar.InheritMetaData(SourceTableVar.MetaData);
            CopyTableVarColumns(SourceTableVar.Columns);
            DetermineRemotable(plan);

            bool quotaOrderIncludesKey = false;

            foreach (Schema.Key key in SourceNode.TableVar.Keys)
            {
                if (Compiler.OrderIncludesKey(plan, _quotaOrder, key))
                {
                    quotaOrderIncludesKey = true;
                    break;
                }
            }

            if (quotaOrderIncludesKey)
            {
                if ((Nodes[1].IsLiteral) && ((int)plan.EvaluateLiteralArgument(Nodes[1], "quota") == 1))
                {
                    Schema.Key key = new Schema.Key();
                    key.IsInherited = true;
                    TableVar.Keys.Add(key);
                }
                else
                {
                    CopyKeys(SourceTableVar.Keys);
                }
            }
            else
            {
                CopyKeys(SourceTableVar.Keys);
            }

            CopyOrders(SourceTableVar.Orders);
            if (SourceNode.Order != null)
            {
                Order = CopyOrder(SourceNode.Order);
            }

                        #if UseReferenceDerivation
                        #if UseElaborable
            if (plan.CursorContext.CursorCapabilities.HasFlag(CursorCapability.Elaborable))
                        #endif
            CopyReferences(plan, SourceTableVar);
                        #endif

            plan.EnterRowContext();
            try
            {
                                #if USENAMEDROWVARIABLES
                _quotaRowType = new Schema.RowType(_quotaOrder.Columns);
                plan.Symbols.Push(new Symbol(Keywords.Left, _quotaRowType));
                                #else
                Schema.IRowType leftRowType = new Schema.RowType(FQuotaOrder.Columns, Keywords.Left);
                APlan.Symbols.Push(new Symbol(String.Empty, leftRowType));
                                #endif
                try
                {
                                        #if USENAMEDROWVARIABLES
                    plan.Symbols.Push(new Symbol(Keywords.Right, _quotaRowType));
                                        #else
                    Schema.IRowType rightRowType = new Schema.RowType(FQuotaOrder.Columns, Keywords.Right);
                    APlan.Symbols.Push(new Symbol(String.Empty, rightRowType));
                                        #endif
                    try
                    {
                        _equalNode =
                                                        #if USENAMEDROWVARIABLES
                            Compiler.CompileExpression(plan, Compiler.BuildRowEqualExpression(plan, Keywords.Left, Keywords.Right, _quotaRowType.Columns, _quotaRowType.Columns));
                                                        #else
                            Compiler.CompileExpression(APlan, Compiler.BuildRowEqualExpression(APlan, leftRowType.Columns, rightRowType.Columns));
                                                        #endif
                    }
                    finally
                    {
                        plan.Symbols.Pop();
                    }
                }
                finally
                {
                    plan.Symbols.Pop();
                }
            }
            finally
            {
                plan.ExitRowContext();
            }
        }
Beispiel #13
0
 public bool OrderIncludesKey(Schema.Order includingOrder, Schema.Key includedKey)
 {
     return(Compiler.OrderIncludesKey(_plan, includingOrder, includedKey));
 }
Beispiel #14
0
        public override void DetermineDataType(Plan plan)
        {
            DetermineModifiers(plan);
            _dataType       = new Schema.TableType();
            _tableVar       = new Schema.ResultTableVar(this);
            _tableVar.Owner = plan.User;
            _tableVar.InheritMetaData(SourceTableVar.MetaData);
            _tableVar.MergeMetaData(MetaData);
            AlterNode.AlterMetaData(_tableVar, AlterMetaData, true);
            CopyTableVarColumns(SourceTableVar.Columns);
            int sourceColumnIndex;

            Schema.TableVarColumn sourceColumn;
            Schema.TableVarColumn newColumn;
            _isRestrict = false;
            PlanNode restrictNode = null;
            PlanNode constraintNode;

            foreach (AdornColumnExpression expression in _expressions)
            {
                sourceColumnIndex = TableVar.Columns.IndexOf(expression.ColumnName);
                sourceColumn      = TableVar.Columns[expression.ColumnName];
                newColumn         = CopyTableVarColumn(sourceColumn);
                if (expression.ChangeNilable)
                {
                    newColumn.IsNilable = expression.IsNilable;
                }
                newColumn.MergeMetaData(expression.MetaData);
                AlterNode.AlterMetaData(newColumn, expression.AlterMetaData, true);
                newColumn.ReadOnly = Convert.ToBoolean(MetaData.GetTag(newColumn.MetaData, "Frontend.ReadOnly", newColumn.ReadOnly.ToString()));

                foreach (ConstraintDefinition constraint in expression.Constraints)
                {
                    _isRestrict = true;
                    Schema.TableVarColumnConstraint newConstraint = Compiler.CompileTableVarColumnConstraint(plan, TableVar, newColumn, constraint);

                    //Schema.TableVarColumnConstraint newConstraint = new Schema.TableVarColumnConstraint(Schema.Object.GetObjectID(constraint.MetaData), constraint.ConstraintName);
                    //newConstraint.ConstraintType = Schema.ConstraintType.Column;
                    //newConstraint.MergeMetaData(constraint.MetaData);
                    plan.PushCreationObject(newConstraint);
                    try
                    {
                        plan.Symbols.Push(new Symbol(Keywords.Value, newColumn.DataType));
                        try
                        {
                            //PlanNode node = Compiler.CompileBooleanExpression(plan, constraint.Expression);
                            //newConstraint.Node = node;
                            //newConstraint.IsRemotable = true;
                            //if (newConstraint.HasDependencies())
                            //	for (int index = 0; index < newConstraint.Dependencies.Count; index++)
                            //	{
                            //		Schema.Object objectValue = newConstraint.Dependencies.Objects[index];
                            //		if (objectValue != null)
                            //		{
                            //			if (!objectValue.IsRemotable)
                            //			{
                            //				newConstraint.IsRemotable = false;
                            //				break;
                            //			}
                            //		}
                            //		else
                            //		{
                            //			Error.Fail("Missing object dependency in AdornNode.");
                            //			//Schema.ObjectHeader LHeader = APlan.CatalogDeviceSession.SelectObjectHeader(LNewConstraint.Dependencies.IDs[LIndex]);
                            //			//if (!LHeader.IsRemotable)
                            //			//{
                            //			//    LNewConstraint.IsRemotable = false;
                            //			//    break;
                            //			//}
                            //		}
                            //	}

                            newColumn.Constraints.Add(newConstraint);

                            constraintNode = Compiler.CompileBooleanExpression(plan, constraint.Expression);
                            constraintNode = ReplaceColumnReferences(plan, constraintNode, sourceColumn.Name, sourceColumnIndex);
                            if (restrictNode == null)
                            {
                                restrictNode = constraintNode;
                            }
                            else
                            {
                                restrictNode = Compiler.EmitBinaryNode(plan, restrictNode, Instructions.And, constraintNode);
                            }
                        }
                        finally
                        {
                            plan.Symbols.Pop();
                        }
                    }
                    finally
                    {
                        plan.PopCreationObject();
                    }

                    if (newConstraint.HasDependencies())
                    {
                        plan.AttachDependencies(newConstraint.Dependencies);
                    }
                }

                // TODO: verify that the default satisfies the constraints
                if (expression.Default != null)
                {
                    newColumn.Default = Compiler.CompileTableVarColumnDefault(plan, _tableVar, newColumn, expression.Default);
                    if (newColumn.Default.HasDependencies())
                    {
                        plan.AttachDependencies(newColumn.Default.Dependencies);
                    }
                }

                if (expression.MetaData != null)
                {
                    Tag tag;
                    tag = expression.MetaData.Tags.GetTag("DAE.IsDefaultRemotable");
                    if (tag != Tag.None)
                    {
                        newColumn.IsDefaultRemotable = newColumn.IsDefaultRemotable && Convert.ToBoolean(tag.Value);
                    }

                    tag = expression.MetaData.Tags.GetTag("DAE.IsChangeRemotable");
                    if (tag != Tag.None)
                    {
                        newColumn.IsChangeRemotable = newColumn.IsChangeRemotable && Convert.ToBoolean(tag.Value);
                    }

                    tag = expression.MetaData.Tags.GetTag("DAE.IsValidateRemotable");
                    if (tag != Tag.None)
                    {
                        newColumn.IsValidateRemotable = newColumn.IsValidateRemotable && Convert.ToBoolean(tag.Value);
                    }
                }

                DataType.Columns[sourceColumnIndex] = newColumn.Column;
                TableVar.Columns[sourceColumnIndex] = newColumn;
            }

            // Keys
            CopyKeys(SourceTableVar.Keys);
            foreach (DropKeyDefinition keyDefinition in _dropKeys)
            {
                Schema.Key oldKey = Compiler.FindKey(plan, TableVar, keyDefinition);

                TableVar.Keys.SafeRemove(oldKey);
                TableVar.Constraints.SafeRemove(oldKey.Constraint);
                TableVar.InsertConstraints.SafeRemove(oldKey.Constraint);
                TableVar.UpdateConstraints.SafeRemove(oldKey.Constraint);
            }

            foreach (AlterKeyDefinition keyDefinition in _alterKeys)
            {
                Schema.Key oldKey = Compiler.FindKey(plan, TableVar, keyDefinition);
                AlterNode.AlterMetaData(oldKey, keyDefinition.AlterMetaData);
            }

            Compiler.CompileTableVarKeys(plan, _tableVar, _keys, false);

            // Orders
            CopyOrders(SourceTableVar.Orders);

            foreach (DropOrderDefinition orderDefinition in _dropOrders)
            {
                Schema.Order oldOrder = Compiler.FindOrder(plan, TableVar, orderDefinition);

                TableVar.Orders.SafeRemove(oldOrder);
            }

            foreach (AlterOrderDefinition orderDefinition in _alterOrders)
            {
                AlterNode.AlterMetaData(Compiler.FindOrder(plan, TableVar, orderDefinition), orderDefinition.AlterMetaData);
            }

            Compiler.CompileTableVarOrders(plan, _tableVar, _orders);

            if (SourceNode.Order != null)
            {
                Order = CopyOrder(SourceNode.Order);
            }

            // Constraints
            Compiler.CompileTableVarConstraints(plan, _tableVar, _constraints);

            if (_tableVar.HasConstraints())
            {
                foreach (Schema.TableVarConstraint constraint in _tableVar.Constraints)
                {
                    if (restrictNode == null)
                    {
                        if (constraint is Schema.RowConstraint)
                        {
                            restrictNode = ((Schema.RowConstraint)constraint).Node;
                            _isRestrict  = true;
                        }
                    }
                    else
                    {
                        if (constraint is Schema.RowConstraint)
                        {
                            restrictNode = Compiler.EmitBinaryNode(plan, restrictNode, Instructions.And, ((Schema.RowConstraint)constraint).Node);
                            _isRestrict  = true;
                        }
                    }

                    if (constraint.HasDependencies())
                    {
                        plan.AttachDependencies(constraint.Dependencies);
                    }
                }
            }

            if (_isRestrict)
            {
                Nodes[0] = Compiler.EmitRestrictNode(plan, Nodes[0], restrictNode);
            }

            DetermineRemotable(plan);

            if (MetaData != null)
            {
                Tag tag;
                Schema.ResultTableVar tableVar = (Schema.ResultTableVar)TableVar;
                tag = MetaData.Tags.GetTag("DAE.IsDefaultRemotable");
                if (tag != Tag.None)
                {
                    tableVar.InferredIsDefaultRemotable = tableVar.InferredIsDefaultRemotable && Convert.ToBoolean(tag.Value);
                }

                tag = MetaData.Tags.GetTag("DAE.IsChangeRemotable");
                if (tag != Tag.None)
                {
                    tableVar.InferredIsChangeRemotable = tableVar.InferredIsChangeRemotable && Convert.ToBoolean(tag.Value);
                }

                tag = MetaData.Tags.GetTag("DAE.IsValidateRemotable");
                if (tag != Tag.None)
                {
                    tableVar.InferredIsValidateRemotable = tableVar.InferredIsValidateRemotable && Convert.ToBoolean(tag.Value);
                }
            }

            if (Order == null)
            {
                string orderName = MetaData.GetTag(MetaData, "DAE.DefaultOrder", String.Empty);
                if (orderName != String.Empty)
                {
                    Order =
                        Compiler.CompileOrderDefinition
                        (
                            plan,
                            TableVar,
                            new Parser().ParseOrderDefinition
                            (
                                MetaData.GetTag
                                (
                                    MetaData,
                                    "DAE.DefaultOrder",
                                    String.Empty
                                )
                            ),
                            false
                        );
                }
            }

            if ((Order != null) && !TableVar.Orders.Contains(Order))
            {
                TableVar.Orders.Add(Order);
            }

                        #if UseReferenceDerivation
                        #if UseElaborable
            if (plan.CursorContext.CursorCapabilities.HasFlag(CursorCapability.Elaborable))
                        #endif
            CopyReferences(plan, SourceTableVar);
                        #endif

            foreach (ReferenceDefinition referenceDefinition in _references)
            {
                // Create a reference on the table var
                Schema.Reference reference = new Schema.Reference(Schema.Object.GetObjectID(referenceDefinition.MetaData), referenceDefinition.ReferenceName, referenceDefinition.MetaData);
                reference.Enforced    = false;
                reference.SourceTable = TableVar;

                foreach (ReferenceColumnDefinition column in referenceDefinition.Columns)
                {
                    reference.SourceKey.Columns.Add(reference.SourceTable.Columns[column.ColumnName]);
                }
                foreach (Schema.Key key in reference.SourceTable.Keys)
                {
                    if (reference.SourceKey.Columns.IsSupersetOf(key.Columns))
                    {
                        reference.SourceKey.IsUnique = true;
                        break;
                    }
                }

                Schema.Object schemaObject = Compiler.ResolveCatalogIdentifier(plan, referenceDefinition.ReferencesDefinition.TableVarName, true);
                if (!(schemaObject is Schema.TableVar))
                {
                    throw new CompilerException(CompilerException.Codes.InvalidReferenceObject, referenceDefinition, referenceDefinition.ReferenceName, referenceDefinition.ReferencesDefinition.TableVarName);
                }
                if (schemaObject.IsATObject)
                {
                    referenceDefinition.ReferencesDefinition.TableVarName = Schema.Object.EnsureRooted(((Schema.TableVar)schemaObject).SourceTableName);
                }
                else
                {
                    referenceDefinition.ReferencesDefinition.TableVarName = Schema.Object.EnsureRooted(schemaObject.Name);                     // Set the TableVarName in the references expression to the resolved identifier so that subsequent compiles do not depend on current library context (This really only matters in remote contexts, but there it is imperative, or this could be an ambiguous identifier)
                }
                plan.AttachDependency(schemaObject);
                reference.TargetTable = (Schema.TableVar)schemaObject;
                reference.AddDependency(schemaObject);

                foreach (ReferenceColumnDefinition column in referenceDefinition.ReferencesDefinition.Columns)
                {
                    reference.TargetKey.Columns.Add(reference.TargetTable.Columns[column.ColumnName]);
                }
                foreach (Schema.Key key in reference.TargetTable.Keys)
                {
                    if (reference.TargetKey.Columns.IsSupersetOf(key.Columns))
                    {
                        reference.TargetKey.IsUnique = true;
                        break;
                    }
                }

                if (!reference.TargetKey.IsUnique)
                {
                    throw new CompilerException(CompilerException.Codes.ReferenceMustTargetKey, referenceDefinition, referenceDefinition.ReferenceName, referenceDefinition.ReferencesDefinition.TableVarName);
                }

                if (reference.SourceKey.Columns.Count != reference.TargetKey.Columns.Count)
                {
                    throw new CompilerException(CompilerException.Codes.InvalidReferenceColumnCount, referenceDefinition, referenceDefinition.ReferenceName);
                }

                TableVar.References.Add(reference);
            }

            if (!plan.IsEngine)
            {
                foreach (AlterReferenceDefinition alterReference in _alterReferences)
                {
                    int referenceIndex = TableVar.References.IndexOf(alterReference.ReferenceName);
                    if (referenceIndex < 0)
                    {
                        referenceIndex = TableVar.References.IndexOfOriginatingReference(alterReference.ReferenceName);
                    }

                    if
                    (
                        (referenceIndex >= 0) ||
                        (
                            (plan.ApplicationTransactionID == Guid.Empty) &&
                            (!plan.InLoadingContext()) &&
                            !plan.InATCreationContext                             // We will be in an A/T creation context if we are reinfering view references for an A/T view
                        )
                    )
                    {
                        Schema.ReferenceBase referenceToAlter;
                        if (referenceIndex < 0)
                        {
                            referenceToAlter = TableVar.References[alterReference.ReferenceName];                             // This is just to throw the object not found error
                        }
                        else
                        {
                            referenceToAlter = TableVar.References[referenceIndex];
                        }
                        AlterNode.AlterMetaData(referenceToAlter, alterReference.AlterMetaData);
                        Schema.Object originatingReference = Compiler.ResolveCatalogIdentifier(plan, referenceToAlter.OriginatingReferenceName(), false);
                        if (originatingReference != null)
                        {
                            plan.AttachDependency(originatingReference);
                        }
                    }
                }
            }

            foreach (DropReferenceDefinition dropReference in _dropReferences)
            {
                //if (TableVar.HasDerivedReferences())
                //{
                //	int referenceIndex = TableVar.DerivedReferences.IndexOf(dropReference.ReferenceName);
                //	if (referenceIndex >= 0)
                //		TableVar.DerivedReferences.RemoveAt(referenceIndex);

                //	referenceIndex = TableVar.DerivedReferences.IndexOfOriginatingReference(dropReference.ReferenceName);
                //	if (referenceIndex >= 0)
                //		TableVar.DerivedReferences.RemoveAt(referenceIndex);
                //}

                //if (TableVar.HasSourceReferences())
                //{
                //	int referenceIndex = TableVar.SourceReferences.IndexOf(dropReference.ReferenceName);
                //	if (referenceIndex >= 0)
                //		TableVar.SourceReferences.RemoveAt(referenceIndex);

                //	referenceIndex = TableVar.SourceReferences.IndexOfOriginatingReference(dropReference.ReferenceName);
                //	if (referenceIndex >= 0)
                //		TableVar.SourceReferences.RemoveAt(referenceIndex);
                //}

                //if (TableVar.HasTargetReferences())
                //{
                //	int referenceIndex = TableVar.TargetReferences.IndexOf(dropReference.ReferenceName);
                //	if (referenceIndex >= 0)
                //		TableVar.TargetReferences.RemoveAt(referenceIndex);

                //	referenceIndex = TableVar.TargetReferences.IndexOfOriginatingReference(dropReference.ReferenceName);
                //	if (referenceIndex >= 0)
                //		TableVar.TargetReferences.RemoveAt(referenceIndex);
                //}

                if (TableVar.HasReferences())
                {
                    int referenceIndex = TableVar.References.IndexOf(dropReference.ReferenceName);
                    if (referenceIndex >= 0)
                    {
                        TableVar.References.RemoveAt(referenceIndex);
                    }

                    referenceIndex = TableVar.References.IndexOfOriginatingReference(dropReference.ReferenceName);
                    if (referenceIndex >= 0)
                    {
                        TableVar.References.RemoveAt(referenceIndex);
                    }
                }
            }
        }