Example #1
0
        protected List <object> DoList()
        {
            bool statsEnabled = session.Factory.Statistics.IsStatisticsEnabled;
            var  stopWatch    = new Stopwatch();

            if (statsEnabled)
            {
                stopWatch.Start();
            }
            int rowCount = 0;

            var results = new List <object>();

            var hydratedObjects = new List <object> [Translators.Count];

            List <EntityKey[]>[] subselectResultKeys = new List <EntityKey[]> [Translators.Count];
            bool[] createSubselects = new bool[Translators.Count];
            var    cacheBatcher     = new CacheBatcher(session);

            try
            {
                using (var reader = resultSetsCommand.GetReader(_timeout))
                {
                    if (log.IsDebugEnabled())
                    {
                        log.Debug("Executing {0} queries", translators.Count);
                    }
                    for (int i = 0; i < translators.Count; i++)
                    {
                        ITranslator     translator = Translators[i];
                        QueryParameters parameter  = Parameters[i];

                        int entitySpan = translator.Loader.EntityPersisters.Length;
                        hydratedObjects[i] = entitySpan > 0 ? new List <object>() : null;
                        RowSelection selection = parameter.RowSelection;
                        int          maxRows   = Loader.Loader.HasMaxRows(selection) ? selection.MaxRows : int.MaxValue;
                        if (!dialect.SupportsLimitOffset || !translator.Loader.UseLimit(selection, dialect))
                        {
                            Loader.Loader.Advance(reader, selection);
                        }

                        if (parameter.HasAutoDiscoverScalarTypes)
                        {
                            translator.Loader.AutoDiscoverTypes(reader, parameter, null);
                        }

                        LockMode[] lockModeArray     = translator.Loader.GetLockModes(parameter.LockModes);
                        EntityKey  optionalObjectKey = Loader.Loader.GetOptionalObjectKey(parameter, session);

                        createSubselects[i]    = translator.Loader.IsSubselectLoadingEnabled;
                        subselectResultKeys[i] = createSubselects[i] ? new List <EntityKey[]>() : null;

                        translator.Loader.HandleEmptyCollections(parameter.CollectionKeys, reader, session);
                        EntityKey[] keys = new EntityKey[entitySpan];                         // we can reuse it each time

                        if (log.IsDebugEnabled())
                        {
                            log.Debug("processing result set");
                        }

                        IList tempResults = new List <object>();
                        int   count;
                        for (count = 0; count < maxRows && reader.Read(); count++)
                        {
                            if (log.IsDebugEnabled())
                            {
                                log.Debug("result set row: {0}", count);
                            }

                            rowCount++;
                            object result = translator.Loader.GetRowFromResultSet(
                                reader, session, parameter, lockModeArray, optionalObjectKey, hydratedObjects[i], keys, true, null, null,
                                (persister, data) => cacheBatcher.AddToBatch(persister, data));
                            tempResults.Add(result);

                            if (createSubselects[i])
                            {
                                subselectResultKeys[i].Add(keys);
                                keys = new EntityKey[entitySpan];                                 //can't reuse in this case
                            }
                        }

                        if (log.IsDebugEnabled())
                        {
                            log.Debug("done processing result set ({0} rows)", count);
                        }

                        results.Add(tempResults);

                        if (log.IsDebugEnabled())
                        {
                            log.Debug("Query {0} returned {1} results", i, tempResults.Count);
                        }

                        reader.NextResult();
                    }

                    for (int i = 0; i < translators.Count; i++)
                    {
                        ITranslator     translator = translators[i];
                        QueryParameters parameter  = parameters[i];

                        translator.Loader.InitializeEntitiesAndCollections(hydratedObjects[i], reader, session, false, cacheBatcher);

                        if (createSubselects[i])
                        {
                            translator.Loader.CreateSubselects(subselectResultKeys[i], parameter, session);
                        }
                    }

                    cacheBatcher.ExecuteBatch();
                }
            }
            catch (Exception sqle)
            {
                log.Error(sqle, "Failed to execute multi query: [{0}]", resultSetsCommand.Sql);
                throw ADOExceptionHelper.Convert(session.Factory.SQLExceptionConverter, sqle, "Failed to execute multi query", resultSetsCommand.Sql);
            }

            if (statsEnabled)
            {
                stopWatch.Stop();
                session.Factory.StatisticsImplementor.QueryExecuted(string.Format("{0} queries (MultiQuery)", translators.Count), rowCount, stopWatch.Elapsed);
            }
            return(results);
        }
Example #2
0
 public void SelectRow(int y)
 {
     Selections.ClearSelection();
     Selections.StartAt(0, y);
     Selections.Add(RowSelection.FullRowSelection(y));
 }
Example #3
0
        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 Workbook GenerateWorkBook()
        {
            this.headerRowCount  = this.ShowColumnHeaders ? 1 : 0;
            this.headerRowCount += this.ChildrenOfType <GridViewColumnGroupRow>().Count();
            Workbook workbook = null;

            workbook = this.ExportToWorkbook();

            var worksheet = workbook.ActiveWorksheet;

            worksheet.GroupingProperties.SummaryRowIsBelow = false;
            DataTemplate     template = this.HierarchyChildTemplate;
            DependencyObject content  = template.LoadContent();
            var childGrid             = content as RadGridView;
            var parentItemCount       = 0;

            foreach (var parentItem in parentItemsDictionary)
            {
                var rowIndex = parentItem.ExportIndex + headerRowCount + parentItemCount + 1;
                parentItemCount++;
                RowSelection selection = worksheet.Rows[rowIndex, rowIndex + parentItem.SubItems.Count];
                selection.Insert();
                for (var j = 0; j < childGrid.Columns.Count; j++)
                {
                    var column = childGrid.Columns[j] as GridViewDataColumn;
                    var header = column.Header != null?column.Header.ToString() : column.DataMemberBinding.Path.Path;

                    var headerCell = worksheet.Cells[rowIndex, j];
                    headerCell.SetValueAsText(header);
                    var headerCellFill = new PatternFill(PatternType.Solid, Color.FromArgb(255, 150, 150, 150), Colors.Transparent);
                    headerCell.SetFill(headerCellFill);
                    headerCell.SetIsBold(true);

                    for (var i = 0; i < parentItem.SubItems.Count; i++)
                    {
                        var item = parentItem.SubItems[i];

                        var cell     = worksheet.Cells[rowIndex + 1 + i, j];
                        var property = item.GetType().GetProperty(column.DataMemberBinding.Path.Path);
                        var value    = property != null?property.GetValue(item).ToString() : string.Empty;

                        cell.SetValueAsText(value);
                        var subItemCellFill = new PatternFill(PatternType.Solid, Color.FromArgb(255, 46, 204, 113), Colors.Transparent);
                        cell.SetFill(subItemCellFill);
                    }
                }

                selection.Group();
                var originalItem = this.Items[parentItem.OriginalIndex];
                var isExpanded   = (bool)originalItem.GetType().GetProperty("IsExpanded").GetValue(originalItem);
                if (!isExpanded)
                {
                    selection.SetHidden(true);
                }
            }

            for (var j = 0; j < childGrid.Columns.Count; j++)
            {
                worksheet.Columns[j].AutoFitWidth();
            }

            return(workbook);
        }
Example #5
0
        protected SqlString GetSubSelectWithLimits(SqlString subquery, ICollection <IParameterSpecification> parameterSpecs, RowSelection processedRowSelection, IDictionary <string, TypedValue> parameters)
        {
            ISessionFactoryImplementor sessionFactory = Factory;

            Dialect.Dialect dialect = sessionFactory.Dialect;

            RowSelection selection = processedRowSelection;
            bool         useLimit  = UseLimit(selection, dialect);

            if (useLimit)
            {
                bool hasFirstRow = GetFirstRow(selection) > 0;
                bool useOffset   = hasFirstRow && dialect.SupportsLimitOffset;
                int  max         = GetMaxOrLimit(dialect, selection);
                int? skip        = useOffset ? (int?)dialect.GetOffsetValue(GetFirstRow(selection)) : null;
                int? take        = max != int.MaxValue ? (int?)max : null;

                Parameter skipSqlParameter = null;
                Parameter takeSqlParameter = null;
                if (skip.HasValue)
                {
                    string skipParameterName = "nhsubselectskip";
                    var    skipParameter     = new NamedParameterSpecification(1, 0, skipParameterName)
                    {
                        ExpectedType = NHibernateUtil.Int32
                    };
                    skipSqlParameter           = Parameter.Placeholder;
                    skipSqlParameter.BackTrack = skipParameter.GetIdsForBackTrack(sessionFactory).First();
                    parameters.Add(skipParameterName, new TypedValue(skipParameter.ExpectedType, skip.Value));
                    parameterSpecs.Add(skipParameter);
                }
                if (take.HasValue)
                {
                    string takeParameterName = "nhsubselecttake";
                    var    takeParameter     = new NamedParameterSpecification(1, 0, takeParameterName)
                    {
                        ExpectedType = NHibernateUtil.Int32
                    };
                    takeSqlParameter           = Parameter.Placeholder;
                    takeSqlParameter.BackTrack = takeParameter.GetIdsForBackTrack(sessionFactory).First();
                    parameters.Add(takeParameterName, new TypedValue(takeParameter.ExpectedType, take.Value));
                    parameterSpecs.Add(takeParameter);
                }

                // The dialect can move the given parameters where he need, what it can't do is generates new parameters loosing the BackTrack.
                SqlString result;
                if (TryGetLimitString(dialect, subquery, skip, take, skipSqlParameter, takeSqlParameter, out result))
                {
                    return(result);
                }
            }
            return(subquery);
        }
Example #6
0
        public void PerformList(QueryParameters queryParameters, ISessionImplementor session, IList results)
        {
            if (Log.IsDebugEnabled)
            {
                Log.Debug("find: " + _sourceQuery);
                queryParameters.LogParameters(session.Factory);
            }

            bool            hasLimit   = queryParameters.RowSelection != null && queryParameters.RowSelection.DefinesLimits;
            bool            needsLimit = hasLimit && Translators.Length > 1;
            QueryParameters queryParametersToUse;

            if (needsLimit)
            {
                Log.Warn("firstResult/maxResults specified on polymorphic query; applying in memory!");
                RowSelection selection = new RowSelection();
                selection.FetchSize  = queryParameters.RowSelection.FetchSize;
                selection.Timeout    = queryParameters.RowSelection.Timeout;
                queryParametersToUse = queryParameters.CreateCopyUsing(selection);
            }
            else
            {
                queryParametersToUse = queryParameters;
            }

            IList       combinedResults = results ?? new List <object>();
            IdentitySet distinction     = new IdentitySet();
            int         includedCount   = -1;

            for (int i = 0; i < Translators.Length; i++)
            {
                IList tmp = Translators[i].List(session, queryParametersToUse);
                if (needsLimit)
                {
                    // NOTE : firstRow is zero-based
                    int first = queryParameters.RowSelection.FirstRow == RowSelection.NoValue
                                                                                                ? 0
                                                                                                : queryParameters.RowSelection.FirstRow;

                    int max = queryParameters.RowSelection.MaxRows == RowSelection.NoValue
                                                                                        ? RowSelection.NoValue
                                                                                        : queryParameters.RowSelection.MaxRows;

                    int size = tmp.Count;
                    for (int x = 0; x < size; x++)
                    {
                        object result = tmp[x];
                        if (distinction.Add(result))
                        {
                            continue;
                        }
                        includedCount++;
                        if (includedCount < first)
                        {
                            continue;
                        }
                        combinedResults.Add(result);
                        if (max >= 0 && includedCount > max)
                        {
                            // break the outer loop !!!
                            return;
                        }
                    }
                }
                else
                {
                    ArrayHelper.AddAll(combinedResults, tmp);
                }
            }
        }
Example #7
0
        protected ArrayList DoList()
        {
            bool statsEnabled = session.Factory.Statistics.IsStatisticsEnabled;
            var  stopWatch    = new Stopwatch();

            if (statsEnabled)
            {
                stopWatch.Start();
            }
            int rowCount = 0;

            IDbCommand command = PrepareQueriesCommand();

            BindParameters(command);

            ArrayList results = new ArrayList();

            log.Info(command.CommandText);
            if (commandTimeout != RowSelection.NoValue)
            {
                command.CommandTimeout = commandTimeout;
            }
            ArrayList[]          hydratedObjects     = new ArrayList[Translators.Count];
            List <EntityKey[]>[] subselectResultKeys = new List <EntityKey[]> [Translators.Count];
            bool[]      createSubselects             = new bool[Translators.Count];
            IDataReader reader = session.Batcher.ExecuteReader(command);

            try
            {
                if (log.IsDebugEnabled)
                {
                    log.DebugFormat("Executing {0} queries", translators.Count);
                }
                for (int i = 0; i < translators.Count; i++)
                {
                    IQueryTranslator translator = Translators[i];
                    QueryParameters  parameter  = Parameters[i];
                    IList            tempResults;
                    if (resultCollectionGenericType[i] == typeof(object))
                    {
                        tempResults = new ArrayList();
                    }
                    else
                    {
                        tempResults = (IList)Activator.CreateInstance(typeof(List <>).MakeGenericType(resultCollectionGenericType[i]));
                    }
                    int entitySpan = translator.Loader.EntityPersisters.Length;
                    hydratedObjects[i] = entitySpan > 0 ? new ArrayList() : null;
                    RowSelection selection = parameter.RowSelection;
                    int          maxRows   = Loader.Loader.HasMaxRows(selection) ? selection.MaxRows : int.MaxValue;
                    if (!dialect.SupportsLimitOffset || !Loader.Loader.UseLimit(selection, dialect))
                    {
                        Loader.Loader.Advance(reader, selection);
                    }

                    LockMode[] lockModeArray     = translator.Loader.GetLockModes(parameter.LockModes);
                    EntityKey  optionalObjectKey = Loader.Loader.GetOptionalObjectKey(parameter, session);

                    createSubselects[i]    = translator.Loader.IsSubselectLoadingEnabled;
                    subselectResultKeys[i] = createSubselects[i] ? new List <EntityKey[]>() : null;

                    translator.Loader.HandleEmptyCollections(parameter.CollectionKeys, reader, session);
                    EntityKey[] keys = new EntityKey[entitySpan];                     // we can reuse it each time

                    if (log.IsDebugEnabled)
                    {
                        log.Debug("processing result set");
                    }

                    int count;
                    for (count = 0; count < maxRows && reader.Read(); count++)
                    {
                        if (log.IsDebugEnabled)
                        {
                            log.Debug("result set row: " + count);
                        }

                        rowCount++;

                        object result =
                            translator.Loader.GetRowFromResultSet(reader,
                                                                  session,
                                                                  parameter,
                                                                  lockModeArray,
                                                                  optionalObjectKey,
                                                                  hydratedObjects[i],
                                                                  keys,
                                                                  false);

                        tempResults.Add(result);

                        if (createSubselects[i])
                        {
                            subselectResultKeys[i].Add(keys);
                            keys = new EntityKey[entitySpan];                             //can't reuse in this case
                        }
                    }

                    if (log.IsDebugEnabled)
                    {
                        log.Debug(string.Format("done processing result set ({0} rows)", count));
                    }

                    results.Add(tempResults);

                    if (log.IsDebugEnabled)
                    {
                        log.DebugFormat("Query {0} returned {1} results", i, tempResults.Count);
                    }

                    reader.NextResult();
                }
            }
            catch (Exception ex)
            {
                log.Error("Failed to execute multi query: [" + command.CommandText + "]", ex);
                throw new HibernateException("Failed to execute multi query: [" + command.CommandText + "]", ex);
            }
            finally
            {
                session.Batcher.CloseCommand(command, reader);
            }
            for (int i = 0; i < translators.Count; i++)
            {
                IQueryTranslator translator = translators[i];
                QueryParameters  parameter  = parameters[i];

                translator.Loader.InitializeEntitiesAndCollections(hydratedObjects[i], reader, session, false);

                if (createSubselects[i])
                {
                    translator.Loader.CreateSubselects(subselectResultKeys[i], parameter, session);
                }
            }
            if (statsEnabled)
            {
                stopWatch.Stop();
                session.Factory.StatisticsImplementor.QueryExecuted(string.Format("{0} queries (MultiQuery)", translators.Count), rowCount, stopWatch.Elapsed);
            }
            return(results);
        }
Example #8
0
        void IRowElement.Setup(RowPresenter p)
        {
            var dataPresenter = p.DataPresenter;

            RowSelection.EnsureSetup(dataPresenter);
        }
Example #9
0
        void IScalarElement.Setup(ScalarPresenter scalarPresenter)
        {
            var dataPresenter = scalarPresenter.DataPresenter;

            RowSelection.EnsureSetup(dataPresenter);
        }
        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);
            }
        }
Example #11
0
        public async Task PerformListAsync(QueryParameters queryParameters, ISessionImplementor session, IList results, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            if (Log.IsDebugEnabled())
            {
                Log.Debug("find: {0}", _sourceQuery);
                queryParameters.LogParameters(session.Factory);
            }

            bool            hasLimit   = queryParameters.RowSelection != null && queryParameters.RowSelection.DefinesLimits;
            bool            needsLimit = hasLimit && Translators.Length > 1;
            QueryParameters queryParametersToUse;

            if (needsLimit)
            {
                Log.Warn("firstResult/maxResults specified on polymorphic query; applying in memory!");
                RowSelection selection = new RowSelection();
                selection.FetchSize  = queryParameters.RowSelection.FetchSize;
                selection.Timeout    = queryParameters.RowSelection.Timeout;
                queryParametersToUse = queryParameters.CreateCopyUsing(selection);
            }
            else
            {
                queryParametersToUse = queryParameters;
            }

            IList combinedResults = results ?? new List <object>();
            var   distinction     = new HashSet <object>(ReferenceComparer <object> .Instance);
            int   includedCount   = -1;

            for (int i = 0; i < Translators.Length; i++)
            {
                IList tmp = await(Translators[i].ListAsync(session, queryParametersToUse, cancellationToken)).ConfigureAwait(false);
                if (needsLimit)
                {
                    // NOTE : firstRow is zero-based
                    int first = queryParameters.RowSelection.FirstRow == RowSelection.NoValue
                                                                                                ? 0
                                                                                                : queryParameters.RowSelection.FirstRow;

                    int max = queryParameters.RowSelection.MaxRows == RowSelection.NoValue
                                                                                        ? RowSelection.NoValue
                                                                                        : queryParameters.RowSelection.MaxRows;

                    int size = tmp.Count;
                    for (int x = 0; x < size; x++)
                    {
                        object result = tmp[x];
                        if (distinction.Add(result))
                        {
                            continue;
                        }
                        includedCount++;
                        if (includedCount < first)
                        {
                            continue;
                        }
                        combinedResults.Add(result);
                        if (max >= 0 && includedCount > max)
                        {
                            // break the outer loop !!!
                            return;
                        }
                    }
                }
                else
                {
                    ArrayHelper.AddAll(combinedResults, tmp);
                }
            }
        }
        /// <summary>
        /// Create an <see cref="IEnumerable"/> wrapper over an <see cref="IDataReader"/>.
        /// </summary>
        /// <param name="reader">The <see cref="IDataReader"/> to enumerate over.</param>
        /// <param name="cmd">The <see cref="IDbCommand"/> used to create the <see cref="IDataReader"/>.</param>
        /// <param name="sess">The <see cref="ISession"/> to use to load objects.</param>
        /// <param name="types">The <see cref="IType"/>s contained in the <see cref="IDataReader"/>.</param>
        /// <param name="columnNames">The names of the columns in the <see cref="IDataReader"/>.</param>
        /// <param name="selection">The <see cref="RowSelection"/> that should be applied to the <see cref="IDataReader"/>.</param>
        /// <param name="holderType">Optional type of the result holder (used for "select new SomeClass(...)" queries).</param>
        /// <remarks>
        /// The <see cref="IDataReader"/> should already be positioned on the first record in <see cref="RowSelection"/>.
        /// </remarks>
        public EnumerableImpl(IDataReader reader, IDbCommand cmd, ISessionImplementor sess, IType[] types, string[] [] columnNames, RowSelection selection,
                              System.Type holderType)
        {
            _reader    = reader;
            _cmd       = cmd;
            _sess      = sess;
            _types     = types;
            _names     = columnNames;
            _selection = selection;

            if (holderType != null)
            {
                _holderConstructor = NHibernate.Util.ReflectHelper.GetConstructor(
                    holderType, types);
            }

            _single = _types.Length == 1;
        }
        public IEnumerable <Func <DbDataReader, int> > GetResultSetHandler()
        {
            var dialect = Session.Factory.Dialect;

            List <object>[] hydratedObjects = new List <object> [_queryInfos.Count];

            for (var i = 0; i < _queryInfos.Count; i++)
            {
                Loader.Loader loader          = _queryInfos[i].Loader;
                var           queryParameters = _queryInfos[i].Parameters;

                //Skip processing for items already loaded from cache
                if (_queryInfos[i].CacheKey?.ResultTransformer != null && _loaderResults[i] != null)
                {
                    _loaderResults[i] = loader.TransformCacheableResults(queryParameters, _queryInfos[i].CacheKey.ResultTransformer, _loaderResults[i]);
                    continue;
                }

                int entitySpan = loader.EntityPersisters.Length;
                hydratedObjects[i] = entitySpan == 0 ? null : new List <object>(entitySpan);
                EntityKey[] keys = new EntityKey[entitySpan];

                RowSelection selection        = queryParameters.RowSelection;
                bool         createSubselects = loader.IsSubselectLoadingEnabled;

                _subselectResultKeys[i] = createSubselects ? new List <EntityKey[]>() : null;
                int  maxRows          = Loader.Loader.HasMaxRows(selection) ? selection.MaxRows : int.MaxValue;
                bool advanceSelection = !dialect.SupportsLimitOffset || !loader.UseLimit(selection, dialect);

                var index = i;
                yield return(reader =>
                {
                    if (advanceSelection)
                    {
                        Loader.Loader.Advance(reader, selection);
                    }
                    if (queryParameters.HasAutoDiscoverScalarTypes)
                    {
                        loader.AutoDiscoverTypes(reader, queryParameters, null);
                    }

                    LockMode[] lockModeArray = loader.GetLockModes(queryParameters.LockModes);
                    EntityKey optionalObjectKey = Loader.Loader.GetOptionalObjectKey(queryParameters, Session);
                    int rowCount = 0;
                    var tmpResults = new List <object>();

                    int count;
                    for (count = 0; count < maxRows && reader.Read(); count++)
                    {
                        rowCount++;

                        object o =
                            loader.GetRowFromResultSet(
                                reader,
                                Session,
                                queryParameters,
                                lockModeArray,
                                optionalObjectKey,
                                hydratedObjects[index],
                                keys,
                                true,
                                _queryInfos[index].CacheKey?.ResultTransformer
                                );
                        if (loader.IsSubselectLoadingEnabled)
                        {
                            _subselectResultKeys[index].Add(keys);
                            keys = new EntityKey[entitySpan];                             //can't reuse in this case
                        }

                        tmpResults.Add(o);
                    }
                    _loaderResults[index] = tmpResults;

                    if (index == _queryInfos.Count - 1)
                    {
                        InitializeEntitiesAndCollections(reader, hydratedObjects);
                    }
                    return rowCount;
                });
            }
        }
Example #14
0
        public IList List(ISessionImplementor session, QueryParameters queryParameters)
        {
            // Delegate to the QueryLoader...
            ErrorIfDML();
            var  query            = ( QueryNode )_sqlAst;
            bool hasLimit         = queryParameters.RowSelection != null && queryParameters.RowSelection.DefinesLimits;
            bool needsDistincting = (query.GetSelectClause().IsDistinct || hasLimit) && ContainsCollectionFetches;

            QueryParameters queryParametersToUse;

            if (hasLimit && ContainsCollectionFetches)
            {
                log.Warn("firstResult/maxResults specified with collection fetch; applying in memory!");
                var selection = new RowSelection
                {
                    FetchSize = queryParameters.RowSelection.FetchSize,
                    Timeout   = queryParameters.RowSelection.Timeout
                };
                queryParametersToUse = queryParameters.CreateCopyUsing(selection);
            }
            else
            {
                queryParametersToUse = queryParameters;
            }

            IList results = _queryLoader.List(session, queryParametersToUse);

            if (needsDistincting)
            {
                int includedCount = -1;
                // NOTE : firstRow is zero-based
                int first = !hasLimit || queryParameters.RowSelection.FirstRow == RowSelection.NoValue
                                                        ? 0
                                                        : queryParameters.RowSelection.FirstRow;
                int max = !hasLimit || queryParameters.RowSelection.MaxRows == RowSelection.NoValue
                                                        ? -1
                                                        : queryParameters.RowSelection.MaxRows;

                int size        = results.Count;
                var tmp         = new List <object>();
                var distinction = new IdentitySet();

                for (int i = 0; i < size; i++)
                {
                    object result = results[i];
                    if (!distinction.Add(result))
                    {
                        continue;
                    }
                    includedCount++;
                    if (includedCount < first)
                    {
                        continue;
                    }
                    tmp.Add(result);
                    // NOTE : ( max - 1 ) because first is zero-based while max is not...
                    if (max >= 0 && (includedCount - first) >= (max - 1))
                    {
                        break;
                    }
                }

                results = tmp;
            }

            return(results);
        }
Example #15
0
        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);
            }
        }
Example #16
0
        // DONE : H3.2 Executable query (now can be supported for named SQL query/ storedProcedure)
        public async Task <int> PerformExecuteUpdateAsync(QueryParameters queryParameters, ISessionImplementor session, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            CoordinateSharedCacheCleanup(session);

            if (queryParameters.Callable)
            {
                throw new ArgumentException("callable not yet supported for native queries");
            }

            RowSelection selection = queryParameters.RowSelection;

            int result;

            try
            {
                var       parametersSpecifications = customQuery.CollectedParametersSpecifications.ToList();
                SqlString sql = ExpandDynamicFilterParameters(customQuery.SQL, parametersSpecifications, session);
                // After the last modification to the SqlString we can collect all parameters types.
                parametersSpecifications.ResetEffectiveExpectedType(queryParameters);

                var       sqlParametersList = sql.GetParameters().ToList();
                SqlType[] sqlTypes          = parametersSpecifications.GetQueryParameterTypes(sqlParametersList, session.Factory);

                var ps = await(session.Batcher.PrepareCommandAsync(CommandType.Text, sql, sqlTypes, cancellationToken)).ConfigureAwait(false);

                try
                {
                    if (selection != null && selection.Timeout != RowSelection.NoValue)
                    {
                        // NH Difference : set Timeout for native query
                        ps.CommandTimeout = selection.Timeout;
                    }

                    foreach (IParameterSpecification parameterSpecification in parametersSpecifications)
                    {
                        await(parameterSpecification.BindAsync(ps, sqlParametersList, queryParameters, session, cancellationToken)).ConfigureAwait(false);
                    }

                    result = await(session.Batcher.ExecuteNonQueryAsync(ps, cancellationToken)).ConfigureAwait(false);
                }
                finally
                {
                    if (ps != null)
                    {
                        session.Batcher.CloseCommand(ps, null);
                    }
                }
            }
            catch (OperationCanceledException) { throw; }
            catch (HibernateException)
            {
                throw;
            }
            catch (Exception sqle)
            {
                throw ADOExceptionHelper.Convert(session.Factory.SQLExceptionConverter, sqle,
                                                 "could not execute native bulk manipulation query:" + sourceQuery);
            }

            return(result);
        }
Example #17
0
        public QueryParameters GetQueryParameters()
        {
            RowSelection selection = new RowSelection();

            selection.FirstRow  = rootCriteria.FirstResult;
            selection.MaxRows   = rootCriteria.MaxResults;
            selection.Timeout   = rootCriteria.Timeout;
            selection.FetchSize = rootCriteria.FetchSize;

            Dictionary <string, LockMode> lockModes = new Dictionary <string, LockMode>();

            foreach (KeyValuePair <string, LockMode> me in rootCriteria.LockModes)
            {
                ICriteria subcriteria = GetAliasedCriteria(me.Key);
                lockModes[GetSQLAlias(subcriteria)] = me.Value;
            }

            List <TypedValue> typedValues = new List <TypedValue>();

            // NH-specific: Get parameters for projections first
            if (this.HasProjection)
            {
                typedValues.AddRange(rootCriteria.Projection.GetTypedValues(rootCriteria, this));
            }

            foreach (CriteriaImpl.Subcriteria subcriteria in rootCriteria.IterateSubcriteria())
            {
                LockMode lm = subcriteria.LockMode;
                if (lm != null)
                {
                    lockModes[GetSQLAlias(subcriteria)] = lm;
                }
                // Get parameters that may be used in JOINs
                if (subcriteria.WithClause != null)
                {
                    typedValues.AddRange(subcriteria.WithClause.GetTypedValues(subcriteria, this));
                }
            }

            List <TypedValue> groupedTypedValues = new List <TypedValue>();

            // Type and value gathering for the WHERE clause needs to come AFTER lock mode gathering,
            // because the lock mode gathering loop now contains join clauses which can contain
            // parameter bindings (as in the HQL WITH clause).
            foreach (CriteriaImpl.CriterionEntry ce in rootCriteria.IterateExpressionEntries())
            {
                bool          criteriaContainsGroupedProjections = false;
                IProjection[] projections = ce.Criterion.GetProjections();

                if (projections != null)
                {
                    foreach (IProjection projection in projections)
                    {
                        if (projection.IsGrouped)
                        {
                            criteriaContainsGroupedProjections = true;
                            break;
                        }
                    }
                }

                if (criteriaContainsGroupedProjections)
                {
                    // GROUP BY/HAVING parameters need to be added after WHERE parameters - so don't add them
                    // to typedValues yet
                    groupedTypedValues.AddRange(ce.Criterion.GetTypedValues(ce.Criteria, this));
                }
                else
                {
                    typedValues.AddRange(ce.Criterion.GetTypedValues(ce.Criteria, this));
                }
            }

            // NH-specific: GROUP BY/HAVING parameters need to appear after WHERE parameters
            if (groupedTypedValues.Count > 0)
            {
                typedValues.AddRange(groupedTypedValues);
            }

            // NH-specific: To support expressions/projections used in ORDER BY
            foreach (CriteriaImpl.OrderEntry oe in rootCriteria.IterateOrderings())
            {
                typedValues.AddRange(oe.Order.GetTypedValues(oe.Criteria, this));
            }

            return
                (new QueryParameters(
                     typedValues.Select(tv => tv.Type).ToArray(),
                     typedValues.Select(tv => tv.Value).ToArray(),
                     lockModes,
                     selection,
                     rootCriteria.IsReadOnlyInitialized,
                     rootCriteria.IsReadOnlyInitialized ? rootCriteria.IsReadOnly : false,
                     rootCriteria.Cacheable,
                     rootCriteria.CacheRegion,
                     rootCriteria.Comment,
                     rootCriteria.LookupByNaturalKey,
                     rootCriteria.ResultTransformer,
                     _tempPagingParameterIndexes));
        }