/// <summary>
		/// 
		/// </summary>
		/// <param name="queryString"></param>
		/// <param name="session"></param>
		public AbstractQueryImpl( string queryString, ISessionImplementor session )
		{
			this.session = session;
			this.queryString = queryString;
			selection = new RowSelection();
			InitParameterBookKeeping();
		}
		public QueryParameters(IType[] positionalParameterTypes, object[] positionalParameterValues,
		                       IDictionary<string, LockMode> lockModes, RowSelection rowSelection, bool cacheable,
		                       string cacheRegion, string comment, bool isLookupByNaturalKey, IResultTransformer transformer)
			: this(
				positionalParameterTypes, positionalParameterValues, null, lockModes, rowSelection, false, cacheable, cacheRegion,
				comment, null, transformer)
		{
			NaturalKeyLookup = isLookupByNaturalKey;
		}
Ejemplo n.º 3
0
		public QueryParameters(IDictionary<string, TypedValue> namedParameters, IDictionary<string, LockMode> lockModes, RowSelection rowSelection, bool isReadOnlyInitialized,
		                       bool readOnly, bool cacheable, string cacheRegion, string comment, bool isLookupByNaturalKey, IResultTransformer transformer)
			: this(
				ArrayHelper.EmptyTypeArray, ArrayHelper.EmptyObjectArray, namedParameters, lockModes, rowSelection, isReadOnlyInitialized, readOnly, cacheable, cacheRegion, comment, null,
				transformer)
		{
			// used by CriteriaTranslator
			NaturalKeyLookup = isLookupByNaturalKey;
		}
Ejemplo n.º 4
0
		public QueryParameters(IType[] positionalParameterTypes, object[] positionalParameterValues, IDictionary<string, TypedValue> namedParameters,
		                       IDictionary<string, LockMode> lockModes, RowSelection rowSelection, bool isReadOnlyInitialized, bool readOnly, bool cacheable, string cacheRegion,
		                       string comment, object[] collectionKeys, object optionalObject, string optionalEntityName, object optionalId, IResultTransformer transformer)
			: this(
				positionalParameterTypes, positionalParameterValues, namedParameters, lockModes, rowSelection, isReadOnlyInitialized, readOnly, cacheable, cacheRegion, comment, collectionKeys,
				transformer)
		{
			OptionalEntityName = optionalEntityName;
			OptionalId = optionalId;
			OptionalObject = optionalObject;
		}
Ejemplo n.º 5
0
		/// <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="holderInstantiator">Instantiator 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,
		                      HolderInstantiator holderInstantiator)
		{
			_reader = reader;
			_cmd = cmd;
			_sess = sess;
			_types = types;
			_names = columnNames;
			_selection = selection;
			_holderInstantiator = holderInstantiator;

			_single = _types.Length == 1;
		}
Ejemplo n.º 6
0
		public QueryParameters(IType[] positionalParameterTypes, object[] positionalParameterValues, IDictionary<string, TypedValue> namedParameters, IDictionary<string, LockMode> lockModes, RowSelection rowSelection, bool isReadOnlyInitialized, bool readOnly, bool cacheable, string cacheRegion, string comment, object[] collectionKeys, IResultTransformer transformer)
		{
			_positionalParameterTypes = positionalParameterTypes;
			_positionalParameterValues = positionalParameterValues;
			_namedParameters = namedParameters;
			_lockModes = lockModes;
			_rowSelection = rowSelection;
			_cacheable = cacheable;
			_cacheRegion = cacheRegion;
			_comment = comment;
			_collectionKeys = collectionKeys;
			_isReadOnlyInitialized = isReadOnlyInitialized;
			_readOnly = readOnly;
			_resultTransformer = transformer;
		}
Ejemplo n.º 7
0
		public QueryParameters(IType[] positionalParameterTypes, object[] positionalParameterValues, IDictionary<string, TypedValue> namedParameters,
		                       IDictionary<string, LockMode> lockModes, RowSelection rowSelection, bool isReadOnlyInitialized, bool readOnly, bool cacheable, string cacheRegion,
		                       string comment, object[] collectionKeys, IResultTransformer transformer)
		{
			PositionalParameterTypes = positionalParameterTypes ?? new IType[0];
			PositionalParameterValues = positionalParameterValues ?? new IType[0];
			NamedParameters = namedParameters ?? new Dictionary<string, TypedValue>(1);
			LockModes = lockModes;
			RowSelection = rowSelection;
			Cacheable = cacheable;
			CacheRegion = cacheRegion;
			Comment = comment;
			CollectionKeys = collectionKeys;
			IsReadOnlyInitialized = isReadOnlyInitialized;
			this.readOnly = readOnly;
			ResultTransformer = transformer;
		}
		/// <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;
		}
		/// <summary>
		/// Initializes an instance of the <see cref="QueryParameters"/> class.
		/// </summary>
		/// <param name="positionalParameterTypes">An array of <see cref="IType"/> objects for the parameters.</param>
		/// <param name="positionalParameterValues">An array of <see cref="object"/> objects for the parameters.</param>
		/// <param name="namedParameters">An <see cref="IDictionary"/> that is <c>parameter name</c> keyed to a <see cref="TypedValue"/> value.</param>
		/// <param name="lockModes">An <see cref="IDictionary"/> that is <c>hql alias</c> keyed to a LockMode value.</param>
		/// <param name="rowSelection"></param>
		public QueryParameters(
			IType[ ] positionalParameterTypes,
			object[ ] positionalParameterValues,
			IDictionary namedParameters,
			IDictionary lockModes,
			RowSelection rowSelection,
			bool cacheable,
			string cacheRegion,
			bool forceCacheRefresh )
		{
			_positionalParameterTypes = positionalParameterTypes;
			_positionalParameterValues = positionalParameterValues;
			_namedParameters = namedParameters;
			_lockModes = lockModes;
			_rowSelection = rowSelection;
			_cacheable = cacheable;
			_cacheRegion = cacheRegion;
			_forceCacheRefresh = forceCacheRefresh;
		}
Ejemplo n.º 10
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, EntityMode.Poco));
					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, EntityMode.Poco));
					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;
		}
Ejemplo n.º 11
0
		/// <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="session">The <see cref="ISession"/> to use to load objects.</param>
		/// <param name="readOnly"></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="holderInstantiator">Instantiator 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,
							  IEventSource session,
							  bool readOnly,
							  IType[] types,
							  string[][] columnNames,
							  RowSelection selection,
							  HolderInstantiator holderInstantiator)
		{
			_reader = reader;
			_cmd = cmd;
			_session = session;
			_readOnly = readOnly;
			_types = types;
			_names = columnNames;
			_selection = selection;
			_holderInstantiator = holderInstantiator;

			_single = _types.Length == 1;
		}
Ejemplo n.º 12
0
		/// <summary>
		/// Fetch a <c>IDbCommand</c>, call <c>SetMaxRows</c> and then execute it,
		/// advance to the first result and return an SQL <c>IDataReader</c>
		/// </summary>
		/// <param name="st">The <see cref="IDbCommand" /> to execute.</param>
		/// <param name="selection">The <see cref="RowSelection"/> to apply to the <see cref="IDbCommand"/> and <see cref="IDataReader"/>.</param>
		/// <param name="autoDiscoverTypes">true if result types need to be auto-discovered by the loader; false otherwise.</param>
		/// <param name="session">The <see cref="ISession" /> to load in.</param>
		/// <param name="callable"></param>
		/// <returns>An IDataReader advanced to the first record in RowSelection.</returns>
		protected IDataReader GetResultSet(IDbCommand st, bool autoDiscoverTypes, bool callable, RowSelection selection,
		                                   ISessionImplementor session)
		{
			IDataReader rs = null;
			try
			{
				log.Info(st.CommandText);
				// TODO NH: Callable
				rs = session.Batcher.ExecuteReader(st);

				//NH: this is checked outside the WrapResultSet because we
				// want to avoid the syncronization overhead in the vast majority
				// of cases where IsWrapResultSetsEnabled is set to false
				if (session.Factory.Settings.IsWrapResultSetsEnabled)
					rs = WrapResultSet(rs);

				Dialect.Dialect dialect = session.Factory.Dialect;
				if (!dialect.SupportsLimitOffset || !UseLimit(selection, dialect))
				{
					Advance(rs, selection);
				}

				if (autoDiscoverTypes)
				{
					AutoDiscoverTypes(rs);
				}
				return rs;
			}
			catch (Exception sqle)
			{
				ADOExceptionReporter.LogExceptions(sqle);
				session.Batcher.CloseCommand(st, rs);
				throw;
			}
		}
Ejemplo n.º 13
0
		/// <summary>
		/// Performs dialect-specific manipulations on the limit value before returning it.
		/// This method is applicable for use in limit statements only.
		/// </summary>
		internal static int? GetLimitUsingDialect(RowSelection selection, Dialect.Dialect dialect)
		{
			if (selection == null || selection.MaxRows == RowSelection.NoValue)
				return null;
			return dialect.GetLimitValue(GetFirstRow(selection), selection.MaxRows);
		}
Ejemplo n.º 14
0
		/// <summary>
		/// Should we pre-process the SQL string, adding a dialect-specific
		/// LIMIT clause.
		/// </summary>
		/// <param name="selection"></param>
		/// <param name="dialect"></param>
		/// <returns></returns>
		internal bool UseLimit(RowSelection selection, Dialect.Dialect dialect)
		{
			return dialect.SupportsLimit && (HasMaxRows(selection) || HasOffset(selection));
		}
Ejemplo n.º 15
0
 public QueryParameters(IType[] positionalParameterTypes, object[] positionalParameterValues, IDictionary <string, TypedValue> namedParameters, IDictionary <string, LockMode> lockModes, RowSelection rowSelection, bool isReadOnlyInitialized, bool readOnly, bool cacheable, string cacheRegion, string comment, object[] collectionKeys, IResultTransformer transformer)
 {
     _positionalParameterTypes  = positionalParameterTypes;
     _positionalParameterValues = positionalParameterValues;
     _namedParameters           = namedParameters;
     _lockModes             = lockModes;
     _rowSelection          = rowSelection;
     _cacheable             = cacheable;
     _cacheRegion           = cacheRegion;
     _comment               = comment;
     _collectionKeys        = collectionKeys;
     _isReadOnlyInitialized = isReadOnlyInitialized;
     _readOnly              = readOnly;
     _resultTransformer     = transformer;
 }
Ejemplo n.º 16
0
 public QueryParameters(IType[] positionalParameterTypes, object[] positionalParameterValues, IDictionary <string, LockMode> lockModes, RowSelection rowSelection, bool isReadOnlyInitialized, bool readOnly, bool cacheable, string cacheRegion, string comment, bool isLookupByNaturalKey, IResultTransformer transformer, IDictionary <int, int> tempPagingParameterIndexes)
     : this(positionalParameterTypes, positionalParameterValues, null, lockModes, rowSelection, isReadOnlyInitialized, readOnly, cacheable, cacheRegion, comment, null, transformer)
 {
     NaturalKeyLookup            = isLookupByNaturalKey;
     _tempPagingParameterIndexes = tempPagingParameterIndexes;
 }
Ejemplo n.º 17
0
 public QueryParameters(IType[] positionalParameterTypes, object[] positionalParameterValues, IDictionary <string, TypedValue> namedParameters, IDictionary <string, LockMode> lockModes, RowSelection rowSelection, bool isReadOnlyInitialized, bool readOnly, bool cacheable, string cacheRegion, string comment, object[] collectionKeys, object optionalObject, string optionalEntityName, object optionalId, IResultTransformer transformer)
     : this(positionalParameterTypes, positionalParameterValues, namedParameters, lockModes, rowSelection, isReadOnlyInitialized, readOnly, cacheable, cacheRegion, comment, collectionKeys, transformer)
 {
     _optionalEntityName = optionalEntityName;
     _optionalId         = optionalId;
     _optionalObject     = optionalObject;
 }
Ejemplo n.º 18
0
 public QueryParameters(IDictionary <string, TypedValue> namedParameters, IDictionary <string, LockMode> lockModes, RowSelection rowSelection, bool isReadOnlyInitialized,
                        bool readOnly, bool cacheable, string cacheRegion, string comment, bool isLookupByNaturalKey, IResultTransformer transformer)
     : this(
         ArrayHelper.EmptyTypeArray, ArrayHelper.EmptyObjectArray, namedParameters, lockModes, rowSelection, isReadOnlyInitialized, readOnly, cacheable, cacheRegion, comment, null,
         transformer)
 {
     // used by CriteriaTranslator
     NaturalKeyLookup = isLookupByNaturalKey;
 }
		public QueryParameters GetQueryParameters()
		{
			ArrayList values = new ArrayList(usedTypedValues.Count);
			List<IType> types = new List<IType>(usedTypedValues.Count);

			foreach (TypedValue value in usedTypedValues)
			{
				values.Add(value.Value);
				types.Add(value.Type);
			}

			object[] valueArray = values.ToArray();
			IType[] typeArray = types.ToArray();

			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;
			}

			foreach (CriteriaImpl.Subcriteria subcriteria in rootCriteria.IterateSubcriteria())
			{
				LockMode lm = subcriteria.LockMode;
				if (lm != null)
				{
					lockModes[GetSQLAlias(subcriteria)] = lm;
				}
			}

			return
				new QueryParameters(typeArray, valueArray, lockModes, selection, rootCriteria.Cacheable, rootCriteria.CacheRegion,
									rootCriteria.Comment, rootCriteria.LookupByNaturalKey, rootCriteria.ResultTransformer);
		}
Ejemplo n.º 20
0
		private static bool HasOffset(RowSelection selection)
		{
			return selection != null && selection.MaxRows != RowSelection.NoValue;
		}
Ejemplo n.º 21
0
		public QueryParameters GetQueryParameters()
		{
			ArrayList values = new ArrayList();
			ArrayList types = new ArrayList();

			foreach (CriteriaImpl.CriterionEntry ce in rootCriteria.IterateExpressionEntries())
			{
				TypedValue[] tv = ce.Criterion.GetTypedValues(ce.Criteria, this);
				for (int i = 0; i < tv.Length; i++)
				{
					values.Add(tv[i].Value);
					types.Add(tv[i].Type);
				}
			}
			if (rootCriteria.Projection != null)
			{
				TypedValue[] tv = rootCriteria.Projection.GetTypedValues(rootCriteria.ProjectionCriteria, this);
				for (int i = 0; i < tv.Length; i++)
				{
					values.Add(tv[i].Value);
					types.Add(tv[i].Type);
				}
			}

			object[] valueArray = values.ToArray();
			IType[] typeArray = (IType[])types.ToArray(typeof(IType));

			RowSelection selection = new RowSelection();
			selection.FirstRow = rootCriteria.FirstResult;
			selection.MaxRows = rootCriteria.MaxResults;
			selection.Timeout = rootCriteria.Timeout;
			selection.FetchSize = rootCriteria.FetchSize;

			IDictionary lockModes = new Hashtable();
			foreach (DictionaryEntry me in rootCriteria.LockModes)
			{
				ICriteria subcriteria = GetAliasedCriteria((string)me.Key);
				lockModes[GetSQLAlias(subcriteria)] = me.Value;
			}

			foreach (CriteriaImpl.Subcriteria subcriteria in rootCriteria.IterateSubcriteria())
			{
				LockMode lm = subcriteria.LockMode;
				if (lm != null)
				{
					lockModes[GetSQLAlias(subcriteria)] = lm;
				}
			}

			return new QueryParameters(
				typeArray,
				valueArray,
				lockModes,
				selection,
				rootCriteria.Cacheable,
				rootCriteria.CacheRegion,
				string.Empty, // TODO H3: rootCriteria.Comment,
				rootCriteria.IsLookupByNaturalKey(),
				null
				);
		}
Ejemplo n.º 22
0
		/// <summary>
		/// Performs dialect-specific manipulations on the offset value before returning it.
		/// This method is applicable for use in limit statements only.
		/// </summary>
		internal static int? GetOffsetUsingDialect(RowSelection selection, Dialect.Dialect dialect)
		{
			int firstRow = GetFirstRow(selection);
			if (firstRow == 0)
				return null;
			return dialect.GetOffsetValue(firstRow);
		}
Ejemplo n.º 23
0
		internal static bool HasMaxRows(RowSelection selection)
		{
			// it used to be selection.MaxRows != null -> since an Int32 will always
			// have a value I'll compare it to the static field NoValue used to initialize 
			// max rows to nothing
			return selection != null && selection.MaxRows != RowSelection.NoValue;
		}
Ejemplo n.º 24
0
		/// <summary> 
		/// Some dialect-specific LIMIT clauses require the maximium last row number
		/// (aka, first_row_number + total_row_count), while others require the maximum
		/// returned row count (the total maximum number of rows to return). 
		/// </summary>
		/// <param name="selection">The selection criteria </param>
		/// <param name="dialect">The dialect </param>
		/// <returns> The appropriate value to bind into the limit clause. </returns>
		internal static int GetMaxOrLimit(Dialect.Dialect dialect, RowSelection selection)
		{
			int firstRow = GetFirstRow(selection);
			int rowCount = selection.MaxRows;

			if (rowCount == RowSelection.NoValue)
				return int.MaxValue;

			return dialect.GetLimitValue(firstRow, rowCount);
		}
Ejemplo n.º 25
0
		/// <summary>
		/// Should we pre-process the SQL string, adding a dialect-specific
		/// LIMIT clause.
		/// </summary>
		/// <param name="selection"></param>
		/// <param name="dialect"></param>
		/// <returns></returns>
		internal static bool UseLimit(RowSelection selection, Dialect.Dialect dialect)
		{
			return dialect.SupportsLimit && HasMaxRows(selection);
		}
Ejemplo n.º 26
0
		/// <summary>
		/// Advance the cursor to the first required row of the <c>IDataReader</c>
		/// </summary>
		internal static void Advance(IDataReader rs, RowSelection selection)
		{
			int firstRow = GetFirstRow(selection);

			if (firstRow != 0)
			{
				// DataReaders are forward-only, readonly, so we have to step through
				for (int i = 0; i < firstRow; i++)
				{
					rs.Read();
				}
			}
		}
Ejemplo n.º 27
0
		/// <summary>
		/// Bind parameters needed by the dialect-specific LIMIT clause
		/// </summary>
		/// <returns>The number of parameters bound</returns>
		internal static int BindLimitParameters(IDbCommand st, int index, RowSelection selection, ISessionImplementor session)
		{
			Dialect.Dialect dialect = session.Factory.Dialect;
			if (!dialect.SupportsVariableLimit)
			{
				return 0;
			}
			if (!HasMaxRows(selection))
			{
				throw new AssertionFailure("max results not set");
			}
			int firstRow = GetFirstRow(selection);
			int lastRow = GetMaxOrLimit(dialect, selection);

			bool hasFirstRow = firstRow > 0 && dialect.SupportsLimitOffset;
			bool reverse = dialect.BindLimitParametersInReverseOrder;

			if (hasFirstRow)
			{
				((IDataParameter) st.Parameters[index + (reverse ? 1 : 0)]).Value = firstRow;
			}
			((IDataParameter) st.Parameters[index + ((reverse || !hasFirstRow) ? 0 : 1)]).Value = lastRow;

			return hasFirstRow ? 2 : 1;
		}
Ejemplo n.º 28
0
		internal static int GetFirstRow(RowSelection selection)
		{
			if (selection == null || !selection.DefinesLimits)
			{
				return 0;
			}
			else
			{
				return selection.FirstRow > 0 ? selection.FirstRow : 0;
			}
		}
		public QueryParameters CreateCopyUsing(RowSelection selection)
		{
			var copy = new QueryParameters(_positionalParameterTypes, _positionalParameterValues, _namedParameters, _lockModes,
			                               selection, _readOnly, _cacheable, _cacheRegion, _comment, _collectionKeys,
			                               _optionalObject, _optionalEntityName, _optionalId, _resultTransformer);
			copy._positionalParameterLocations = _positionalParameterLocations;
			copy.processedSQL = processedSQL;
			copy.filteredParameterTypes = filteredParameterTypes;
			copy.filteredParameterValues = filteredParameterValues;
			copy.filteredParameterLocations = filteredParameterLocations;
			return copy;
		}
Ejemplo n.º 30
0
		/// <summary> 
		/// Some dialect-specific LIMIT clauses require the maximium last row number
		/// (aka, first_row_number + total_row_count), while others require the maximum
		/// returned row count (the total maximum number of rows to return). 
		/// </summary>
		/// <param name="selection">The selection criteria </param>
		/// <param name="dialect">The dialect </param>
		/// <returns> The appropriate value to bind into the limit clause. </returns>
		internal static int GetMaxOrLimit(Dialect.Dialect dialect, RowSelection selection)
		{
			int firstRow = GetFirstRow(selection);
			int lastRow = selection.MaxRows;

			if (dialect.UseMaxForLimit)
			{
				return lastRow + firstRow;
			}
			else
			{
				return lastRow;
			}
		}
		public QueryParameters GetQueryParameters()
		{
			RowSelection selection = new RowSelection();
			selection.FirstRow = rootCriteria.FirstResult;
			selection.MaxRows = rootCriteria.MaxResults;
			selection.Timeout = rootCriteria.Timeout;
			selection.FetchSize = rootCriteria.FetchSize;

			var lockModes = new Dictionary<string, LockMode>();
			foreach (KeyValuePair<string, LockMode> me in rootCriteria.LockModes)
			{
				ICriteria subcriteria = GetAliasedCriteria(me.Key);
				lockModes[GetSQLAlias(subcriteria)] = me.Value;
			}
			
			foreach (CriteriaImpl.Subcriteria subcriteria in rootCriteria.IterateSubcriteria())
			{
				LockMode lm = subcriteria.LockMode;
				if (lm != null)
				{
					lockModes[GetSQLAlias(subcriteria)] = lm;
				}
			}
			
			IDictionary<string, TypedValue> queryNamedParameters = CollectedParameters.ToDictionary(np => np.Name, np => new TypedValue(np.Type, np.Value, EntityMode.Poco));

			return
				new QueryParameters(
					queryNamedParameters,
					lockModes,
					selection,
					rootCriteria.IsReadOnlyInitialized,
					rootCriteria.IsReadOnlyInitialized ? rootCriteria.IsReadOnly : false,
					rootCriteria.Cacheable,
					rootCriteria.CacheRegion,
					rootCriteria.Comment,
					rootCriteria.LookupByNaturalKey,
					rootCriteria.ResultTransformer);
		}
Ejemplo n.º 32
0
		/// <summary>
		/// Limits the number of rows returned by the Sql query if necessary.
		/// </summary>
		/// <param name="st">The IDbCommand to limit.</param>
		/// <param name="selection">The RowSelection that contains the MaxResults info.</param>
		/// <remarks>TODO: This does not apply to ADO.NET at all</remarks>
		protected void SetMaxRows(IDbCommand st, RowSelection selection)
		{
			//TODO: H2.0.3 - do we need this method??
			//if (HasMaxRows(selection))
			//{
			//  // there is nothing in ADO.NET to do anything  similar
			//  // to Java's PreparedStatement.setMaxRows(int)
			//}
		}
Ejemplo n.º 33
0
		public QueryParameters CreateCopyUsing(RowSelection selection)
		{
			var copy = new QueryParameters(PositionalParameterTypes, PositionalParameterValues, NamedParameters, LockModes,
			                               selection, IsReadOnlyInitialized, readOnly, Cacheable, CacheRegion, Comment, CollectionKeys,
			                               OptionalObject, OptionalEntityName, OptionalId, ResultTransformer)
			           {
			           	ProcessedSql = ProcessedSql,
			           	ProcessedSqlParameters = ProcessedSqlParameters.ToList()
			           };
			return copy;
		}
Ejemplo n.º 34
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;
		}
Ejemplo n.º 35
0
 /// <summary>
 /// Initializes an instance of the <see cref="QueryParameters"/> class.
 /// </summary>
 /// <param name="positionalParameterTypes">An array of <see cref="IType"/> objects for the parameters.</param>
 /// <param name="positionalParameterValues">An array of <see cref="object"/> objects for the parameters.</param>
 /// <param name="lockModes">An <see cref="IDictionary"/> that is hql alias keyed to a LockMode value.</param>
 /// <param name="rowSelection"></param>
 public QueryParameters(IType[] positionalParameterTypes, object[] positionalParameterValues, IDictionary lockModes, RowSelection rowSelection)
     : this(positionalParameterTypes, positionalParameterValues, null, lockModes, rowSelection, false, null, false)
 {
 }