예제 #1
0
 public bool ShouldEmitDrop(Schema.Object objectValue)
 {
     return
         (
         (
             (objectValue is CatalogObject) &&
             (
                 IncludeSystem ||
                 ((LibraryName == String.Empty) && ((objectValue.Library == null) || (objectValue.Library.Name == Engine.SystemLibraryName))) ||
                 (LibraryName != Engine.SystemLibraryName)
             ) ||
             (
                 !(objectValue is CatalogObject) &&
                 (IncludeSystem || !objectValue.IsSystem)
             )
         ) &&
         (!objectValue.IsGenerated || IncludeGenerated || (objectValue.IsSessionObject) || (RequestedObjects.Count > 0)) &&
         (
             (objectValue is CatalogObject) ||
             (objectValue is Schema.Representation) ||
             (objectValue is Schema.Default) ||
             (objectValue is Schema.Special) ||
             (objectValue is Schema.Constraint)
         )
         );
 }
예제 #2
0
 public bool ShouldEmitWithLibrary(Schema.Object objectValue)
 {
     return
         (
         (LibraryName == String.Empty) ||
         (
             (LibraryName != String.Empty) &&
             (objectValue.Library != null) &&
             Schema.Object.NamesEqual(objectValue.Library.Name, LibraryName)
         )
         );
 }
예제 #3
0
 public void PushCreationObject(Schema.Object objectValue, LineInfo lineInfo)
 {
     if (_creationObjects == null)
     {
         _creationObjects = new List <Schema.Object>();
     }
     _creationObjects.Add(objectValue);
     if (_compilingOffsets == null)
     {
         _compilingOffsets = new List <LineInfo>();
     }
     _compilingOffsets.Add(lineInfo);
 }
예제 #4
0
 public bool ShouldEmit(Schema.Object objectValue)
 {
     return
         (
         (
             (RequestedObjects.Count == 0) ||
             (RequestedObjects.Contains(objectValue.ID))
         ) &&
         (IncludeSystem || !objectValue.IsSystem) &&
         (!(objectValue is DeviceObject) || (Mode != EmitMode.ForRemote)) &&
         (
             !(objectValue.IsGenerated && (objectValue.GeneratorID > 0)) ||                          // A sort will be generated, but will not have a generator and so must be emitted
             IncludeGenerated ||
             (objectValue.IsSessionObject) ||
             (objectValue.IsATObject && RequestedObjects.Contains(objectValue.ID))
         )                         // an AT object will be generated, but must be emitted if specifically requested
         );
 }
예제 #5
0
 public void CheckClassDependency(ClassDefinition classDefinition)
 {
     if ((_creationObjects != null) && (_creationObjects.Count > 0))
     {
         Schema.Object creationObject = (Schema.Object)_creationObjects[_creationObjects.Count - 1];
         if
         (
             (creationObject is Schema.CatalogObject) &&
             (((Schema.CatalogObject)creationObject).Library != null) &&
             (((Schema.CatalogObject)creationObject).SessionObjectName == null) &&
             (
                 !(creationObject is Schema.TableVar) ||
                 (((Schema.TableVar)creationObject).SourceTableName == null)
             )
         )
         {
             CheckClassDependency(((Schema.CatalogObject)creationObject).Library, classDefinition);
         }
     }
 }
예제 #6
0
        private Schema.IDataType GetDataType()
        {
            bool timeStampSet = false;

            try
            {
                LocalServer.WaitForCacheTimeStamp(_process, _descriptor.CacheChanged ? _descriptor.ClientCacheTimeStamp - 1 : _descriptor.ClientCacheTimeStamp);
                LocalServer.AcquireCacheLock(_process, _descriptor.CacheChanged ? LockMode.Exclusive : LockMode.Shared);
                try
                {
                    if (_descriptor.CacheChanged)
                    {
                        LocalServer.EnsureCacheConsistent(_descriptor.CacheTimeStamp);
                        try
                        {
                            if (_descriptor.Catalog != String.Empty)
                            {
                                IServerScript script = ((IServerProcess)_process._internalProcess).PrepareScript(_descriptor.Catalog);
                                try
                                {
                                    script.Execute(_params);
                                }
                                finally
                                {
                                    ((IServerProcess)_process._internalProcess).UnprepareScript(script);
                                }
                            }
                        }
                        finally
                        {
                            LocalServer.SetCacheTimeStamp(_process, _descriptor.ClientCacheTimeStamp);
                            timeStampSet = true;
                        }
                    }

                    if (LocalServer.Catalog.ContainsName(_descriptor.ObjectName))
                    {
                        Schema.Object objectValue = LocalServer.Catalog[_descriptor.ObjectName];
                        if (objectValue is Schema.TableVar)
                        {
                            _tableVar = (Schema.TableVar)objectValue;
                            Plan plan = new Plan(_process._internalProcess);
                            try
                            {
                                if (_params != null)
                                {
                                    foreach (DataParam param in _params)
                                    {
                                        plan.Symbols.Push(new Symbol(param.Name, param.DataType));
                                    }
                                }

                                foreach (DataParam param in _process._internalProcess.ProcessLocals)
                                {
                                    plan.Symbols.Push(new Symbol(param.Name, param.DataType));
                                }

                                _tableNode = (TableNode)Compiler.EmitTableVarNode(plan, _tableVar);
                            }
                            finally
                            {
                                plan.Dispose();
                            }
                            _dataType = _tableVar.DataType;
                        }
                        else
                        {
                            _dataType = (Schema.IDataType)objectValue;
                        }
                    }
                    else
                    {
                        try
                        {
                            Plan plan = new Plan(_process._internalProcess);
                            try
                            {
                                _dataType = Compiler.CompileTypeSpecifier(plan, new DAE.Language.D4.Parser().ParseTypeSpecifier(_descriptor.ObjectName));
                            }
                            finally
                            {
                                plan.Dispose();
                            }
                        }
                        catch
                        {
                            // Notify the server that the client cache is out of sync
                            Process.Execute(".System.UpdateTimeStamps();", null);
                            throw;
                        }
                    }

                    return(_dataType);
                }
                finally
                {
                    LocalServer.ReleaseCacheLock(_process, _descriptor.CacheChanged ? LockMode.Exclusive : LockMode.Shared);
                }
            }
            catch (Exception E)
            {
                // Notify the server that the client cache is out of sync
                Process.Execute(".System.UpdateTimeStamps();", null);
                E = new ServerException(ServerException.Codes.CacheDeserializationError, E, _descriptor.ClientCacheTimeStamp);
                LocalServer._internalServer.LogError(E);
                throw E;
            }
            finally
            {
                if (!timeStampSet)
                {
                    LocalServer.SetCacheTimeStamp(_process, _descriptor.ClientCacheTimeStamp);
                }
            }
        }
예제 #7
0
        /// <summary>
        /// Transform an XML object into a page object.
        /// </summary>
        /// <param name="obj">The XML object to transform.</param>
        /// <param name="engine">A reference to the active <see cref="Engine" />.</param>
        /// <returns>A page object based on the XML object data.</returns>
        private static IObject TransformObject(Schema.Object obj, Engine engine)
        {
            IObject newObject;

            // Determine the specific type of Object and add it to the list.
            // TODO: This sucks. Make it suck less.
            if (obj.GetType() == typeof(FlagObject))
            {
                var flag = (FlagObject)obj;
                newObject = new Flag();
                if (flag.SettingSpecified)
                {
                    switch (flag.Setting)
                    {
                    case FlagObjectSetting.set:
                        ((Flag)newObject).Setting = Flag.FlagAction.Set;
                        break;

                    case FlagObjectSetting.clear:
                        ((Flag)newObject).Setting = Flag.FlagAction.Clear;
                        break;

                    case FlagObjectSetting.toggle:
                        ((Flag)newObject).Setting = Flag.FlagAction.Toggle;
                        break;

                    default:
                        throw new ArgumentOutOfRangeException();
                    }
                }
            }
            else if (obj.GetType() == typeof(VariableObject))
            {
                var variable = (VariableObject)obj;
                newObject = new Variable {
                    Operation = Variable.VariableAction.Set, Expression = variable.Expression
                };
                if (variable.OperationSpecified)
                {
                    switch (variable.Operation)
                    {
                    case VariableObjectOperation.set:
                        ((Variable)newObject).Operation = Variable.VariableAction.Set;
                        break;

                    case VariableObjectOperation.add:
                        ((Variable)newObject).Operation = Variable.VariableAction.Add;
                        break;

                    case VariableObjectOperation.subtract:
                        ((Variable)newObject).Operation = Variable.VariableAction.Subtract;
                        break;

                    case VariableObjectOperation.multiply:
                        ((Variable)newObject).Operation = Variable.VariableAction.Multiply;
                        break;

                    case VariableObjectOperation.divide:
                        ((Variable)newObject).Operation = Variable.VariableAction.Divide;
                        break;

                    case VariableObjectOperation.modulus:
                        ((Variable)newObject).Operation = Variable.VariableAction.Modulus;
                        break;

                    default:
                        throw new ArgumentOutOfRangeException();
                    }
                }
            }
            else if (obj.GetType() == typeof(RedirectObject))
            {
                var redirect = (RedirectObject)obj;
                newObject = new Redirect {
                    TargetName = redirect.Target
                };
            }
            else if (obj.GetType() == typeof(ChoiceObject))
            {
                var choice = (ChoiceObject)obj;
                newObject = new Choice {
                    FormattedText = new TextSequence(choice.Value), Shortcut = string.IsNullOrEmpty(choice.Shortcut) ? (char?)null : Convert.ToChar(choice.Shortcut.Substring(0, 1)), TargetName = choice.Target
                };
            }
            else if (obj.GetType() == typeof(ImageObject))
            {
                var image = (ImageObject)obj;
                newObject = new Image {
                    FormattedText = new TextSequence(image.Value), Source = image.Source
                };
            }
            else
            {
                // If all else fails, it's probably a paragraph.
                newObject = new Paragraph {
                    FormattedText = new TextSequence(obj.Value)
                };
            }

            // Transform common properties.
            newObject.Name   = obj.Name;
            newObject.ShowIf = obj.ShowIf;
            newObject.HideIf = obj.HideIf;

            // Apply style (if this is a PageObject)
            if (obj.GetType().BaseType == typeof(Schema.PageObject))
            {
                var pageObject = (StoryPageObject)newObject;
                pageObject.Style = TransformStyle((Schema.PageObject)obj);
            }

            // Apply ActionObject properties (if applicable).
            if (obj.GetType().BaseType == typeof(Schema.ActionObject))
            {
                var actionObject = (StoryActionObject)newObject;
                actionObject.Engine = engine;
            }

            return(newObject);
        }
예제 #8
0
        public void AttachDependency(Schema.Object objectValue)
        {
            if (_creationObjects == null)
            {
                _creationObjects = new List <Schema.Object>();
            }
            if (_creationObjects.Count > 0)
            {
                // If this is a generated object, attach the dependency to the generator, rather than the object directly.
                // Unless it is a device object, in which case the dependency should be attached to the generated object.
                if (objectValue.IsGenerated && !(objectValue is Schema.DeviceObject) && (objectValue.GeneratorID >= 0))
                {
                    objectValue = objectValue.ResolveGenerator(CatalogDeviceSession);
                }

                if (objectValue is Schema.Property)
                {
                    objectValue = ((Schema.Property)objectValue).Representation;
                }

                Schema.Object localObjectValue = (Schema.Object)_creationObjects[_creationObjects.Count - 1];
                if ((localObjectValue != objectValue) && (!(objectValue is Schema.Reference) || (localObjectValue is Schema.TableVar)) && (!localObjectValue.HasDependencies() || !localObjectValue.Dependencies.Contains(objectValue.ID)))
                {
                    if (!_serverProcess.ServerSession.Server.IsEngine)
                    {
                        if
                        (
                            (localObjectValue.Library != null) &&
                            !localObjectValue.IsSessionObject &&
                            !localObjectValue.IsATObject
                        )
                        {
                            Schema.LoadedLibrary library          = localObjectValue.Library;
                            Schema.LoadedLibrary dependentLibrary = objectValue.Library;
                            if (dependentLibrary == null)
                            {
                                throw new Schema.SchemaException(Schema.SchemaException.Codes.NonLibraryDependency, localObjectValue.Name, library.Name, objectValue.Name);
                            }
                            if (!library.IsRequiredLibrary(dependentLibrary) && (!String.Equals(dependentLibrary.Name, Engine.SystemLibraryName, StringComparison.OrdinalIgnoreCase)))                             // Ignore dependencies to the system library, these are implicitly available
                            {
                                throw new Schema.SchemaException(Schema.SchemaException.Codes.NonRequiredLibraryDependency, localObjectValue.Name, library.Name, objectValue.Name, dependentLibrary.Name);
                            }
                        }

                        // if LObject is not a session object or an AT object, AObject cannot be a session object
                        if ((localObjectValue is Schema.CatalogObject) && !localObjectValue.IsSessionObject && !localObjectValue.IsATObject && objectValue.IsSessionObject)
                        {
                            throw new Schema.SchemaException(Schema.SchemaException.Codes.SessionObjectDependency, localObjectValue.Name, ((Schema.CatalogObject)objectValue).SessionObjectName);
                        }

                        // if LObject is not a generated or an AT object or a plan object (Name == SessionObjectName), AObject cannot be an AT object
                        if (((localObjectValue is Schema.CatalogObject) && (((Schema.CatalogObject)localObjectValue).SessionObjectName != localObjectValue.Name)) && !localObjectValue.IsGenerated && !localObjectValue.IsATObject && objectValue.IsATObject)
                        {
                            if (objectValue is Schema.TableVar)
                            {
                                throw new Schema.SchemaException(Schema.SchemaException.Codes.ApplicationTransactionObjectDependency, localObjectValue.Name, ((Schema.TableVar)objectValue).SourceTableName);
                            }
                            else
                            {
                                throw new Schema.SchemaException(Schema.SchemaException.Codes.ApplicationTransactionObjectDependency, localObjectValue.Name, ((Schema.Operator)objectValue).SourceOperatorName);
                            }
                        }
                    }

                    Error.AssertFail(objectValue.ID > 0, "Object {0} does not have an object id and cannot be tracked as a dependency.", objectValue.Name);
                    localObjectValue.AddDependency(objectValue);
                }
            }
        }
예제 #9
0
 public void PushCreationObject(Schema.Object objectValue)
 {
     PushCreationObject(objectValue, new LineInfo(LineInfo.StartingOffset));
 }
예제 #10
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);
                    }
                }
            }
        }