This class inherits from the Criteria class and implements a ToString(Habanero.Base.ISqlFormatter,Habanero.Base.CriteriaDB.AddParameterDelegate,System.Collections.Generic.IDictionary{string,string}) behaviour. This allows the formatting of a criteria object into a format specific for the database.
Inheritance: Criteria
示例#1
0
        public void TestConstructor()
        {
            //-------------Setup Test Pack ------------------
            const string surname = "Surname";
            string surnameValue = TestUtil.GetRandomString();
            Criteria criteria = new Criteria(surname, Criteria.ComparisonOp.Equals, surnameValue);

            //-------------Execute test ---------------------
            CriteriaDB criteriaDB = new CriteriaDB(criteria);
            //-------------Test Result ----------------------
            Assert.AreEqual(criteria, criteriaDB);
        }
示例#2
0
        public void Test_ToString_IsNullCriteria()
        {
            //-------------Setup Test Pack ------------------
            const string surnameField = "Surname";
            Criteria criteria = new Criteria(surnameField, Criteria.ComparisonOp.Is, null);
            const string surnameTable = "surname_table";
            criteria.Field.Source = new Source(surnameTable);
            CriteriaDB surnameCriteria = new CriteriaDB(criteria);

            //-------------Execute test ---------------------
            string tostring = surnameCriteria.ToString(new SqlFormatter("<<", ">>", "",""),
                                                       delegate(object value) { return Convert.ToString(value); },
                                                       SetupSingleAlias(surnameTable));
            //-------------Test Result ----------------------

            Assert.AreEqual(string.Format("a1.<<{0}>> IS NULL",  surnameField), tostring);
        }
示例#3
0
        public void Test_ToString_BlankSource()
        {
            //-------------Setup Test Pack ------------------
            string surnameValue = Guid.NewGuid().ToString("N");
            const string surname = "Surname";
            Criteria criteria = new Criteria(surname, Criteria.ComparisonOp.Equals, surnameValue);
            criteria.Field.Source = new Source("");
            CriteriaDB surnameCriteria = new CriteriaDB(criteria);

            //-------------Execute test ---------------------
            
            string tostring = surnameCriteria.ToString(new SqlFormatter("<<", ">>", "", ""),
                                                       delegate(object value) { return Convert.ToString(value); }, 
                                                       SetupSingleAlias(""));
            //-------------Test Result ----------------------

            Assert.AreEqual(string.Format("a1.<<{0}>> = {1}", surname, surnameValue), tostring);
        }
示例#4
0
        private void AppendWhereClause(StringBuilder builder, SqlStatement statement)
        {
            Criteria fullCriteria = Criteria.MergeCriteria(_selectQuery.Criteria, _selectQuery.DiscriminatorCriteria);
            ClassDef classDef = (ClassDef) _selectQuery.ClassDef;
            if (classDef != null && classDef.ClassID.HasValue)
            {
                Criteria classIDCriteria = new Criteria("DMClassID", Criteria.ComparisonOp.Equals, classDef.ClassID.Value);
                classIDCriteria.Field.Source = this.Source;
                fullCriteria = Criteria.MergeCriteria(fullCriteria, classIDCriteria);
            }

            if (fullCriteria == null) return;
            builder.Append(" WHERE ");
            CriteriaDB criteriaDB = new CriteriaDB(fullCriteria);

            string whereClause = criteriaDB.ToString(_sqlFormatter, value => AddParameter(value, statement),Aliases);

            builder.Append(whereClause);
        }
示例#5
0
        /// <summary>
        /// Converts this Criteria object to a string, using field names instead of property names and entity names instead of
        /// source names. The <see cref="AddParameterDelegate"/> allows a database query builder to create a parameter value
        /// when adding the value to the string for use with parametrized SQL.  Also see <see cref="ISqlStatement"/>.
        /// 
        /// The <see cref="ToString()"/> method uses this method with a simple delegate that converts DateTimes and Guids 
        /// to sensible string representations and to 
        /// </summary>
        /// See <see cref="PropNameConverterDelegate"/>
        /// <param name="formatter">A formatter for any specific database <see cref="SqlFormatter"/></param>
        /// <param name="addParameter">The delegate to use to convert the value in object form to a value in string form. 
        /// See <see cref="AddParameterDelegate"/></param>
        /// <returns>The Criteria in string form.</returns>
        public string ToString(ISqlFormatter formatter, AddParameterDelegate addParameter, IDictionary<string, string> aliases)
        {
            if (IsComposite())
            {
                string rightCriteriaAsString;
                if (LogicalOperator == LogicalOp.Not)
                {
                    rightCriteriaAsString = new CriteriaDB(RightCriteria).ToString(formatter, addParameter, aliases);
                    return string.Format("{0} ({1})", _logicalOps[(int)LogicalOperator], rightCriteriaAsString);
                } 
                string leftCriteriaAsString = new CriteriaDB(LeftCriteria).ToString(formatter, addParameter, aliases);
                rightCriteriaAsString = new CriteriaDB(RightCriteria).ToString(formatter, addParameter, aliases);
                return string.Format("({0}) {1} ({2})", leftCriteriaAsString, _logicalOps[(int)LogicalOperator],
                                     rightCriteriaAsString);
            }
            string valueString;
            string comparisonOperator = ComparisonOperatorString();
            if (_criteria.CanBeParametrised())
            {
                valueString = addParameter(FieldValue);
            } else
            {
                if (FieldValue == null)
                {
                    valueString = "NULL";
                    if (this.ComparisonOperator == ComparisonOp.Equals) comparisonOperator = "IS";
                    if (this.ComparisonOperator == ComparisonOp.NotEquals) comparisonOperator = "IS NOT";
                }
                else
                {
                    valueString = Convert.ToString(FieldValue);
                }

            }
            string sourceEntityName = "";
            string separator = "";
            if (Field.Source != null)
            {
            	var fieldSourceName = Field.Source.ChildSourceLeaf.ToString();
            	if (!aliases.ContainsKey(fieldSourceName))
				{
					var userMessage = string.Format("The source '{0}' for the property '{1}' " 
						+ "in the given criteria does not have an alias provided for it.",
						Field.Source, Field.PropertyName);
					var developerMessage = userMessage
						+ " The criteria object may have not been prepared correctly before the aliases were set up.";
					throw new HabaneroDeveloperException(userMessage, developerMessage);
				}
				sourceEntityName = aliases[fieldSourceName];
                separator = ".";
            }
            string fieldNameString = formatter.DelimitField(Field.FieldName);
            return string.Format("{0}{1}{2} {3} {4}", sourceEntityName, separator, fieldNameString, comparisonOperator, valueString);
        }
示例#6
0
        /// <summary>
        /// Converts this Criteria object to a string, using field names instead of property names and entity names (aliased) instead of
        /// source names. The <see cref="AddParameterDelegate"/> allows a database query builder to create a parameter value
        /// when adding the value to the string for use with parametrized SQL.  Also see <see cref="ISqlStatement"/>.
        ///
        /// The <see cref="ToString()"/> method uses this method with a simple delegate that converts DateTimes and Guids
        /// to sensible string representations and to
        ///
        /// Provide a set of aliases to replace entity names with their aliases.
        /// </summary>
        /// See <see cref="PropNameConverterDelegate"/>
        /// <param name="formatter">A formatter for any specific database <see cref="SqlFormatter"/></param>
        /// <param name="addParameter">The delegate to use to convert the value in object form to a value in string form.
        /// See <see cref="AddParameterDelegate"/></param>
        /// <param name="aliases">The mapping of aliases to use</param>
        /// <returns>The Criteria in string form.</returns>
        public string ToString(ISqlFormatter formatter, AddParameterDelegate addParameter, IDictionary <string, string> aliases)
        {
            if (IsComposite())
            {
                string rightCriteriaAsString;
                if (LogicalOperator == LogicalOp.Not)
                {
                    rightCriteriaAsString = new CriteriaDB(RightCriteria).ToString(formatter, addParameter, aliases);
                    return(string.Format("{0} ({1})", _logicalOps[(int)LogicalOperator], rightCriteriaAsString));
                }
                string leftCriteriaAsString = new CriteriaDB(LeftCriteria).ToString(formatter, addParameter, aliases);
                rightCriteriaAsString = new CriteriaDB(RightCriteria).ToString(formatter, addParameter, aliases);
                return(string.Format("({0}) {1} ({2})", leftCriteriaAsString, _logicalOps[(int)LogicalOperator],
                                     rightCriteriaAsString));
            }
            string valueString;
            string comparisonOperator = ComparisonOperatorString();

            if (_criteria.CanBeParametrised())
            {
                valueString = addParameter(FieldValue);
            }
            else
            {
                if (FieldValue == null)
                {
                    valueString = "NULL";
                    if (this.ComparisonOperator == ComparisonOp.Equals)
                    {
                        comparisonOperator = "IS";
                    }
                    if (this.ComparisonOperator == ComparisonOp.NotEquals)
                    {
                        comparisonOperator = "IS NOT";
                    }
                }
                else
                {
                    valueString = Convert.ToString(FieldValue);
                }
            }
            string sourceEntityName = "";
            string separator        = "";

            if (Field.Source != null)
            {
                var fieldSourceName = Field.Source.ChildSourceLeaf.ToString();
                if (!aliases.ContainsKey(fieldSourceName))
                {
                    var userMessage = string.Format("The source '{0}' for the property '{1}' "
                                                    + "in the given criteria does not have an alias provided for it.",
                                                    Field.Source, Field.PropertyName);
                    var developerMessage = userMessage
                                           + " The criteria object may have not been prepared correctly before the aliases were set up.";
                    throw new HabaneroDeveloperException(userMessage, developerMessage);
                }
                sourceEntityName = aliases[fieldSourceName];
                separator        = ".";
            }
            string fieldNameString = formatter.DelimitField(Field.FieldName);

            return(string.Format("{0}{1}{2} {3} {4}", sourceEntityName, separator, fieldNameString, comparisonOperator, valueString));
        }
示例#7
0
		public void Test_ToString_WithFieldHavingSource_WhenAliasMissing_ShouldThrowError()
		{
			//---------------Set up test pack-------------------
			const string sourceName = "mysource";
			const string propertyName = "testproperty";
			QueryField queryField = new QueryField(propertyName, "testfield", new Source(sourceName));
			Criteria criteria = new Criteria(queryField, Criteria.ComparisonOp.Equals, "myvalue");
			IDictionary<string, string> aliases = new Dictionary<string, string>();
			CriteriaDB criteriaDb = new CriteriaDB(criteria);
			SqlFormatter sqlFormatter = new SqlFormatter("[", "]", "", "LIMIT");
			//---------------Execute Test ----------------------
			var habaneroDeveloperException = Assert.Throws<HabaneroDeveloperException>(() =>
			{
				criteriaDb.ToString(sqlFormatter, value => "Param", aliases);
			});
			//---------------Test Result -----------------------
			Assert.IsNotNull(habaneroDeveloperException);
			var expectedMessage = string.Format("The source '{0}' for the property '{1}' " + "in the given criteria does not have an alias provided for it.", sourceName, queryField.PropertyName);
			var expectedDeveloperMessage = expectedMessage 
				+ " The criteria object may have not been prepared correctly before the aliases were set up.";
			Assert.AreEqual(expectedMessage, habaneroDeveloperException.Message);
			Assert.AreEqual(expectedDeveloperMessage, habaneroDeveloperException.DeveloperMessage);
    }
示例#8
0
		public void Test_ToString_ShouldUseAliases()
        {
            //---------------Set up test pack-------------------
            const string sourceName = "mysource";
            var source1 = new Source(sourceName);
            Source field1Source = source1;
            QueryField field1 = new QueryField("testfield", "testfield", field1Source);
            Criteria criteria = new Criteria(field1, Criteria.ComparisonOp.Equals, "myvalue");
			IDictionary<string, string> aliases = new Dictionary<string, string>() { { source1.ToString(), "a1" } };
            CriteriaDB criteriaDb = new CriteriaDB(criteria);
            SqlFormatter sqlFormatter = new SqlFormatter("[", "]", "", "LIMIT");
            //---------------Execute Test ----------------------
            string whereClause = criteriaDb.ToString(sqlFormatter, value => "Param", aliases);
            //---------------Test Result -----------------------
            StringAssert.AreEqualIgnoringCase("a1.[testfield] = Param", whereClause);
        }
示例#9
0
        public void Test_ToString_NotIn()
        {
            //---------------Set up test pack-------------------
            string surnameValue1 = Guid.NewGuid().ToString("N");
            string surnameValue2 = Guid.NewGuid().ToString("N");
            const string surname = "Surname";
            CriteriaDB surnameCriteria =
                new CriteriaDB(new Criteria(surname, Criteria.ComparisonOp.NotIn, new object[] { surnameValue1, surnameValue2 }));
            //---------------Assert PreConditions---------------            
            //---------------Execute Test ----------------------
            string criteriaAsString = surnameCriteria.ToString(new SqlFormatter("", "", "", ""), value => value.ToString());

            //---------------Test Result -----------------------
            string expectedString = string.Format("Surname NOT IN ('{0}', '{1}')", surnameValue1, surnameValue2);
            StringAssert.AreEqualIgnoringCase(expectedString, criteriaAsString);
            //---------------Tear Down -------------------------          
        }
示例#10
0
        public void Test_ToString_UsingDelegates()
        {
            //---------------Set up test pack-------------------
            string surnameValue = Guid.NewGuid().ToString("N");
            const string surname = "Surname";
            CriteriaDB surnameCriteria =
                new CriteriaDB(new Criteria(surname, Criteria.ComparisonOp.Equals, surnameValue));
            DateTime dateTimeValue = DateTime.Now;
            const string datetimePropName = "DateTime";
            CriteriaDB dateTimeCriteria =
                new CriteriaDB(new Criteria(datetimePropName, Criteria.ComparisonOp.GreaterThan, dateTimeValue));

            CriteriaDB andCriteria =
                new CriteriaDB(new Criteria(surnameCriteria, Criteria.LogicalOp.And, dateTimeCriteria));

            //---------------Execute Test ----------------------
            int i = 0;
            string criteriaAsString = andCriteria.ToString(new SqlFormatter("", "","",""), delegate { return "param" + i++; });

            //---------------Test Result -----------------------
            const string expectedString = "(Surname = param0) AND (DateTime > param1)";
            StringAssert.AreEqualIgnoringCase(expectedString, criteriaAsString);

            //---------------Tear Down -------------------------
        }