-
Notifications
You must be signed in to change notification settings - Fork 936
/
Copy pathForeignKey.cs
253 lines (227 loc) · 7.37 KB
/
ForeignKey.cs
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
using System.Collections.Generic;
using System.Text;
using NHibernate.Util;
using System;
namespace NHibernate.Mapping
{
/// <summary>
/// A Foreign Key constraint in the database.
/// </summary>
[Serializable]
public class ForeignKey : Constraint
{
private Table referencedTable;
private string referencedEntityName;
private bool cascadeDeleteEnabled;
private readonly List<Column> referencedColumns = new List<Column>();
/// <summary>
/// Generates the SQL string to create the named Foreign Key Constraint in the database.
/// </summary>
/// <param name="d">The <see cref="Dialect.Dialect"/> to use for SQL rules.</param>
/// <param name="constraintName">The name to use as the identifier of the constraint in the database.</param>
/// <param name="defaultSchema"></param>
/// <param name="defaultCatalog"></param>
/// <returns>
/// A string that contains the SQL to create the named Foreign Key Constraint.
/// </returns>
public override string SqlConstraintString(Dialect.Dialect d, string constraintName, string defaultCatalog, string defaultSchema)
{
string[] cols = new string[ColumnSpan];
string[] refcols = new string[ColumnSpan];
int i = 0;
IEnumerable<Column> refiter;
if (IsReferenceToPrimaryKey)
refiter = referencedTable.PrimaryKey.ColumnIterator;
else
refiter = referencedColumns;
foreach (Column column in ColumnIterator)
{
cols[i] = column.GetQuotedName(d);
i++;
}
i = 0;
foreach (Column column in refiter)
{
refcols[i] = column.GetQuotedName(d);
i++;
}
string result = d.GetAddForeignKeyConstraintString(constraintName, cols, referencedTable.GetQualifiedName(d, defaultCatalog, defaultSchema), refcols, IsReferenceToPrimaryKey);
return cascadeDeleteEnabled && d.SupportsCascadeDelete ? result + " on delete cascade" : result;
}
/// <summary>
/// Gets or sets the <see cref="Table"/> that the Foreign Key is referencing.
/// </summary>
/// <value>The <see cref="Table"/> the Foreign Key is referencing.</value>
/// <exception cref="MappingException">
/// Thrown when the number of columns in this Foreign Key is not the same
/// amount of columns as the Primary Key in the ReferencedTable.
/// </exception>
public Table ReferencedTable
{
get { return referencedTable; }
set { referencedTable = value; }
}
public bool CascadeDeleteEnabled
{
get { return cascadeDeleteEnabled; }
set { cascadeDeleteEnabled = value; }
}
#region IRelationalModel Memebers
/// <summary>
/// Get the SQL string to drop this Constraint in the database.
/// </summary>
/// <param name="dialect">The <see cref="Dialect.Dialect"/> to use for SQL rules.</param>
/// <param name="defaultSchema"></param>
/// <param name="defaultCatalog"></param>
/// <returns>
/// A string that contains the SQL to drop this Constraint.
/// </returns>
public override string SqlDropString(Dialect.Dialect dialect, string defaultCatalog, string defaultSchema)
{
var catalog = Table.GetQuotedCatalog(dialect, defaultCatalog);
var schema = Table.GetQuotedSchema(dialect, defaultSchema);
var quotedName = Table.GetQuotedName(dialect);
return new StringBuilder()
.AppendLine(dialect.GetIfExistsDropConstraint(catalog, schema, quotedName, Name))
.AppendFormat("alter table ")
.Append(Table.GetQualifiedName(dialect, defaultCatalog, defaultSchema))
.Append(" ")
.AppendLine(dialect.GetDropForeignKeyConstraintString(Name))
.Append(dialect.GetIfExistsDropConstraintEnd(catalog, schema, quotedName, Name))
.ToString();
}
#endregion
/// <summary>
/// Validates that columnspan of the foreignkey and the primarykey is the same.
/// Furthermore it aligns the length of the underlying tables columns.
/// </summary>
public void AlignColumns()
{
if (IsReferenceToPrimaryKey)
AlignColumns(referencedTable);
}
private void AlignColumns(Table referencedTable)
{
if (referencedTable.PrimaryKey.ColumnSpan != ColumnSpan)
{
StringBuilder sb = new StringBuilder();
sb.Append("Foreign key (")
.Append(Name + ":")
.Append(Table.Name)
.Append(" [");
AppendColumns(sb, ColumnIterator);
sb.Append("])")
.Append(") must have same number of columns as the referenced primary key (")
.Append(referencedTable.Name).Append(" [");
AppendColumns(sb, referencedTable.PrimaryKey.ColumnIterator);
sb.Append("])");
throw new FKUnmatchingColumnsException(sb.ToString());
}
AlignColumns(ColumnIterator, referencedTable.PrimaryKey.ColumnIterator);
}
internal static void AlignColumns(IEnumerable<Column> fk, IEnumerable<Column> pk)
{
using (var fkCols = fk.GetEnumerator())
using (var pkCols = pk.GetEnumerator())
{
while (fkCols.MoveNext() && pkCols.MoveNext())
{
if (pkCols.Current.IsLengthDefined() || fkCols.Current.IsLengthDefined())
fkCols.Current.Length = pkCols.Current.Length;
if (pkCols.Current.IsPrecisionDefined() || fkCols.Current.IsPrecisionDefined())
fkCols.Current.Precision = pkCols.Current.Precision;
if (pkCols.Current.IsScaleDefined() || fkCols.Current.IsScaleDefined())
fkCols.Current.Scale = pkCols.Current.Scale;
}
}
}
private static void AppendColumns(StringBuilder buf, IEnumerable<Column> columns)
{
bool commaNeeded = false;
foreach (Column column in columns)
{
if (commaNeeded)
buf.Append(StringHelper.CommaSpace);
commaNeeded = true;
buf.Append(column.Name);
}
}
public virtual void AddReferencedColumns(IEnumerable<Column> referencedColumnsIterator)
{
foreach (Column col in referencedColumnsIterator)
{
if (!col.IsFormula)
AddReferencedColumn(col);
}
}
private void AddReferencedColumn(Column column)
{
if (!referencedColumns.Contains(column))
referencedColumns.Add(column);
}
internal void AddReferencedTable(PersistentClass referencedClass)
{
if (referencedColumns.Count > 0)
{
referencedTable = referencedColumns[0].Value.Table;
}
else
{
referencedTable = referencedClass.Table;
}
}
public override string ToString()
{
if (!IsReferenceToPrimaryKey)
{
var result = new StringBuilder();
result.Append(GetType().FullName)
.Append('(')
.Append(Table.Name)
.Append(string.Join(", ", Columns))
.Append(" ref-columns:")
.Append('(')
.Append(string.Join(", ", ReferencedColumns))
.Append(") as ")
.Append(Name);
return result.ToString();
}
return base.ToString();
}
public bool HasPhysicalConstraint
{
get
{
return referencedTable.IsPhysicalTable && Table.IsPhysicalTable && !referencedTable.HasDenormalizedTables;
}
}
public IList<Column> ReferencedColumns
{
get { return referencedColumns; }
}
public string ReferencedEntityName
{
get { return referencedEntityName; }
set { referencedEntityName = value; }
}
/// <summary>Does this foreignkey reference the primary key of the reference table </summary>
public bool IsReferenceToPrimaryKey
{
get { return referencedColumns.Count == 0; }
}
public string GeneratedConstraintNamePrefix => "FK_";
public override bool IsGenerated(Dialect.Dialect dialect)
{
if (!HasPhysicalConstraint)
return false;
if (dialect.SupportsNullInUnique || IsReferenceToPrimaryKey)
return true;
foreach (var column in ReferencedColumns)
{
if (column.IsNullable)
return false;
}
return true;
}
}
}