public override SqlString ToSqlString(ICriteria criteria, ICriteriaQuery criteriaQuery, IDictionary enabledFilters)
		{
			//TODO: add default capacity
			SqlStringBuilder sqlBuilder = new SqlStringBuilder();
			string[] columnNames = criteriaQuery.GetColumnsUsingProjection(criteria, _propertyName);

			if (columnNames.Length != 1)
			{
				throw new HibernateException("insensitive like may only be used with single-column properties");
			}

			if (criteriaQuery.Factory.Dialect is PostgreSQLDialect)
			{
				sqlBuilder.Add(columnNames[0]);
				sqlBuilder.Add(" ilike ");
			}
			else
			{
				sqlBuilder.Add(criteriaQuery.Factory.Dialect.LowercaseFunction)
					.Add("(")
					.Add(columnNames[0])
					.Add(")")
					.Add(" like ");
			}

			sqlBuilder.AddParameter();

			return sqlBuilder.ToSqlString();
		}
		public override SqlString RenderText(ISessionFactoryImplementor sessionFactory)
		{
			int count;
			if (ExpectedType != null && (count = ExpectedType.GetColumnSpan(sessionFactory)) > 1)
			{
				SqlStringBuilder buffer = new SqlStringBuilder();
				buffer.Add("(");
				buffer.AddParameter();
				for (int i = 1; i < count; i++)
				{
					buffer.Add(",");
					buffer.AddParameter();
				}
				buffer.Add(")");
				return buffer.ToSqlString();
			}
			else
			{
				return new SqlString(Parameter.Placeholder);
			}
		}
		private void AddValueOrProjection(ICriteria criteria, ICriteriaQuery criteriaQuery, IDictionary<string, IFilter> enabledFilters, SqlStringBuilder result)
		{
			if (_projection == null)
			{
				result.AddParameter();
			}
			else
			{
				SqlString sql = _projection.ToSqlString(criteria, GetHashCode(),criteriaQuery, enabledFilters);
				result.Add(StringHelper.RemoveAsAliasesFromSql(sql));
			}
		}
		public override SqlString ToSqlString(ICriteria criteria, ICriteriaQuery criteriaQuery, IDictionary enabledFilters)
		{
			IType type = criteriaQuery.GetTypeUsingProjection(criteria, _propertyName);
			if (type.IsCollectionType)
			{
				throw new QueryException("Cannot use collections with InExpression");
			}

			if (_values.Length == 0)
			{
				// "something in ()" is always false
				return new SqlString("1=0");
			}

			//TODO: add default capacity
			SqlStringBuilder result = new SqlStringBuilder();
			string[] columnNames = criteriaQuery.GetColumnsUsingProjection(criteria, _propertyName);

			// Generate SqlString of the form:
			// columnName1 in (values) and columnName2 in (values) and ...

			for (int columnIndex = 0; columnIndex < columnNames.Length; columnIndex++)
			{
				string columnName = columnNames[columnIndex];

				if (columnIndex > 0)
				{
					result.Add(" and ");
				}

				result
					.Add(columnName)
					.Add(" in (");

				for (int i = 0; i < _values.Length; i++)
				{
					if (i > 0)
					{
						result.Add(StringHelper.CommaSpace);
					}
					result.AddParameter();
				}

				result.Add(")");
			}

			return result.ToSqlString();
		}
Beispiel #5
0
		public override SqlString ToSqlString(ICriteria criteria, ICriteriaQuery criteriaQuery,
		                                      IDictionary<string, IFilter> enabledFilters)
		{
			if (projection == null)
				AssertPropertyIsNotCollection(criteriaQuery, criteria);

			if (_values.Length == 0)
			{
				// "something in ()" is always false
				return new SqlString("1=0");
			}

			//TODO: add default capacity
			SqlStringBuilder result = new SqlStringBuilder();
			SqlString[] columnNames =
				CriterionUtil.GetColumnNames(_propertyName, projection, criteriaQuery, criteria, enabledFilters);
			
			// Generate SqlString of the form:
			// columnName1 in (values) and columnName2 in (values) and ...

			for (int columnIndex = 0; columnIndex < columnNames.Length; columnIndex++)
			{
				SqlString columnName = columnNames[columnIndex];

				if (columnIndex > 0)
				{
					result.Add(" and ");
				}

				result
					.Add(columnName)
					.Add(" in (");

				for (int i = 0; i < _values.Length; i++)
				{
					if (i > 0)
					{
						result.Add(StringHelper.CommaSpace);
					}
					result.AddParameter();
				}

				result.Add(")");
			}

			return result.ToSqlString();
		}
Beispiel #6
0
        /// <summary>
        /// Parse SQL in <paramref name="sql" /> and create a SqlString representing it.
        /// </summary>
        /// <remarks>
        /// Parameter marks in single quotes will be correctly skipped, but otherwise the
        /// lexer is very simple and will not parse double quotes or escape sequences
        /// correctly, for example.
        /// </remarks>
        public static SqlString Parse(string sql)
        {
            SqlStringBuilder result = new SqlStringBuilder();

            bool inQuote = false;

            StringBuilder stringPart = new StringBuilder();

            foreach (char ch in sql)
            {
                switch (ch)
                {
                case '?':
                    if (inQuote)
                    {
                        stringPart.Append(ch);
                    }
                    else
                    {
                        if (stringPart.Length > 0)
                        {
                            result.Add(stringPart.ToString());
                            stringPart.Length = 0;
                        }
                        result.AddParameter();
                    }
                    break;

                case '\'':
                    inQuote = !inQuote;
                    stringPart.Append(ch);
                    break;

                default:
                    stringPart.Append(ch);
                    break;
                }
            }

            if (stringPart.Length > 0)
            {
                result.Add(stringPart.ToString());
            }

            return(result.ToSqlString());
        }
		public void WithParameterTest()
		{
			using (ISession session = factory.OpenSession())
			{
				SqlStringBuilder builder = new SqlStringBuilder();

				string expectedSql = "sql_alias.address = ?";

				builder.Add("{alias}.address = ");
				builder.AddParameter();

				ICriterion sqlExpression = Expression.Sql(builder.ToSqlString(), "some address", NHibernateUtil.String);

				CreateObjects(typeof(Simple), session);
				SqlString sqlString = sqlExpression.ToSqlString(criteria, criteriaQuery, new CollectionHelper.EmptyMapClass<string, IFilter>());

				CompareSqlStrings(sqlString, expectedSql, 1);
			}
		}
Beispiel #8
0
		/// <summary>
		/// Parse SQL in <paramref name="sql" /> and create a SqlString representing it.
		/// </summary>
		/// <remarks>
		/// Parameter marks in single quotes will be correctly skipped, but otherwise the
		/// lexer is very simple and will not parse double quotes or escape sequences
		/// correctly, for example.
		/// </remarks>
		public static SqlString Parse(string sql)
		{
			SqlStringBuilder result = new SqlStringBuilder();

			bool inQuote = false;

			StringBuilder stringPart = new StringBuilder();

			foreach (char ch in sql)
			{
				switch (ch)
				{
					case '?':
						if (inQuote)
						{
							stringPart.Append(ch);
						}
						else
						{
							if (stringPart.Length > 0)
							{
								result.Add(stringPart.ToString());
								stringPart.Length = 0;
							}
							result.AddParameter();
						}
						break;

					case '\'':
						inQuote = !inQuote;
						stringPart.Append(ch);
						break;

					default:
						stringPart.Append(ch);
						break;
				}
			}

			if (stringPart.Length > 0)
			{
				result.Add(stringPart.ToString());
			}

			return result.ToSqlString();
		}
		public override SqlString ApplyLocksToSql(SqlString sql, IDictionary<string, LockMode> aliasedLockModes, IDictionary<string, string[]> keyColumnNames)
		{
			bool doWork = false;

			foreach (KeyValuePair<string, LockMode> de in aliasedLockModes)
			{
				if (NeedsLockHint(de.Value))
				{
					doWork = true;
					break;
				}
			}

			if (!doWork)
			{
				return sql;
			}

			// Regex matching any alias out of those given. Aliases should contain
			// no dangerous characters (they are identifiers) so they are not escaped.
			string aliasesPattern = StringHelper.Join("|", aliasedLockModes.Keys);

			// Match < alias >, < alias,>, or < alias$>, the intent is to capture alias names
			// in various kinds of "FROM table1 alias1, table2 alias2".
			Regex matchRegex = new Regex(" (" + aliasesPattern + ")([, ]|$)");

			SqlStringBuilder result = new SqlStringBuilder();
			MatchEvaluator evaluator = new LockHintAppender(this, aliasedLockModes).ReplaceMatch;

			foreach (object part in sql.Parts)
			{
				if (part == Parameter.Placeholder)
				{
					result.AddParameter();
					continue;
				}

				result.Add(matchRegex.Replace((string)part, evaluator));
			}

			return result.ToSqlString();
		}
		public void ProcessFilters(SqlString sql, ISessionImplementor session)
		{
			filteredParameterValues = new List<object>();
			filteredParameterTypes = new List<IType>();
			filteredParameterLocations = new List<int>();

			if (session.EnabledFilters.Count == 0 || sql.ToString().IndexOf(ParserHelper.HqlVariablePrefix) < 0)
			{
				processedSQL = sql.Copy();
				return;
			}

			Dialect.Dialect dialect = session.Factory.Dialect;
			string symbols = ParserHelper.HqlSeparators + dialect.OpenQuote + dialect.CloseQuote;

			var result = new SqlStringBuilder();

			int originalParameterIndex = 0; // keep track of the positional parameter
			int newParameterIndex = 0;
			_adjustedParameterLocations = new Dictionary<int, int>();

			foreach (var part in sql.Parts)
			{
				if (part is Parameter)
				{
					result.AddParameter();

					// (?) can be a position parameter or a named parameter (already substituted by (?),
					// but only the positional parameters are available at this point. Adding them in the
					// order of appearance is best that can be done at this point of time, but if they
					// are mixed with named parameters, the order is still wrong, because values and
					// types for the named parameters are added later to the end of the list.
					// see test fixture NH-1098

					_adjustedParameterLocations[originalParameterIndex] = newParameterIndex;
					originalParameterIndex++;
					newParameterIndex++;
					continue;
				}

				var tokenizer = new StringTokenizer((string) part, symbols, true);

				foreach (var token in tokenizer)
				{
					if (token.StartsWith(ParserHelper.HqlVariablePrefix))
					{
						string filterParameterName = token.Substring(1);
						object value = session.GetFilterParameterValue(filterParameterName);
						IType type = session.GetFilterParameterType(filterParameterName);

						// If the value is not a value of the type but a collection of values...
						if (value != null && !type.ReturnedClass.IsAssignableFrom(value.GetType()) && // Added to fix NH-882
						    typeof (ICollection).IsAssignableFrom(value.GetType()))
						{
							var coll = (ICollection) value;
							int i = 0;
							foreach (var elementValue in coll)
							{
								i++;
								int span = type.GetColumnSpan(session.Factory);
								if (span > 0)
								{
									result.AddParameter();
									filteredParameterTypes.Add(type);
									filteredParameterValues.Add(elementValue);
									filteredParameterLocations.Add(newParameterIndex);
									newParameterIndex++;
									if (i < coll.Count)
									{
										result.Add(", ");
									}
								}
							}
						}
						else
						{
							int span = type.GetColumnSpan(session.Factory);
							if (span > 0)
							{
								result.AddParameter();
								filteredParameterTypes.Add(type);
								filteredParameterValues.Add(value);
								filteredParameterLocations.Add(newParameterIndex);
								newParameterIndex++;
							}
						}
					}
					else
					{
						result.Add(token);
					}
				}
			}

			processedSQL = result.ToSqlString();
		}
        private void AddParameters(String propertyName, SqlStringBuilder sql, ICriteria criteria, ICriteriaQuery criteriaQuery)
        {
            bool hasProperty = false;
            bool hasParameter = false;

            sql.Add(FunctionName).Add("(");

            if (ParameterValues != null && ParameterValues.Length > 0)
            {
                for (int i = 0; i < ParameterValues.Length; i++)
                {
                    if (PropertyPosition == i)
                    {
                        if (i > 0) sql.Add(", ");
                        sql.Add(criteriaQuery.GetColumn(criteria, propertyName)).Add(", ");
                        hasProperty = true;
                    }
                    else if (i > 0)
                    {
                        sql.Add(", ");
                    }

                    sql.AddParameter();
                    hasParameter = true;
                }
            }
            if (!hasProperty)
            {
                if (hasParameter) sql.Add(", ");
                sql.Add(criteriaQuery.GetColumn(criteria, propertyName));
            }

            sql.Add(")");
        }
        public virtual SqlString ToSqlString(ICriteria criteria, ICriteriaQuery criteriaQuery,
            IDictionary<string, IFilter> enabledFilters)
        {
            var sql = new SqlStringBuilder();
            string leftPropertyName = null;
            string rightPropertyName = null;

            if (InnerCriterion is SimpleExpression)
            {
                leftPropertyName = ((SimpleExpression)InnerCriterion).PropertyName;
            }
            else if (InnerCriterion is PropertyExpression)
            {
                System.Type type = typeof(PropertyExpression);
                leftPropertyName =
                    type.GetField("_lhsPropertyName", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(InnerCriterion) as
                    String;
                rightPropertyName =
                    type.GetField("_rhsPropertyName", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(InnerCriterion) as
                    String;
            }

            AddParameters(leftPropertyName, sql, criteria, criteriaQuery);
            sql.Add(" ").Add(Op).Add(" ");

            if (RightFunction != null)
            {
                RightFunction.AddParameters(rightPropertyName, sql, criteria, criteriaQuery);
            }
            else
            {
                sql.AddParameter();
            }

            return sql.ToSqlString();
        }