-
Notifications
You must be signed in to change notification settings - Fork 934
/
Copy pathTableGenerator.cs
288 lines (252 loc) · 9.14 KB
/
TableGenerator.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
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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Runtime.CompilerServices;
using NHibernate.AdoNet.Util;
using NHibernate.Dialect;
using NHibernate.Engine;
using NHibernate.SqlCommand;
using NHibernate.SqlTypes;
using NHibernate.Type;
using NHibernate.Util;
namespace NHibernate.Id
{
/// <summary>
/// An <see cref="IIdentifierGenerator" /> that uses a database table to store the last
/// generated value.
/// </summary>
/// <remarks>
/// <p>
/// It is not intended that applications use this strategy directly. However,
/// it may be used to build other (efficient) strategies. The return type is
/// <c>System.Int32</c>
/// </p>
/// <p>
/// The hi value MUST be fetched in a separate transaction to the <c>ISession</c>
/// transaction so the generator must be able to obtain a new connection and commit it.
/// Hence this implementation may not be used when the user is supplying connections.
/// </p>
/// <p>
/// The mapping parameters <c>table</c> and <c>column</c> are required.
/// </p>
/// </remarks>
public partial class TableGenerator : TransactionHelper, IPersistentIdentifierGenerator, IConfigurable
{
private static readonly INHibernateLogger log = NHibernateLogger.For(typeof (TableGenerator));
/// <summary>
/// An additional where clause that is added to
/// the queries against the table.
/// </summary>
public const string Where = "where";
/// <summary>
/// The name of the column parameter.
/// </summary>
public const string ColumnParamName = "column";
/// <summary>
/// The name of the table parameter.
/// </summary>
public const string TableParamName = "table";
/// <summary>Default column name </summary>
public const string DefaultColumnName = "next_hi";
/// <summary>Default table name </summary>
public const string DefaultTableName = "hibernate_unique_key";
private string tableName;
private string columnName;
private string whereClause;
private string query;
protected SqlType columnSqlType;
protected PrimitiveType columnType;
private SqlString updateSql;
private SqlType[] parameterTypes;
private readonly AsyncLock _asyncLock = new AsyncLock();
#region IConfigurable Members
/// <summary>
/// Configures the TableGenerator by reading the value of <c>table</c>,
/// <c>column</c>, and <c>schema</c> from the <c>parms</c> parameter.
/// </summary>
/// <param name="type">The <see cref="IType"/> the identifier should be.</param>
/// <param name="parms">An <see cref="IDictionary"/> of Param values that are keyed by parameter name.</param>
/// <param name="dialect">The <see cref="Dialect"/> to help with Configuration.</param>
public virtual void Configure(IType type, IDictionary<string, string> parms, Dialect.Dialect dialect)
{
tableName = PropertiesHelper.GetString(TableParamName, parms, DefaultTableName);
columnName = PropertiesHelper.GetString(ColumnParamName, parms, DefaultColumnName);
whereClause = PropertiesHelper.GetString(Where, parms, "");
string schemaName = PropertiesHelper.GetString(PersistentIdGeneratorParmsNames.Schema, parms, null);
string catalogName = PropertiesHelper.GetString(PersistentIdGeneratorParmsNames.Catalog, parms, null);
if (tableName.IndexOf('.') < 0)
{
tableName = dialect.Qualify(catalogName, schemaName, tableName);
}
var selectBuilder = new SqlStringBuilder(100);
selectBuilder.Add("select " + columnName)
.Add(" from " + dialect.AppendLockHint(LockMode.Upgrade, tableName));
if (string.IsNullOrEmpty(whereClause) == false)
{
selectBuilder.Add(" where ").Add(whereClause);
}
selectBuilder.Add(dialect.ForUpdateString);
query = selectBuilder.ToString();
columnType = type as PrimitiveType;
if (columnType == null)
{
log.Error("Column type for TableGenerator is not a value type");
throw new ArgumentException("type is not a ValueTypeType", "type");
}
// build the sql string for the Update since it uses parameters
if (type is Int16Type)
{
columnSqlType = SqlTypeFactory.Int16;
}
else if (type is Int64Type)
{
columnSqlType = SqlTypeFactory.Int64;
}
else
{
columnSqlType = SqlTypeFactory.Int32;
}
parameterTypes = new[] {columnSqlType, columnSqlType};
var builder = new SqlStringBuilder(100);
builder.Add("update " + tableName + " set ")
.Add(columnName).Add(" = ").Add(Parameter.Placeholder)
.Add(" where ")
.Add(columnName).Add(" = ").Add(Parameter.Placeholder);
if (string.IsNullOrEmpty(whereClause) == false)
{
builder.Add(" and ").Add(whereClause);
}
updateSql = builder.ToSqlString();
}
#endregion
#region IIdentifierGenerator Members
/// <summary>
/// Generate a <see cref="short"/>, <see cref="int"/>, or <see cref="long"/>
/// for the identifier by selecting and updating a value in a table.
/// </summary>
/// <param name="session">The <see cref="ISessionImplementor"/> this id is being generated in.</param>
/// <param name="obj">The entity for which the id is being generated.</param>
/// <returns>The new identifier as a <see cref="short"/>, <see cref="int"/>, or <see cref="long"/>.</returns>
public virtual object Generate(ISessionImplementor session, object obj)
{
using (_asyncLock.Lock())
{
// This has to be done using a different connection to the containing
// transaction becase the new hi value must remain valid even if the
// containing transaction rolls back.
return DoWorkInNewTransaction(session);
}
}
#endregion
#region IPersistentIdentifierGenerator Members
/// <summary>
/// The SQL required to create the database objects for a TableGenerator.
/// </summary>
/// <param name="dialect">The <see cref="Dialect"/> to help with creating the sql.</param>
/// <returns>
/// An array of <see cref="string"/> objects that contain the Dialect specific sql to
/// create the necessary database objects and to create the first value as <c>1</c>
/// for the TableGenerator.
/// </returns>
public virtual string[] SqlCreateStrings(Dialect.Dialect dialect)
{
// changed the first value to be "1" by default since an uninitialized Int32 is 0 - leaving
// it at 0 would cause problems with an unsaved-value="0" which is what most people are
// defaulting <id>'s with Int32 types at.
return new[]
{
"create table " + tableName + " ( " + columnName + " " + dialect.GetTypeName(columnSqlType) + " )",
"insert into " + tableName + " values ( 1 )"
};
}
/// <summary>
/// The SQL required to remove the underlying database objects for a TableGenerator.
/// </summary>
/// <param name="dialect">The <see cref="Dialect"/> to help with creating the sql.</param>
/// <returns>
/// A <see cref="string"/> that will drop the database objects for the TableGenerator.
/// </returns>
public virtual string[] SqlDropString(Dialect.Dialect dialect)
{
return new[] {dialect.GetDropTableString(tableName)};
}
/// <summary>
/// Return a key unique to the underlying database objects for a TableGenerator.
/// </summary>
/// <returns>
/// The configured table name.
/// </returns>
public string GeneratorKey()
{
return tableName;
}
#endregion
public override object DoWorkInCurrentTransaction(ISessionImplementor session, DbConnection conn,
DbTransaction transaction)
{
long result;
int rows;
do
{
//the loop ensure atomicitiy of the
//select + update even for no transaction
//or read committed isolation level (needed for .net?)
var qps = conn.CreateCommand();
DbDataReader rs = null;
qps.CommandText = query;
qps.CommandType = CommandType.Text;
qps.Transaction = transaction;
PersistentIdGeneratorParmsNames.SqlStatementLogger.LogCommand("Reading high value:", qps, FormatStyle.Basic);
try
{
rs = qps.ExecuteReader();
if (!rs.Read())
{
var errFormat = string.IsNullOrEmpty(whereClause)
? "could not read a hi value - you need to populate the table: {0}"
: "could not read a hi value from table '{0}' using the where clause ({1})- you need to populate the table.";
log.Error(errFormat, tableName, whereClause);
throw new IdentifierGenerationException(string.Format(errFormat, tableName, whereClause));
}
result = Convert.ToInt64(columnType.Get(rs, 0, session));
}
catch (Exception e)
{
log.Error(e, "could not read a hi value");
throw;
}
finally
{
if (rs != null)
{
rs.Close();
}
qps.Dispose();
}
var ups = session.Factory.ConnectionProvider.Driver.GenerateCommand(CommandType.Text, updateSql, parameterTypes);
ups.Connection = conn;
ups.Transaction = transaction;
try
{
columnType.Set(ups, result + 1, 0, session);
columnType.Set(ups, result, 1, session);
PersistentIdGeneratorParmsNames.SqlStatementLogger.LogCommand("Updating high value:", ups, FormatStyle.Basic);
rows = ups.ExecuteNonQuery();
}
catch (Exception e)
{
log.Error(e, "could not update hi value in: {0}", tableName);
throw;
}
finally
{
ups.Dispose();
}
}
while (rows == 0);
return result;
}
}
}