public WhereClause AddConstraint(Constraint constraint) { constraint.ThrowIfNull(() => new ArgumentNullException("constraint")); constraint.Parent = this; Constraints.Add(constraint); return this; }
public bool GetNext() { this.currentObject = null; while (this.tables != null) { if (this.constraints == null) { if (!this.tables.MoveNext()) { this.tables = null; return false; } this.constraints = ((DataTable) this.tables.Current).Constraints.GetEnumerator(); } if (!this.constraints.MoveNext()) { this.constraints = null; } else { Constraint current = (Constraint) this.constraints.Current; if (this.IsValidCandidate(current)) { this.currentObject = current; return true; } } } return false; }
public bool GetNext() { Constraint candidate; currentObject = null; while (tables != null) { if (constraints == null) { if (!tables.MoveNext()) { tables = null; return false; } constraints = ((DataTable)tables.Current).Constraints.GetEnumerator(); } if (!constraints.MoveNext()) { constraints = null; continue; } Debug.Assert(constraints.Current is Constraint, "ConstraintEnumerator, contains object which is not constraint"); candidate = (Constraint)constraints.Current; if (IsValidCandidate(candidate)) { currentObject = candidate; return true; } } return false; }
/// <summary> /// 打印 Constraint . /// </summary> /// <param name="sb">输出缓冲区.</param> /// <param name="indent">缩进.</param> /// <param name="obj">对象.</param> public static void PrintConstraint(StringBuilder sb, int indent, Constraint obj) { if (obj is UniqueConstraint) { PrintConstraint_UniqueConstraint(sb, indent, obj as UniqueConstraint); } else if (obj is ForeignKeyConstraint) { PrintConstraint_ForeignKeyConstraint(sb, indent, obj as ForeignKeyConstraint); } else { PrintConstraint_base(sb, indent, obj); } }
internal void Add(Constraint constraint, bool addUniqueWhenAddingForeign) { if (constraint == null) { throw ExceptionBuilder.ArgumentNull("constraint"); } if (this.FindConstraint(constraint) != null) { throw ExceptionBuilder.DuplicateConstraint(this.FindConstraint(constraint).ConstraintName); } if ((1 < this.table.NestedParentRelations.Length) && !this.AutoGenerated(constraint)) { throw ExceptionBuilder.CantAddConstraintToMultipleNestedTable(this.table.TableName); } if (constraint is UniqueConstraint) { if (((UniqueConstraint) constraint).bPrimaryKey && (this.Table.primaryKey != null)) { throw ExceptionBuilder.AddPrimaryKeyConstraint(); } this.AddUniqueConstraint((UniqueConstraint) constraint); } else if (constraint is ForeignKeyConstraint) { ForeignKeyConstraint constraint2 = (ForeignKeyConstraint) constraint; if (addUniqueWhenAddingForeign && (constraint2.RelatedTable.Constraints.FindKeyConstraint(constraint2.RelatedColumnsReference) == null)) { if (constraint.ConstraintName.Length == 0) { constraint.ConstraintName = this.AssignName(); } else { this.RegisterName(constraint.ConstraintName); } UniqueConstraint constraint3 = new UniqueConstraint(constraint2.RelatedColumnsReference); constraint2.RelatedTable.Constraints.Add(constraint3); } this.AddForeignKeyConstraint((ForeignKeyConstraint) constraint); } this.BaseAdd(constraint); this.ArrayAdd(constraint); this.OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Add, constraint)); if ((constraint is UniqueConstraint) && ((UniqueConstraint) constraint).bPrimaryKey) { this.Table.PrimaryKey = ((UniqueConstraint) constraint).ColumnsReference; } }
protected override List<Constraint> ReadAllConstrains() { List<Constraint> allConstrains = new List<Constraint>(); #region 缓存数据库中的所有约束 using (var constraintReader = this.Db.QueryDataReader(@" SELECT C.CONSTRAINT_NAME, C.CONSTRAINT_TYPE, C.TABLE_NAME, C.COLUMN_NAME, CR.TABLE_NAME FK_TABLE_NAME, CR.COLUMN_NAME FK_COLUMN_NAME, CR.PREP, CR.TABLE_NAME PK_TABLE_NAME, CR.COLUMN_NAME PK_COLUMN_NAME, CR.CONSTRAINT_NAME UNIQUE_CONSTRAINT_NAME, C.DELETE_RULE FROM ( --外键或主键表列 SELECT C.CONSTRAINT_NAME, C.CONSTRAINT_TYPE, C.TABLE_NAME, COL.COLUMN_NAME, C.R_CONSTRAINT_NAME, C.DELETE_RULE FROM USER_CONSTRAINTS C INNER JOIN USER_CONS_COLUMNS COL ON C.CONSTRAINT_NAME = COL.CONSTRAINT_NAME WHERE (C.CONSTRAINT_TYPE = 'P' OR C.CONSTRAINT_TYPE= 'R') AND INSTR(C.CONSTRAINT_NAME, '$') = 0 ) C LEFT JOIN ( --主键表列 SELECT C.CONSTRAINT_NAME, C.TABLE_NAME, COL.COLUMN_NAME, 'TO' PREP FROM USER_CONSTRAINTS C INNER JOIN USER_CONS_COLUMNS COL ON C.CONSTRAINT_NAME = COL.CONSTRAINT_NAME WHERE C.CONSTRAINT_TYPE = 'P' AND INSTR(C.CONSTRAINT_NAME, '$') = 0 ) CR ON C.R_CONSTRAINT_NAME = CR.CONSTRAINT_NAME ")) { while (constraintReader.Read()) { var c = new Constraint() { CONSTRAINT_NAME = constraintReader["CONSTRAINT_NAME"].ToString(), CONSTRAINT_TYPE = constraintReader["CONSTRAINT_TYPE"].ToString(), TABLE_NAME = constraintReader["TABLE_NAME"].ToString(), COLUMN_NAME = constraintReader["COLUMN_NAME"].ToString(), FK_TABLE_NAME = constraintReader["FK_TABLE_NAME"].ToString(), FK_COLUMN_NAME = constraintReader["FK_COLUMN_NAME"].ToString(), PK_TABLE_NAME = constraintReader["PK_TABLE_NAME"].ToString(), PK_COLUMN_NAME = constraintReader["PK_COLUMN_NAME"].ToString(), UNIQUE_CONSTRAINT_NAME = constraintReader["UNIQUE_CONSTRAINT_NAME"].ToString(), DELETE_RULE = constraintReader["DELETE_RULE"].ToString() }; if (c.CONSTRAINT_TYPE == "P") { c.CONSTRAINT_TYPE = "PRIMARY KEY"; } else if (c.CONSTRAINT_TYPE == "R") { c.CONSTRAINT_TYPE = "FOREIGN KEY"; } allConstrains.Add(c); } } #endregion return allConstrains; }
protected override bool IsValidCandidate(Constraint constraint) { return((constraint is ForeignKeyConstraint) && (((ForeignKeyConstraint)constraint).RelatedTable == table)); }
public string GetSQLConstraintAdd(Constraint constraint) { if (constraint == null) return ""; if (constraint is PrimaryKeyConstraint) return GetSQLConstraintAdd(constraint as PrimaryKeyConstraint); if (constraint is UniqueConstraint) return GetSQLConstraintAdd(constraint as UniqueConstraint); if (constraint is CheckConstraint) return GetSQLConstraintAdd(constraint as CheckConstraint); if (constraint is ForeignKeyConstraint) return GetSQLConstraintAdd(constraint as ForeignKeyConstraint); throw new Exception("Unknown constraint type: " + constraint.GetType().Name); }
public string GetSQLConstraintRemove(Constraint constraint) { return string.Format("ALTER TABLE [{0}] DROP CONSTRAINT [{1}]", constraint.Table.Name, constraint.Name); }
public int IndexOf (Constraint constraint) { int index = 0; foreach (Constraint c in this) { if (c == constraint) return index; index++; } return -1; }
internal bool CanRemove(Constraint constraint, bool fThrowException) { return constraint.CanBeRemovedFromCollection(this, fThrowException); }
private bool _isDuplicateConstraintName (string constraintName, Constraint excludeFromComparison) { foreach (Constraint cst in List) { if (cst == excludeFromComparison) continue; if (String.Compare (constraintName, cst.ConstraintName, false, Table.Locale) == 0) return true; } return false; }
public void CopyTo(Constraint[] array, int index) { if (array==null) throw ExceptionBuilder.ArgumentNull("array"); if (index < 0) throw ExceptionBuilder.ArgumentOutOfRange("index"); if (array.Length - index < list.Count) throw ExceptionBuilder.InvalidOffsetLength(); for(int i = 0; i < list.Count; ++i) { array[index + i] = (Constraint)list[i]; } }
/// <devdoc> /// <para> /// Adds the constraint to the collection.</para> /// </devdoc> public void Add(Constraint constraint) { Add(constraint, true); }
protected virtual bool IsValidCandidate(Constraint constraint) { return true; }
/// <devdoc> /// <para> /// Removes the specified <see cref='System.Data.Constraint'/> /// from the collection.</para> /// </devdoc> public void Remove(Constraint constraint) { if (constraint == null) throw ExceptionBuilder.ArgumentNull("constraint"); // this will throw an exception if it can't be removed, otherwise indicates // whether we need to remove it from the collection. if (CanRemove(constraint, true)) { // constraint can be removed BaseRemove(constraint); ArrayRemove(constraint); if (constraint is UniqueConstraint && ((UniqueConstraint)constraint).IsPrimaryKey) { Table.PrimaryKey = null; } OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Remove, constraint)); } }
/// <devdoc> /// <para>Returns the index of the specified <see cref='System.Data.Constraint'/> .</para> /// </devdoc> public int IndexOf(Constraint constraint) { if (null != constraint) { int count = Count; for (int i = 0; i < count; ++i) { if (constraint == (Constraint) List[i]) return i; } // didnt find the constraint } return -1; }
/// <devdoc> /// Returns a matching constriant object. /// </devdoc> internal Constraint FindConstraint(Constraint constraint) { int constraintCount = List.Count; for (int i = 0; i < constraintCount; i++) { if (((Constraint)List[i]).Equals(constraint)) return(Constraint)List[i]; } return null; }
public ConstraintEnumerator(DataSet dataSet) { tables = (dataSet != null) ? dataSet.Tables.GetEnumerator() : null; currentObject = null; }
public void AddRange (Constraint[] constraints) { //When AddRange() occurs after BeginInit, //it does not add any elements to the collection until EndInit is called. if (Table.InitInProgress) { // Keep reference so that they can be added when EndInit() is called. _mostRecentConstraints = constraints; return; } if (constraints == null) return; for (int i = 0; i < constraints.Length; ++i) { if (constraints [i] != null) Add (constraints [i]); } }
// To add foreign key constraint without adding any unique constraint for internal use. Main purpose : Binary Remoting internal void Add(Constraint constraint, bool addUniqueWhenAddingForeign) { if (constraint == null) throw ExceptionBuilder.ArgumentNull("constraint"); // It is an error if we find an equivalent constraint already in collection if (FindConstraint(constraint) != null) { throw ExceptionBuilder.DuplicateConstraint(FindConstraint(constraint).ConstraintName); } if (1 < table.NestedParentRelations.Length) { if (!AutoGenerated(constraint)) { throw ExceptionBuilder.CantAddConstraintToMultipleNestedTable(table.TableName); } } if (constraint is UniqueConstraint) { if (((UniqueConstraint)constraint).bPrimaryKey) { if (Table.primaryKey != null) { throw ExceptionBuilder.AddPrimaryKeyConstraint(); } } AddUniqueConstraint((UniqueConstraint)constraint); } else if (constraint is ForeignKeyConstraint) { ForeignKeyConstraint fk = (ForeignKeyConstraint)constraint; if (addUniqueWhenAddingForeign) { UniqueConstraint key = fk.RelatedTable.Constraints.FindKeyConstraint(fk.RelatedColumnsReference); if (key == null) { if (constraint.ConstraintName.Length == 0) constraint.ConstraintName = AssignName(); else RegisterName(constraint.ConstraintName); key = new UniqueConstraint(fk.RelatedColumnsReference); fk.RelatedTable.Constraints.Add(key); } } AddForeignKeyConstraint((ForeignKeyConstraint)constraint); } BaseAdd(constraint); ArrayAdd(constraint); OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Add, constraint)); if (constraint is UniqueConstraint) { if (((UniqueConstraint)constraint).bPrimaryKey) { Table.PrimaryKey = ((UniqueConstraint)constraint).ColumnsReference; } } }
/// <devdoc> /// <para>Clears the collection of any <see cref='System.Data.Constraint'/> /// objects.</para> /// </devdoc> public void Clear() { if (table != null) { table.PrimaryKey = null; for (int i = 0; i < table.ParentRelations.Count; i++) { table.ParentRelations[i].SetChildKeyConstraint(null); } for (int i = 0; i < table.ChildRelations.Count; i++) { table.ChildRelations[i].SetParentKeyConstraint(null); } } if (table.fInitInProgress && delayLoadingConstraints != null) { delayLoadingConstraints = null; fLoadForeignKeyConstraintsOnly = false; } int oldLength = List.Count; Constraint[] constraints = new Constraint[List.Count]; List.CopyTo(constraints, 0); try { // this will smartly add and remove the appropriate tables. BaseGroupSwitch(constraints, oldLength, null, 0); } catch (Exception e) { // if (Common.ADP.IsCatchableOrSecurityExceptionType(e)) { // something messed up. restore to original state. BaseGroupSwitch(null, 0, constraints, oldLength); List.Clear(); for (int i = 0; i < oldLength; i++) List.Add(constraints[i]); } throw; } List.Clear(); OnCollectionChanged(RefreshEventArgs); }
protected override bool IsValidCandidate(Constraint constraint) { return(constraint is ForeignKeyConstraint); }
public string GetSQLConstraintRemove(Constraint constraint) { if (constraint is PrimaryKeyConstraint) return GetSQLConstraintRemove(constraint as PrimaryKeyConstraint); if (constraint is UniqueConstraint) return string.Format("DROP INDEX `{0}` ON `{1}`", constraint.Name, constraint.Table.Name); if (constraint is CheckConstraint) throw new NotImplementedException("SQLite doesn't support check constraints. Use trigger."); if (constraint is ForeignKeyConstraint) return string.Format("ALTER TABLE `{0}` DROP FOREIGN KEY `{1}`", constraint.Table.Name, constraint.Name); throw new Exception("Unknown constraint type: " + constraint.GetType().Name); }
// Overloaded Add method (5 of them) // to add Constraint object to the collection public void Add (Constraint constraint) { //not null if (null == constraint) throw new ArgumentNullException ("Can not add null."); if (constraint.InitInProgress) throw new ArgumentException ("Hmm .. Failed to Add to collection"); //check constraint membership //can't already exist in this collection or any other if (this == constraint.ConstraintCollection) throw new ArgumentException ("Constraint already belongs to this collection."); if (null != constraint.ConstraintCollection) throw new ArgumentException ("Constraint already belongs to another collection."); //check if a constraint already exists for the datacolums foreach (Constraint c in this) { if (c.Equals (constraint)) throw new DataException ( "Constraint matches contraint named '" + c.ConstraintName + "' already in collection"); } //check for duplicate name if (_isDuplicateConstraintName (constraint.ConstraintName, null)) throw new DuplicateNameException ("Constraint name already exists."); //Allow constraint to run validation rules and setup constraint.AddToConstraintCollectionSetup (this); //may throw if it can't setup //if name is null or empty give it a name if (constraint.ConstraintName == null || constraint.ConstraintName == "") constraint.ConstraintName = _createNewConstraintName (); //Add event handler for ConstraintName change constraint.BeforeConstraintNameChange += new DelegateConstraintNameChange (_handleBeforeConstraintNameChange); constraint.ConstraintCollection = this; List.Add (constraint); if (constraint is UniqueConstraint && ((UniqueConstraint) constraint).IsPrimaryKey) table.PrimaryKey = ((UniqueConstraint) constraint).Columns; OnCollectionChanged (new CollectionChangeEventArgs (CollectionChangeAction.Add, this)); }
// Overloaded Add method (5 of them) // to add Constraint object to the collection public void Add(Constraint constraint) { //not null if (null == constraint) throw new ArgumentNullException("Can not add null."); //check constraint membership //can't already exist in this collection or any other if (this == constraint.ConstraintCollection) throw new ArgumentException("Constraint already belongs to this collection."); if (null != constraint.ConstraintCollection) throw new ArgumentException("Constraint already belongs to another collection."); //check for duplicate name if (_isDuplicateConstraintName(constraint.ConstraintName,null) ) throw new DuplicateNameException("Constraint name already exists."); // Check whether Constraint is UniqueConstraint and initailized with the special // constructor - UniqueConstraint( string, string[], bool ); // If yes, It must be added via AddRange() only // Environment.StackTrace can help us // FIXME: Is a different mechanism to do this? if (constraint is UniqueConstraint){ if ((constraint as UniqueConstraint).DataColsNotValidated == true){ if ( Environment.StackTrace.IndexOf( "AddRange" ) == -1 ){ throw new ArgumentException(" Some DataColumns are invalid - They may not belong to the table associated with this Constraint Collection" ); } } } if (constraint is ForeignKeyConstraint){ if ((constraint as ForeignKeyConstraint).DataColsNotValidated == true){ if ( Environment.StackTrace.IndexOf( "AddRange" ) == -1 ){ throw new ArgumentException(" Some DataColumns are invalid - They may not belong to the table associated with this Constraint Collection" ); } } } //Allow constraint to run validation rules and setup constraint.AddToConstraintCollectionSetup(this); //may throw if it can't setup //Run Constraint to check existing data in table // this is redundant, since AddToConstraintCollectionSetup // calls AssertConstraint right before this call //constraint.AssertConstraint(); //if name is null or empty give it a name if (constraint.ConstraintName == null || constraint.ConstraintName == "" ) { constraint.ConstraintName = _createNewConstraintName(); } //Add event handler for ConstraintName change constraint.BeforeConstraintNameChange += new DelegateConstraintNameChange( _handleBeforeConstraintNameChange); constraint.ConstraintCollection = this; List.Add(constraint); if (constraint is UniqueConstraint && ((UniqueConstraint)constraint).IsPrimaryKey) { table.PrimaryKey = ((UniqueConstraint)constraint).Columns; } OnCollectionChanged( new CollectionChangeEventArgs( CollectionChangeAction.Add, this) ); }
public bool CanRemove (Constraint constraint) { return constraint.CanRemoveFromCollection (this, false); }
public void AddRange(Constraint[] constraints) { //When AddRange() occurs after BeginInit, //it does not add any elements to the collection until EndInit is called. if (this.table.fInitInProgress) { // Keep reference so that they can be added when EndInit() is called. _mostRecentConstraints = constraints; return; } if ( (constraints == null) || (constraints.Length == 0)) return; // Check whether the constraint is UniqueConstraint // And whether it was initialized with the special ctor // i.e UniqueConstraint( string, string[], bool ); for (int i = 0; i < constraints.Length; i++){ if (constraints[i] is UniqueConstraint){ if (( constraints[i] as UniqueConstraint).DataColsNotValidated == true){ PostAddRange _postAddRange= new PostAddRange ((constraints[i] as UniqueConstraint).PostAddRange); // UniqueConstraint.PostAddRange() validates whether all named // columns exist in the table associated with this instance of // ConstraintCollection. _postAddRange (this.table); } } else if (constraints [i] is ForeignKeyConstraint){ if (( constraints [i] as ForeignKeyConstraint).DataColsNotValidated == true){ (constraints [i] as ForeignKeyConstraint).postAddRange (this.table); } } } foreach (Constraint constraint in constraints) Add (constraint); }
public void Remove (Constraint constraint) { //LAMESPEC: spec doesn't document the ArgumentException the //will be thrown if the CanRemove rule is violated //LAMESPEC: spec says an exception will be thrown //if the element is not in the collection. The implementation //doesn't throw an exception. ArrayList.Remove doesn't throw if the //element doesn't exist //ALSO the overloaded remove in the spec doesn't say it throws any exceptions //not null if (null == constraint) throw new ArgumentNullException(); if (!constraint.CanRemoveFromCollection (this, true)) return; constraint.RemoveFromConstraintCollectionCleanup (this); constraint.ConstraintCollection = null; List.Remove (constraint); OnCollectionChanged (new CollectionChangeEventArgs (CollectionChangeAction.Remove, this)); }
public int IndexOf(Constraint constraint) { return List.IndexOf(constraint); }