forked from nhibernate/nhibernate-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQueryBatchItemBase.cs
411 lines (342 loc) · 11.7 KB
/
QueryBatchItemBase.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
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
411
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using NHibernate.Cache;
using NHibernate.Engine;
using NHibernate.Loader;
using NHibernate.SqlCommand;
using NHibernate.Type;
using NHibernate.Util;
namespace NHibernate.Multi
{
/// <summary>
/// Base class for both ICriteria and IQuery queries
/// </summary>
public abstract partial class QueryBatchItemBase<TResult> : IQueryBatchItem<TResult>, IQueryBatchItemWithAsyncProcessResults
{
private static readonly INHibernateLogger Log = NHibernateLogger.For(typeof(QueryBatch));
protected ISessionImplementor Session;
private List<EntityKey[]>[] _subselectResultKeys;
private List<QueryInfo> _queryInfos;
private CacheMode? _cacheMode;
private IList<TResult> _finalResults;
private DbDataReader _reader;
private List<object>[] _hydratedObjects;
protected class QueryInfo : ICachingInformation, ICachingInformationWithFetches
{
// Since 5.5
[Obsolete("Use QueryLoader property instead")]
public Loader.Loader Loader => QueryLoader as Loader.Loader ?? throw new NotSupportedException("Custom loader is not supported.");
/// <summary>
/// The query loader.
/// </summary>
public ILoader QueryLoader { get; }
/// <summary>
/// The query result.
/// </summary>
public IList Result { get; set; }
/// <inheritdoc />
public QueryParameters Parameters { get; }
/// <inheritdoc />
public ISet<string> QuerySpaces { get; }
//Cache related properties:
/// <inheritdoc />
public bool IsCacheable { get; }
/// <inheritdoc />
public QueryKey CacheKey { get; }
/// <inheritdoc />
public bool CanGetFromCache { get; }
// Do not store but forward instead: Loader.ResultTypes can be null initially (if AutoDiscoverTypes
// is enabled).
/// <inheritdoc />
public IType[] ResultTypes => QueryLoader.ResultTypes;
/// <inheritdoc />
public IType[] CacheTypes => QueryLoader.CacheTypes;
/// <inheritdoc />
public string QueryIdentifier => QueryLoader.QueryIdentifier;
/// <inheritdoc />
public IList ResultToCache { get; set; }
/// <summary>
/// Indicates if the query result was obtained from the cache.
/// </summary>
public bool IsResultFromCache { get; private set; }
/// <summary>
/// Should a result retrieved from database be cached?
/// </summary>
public bool CanPutToCache { get; }
/// <summary>
/// The cache batcher to use for entities and collections puts.
/// </summary>
public CacheBatcher CacheBatcher { get; private set; }
/// <summary>
/// Create a new <c>QueryInfo</c>.
/// </summary>
/// <param name="parameters">The query parameters.</param>
/// <param name="loader">The loader.</param>
/// <param name="querySpaces">The query spaces.</param>
/// <param name="session">The session of the query.</param>
// Since 5.5.
[Obsolete("Use overload taking an ILoader instead.")]
public QueryInfo(
QueryParameters parameters, Loader.Loader loader, ISet<string> querySpaces,
ISessionImplementor session) : this(parameters, (ILoader)loader, querySpaces, session)
{
}
/// <summary>
/// Create a new <c>QueryInfo</c>.
/// </summary>
/// <param name="parameters">The query parameters.</param>
/// <param name="loader">The loader.</param>
/// <param name="querySpaces">The query spaces.</param>
/// <param name="session">The session of the query.</param>
public QueryInfo(
QueryParameters parameters, ILoader loader, ISet<string> querySpaces,
ISessionImplementor session)
{
Parameters = parameters;
QueryLoader = loader;
QuerySpaces = querySpaces;
IsCacheable = loader.IsCacheable(parameters);
if (!IsCacheable)
return;
CacheKey = QueryLoader.GenerateQueryKey(session, Parameters);
CanGetFromCache = Parameters.CanGetFromCache(session);
CanPutToCache = Parameters.CanPutToCache(session);
}
/// <inheritdoc />
public void SetCachedResult(IList result)
{
if (!IsCacheable)
throw new InvalidOperationException("Cannot set cached result on a non cacheable query");
if (Result != null)
throw new InvalidOperationException("Result is already set");
Result = result;
IsResultFromCache = result != null;
}
/// <inheritdoc />
public void SetCacheBatcher(CacheBatcher cacheBatcher)
{
CacheBatcher = cacheBatcher;
}
}
protected abstract List<QueryInfo> GetQueryInformation(ISessionImplementor session);
/// <inheritdoc />
public IEnumerable<ICachingInformation> CachingInformation
{
get
{
ThrowIfNotInitialized();
return _queryInfos;
}
}
/// <inheritdoc />
public virtual void Init(ISessionImplementor session)
{
Session = session;
_queryInfos = GetQueryInformation(session);
// Cache and readonly parameters are the same for all translators
_cacheMode = _queryInfos.First().Parameters.CacheMode;
var count = _queryInfos.Count;
_subselectResultKeys = new List<EntityKey[]>[count];
_finalResults = null;
}
/// <inheritdoc />
public IEnumerable<string> GetQuerySpaces()
{
return _queryInfos.SelectMany(q => q.QuerySpaces);
}
/// <inheritdoc />
public IEnumerable<ISqlCommand> GetCommands()
{
ThrowIfNotInitialized();
foreach (var qi in _queryInfos)
{
if (qi.IsResultFromCache)
continue;
yield return qi.QueryLoader.CreateSqlCommand(qi.Parameters, Session);
}
}
/// <inheritdoc />
public int ProcessResultsSet(DbDataReader reader)
{
ThrowIfNotInitialized();
var dialect = Session.Factory.Dialect;
var hydratedObjects = new List<object>[_queryInfos.Count];
var isDebugLog = Log.IsDebugEnabled();
using (Session.SwitchCacheMode(_cacheMode))
{
var rowCount = 0;
for (var i = 0; i < _queryInfos.Count; i++)
{
var queryInfo = _queryInfos[i];
var loader = queryInfo.QueryLoader;
var queryParameters = queryInfo.Parameters;
//Skip processing for items already loaded from cache
if (queryInfo.IsResultFromCache)
{
continue;
}
var entitySpan = loader.EntityPersisters.Length;
hydratedObjects[i] = entitySpan == 0 ? null : new List<object>(entitySpan);
var keys = new EntityKey[entitySpan];
var selection = queryParameters.RowSelection;
var createSubselects = loader.IsSubselectLoadingEnabled;
_subselectResultKeys[i] = createSubselects ? new List<EntityKey[]>() : null;
var maxRows = Loader.Loader.HasMaxRows(selection) ? selection.MaxRows : int.MaxValue;
var advanceSelection = !dialect.SupportsLimitOffset || !loader.UseLimit(selection, dialect);
if (advanceSelection)
{
Loader.Loader.Advance(reader, selection);
}
var forcedResultTransformer = queryInfo.CacheKey?.ResultTransformer;
if (queryParameters.HasAutoDiscoverScalarTypes)
{
loader.AutoDiscoverTypes(reader, queryParameters, forcedResultTransformer);
}
var lockModeArray = loader.GetLockModes(queryParameters.LockModes);
var optionalObjectKey = Loader.Loader.GetOptionalObjectKey(queryParameters, Session);
var tmpResults = new List<object>();
var queryCacheBuilder = queryInfo.IsCacheable ? new QueryCacheResultBuilder(loader) : null;
var cacheBatcher = queryInfo.CacheBatcher;
var ownCacheBatcher = cacheBatcher == null;
if (ownCacheBatcher)
cacheBatcher = new CacheBatcher(Session);
if (isDebugLog)
Log.Debug("processing result set");
int count;
for (count = 0; count < maxRows && reader.Read(); count++)
{
if (isDebugLog)
Log.Debug("result set row: {0}", count);
rowCount++;
var o =
loader.GetRowFromResultSet(
reader,
Session,
queryParameters,
lockModeArray,
optionalObjectKey,
hydratedObjects[i],
keys,
true,
forcedResultTransformer,
queryCacheBuilder,
(persister, data) => cacheBatcher.AddToBatch(persister, data)
);
if (loader.IsSubselectLoadingEnabled)
{
_subselectResultKeys[i].Add(keys);
keys = new EntityKey[entitySpan]; //can't reuse in this case
}
tmpResults.Add(o);
}
if (isDebugLog)
Log.Debug("done processing result set ({0} rows)", count);
queryInfo.Result = tmpResults;
if (queryInfo.CanPutToCache)
queryInfo.ResultToCache = queryCacheBuilder.Result;
if (ownCacheBatcher)
cacheBatcher.ExecuteBatch();
reader.NextResult();
}
StopLoadingCollections(reader);
_reader = reader;
_hydratedObjects = hydratedObjects;
return rowCount;
}
}
/// <inheritdoc cref="IQueryBatchItem.ProcessResults" />
public void ProcessResults()
{
ThrowIfNotInitialized();
using (Session.SwitchCacheMode(_cacheMode))
InitializeEntitiesAndCollections(_reader, _hydratedObjects);
for (var i = 0; i < _queryInfos.Count; i++)
{
var queryInfo = _queryInfos[i];
if (_subselectResultKeys[i] != null)
{
queryInfo.QueryLoader.CreateSubselects(_subselectResultKeys[i], queryInfo.Parameters, Session);
}
if (queryInfo.IsCacheable)
{
if (queryInfo.IsResultFromCache)
{
var queryCacheBuilder = new QueryCacheResultBuilder(queryInfo.QueryLoader);
queryInfo.Result = queryCacheBuilder.GetResultList(queryInfo.Result);
}
// This transformation must not be applied to ResultToCache.
queryInfo.Result =
queryInfo.QueryLoader.TransformCacheableResults(
queryInfo.Parameters, queryInfo.CacheKey.ResultTransformer, queryInfo.Result);
}
}
AfterLoadCallback?.Invoke(GetResults());
}
/// <inheritdoc />
public void ExecuteNonBatched()
{
_finalResults = GetResultsNonBatched();
AfterLoadCallback?.Invoke(_finalResults);
}
protected abstract IList<TResult> GetResultsNonBatched();
protected List<T> GetTypedResults<T>()
{
ThrowIfNotInitialized();
if (_queryInfos.Any(qi => qi.Result == null))
{
throw new InvalidOperationException("Some query results are missing, batch is likely not fully executed yet.");
}
var results = new List<T>(_queryInfos.Sum(qi => qi.Result.Count));
foreach (var queryInfo in _queryInfos)
{
var list = queryInfo.QueryLoader.GetResultList(
queryInfo.Result,
queryInfo.Parameters.ResultTransformer);
ArrayHelper.AddAll(results, list);
}
return results;
}
/// <inheritdoc />
public IList<TResult> GetResults()
{
return _finalResults ?? (_finalResults = DoGetResults());
}
/// <inheritdoc />
public Action<IList<TResult>> AfterLoadCallback { get; set; }
protected abstract List<TResult> DoGetResults();
private void InitializeEntitiesAndCollections(DbDataReader reader, List<object>[] hydratedObjects)
{
for (var i = 0; i < _queryInfos.Count; i++)
{
var queryInfo = _queryInfos[i];
if (queryInfo.IsResultFromCache)
continue;
queryInfo.QueryLoader.InitializeEntitiesAndCollections(
hydratedObjects[i], reader, Session, queryInfo.Parameters.IsReadOnly(Session),
queryInfo.CacheBatcher);
}
}
private void StopLoadingCollections(DbDataReader reader)
{
for (var i = 0; i < _queryInfos.Count; i++)
{
var queryInfo = _queryInfos[i];
if (queryInfo.IsResultFromCache)
continue;
queryInfo.QueryLoader.StopLoadingCollections(Session, reader);
}
}
private void ThrowIfNotInitialized()
{
if (_queryInfos == null)
throw new InvalidOperationException(
"The query item has not been initialized. A query item must belong to a batch " +
$"({nameof(IQueryBatch)}) and the batch must be executed ({nameof(IQueryBatch)}." +
$"{nameof(IQueryBatch.Execute)} or {nameof(IQueryBatch)}.{nameof(IQueryBatch.GetResult)}) " +
"before retrieving the item result.");
}
}
}