protected override List <QueryLoadInfo> GetQueryLoadInfo() { var factory = Session.Factory; //for detached criteria if (_criteria.Session == null) { _criteria.Session = Session; } string[] implementors = factory.GetImplementors(_criteria.EntityOrClassName); int size = implementors.Length; var list = new List <QueryLoadInfo>(size); for (int i = 0; i < size; i++) { CriteriaLoader loader = new CriteriaLoader( factory.GetEntityPersister(implementors[i]) as IOuterJoinLoadable, factory, _criteria, implementors[i], Session.EnabledFilters ); list.Add( new QueryLoadInfo() { Loader = loader, Parameters = loader.Translator.GetQueryParameters(), QuerySpaces = loader.QuerySpaces, }); } return(list); }
private void CreateCriteriaLoaders() { //a criteria can use more than a single query (polymorphic queries), need to have a //way to correlate a loader to a result index int criteriaIndex = 0; foreach (CriteriaImpl criteria in criteriaQueries) { string[] implementors = factory.GetImplementors(criteria.EntityOrClassName); int size = implementors.Length; ISet <string> spaces = new HashSet <string>(); for (int i = 0; i < size; i++) { CriteriaLoader loader = new CriteriaLoader( session.GetOuterJoinLoadable(implementors[i]), factory, criteria, implementors[i], session.EnabledFilters ); loaders.Add(loader); loaderCriteriaMap.Add(criteriaIndex); spaces.UnionWith(loader.QuerySpaces); } criteriaIndex += 1; } }
protected virtual IList GetResultList(IList results) { var resultCollections = new List <object>(resultCollectionGenericType.Count); for (int i = 0; i < criteriaQueries.Count; i++) { if (resultCollectionGenericType[i] == typeof(object)) { resultCollections.Add(new List <object>()); } else { resultCollections.Add(Activator.CreateInstance(typeof(List <>).MakeGenericType(resultCollectionGenericType[i]))); } } for (int i = 0; i < loaders.Count; i++) { CriteriaLoader loader = loaders[i]; var resultList = loader.GetResultList((IList)results[i], parameters[i].ResultTransformer); var criteriaIndex = loaderCriteriaMap[i]; ArrayHelper.AddAll((IList)resultCollections[criteriaIndex], resultList); } if (resultTransformer != null) { for (int i = 0; i < results.Count; i++) { resultCollections[i] = resultTransformer.TransformList((IList)resultCollections[i]); } } return(resultCollections); }
protected virtual IList GetResultList(IList results) { for (int i = 0; i < loaders.Count; i++) { CriteriaLoader loader = loaders[i]; results[i] = loader.GetResultList((IList)results[i], parameters[i].ResultTransformer); IList tmpResults; if (resultCollectionGenericType[i] == typeof(object)) { tmpResults = new ArrayList(); } else { tmpResults = (IList)Activator.CreateInstance(typeof(List <>).MakeGenericType(resultCollectionGenericType[i])); } ArrayHelper.AddAll(tmpResults, (IList)results[i]); results[i] = tmpResults; } if (resultTransformer != null) { for (int i = 0; i < results.Count; i++) { results[i] = resultTransformer.TransformList((IList)results[i]); } } return(results); }
private void CreateCriteriaLoaders() { //a criteria can use more than a single query (polymorphic queries), need to have a //way to correlate a loader to a result index int criteriaIndex = 0; foreach (CriteriaImpl criteria in criteriaQueries) { string[] implementors = factory.GetImplementors(criteria.EntityOrClassName); int size = implementors.Length; CriteriaLoader[] tmpLoaders = new CriteriaLoader[size]; ISet <string> spaces = new HashedSet <string>(); for (int i = 0; i < size; i++) { CriteriaLoader loader = new CriteriaLoader( session.GetOuterJoinLoadable(implementors[i]), factory, criteria, implementors[i], session.EnabledFilters ); tmpLoaders[i] = loader; loaderToResultIndex[loader] = criteriaIndex; spaces.AddAll(tmpLoaders[i].QuerySpaces); } loaders.AddRange(tmpLoaders); criteriaIndex += 1; } }
public static String GetCritionSql(NHibernate.ICriteria criteria) { var criteriaImpl = (CriteriaImpl)criteria; var sessionImpl = (SessionImpl)criteriaImpl.Session; var factory = (SessionFactoryImpl)sessionImpl.SessionFactory; var implementors = factory.GetImplementors(criteriaImpl.EntityOrClassName); var loader = new CriteriaLoader((IOuterJoinLoadable)factory.GetEntityPersister(implementors[0]), factory, criteriaImpl, implementors[0], sessionImpl.EnabledFilters); var originalSql = loader.SqlString.ToString(); if (loader.Translator.CollectedParameters.Count > 0) { foreach (var param in loader.Translator.CollectedParameters) { int paramIndex = originalSql.IndexOf("?"); if (param.Type.GetType().Name == "StringType" || param.Type.GetType().Name == "DateTimeType" || param.Type.GetType().Name == "DateTime2Type" || param.Type.GetType().Name == "GuidType") { originalSql = originalSql.Substring(0, paramIndex) + "'" + param.Value + "'" + originalSql.Substring(paramIndex + 1); } else { originalSql = originalSql.Substring(0, paramIndex) + param.Value + originalSql.Substring(paramIndex + 1); } } } var fromIndex = 0; var lastCommaIndex = 0; while (true) { fromIndex = originalSql.IndexOf("from", lastCommaIndex, StringComparison.OrdinalIgnoreCase); var asIndex = originalSql.IndexOf(" as ", lastCommaIndex, StringComparison.OrdinalIgnoreCase); if (asIndex < 0 || asIndex > fromIndex) { break; } else { lastCommaIndex = originalSql.IndexOf(",", lastCommaIndex + 1, StringComparison.OrdinalIgnoreCase); if (lastCommaIndex >= 0 && lastCommaIndex < fromIndex) { originalSql = originalSql.Remove(asIndex, lastCommaIndex - asIndex); lastCommaIndex = asIndex; } else { originalSql = originalSql.Remove(asIndex + 1, fromIndex - asIndex - 1); break; } } } return(originalSql); }
public string GetGeneratedSql(ICriteria criteria) { var criteriaImpl = criteria as CriteriaImpl; var sessionImpl = criteriaImpl.Session; var factory = sessionImpl.Factory; var implementors = factory.GetImplementors(criteriaImpl.EntityOrClassName); var loader = new CriteriaLoader(factory.GetEntityPersister(implementors[0]) as IOuterJoinLoadable, factory, criteriaImpl, implementors[0], sessionImpl.EnabledFilters); return(loader.SqlString.ToString()); }
public override async Task <IList <T> > ListAsync <T>(CriteriaImpl criteria, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); using (BeginProcess()) { // We need to flush the batcher. Otherwise it may have pending operations which will not already have reached the database, // and the query may yield stale data. await(FlushAsync(cancellationToken)).ConfigureAwait(false); string[] implementors = Factory.GetImplementors(criteria.EntityOrClassName); int size = implementors.Length; CriteriaLoader[] loaders = new CriteriaLoader[size]; for (int i = 0; i < size; i++) { loaders[size - 1 - i] = new CriteriaLoader(GetOuterJoinLoadable(implementors[i]), Factory, criteria, implementors[i], EnabledFilters); } bool success = false; try { var results = await(loaders.LoadAllToListAsync <T>(this, cancellationToken)).ConfigureAwait(false); success = true; return(results); } catch (OperationCanceledException) { throw; } catch (HibernateException) { // Do not call Convert on HibernateExceptions throw; } catch (Exception sqle) { throw Convert(sqle, "Unable to perform find"); } finally { await(AfterOperationAsync(success, cancellationToken)).ConfigureAwait(false); temporaryPersistenceContext.Clear(); } } }
public override async Task ListAsync(CriteriaImpl criteria, IList results, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); using (new SessionIdLoggingContext(SessionId)) { CheckAndUpdateSessionStatus(); string[] implementors = Factory.GetImplementors(criteria.EntityOrClassName); int size = implementors.Length; CriteriaLoader[] loaders = new CriteriaLoader[size]; for (int i = 0; i < size; i++) { loaders[i] = new CriteriaLoader(GetOuterJoinLoadable(implementors[i]), Factory, criteria, implementors[i], EnabledFilters); } bool success = false; try { for (int i = size - 1; i >= 0; i--) { ArrayHelper.AddAll(results, await(loaders[i].ListAsync(this, cancellationToken)).ConfigureAwait(false)); } success = true; } catch (HibernateException) { // Do not call Convert on HibernateExceptions throw; } catch (Exception sqle) { throw Convert(sqle, "Unable to perform find"); } finally { await(AfterOperationAsync(success, cancellationToken)).ConfigureAwait(false); } temporaryPersistenceContext.Clear(); } }
public override void List(CriteriaImpl criteria, IList results) { using (BeginProcess()) { string[] implementors = Factory.GetImplementors(criteria.EntityOrClassName); int size = implementors.Length; CriteriaLoader[] loaders = new CriteriaLoader[size]; for (int i = 0; i < size; i++) { loaders[i] = new CriteriaLoader(GetOuterJoinLoadable(implementors[i]), Factory, criteria, implementors[i], EnabledFilters); } bool success = false; try { for (int i = size - 1; i >= 0; i--) { ArrayHelper.AddAll(results, loaders[i].List(this)); } success = true; } catch (HibernateException) { // Do not call Convert on HibernateExceptions throw; } catch (Exception sqle) { throw Convert(sqle, "Unable to perform find"); } finally { AfterOperation(success); } temporaryPersistenceContext.Clear(); } }
private void GetResultsFromDatabase(IList results) { Stopwatch stopWatch = null; if (session.Factory.Statistics.IsStatisticsEnabled) { stopWatch = Stopwatch.StartNew(); } int rowCount = 0; var cacheBatcher = new CacheBatcher(session); try { using (var reader = resultSetsCommand.GetReader(_timeout)) { var hydratedObjects = new List <object> [loaders.Count]; List <EntityKey[]>[] subselectResultKeys = new List <EntityKey[]> [loaders.Count]; bool[] createSubselects = new bool[loaders.Count]; for (int i = 0; i < loaders.Count; i++) { CriteriaLoader loader = loaders[i]; int entitySpan = loader.EntityPersisters.Length; hydratedObjects[i] = entitySpan == 0 ? null : new List <object>(entitySpan); EntityKey[] keys = new EntityKey[entitySpan]; QueryParameters queryParameters = parameters[i]; IList tmpResults = new List <object>(); RowSelection selection = parameters[i].RowSelection; createSubselects[i] = loader.IsSubselectLoadingEnabled; subselectResultKeys[i] = createSubselects[i] ? new List <EntityKey[]>() : null; int maxRows = Loader.Loader.HasMaxRows(selection) ? selection.MaxRows : int.MaxValue; if (!dialect.SupportsLimitOffset || !loader.UseLimit(selection, dialect)) { Loader.Loader.Advance(reader, selection); } int count; for (count = 0; count < maxRows && reader.Read(); count++) { rowCount++; object o = loader.GetRowFromResultSet(reader, session, queryParameters, loader.GetLockModes(queryParameters.LockModes), null, hydratedObjects[i], keys, true, null, null, (persister, data) => cacheBatcher.AddToBatch(persister, data)); if (createSubselects[i]) { subselectResultKeys[i].Add(keys); keys = new EntityKey[entitySpan]; //can't reuse in this case } tmpResults.Add(o); } results.Add(tmpResults); reader.NextResult(); } for (int i = 0; i < loaders.Count; i++) { CriteriaLoader loader = loaders[i]; loader.InitializeEntitiesAndCollections(hydratedObjects[i], reader, session, session.DefaultReadOnly, cacheBatcher); if (createSubselects[i]) { loader.CreateSubselects(subselectResultKeys[i], parameters[i], session); } } cacheBatcher.ExecuteBatch(); } } catch (Exception sqle) { log.Error(sqle, "Failed to execute multi criteria: [{0}]", resultSetsCommand.Sql); throw ADOExceptionHelper.Convert(session.Factory.SQLExceptionConverter, sqle, "Failed to execute multi criteria", resultSetsCommand.Sql); } if (stopWatch != null) { stopWatch.Stop(); session.Factory.StatisticsImplementor.QueryExecuted(string.Format("{0} queries (MultiCriteria)", loaders.Count), rowCount, stopWatch.Elapsed); } }
private void GetResultsFromDatabase(IList results) { bool statsEnabled = session.Factory.Statistics.IsStatisticsEnabled; var stopWatch = new Stopwatch(); if (statsEnabled) { stopWatch.Start(); } int rowCount = 0; using ( IDbCommand command = session.Batcher.PrepareCommand(CommandType.Text, sqlString, types.ToArray())) { BindParameters(command); ArrayList[] hydratedObjects = new ArrayList[loaders.Count]; List <EntityKey[]>[] subselectResultKeys = new List <EntityKey[]> [loaders.Count]; bool[] createSubselects = new bool[loaders.Count]; IDataReader reader = session.Batcher.ExecuteReader(command); try { for (int i = 0; i < loaders.Count; i++) { CriteriaLoader loader = loaders[i]; int entitySpan = loader.EntityPersisters.Length; hydratedObjects[i] = entitySpan == 0 ? null : new ArrayList(entitySpan); EntityKey[] keys = new EntityKey[entitySpan]; QueryParameters queryParameters = parameters[i]; IList tmpResults; if (resultCollectionGenericType[i] == typeof(object)) { tmpResults = new ArrayList(); } else { tmpResults = (IList)Activator.CreateInstance(typeof(List <>).MakeGenericType(resultCollectionGenericType[i])); } RowSelection selection = parameters[i].RowSelection; createSubselects[i] = loader.IsSubselectLoadingEnabled; subselectResultKeys[i] = createSubselects[i] ? new List <EntityKey[]>() : null; int maxRows = Loader.Loader.HasMaxRows(selection) ? selection.MaxRows : int.MaxValue; if (!dialect.SupportsLimitOffset || !NHibernate.Loader.Loader.UseLimit(selection, dialect)) { Loader.Loader.Advance(reader, selection); } int count; for (count = 0; count < maxRows && reader.Read(); count++) { rowCount++; object o = loader.GetRowFromResultSet(reader, session, queryParameters, loader.GetLockModes(queryParameters.LockModes), null, hydratedObjects[i], keys, false); if (createSubselects[i]) { subselectResultKeys[i].Add(keys); keys = new EntityKey[entitySpan]; //can't reuse in this case } tmpResults.Add(o); } results.Add(tmpResults); reader.NextResult(); } } catch (Exception e) { log.Error("Error executing multi criteria : [" + command.CommandText + "]"); throw new HibernateException("Error executing multi criteria : [" + command.CommandText + "]", e); } finally { session.Batcher.CloseCommand(command, reader); } for (int i = 0; i < loaders.Count; i++) { CriteriaLoader loader = loaders[i]; loader.InitializeEntitiesAndCollections(hydratedObjects[i], reader, session, false); if (createSubselects[i]) { loader.CreateSubselects(subselectResultKeys[i], parameters[i], session); } } } if (statsEnabled) { stopWatch.Stop(); session.Factory.StatisticsImplementor.QueryExecuted(string.Format("{0} queries (MultiCriteria)", loaders.Count), rowCount, stopWatch.Elapsed); } }
private async Task GetResultsFromDatabaseAsync(IList results, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); bool statsEnabled = session.Factory.Statistics.IsStatisticsEnabled; var stopWatch = new Stopwatch(); if (statsEnabled) { stopWatch.Start(); } int rowCount = 0; try { using (var reader = await(resultSetsCommand.GetReaderAsync(null, cancellationToken)).ConfigureAwait(false)) { var hydratedObjects = new List <object> [loaders.Count]; List <EntityKey[]>[] subselectResultKeys = new List <EntityKey[]> [loaders.Count]; bool[] createSubselects = new bool[loaders.Count]; for (int i = 0; i < loaders.Count; i++) { CriteriaLoader loader = loaders[i]; int entitySpan = loader.EntityPersisters.Length; hydratedObjects[i] = entitySpan == 0 ? null : new List <object>(entitySpan); EntityKey[] keys = new EntityKey[entitySpan]; QueryParameters queryParameters = parameters[i]; IList tmpResults = new List <object>(); RowSelection selection = parameters[i].RowSelection; createSubselects[i] = loader.IsSubselectLoadingEnabled; subselectResultKeys[i] = createSubselects[i] ? new List <EntityKey[]>() : null; int maxRows = Loader.Loader.HasMaxRows(selection) ? selection.MaxRows : int.MaxValue; if (!dialect.SupportsLimitOffset || !loader.UseLimit(selection, dialect)) { await(Loader.Loader.AdvanceAsync(reader, selection, cancellationToken)).ConfigureAwait(false); } int count; for (count = 0; count < maxRows && await(reader.ReadAsync(cancellationToken)).ConfigureAwait(false); count++) { rowCount++; object o = await(loader.GetRowFromResultSetAsync(reader, session, queryParameters, loader.GetLockModes(queryParameters.LockModes), null, hydratedObjects[i], keys, true, cancellationToken)).ConfigureAwait(false); if (createSubselects[i]) { subselectResultKeys[i].Add(keys); keys = new EntityKey[entitySpan]; //can't reuse in this case } tmpResults.Add(o); } results.Add(tmpResults); await(reader.NextResultAsync(cancellationToken)).ConfigureAwait(false); } for (int i = 0; i < loaders.Count; i++) { CriteriaLoader loader = loaders[i]; await(loader.InitializeEntitiesAndCollectionsAsync(hydratedObjects[i], reader, session, session.DefaultReadOnly, cancellationToken)).ConfigureAwait(false); if (createSubselects[i]) { loader.CreateSubselects(subselectResultKeys[i], parameters[i], session); } } } } catch (Exception sqle) { var message = string.Format("Failed to execute multi criteria: [{0}]", resultSetsCommand.Sql); log.Error(message, sqle); throw ADOExceptionHelper.Convert(session.Factory.SQLExceptionConverter, sqle, "Failed to execute multi criteria", resultSetsCommand.Sql); } if (statsEnabled) { stopWatch.Stop(); session.Factory.StatisticsImplementor.QueryExecuted(string.Format("{0} queries (MultiCriteria)", loaders.Count), rowCount, stopWatch.Elapsed); } }