Welcome to mirror list, hosted at ThFree Co, Russian Federation.

UniqueConstraint.cs « Data « System « System.Data « referencesource « class « mcs - github.com/mono/mono.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: c097f9319c2e8061064a3d051fe427a27b1ef862 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
//------------------------------------------------------------------------------
// <copyright file="UniqueConstraint.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
// <owner current="true" primary="false">[....]</owner>
// <owner current="false" primary="false">[....]</owner>
//------------------------------------------------------------------------------

namespace System.Data {
    using System;
    using System.Diagnostics;
    using System.ComponentModel;

    /// <devdoc>
    ///    <para>
    ///       Represents a restriction on a set of columns in which all values must be unique.
    ///    </para>
    /// </devdoc>
    [
    DefaultProperty("ConstraintName"),
    Editor("Microsoft.VSDesigner.Data.Design.UniqueConstraintEditor, " + AssemblyRef.MicrosoftVSDesigner, "System.Drawing.Design.UITypeEditor, " + AssemblyRef.SystemDrawing),
    ]
    public class UniqueConstraint : Constraint {
        private DataKey key;
        private Index _constraintIndex;
        internal bool bPrimaryKey = false;

        // Design time serialization
        internal string constraintName = null;
        internal string[] columnNames = null;

        /// <devdoc>
        /// <para>Initializes a new instance of the <see cref='System.Data.UniqueConstraint'/> with the specified name and
        /// <see cref='System.Data.DataColumn'/>.</para>
        /// </devdoc>
        public UniqueConstraint(String name, DataColumn column) {
            DataColumn[] columns = new DataColumn[1];
            columns[0] = column;
            Create(name, columns);
        }

        /// <devdoc>
        /// <para>Initializes a new instance of the <see cref='System.Data.UniqueConstraint'/> with the specified <see cref='System.Data.DataColumn'/>.</para>
        /// </devdoc>
        public UniqueConstraint(DataColumn column) {
            DataColumn[] columns = new DataColumn[1];
            columns[0] = column;
            Create(null, columns);
        }

        /// <devdoc>
        /// <para>Initializes a new instance of the <see cref='System.Data.UniqueConstraint'/> with the specified name and array
        ///    of <see cref='System.Data.DataColumn'/> objects.</para>
        /// </devdoc>
        public UniqueConstraint(String name, DataColumn[] columns) {
            Create(name, columns);
        }

        /// <devdoc>
        ///    <para>
        ///       Initializes a new instance of the <see cref='System.Data.UniqueConstraint'/> with the given array of <see cref='System.Data.DataColumn'/>
        ///       objects.
        ///    </para>
        /// </devdoc>
        public UniqueConstraint(DataColumn[] columns) {
            Create(null, columns);
        }

        // Construct design time object
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [Browsable(false)]
        public UniqueConstraint(String name, string[] columnNames, bool isPrimaryKey) {
            this.constraintName = name;
            this.columnNames = columnNames;
            this.bPrimaryKey = isPrimaryKey;
        }

        /// <devdoc>
        /// <para>Initializes a new instance of the <see cref='System.Data.UniqueConstraint'/> with the specified name and
        /// <see cref='System.Data.DataColumn'/>.</para>
        /// </devdoc>
        public UniqueConstraint(String name, DataColumn column, bool isPrimaryKey) {
            DataColumn[] columns = new DataColumn[1];
            columns[0] = column;
            this.bPrimaryKey = isPrimaryKey;
            Create(name, columns);
        }

        /// <devdoc>
        /// <para>Initializes a new instance of the <see cref='System.Data.UniqueConstraint'/> with the specified <see cref='System.Data.DataColumn'/>.</para>
        /// </devdoc>
        public UniqueConstraint(DataColumn column, bool isPrimaryKey) {
            DataColumn[] columns = new DataColumn[1];
            columns[0] = column;
            this.bPrimaryKey = isPrimaryKey;
            Create(null, columns);
        }

        /// <devdoc>
        /// <para>Initializes a new instance of the <see cref='System.Data.UniqueConstraint'/> with the specified name and array
        ///    of <see cref='System.Data.DataColumn'/> objects.</para>
        /// </devdoc>
        public UniqueConstraint(String name, DataColumn[] columns, bool isPrimaryKey) {
            this.bPrimaryKey = isPrimaryKey;
            Create(name, columns);
        }

        /// <devdoc>
        ///    <para>
        ///       Initializes a new instance of the <see cref='System.Data.UniqueConstraint'/> with the given array of <see cref='System.Data.DataColumn'/>
        ///       objects.
        ///    </para>
        /// </devdoc>
        public UniqueConstraint(DataColumn[] columns, bool isPrimaryKey) {
            this.bPrimaryKey = isPrimaryKey;
            Create(null, columns);
        }

        // design time serialization only
        internal string[] ColumnNames {
            get {
                return key.GetColumnNames();
            }
        }

        // VSTFDEVDIV 895693: please note that there are scenarios where ConstraintIndex is not the same as key.GetSortIndex()
        // Use constraint index only for search operations (and use key.GetSortIndex() when enumeration is needed and/or order is important)
        internal Index ConstraintIndex {
            get {
                AssertConstraintAndKeyIndexes();
                return _constraintIndex;
            }
        }

        [Conditional("DEBUG")]
        private void AssertConstraintAndKeyIndexes() {
            Debug.Assert(null != _constraintIndex, "null UniqueConstraint index");

            // ideally, we would like constraintIndex and key.GetSortIndex to share the same index underneath: Debug.Assert(_constraintIndex == key.GetSortIndex)
            // but, due to VSTFDEVDIV #895693 there is a scenario where constraint and key indexes are built from the same list of columns but in a different order
            DataColumn[] sortIndexColumns = new DataColumn[_constraintIndex.IndexFields.Length];
            for (int i = 0; i < sortIndexColumns.Length; i++) {
                sortIndexColumns[i] = _constraintIndex.IndexFields[i].Column;
            }
            Debug.Assert(DataKey.ColumnsEqual(key.ColumnsReference, sortIndexColumns), "UniqueConstraint index columns do not match the key sort index");
        }

        internal void ConstraintIndexClear() {
            if (null != _constraintIndex) {
                _constraintIndex.RemoveRef();
                _constraintIndex = null;
            }
        }
        
        internal void ConstraintIndexInitialize() {
            //Debug.Assert(null == _constraintIndex, "non-null UniqueConstraint index");
            if (null == _constraintIndex) {
                _constraintIndex = key.GetSortIndex();
                _constraintIndex.AddRef();
            }

            AssertConstraintAndKeyIndexes();
        }

        internal override void CheckState() {
           NonVirtualCheckState();
        }

        private  void NonVirtualCheckState() {
            key.CheckState();
        }

        internal override void CheckCanAddToCollection(ConstraintCollection constraints) {
        }

        internal override bool CanBeRemovedFromCollection(ConstraintCollection constraints, bool fThrowException) {
            if (this.Equals(constraints.Table.primaryKey)) {
                Debug.Assert(constraints.Table.primaryKey == this, "If the primary key and this are 'Equal', they should also be '=='");
                if (!fThrowException)
                    return false;
                else
                    throw ExceptionBuilder.RemovePrimaryKey(constraints.Table);
            }
            for (ParentForeignKeyConstraintEnumerator cs = new ParentForeignKeyConstraintEnumerator(Table.DataSet, Table); cs.GetNext();) {
                ForeignKeyConstraint constraint = cs.GetForeignKeyConstraint();
                if (!key.ColumnsEqual(constraint.ParentKey))
                    continue;

                if (!fThrowException)
                    return false;
                else
                    throw ExceptionBuilder.NeededForForeignKeyConstraint(this, constraint);
            }

            return true;
        }

        internal override bool CanEnableConstraint() {
            if (Table.EnforceConstraints)
                return ConstraintIndex.CheckUnique();

            return true;
        }

        internal override bool IsConstraintViolated() {
            bool result = false;
            Index index = ConstraintIndex;
            if (index.HasDuplicates) {
                // 
                object[] uniqueKeys = index.GetUniqueKeyValues();

                for (int i = 0; i < uniqueKeys.Length; i++) {
                    Range r = index.FindRecords((object[])uniqueKeys[i]);
                    if (1 < r.Count) {
                        DataRow[] rows = index.GetRows(r);
                        string error = ExceptionBuilder.UniqueConstraintViolationText(key.ColumnsReference, (object[])uniqueKeys[i]);
                        for (int j = 0; j < rows.Length; j++) {
                            // 
                            rows[j].RowError = error;
                            foreach(DataColumn dataColumn in key.ColumnsReference){
                                rows[j].SetColumnError(dataColumn, error);
                            }
                        }
                        // SQLBU 20011224: set_RowError for all DataRow with a unique constraint violation
                        result = true; 
                    }
                }
            }
            return result;
        }

        internal override void CheckConstraint(DataRow row, DataRowAction action) {
            if (Table.EnforceConstraints &&
                (action == DataRowAction.Add ||
                 action == DataRowAction.Change ||
                 (action == DataRowAction.Rollback && row.tempRecord != -1))) {
                if (row.HaveValuesChanged(ColumnsReference)) {
                    if (ConstraintIndex.IsKeyRecordInIndex(row.GetDefaultRecord())) {
                        object[] values = row.GetColumnValues(ColumnsReference);
                        throw ExceptionBuilder.ConstraintViolation(ColumnsReference, values);
                    }
                }
            }
        }

        internal override bool ContainsColumn(DataColumn column) {
            return key.ContainsColumn(column);
        }

        internal override Constraint Clone(DataSet destination) {
            return Clone(destination, false);
        }

        internal override Constraint Clone(DataSet destination, bool ignorNSforTableLookup) {
            int iDest;
            if (ignorNSforTableLookup) {
                iDest = destination.Tables.IndexOf(Table.TableName);
            }
            else {
                iDest = destination.Tables.IndexOf(Table.TableName, Table.Namespace, false);// pass false for last param to be backward compatable
            }

            if (iDest < 0)
                return null;
            DataTable table = destination.Tables[iDest];

            int keys = ColumnsReference.Length;
            DataColumn[] columns = new DataColumn[keys];

            for (int i = 0; i < keys; i++) {
                DataColumn src = ColumnsReference[i];
                iDest = table.Columns.IndexOf(src.ColumnName);
                if (iDest < 0)
                    return null;
                columns[i] = table.Columns[iDest];
            }

            UniqueConstraint clone = new UniqueConstraint(ConstraintName, columns);

            // ...Extended Properties
            foreach(Object key in this.ExtendedProperties.Keys) {
               clone.ExtendedProperties[key]=this.ExtendedProperties[key];
            }

            return clone;
        }

        internal UniqueConstraint Clone(DataTable table) {
            int keys = ColumnsReference.Length;
            DataColumn[] columns = new DataColumn[keys];

            for (int i = 0; i < keys; i++) {
                DataColumn src = ColumnsReference[i];
                int iDest = table.Columns.IndexOf(src.ColumnName);
                if (iDest < 0)
                    return null;
                columns[i] = table.Columns[iDest];
            }

            UniqueConstraint clone = new UniqueConstraint(ConstraintName, columns);

            // ...Extended Properties
            foreach(Object key in this.ExtendedProperties.Keys) {
               clone.ExtendedProperties[key]=this.ExtendedProperties[key];
            }

            return clone;
        }

        /// <devdoc>
        ///    <para>Gets the array of columns that this constraint affects.</para>
        /// </devdoc>
        [
        ResCategoryAttribute(Res.DataCategory_Data),
        ResDescriptionAttribute(Res.KeyConstraintColumnsDescr),
        ReadOnly(true)
        ]
        public virtual DataColumn[] Columns {
            get {
                return key.ToArray();
            }
        }

        internal DataColumn[] ColumnsReference {
            get {
                return key.ColumnsReference;
            }
        }

        /// <devdoc>
        ///    <para>Gets
        ///       a value indicating whether or not the constraint is on a primary key.</para>
        /// </devdoc>
        [
        ResCategoryAttribute(Res.DataCategory_Data),
        ResDescriptionAttribute(Res.KeyConstraintIsPrimaryKeyDescr)
        ]
        public bool IsPrimaryKey {
            get {
                if (Table == null) {
                    return false;
                }
                return(this == Table.primaryKey);
            }
        }

        private void Create(String constraintName, DataColumn[] columns) {
            for (int i = 0; i < columns.Length; i++) {
                if (columns[i].Computed) {
                    throw ExceptionBuilder.ExpressionInConstraint(columns[i]);
                }
            }
            this.key = new DataKey(columns, true);
            ConstraintName = constraintName;
            NonVirtualCheckState();
        }

        /// <devdoc>
        ///    <para>Compares this constraint to a second to
        ///       determine if both are identical.</para>
        /// </devdoc>
        public override bool Equals(object key2) {
            if (!(key2 is UniqueConstraint))
                return false;

            return Key.ColumnsEqual(((UniqueConstraint)key2).Key);
        }

        public override Int32 GetHashCode() {
            return base.GetHashCode();
        }

        internal override bool InCollection {
            set {
                base.InCollection = value;
                if (key.ColumnsReference.Length == 1) {
                    key.ColumnsReference[0].InternalUnique(value);
                }
            }
        }

        internal DataKey Key {
            get {
                return key;
            }
        }

        /// <devdoc>
        ///    <para>Gets the table to which this constraint belongs.</para>
        /// </devdoc>
        [
        ResCategoryAttribute(Res.DataCategory_Data),
        ResDescriptionAttribute(Res.ConstraintTableDescr),
        ReadOnly(true)
        ]
        public override DataTable Table {
            get {
                if (key.HasValue) {
                    return key.Table;
                }
                return null;
            }
        }

        // misc
    }
}