Ejemplo n.º 1
0
        public void TestStringFilter()
        {
            string              test = "SELECT * FROM (SELECT WidgetName,WidgetID FROM DimWidget) AS [t0] WHERE ([t0].[Foreman] LIKE @p0) ORDER BY [WidgetName];";
            SqlSelectBuilder    q    = new SqlSelectBuilder("SELECT WidgetName,WidgetID FROM DimWidget ORDER BY [WidgetName];");
            SqlStatement        s;
            SqlFilterCollection filters = new SqlFilterCollection();

            q.Filters.Add(new SqlStringMatchFilter(q.Table, "Foreman", SqlWildcardDecoration.BeginsWith, "B"));
            s = q.Render();

            Assert.IsTrue(string.Equals(s.CommandText, test, StringComparison.OrdinalIgnoreCase), "Output CommandText does not match expected result");

            Assert.IsTrue((s.Parameters.Count == 1), "Parameter count should be 1.");
            Assert.IsTrue(((string)s.Parameters.Single().Value == "B%"), "Parameter value is incorrect");

            q.Filters.Clear();
            q.Filters.Add(new SqlStringMatchFilter(q.Table, "Foreman", SqlWildcardDecoration.EndsWith, "B"));
            s = q.Render();

            Assert.IsTrue((s.Parameters.Count == 1), "Parameter count should be 1.");
            Assert.IsTrue(((string)s.Parameters.Single().Value == "%B"), "Parameter value is incorrect");

            q.Filters.Clear();
            q.Filters.Add(new SqlStringMatchFilter(q.Table, "Foreman", SqlWildcardDecoration.Contains, "B"));
            s = q.Render();

            Assert.IsTrue((s.Parameters.Count == 1), "Parameter count should be 1.");
            Assert.IsTrue(((string)s.Parameters.Single().Value == "%B%"), "Parameter value is incorrect");
        }
        private void InitStatementString(IOuterJoinLoadable elementPersister, string alias, int batchSize, SqlString subquery)
        {
            int joins = CountEntityPersisters(associations);

            Suffixes = BasicLoader.GenerateSuffixes(joins + 1);

            int collectionJoins = CountCollectionPersisters(associations) + 1;

            CollectionSuffixes = BasicLoader.GenerateSuffixes(joins + 1, collectionJoins);

            SqlStringBuilder whereString = WhereString(oneToManyPersister.GenerateTableAliasForKeyColumns(alias), oneToManyPersister.KeyColumnNames, subquery, batchSize);
            string           filter      = oneToManyPersister.FilterFragment(alias, EnabledFilters);

            whereString.Insert(0, StringHelper.MoveAndToBeginning(filter));

            JoinFragment     ojf    = MergeOuterJoins(associations);
            SqlSelectBuilder select =
                new SqlSelectBuilder(Factory).SetSelectClause(
                    oneToManyPersister.SelectFragment(null, null, alias, Suffixes[joins], CollectionSuffixes[0], true)
                    + SelectString(associations)).SetFromClause(elementPersister.FromTableFragment(alias)
                                                                + oneToManyPersister.FromJoinFragment(alias, true, true)).SetWhereClause(
                    whereString.ToSqlString()).SetOuterJoins(ojf.ToFromFragmentString,
                                                             ojf.ToWhereFragmentString
                                                             + elementPersister.WhereJoinFragment(alias, true, true));

            select.SetOrderByClause(OrderBy(associations, oneToManyPersister.GetSQLOrderByString(alias)));

            if (Factory.Settings.IsCommentsEnabled)
            {
                select.SetComment("load one-to-many " + oneToManyPersister.Role);
            }

            SqlString = select.ToSqlString();
        }
Ejemplo n.º 3
0
        public void TestSelectFilters()
        {
            var test    = "SELECT [t0].[LastName],[t0].[FirstName] FROM [dbo].[Contact] AS [t0] WHERE ([t0].[LastName]=@p0) AND ([t0].[FirstName]>@p1) ORDER BY [LastName] ASC,[FirstName] DESC;";
            var builder = new SqlSelectBuilder();

            builder.Table = new SqlTable("dbo.Contact");
            builder.Columns.Add(new SqlColumn(builder.Table, "LastName"));
            builder.Columns.Add(new SqlColumn(builder.Table, "FirstName"));
            builder.OrderBy.Add(new SqlOrderColumn()
            {
                ColumnName = "LastName", SortDirection = DbSortDirection.Ascending
            });
            builder.OrderBy.Add(new SqlOrderColumn()
            {
                ColumnName = "FirstName", SortDirection = DbSortDirection.Descending
            });
            builder.Filters.Add(new SqlCompareFilter <string>(builder.Table, "LastName", SqlOperator.Equal, "Buchanan"));
            builder.Filters.Add(new SqlCompareFilter <string>(builder.Table, "FirstName", SqlOperator.GreaterThan, "a"));

            var stmt = builder.Render();

            Assert.IsNotNull(stmt.CommandText);
            Assert.AreEqual(stmt.CommandText, test);
            Assert.AreEqual(stmt.Parameters.ToList()[0].Value, "Buchanan");
            Assert.AreEqual(stmt.Parameters.ToList()[1].Value, "a");
        }
Ejemplo n.º 4
0
        private void InitStatementString(SqlString projection, SqlString condition,
                                         SqlString orderBy, string groupBy, SqlString having, LockMode lockMode)
        {
            int joins = CountEntityPersisters(associations);

            Suffixes = BasicLoader.GenerateSuffixes(joins + 1);
            JoinFragment ojf = MergeOuterJoins(associations);

            SqlString selectClause = projection
                                     ??
                                     new SqlString(persister.SelectFragment(alias, Suffixes[joins]) + SelectString(associations));

            SqlSelectBuilder select = new SqlSelectBuilder(Factory)
                                      .SetLockMode(lockMode)
                                      .SetSelectClause(selectClause)
                                      .SetFromClause(Dialect.AppendLockHint(lockMode, persister.FromTableFragment(alias)) + persister.FromJoinFragment(alias, true, true))
                                      .SetWhereClause(condition)
                                      .SetOuterJoins(ojf.ToFromFragmentString, ojf.ToWhereFragmentString + WhereFragment)
                                      .SetOrderByClause(OrderBy(associations, orderBy))
                                      .SetGroupByClause(groupBy)
                                      .SetHavingClause(having);

            if (Factory.Settings.IsCommentsEnabled)
            {
                select.SetComment(Comment);
            }

            SqlString = select.ToSqlString();
        }
Ejemplo n.º 5
0
        public void SelectStringSqlTest()
        {
            Configuration   cfg     = new Configuration();
            ISessionFactory factory = cfg.BuildSessionFactory();

            ISessionFactoryImplementor factoryImpl = (ISessionFactoryImplementor)factory;
            SqlSelectBuilder           select      = new SqlSelectBuilder(factoryImpl);

            select.SetSelectClause("column1, column2");
            select.SetFromClause("select_test", "select_test_alias");
            select.SetOuterJoins(
                new SqlString(" LEFT OUTER JOIN before ON select_test_alias.column1 = before.column1"),
                new SqlString(" after.some_field = after.another_field "));
            select.SetOrderByClause(new SqlString("column1 DESC"));

            select.SetWhereClause("select_test_alias", new string[] { "identity_column" }, NHibernateUtil.Int64);

            SqlString sqlString = select.ToSqlString();

            string expectedSql = new StringBuilder().Append("SELECT ")
                                 .Append("column1, column2 ")
                                 .Append("FROM select_test select_test_alias ")
                                 .Append("LEFT OUTER JOIN before ON select_test_alias.column1 = before.column1 ")
                                 .Append("WHERE ")
                                 .Append("after.some_field = after.another_field")
                                 .Append(" AND ")
                                 .Append("select_test_alias.identity_column = ? ")
                                 .Append("ORDER BY column1 DESC")
                                 .ToString();


            Assert.AreEqual(expectedSql, sqlString.ToString(), "SQL String");
            Assert.AreEqual(1, sqlString.GetParameterCount(), "One parameter");
        }
Ejemplo n.º 6
0
        public long Count(params Object[] selectionArgs)
        {
            var builder      = Builder;
            var countBuilder = new SqlSelectBuilder
            {
                Source        = builder.Source,
                Dialect       = builder.Dialect,
                WhereClause   = builder.WhereClause,
                GroupByClause = builder.GroupByClause,
                OrderByClause = builder.OrderByClause,
                LimitClause   = builder.LimitClause,
                Clauses       = builder.Clauses,
            };

            foreach (var jc in builder.JoinClauses)
            {
                countBuilder.JoinClauses.Add(jc);
            }
            countBuilder.ResultColumns.Add("count(1)");

            var connection = Connection;

            if (connection != null)
            {
                return(connection.ExecuteScalar <long>(countBuilder.ToString() + ";", parameters: selectionArgs));
            }
            else
            {
                return(Datastore.ExecuteScalar <long>(countBuilder.ToString() + ";", parameters: selectionArgs));
            }
        }
Ejemplo n.º 7
0
        private void InitStatementString(IQueryableCollection persister, string alias, IList associations, int batchSize, ISessionFactoryImplementor factory)
        {
            Suffixes = GenerateSuffixes(associations.Count);

            SqlStringBuilder whereString = WhereString(factory, alias, persister.KeyColumnNames, persister.KeyType, batchSize);

            if (persister.HasWhere)
            {
                whereString
                .Add(" and ")
                .Add(persister.GetSQLWhereString(alias));
            }

            JoinFragment     ojf    = MergeOuterJoins(associations);
            SqlSelectBuilder select = new SqlSelectBuilder(factory)
                                      .SetSelectClause(
                persister.SelectFragment(alias).Append(
                    SelectString(associations, factory)).ToString()
                )
                                      .SetFromClause(persister.TableName, alias)
                                      .SetWhereClause(whereString.ToSqlString())
                                      .SetOuterJoins(
                ojf.ToFromFragmentString,
                ojf.ToWhereFragmentString
                );

            if (persister.HasOrdering)
            {
                select.SetOrderByClause(persister.GetSQLOrderByString(alias));
            }
            SqlString = select.ToSqlString();
        }
Ejemplo n.º 8
0
        public void Extensions_RenderBatch()
        {
            string test       = "SELECT * FROM [dbo].[DimWidget] AS [t0] WHERE ([t0].[WidgetID]=@p0);\r\nSELECT * FROM [dbo].[DimWidget] AS [t1] WHERE ([t1].[WidgetID]=@p1);\r\nSELECT * FROM [dbo].[DimWidget] AS [t2] WHERE ([t2].[WidgetID]=@p2);\r\n";
            var    collection = new List <SqlSelectBuilder>();

            var q1 = new SqlSelectBuilder("dbo.DimWidget");

            q1.Filters.Add(new SqlCompareFilter <int>(q1.Table, "WidgetID", SqlOperator.Equal, 1));
            collection.Add(q1);

            var q2 = new SqlSelectBuilder("dbo.DimWidget");

            q2.Filters.Add(new SqlCompareFilter <int>(q2.Table, "WidgetID", SqlOperator.Equal, 2));
            collection.Add(q2);

            var q3 = new SqlSelectBuilder("dbo.DimWidget");

            q3.Filters.Add(new SqlCompareFilter <int>(q3.Table, "WidgetID", SqlOperator.Equal, 3));
            collection.Add(q3);

            var stmt = collection.RenderBatch();

            Assert.AreEqual(3, stmt.Count);
            Assert.AreEqual(3, stmt.Parameters.Count);
            Assert.AreEqual(1, stmt.Parameters.First().Value);
            Assert.AreEqual(2, stmt.Parameters.Skip(1).First().Value);
            Assert.AreEqual(3, stmt.Parameters.Last().Value);
            Assert.AreEqual(test, stmt.CommandText, true);
        }
Ejemplo n.º 9
0
        //public static QueryBuilder<TResult> From<TResult>(this DbConnection connection, ICommandBuilder commandBuilder = null) where TResult : class, new()
        //{
        //    return From<TResult>(connection, (TableOrSubQuery)null, (ICommandBuilder)null);
        //}

        public static QueryBuilder <TResult> From <TResult>(this DbConnection connection, TableOrSubQuery source = null, ICommandBuilder commandBuilder = null) where TResult : class, new()
        {
            commandBuilder = commandBuilder ?? DefaultCommandBuilder;
            var discription          = GlobalEntityDescriptionLookup.Instance.LookUpEntityByType(typeof(TResult));
            SqlSelectBuilder builder = commandBuilder.BuildSelect(source ?? discription.Source, discription.Fields);

            return(new QueryBuilder <TResult>(connection, builder));
        }
Ejemplo n.º 10
0
        private void ConstructBody()
        {
            CSBlock usingBlock = new CSBlock("using (SqlCommand sqlCommand = new SqlCommand())");
            string  sqlString  = $"{Quotes}{SqlSelectBuilder.CreateSelectAll(datatable)}{Quotes};";

            usingBlock.Statements.Add($"sqlCommand.CommandText = {sqlString}");
            usingBlock.Statements.Add($"return ToList(sqlCommand);");
            this.Statements.Add(usingBlock.ToString());
        }
Ejemplo n.º 11
0
        private void ConstructBody()
        {
            VBBlock usingBlock = new VBBlock(VBBlockStatement.Using, "Using sqlCommand As New SqlCommand()");
            string  sqlString  = $"{Quotes}{SqlSelectBuilder.CreateSelectAll(datatable)}{Quotes}";

            usingBlock.Statements.Add($"sqlCommand.CommandText = {sqlString}");
            usingBlock.Statements.Add($"Return ToList(sqlCommand)");
            this.Statements.Add(usingBlock.ToString());
        }
Ejemplo n.º 12
0
        public void TestParse()
        {
            string       test = "SELECT * FROM (SELECT * FROM DimWidget WHERE WidgetID LIKE 'a%') AS [t0] ORDER BY [WidgetName];";
            var          q    = new SqlSelectBuilder("SELECT * FROM DimWidget WHERE WidgetID LIKE 'a%' ORDER BY [WidgetName];");
            SqlStatement s;

            s = q.Render();

            Assert.IsTrue(string.Equals(s.CommandText, test, StringComparison.OrdinalIgnoreCase), "Output CommandText does not match expected result");
        }
Ejemplo n.º 13
0
        public void TestQueryWithoutOrderBy()
        {
            string           test = "SELECT * FROM (SELECT TOP 10 * FROM Products) AS [t0];";
            SqlSelectBuilder q    = new SqlSelectBuilder("SELECT TOP 10 * FROM Products");
            SqlStatement     s;

            s = q.Render();

            Assert.IsTrue(string.Equals(s.CommandText, test, StringComparison.OrdinalIgnoreCase), "Output CommandText does not match expected result");
        }
Ejemplo n.º 14
0
        private void ConstructBody()
        {
            CSBlock usingBlock = new CSBlock("using (SqlCommand sqlCommand = new SqlCommand())");
            string  sqlString  = $"{Quotes}{SqlSelectBuilder.CreateSelectCountByKeyword(datatable)}{Quotes};";

            usingBlock.Statements.Add($"sqlCommand.CommandText = {sqlString}");
            usingBlock.Statements.Add($"{NewLine}sqlCommand.Parameters.AddWithValue({$"{Quotes}@Keyword{Quotes}"}, keyword);");
            usingBlock.Statements.Add($"return Convert.ToInt32(table.DbAccess.ExecuteScalar(sqlCommand));");
            this.Statements.Add(usingBlock.ToString());
        }
Ejemplo n.º 15
0
        public void TestSelect()
        {
            var test    = "SELECT * FROM [dbo].[Contact] AS [t0];";
            var builder = new SqlSelectBuilder();

            builder.Table = new SqlTable("dbo.Contact");
            var stmt = builder.Render();

            Assert.IsNotNull(stmt.CommandText);
            Assert.AreEqual(stmt.CommandText, test);
        }
Ejemplo n.º 16
0
        public void TestParseOrderBy()
        {
            string           expected = "SELECT * FROM (SELECT * FROM Report_Nrt) AS [t0] ORDER BY [DivisionName];";
            string           query    = "SELECT * FROM Report_Nrt ORDER BY DivisionName";
            SqlSelectBuilder q        = new SqlSelectBuilder(query);
            SqlStatement     s;

            s = q.Render();

            Assert.IsTrue(string.Equals(s.CommandText, expected, StringComparison.OrdinalIgnoreCase), "Output CommandText does not match expected result");
        }
Ejemplo n.º 17
0
        public void TestRawColumn()
        {
            var query = new SqlSelectBuilder("[Foo]");

            query.Columns.Add(new SqlRawColumn("NULL", "Nothing"));
            query.Columns.Add(new SqlRawColumn("1234"));

            var stmt = query.Render();

            Assert.AreEqual("SELECT NULL AS [Nothing],1234 FROM [Foo] AS [t0];", stmt.CommandText);
        }
Ejemplo n.º 18
0
        public void TestLiteralColumn()
        {
            var query = new SqlSelectBuilder("[Foo]");

            query.Columns.Add(new SqlLiteralColumn <int>(1));
            query.Columns.Add(new SqlLiteralColumn <string>("2", "Two"));

            var stmt = query.Render();

            Assert.AreEqual("SELECT 1,'2' AS [Two] FROM [Foo] AS [t0];", stmt.CommandText);
        }
Ejemplo n.º 19
0
        public void TestExpressionColumn()
        {
            string test = "SELECT (Foo + 1) AS [Bar] FROM [TableName] AS [t0];";

            var q   = new SqlSelectBuilder("TableName");
            var col = new SqlExpressionSelectColumn(q.Table, "Foo + 1", "Bar");

            q.Columns.Add(col);
            var s = q.Render();

            Assert.AreEqual(s.CommandText, test);
        }
Ejemplo n.º 20
0
        public void TestColumnAliasing()
        {
            string test = "SELECT [t0].[Foo] AS [Bar] FROM [TableName] AS [t0];";

            var q = new SqlSelectBuilder("TableName");

            q.Columns.Add(new SqlColumn(q.Table, "Foo", "Bar"));

            var s = q.Render();

            Assert.AreEqual(s.CommandText, test);
        }
Ejemplo n.º 21
0
        private void InitStatementString(string alias, int batchSize, SqlString subquery)
        {
            int joins           = CountEntityPersisters(associations);
            int collectionJoins = CountCollectionPersisters(associations) + 1;

            Suffixes           = BasicLoader.GenerateSuffixes(joins);
            CollectionSuffixes = BasicLoader.GenerateSuffixes(joins, collectionJoins);

            SqlStringBuilder whereString = WhereString(alias, collectionPersister.KeyColumnNames, subquery, batchSize);

            string manyToManyOrderBy = string.Empty;
            string filter            = collectionPersister.FilterFragment(alias, EnabledFilters);

            if (collectionPersister.IsManyToMany)
            {
                // from the collection of associations, locate OJA for the
                // ManyToOne corresponding to this persister to fully
                // define the many-to-many; we need that OJA so that we can
                // use its alias here
                // TODO : is there a better way here?
                IAssociationType associationType = (IAssociationType)collectionPersister.ElementType;
                foreach (OuterJoinableAssociation oja in associations)
                {
                    if (oja.JoinableType == associationType)
                    {
                        // we found it
                        filter            += collectionPersister.GetManyToManyFilterFragment(oja.RHSAlias, EnabledFilters);
                        manyToManyOrderBy += collectionPersister.GetManyToManyOrderByString(oja.RHSAlias);
                    }
                }
            }

            whereString.Insert(0, StringHelper.MoveAndToBeginning(filter));
            JoinFragment ojf = MergeOuterJoins(associations);

            SqlSelectBuilder select =
                new SqlSelectBuilder(Factory)
                .SetSelectClause(collectionPersister.SelectFragment(alias, CollectionSuffixes[0])
                                 + SelectString(associations))
                .SetFromClause(collectionPersister.TableName, alias)
                .SetWhereClause(whereString.ToSqlString())
                .SetOuterJoins(ojf.ToFromFragmentString, ojf.ToWhereFragmentString);

            select.SetOrderByClause(OrderBy(associations, MergeOrderings(collectionPersister.GetSQLOrderByString(alias), manyToManyOrderBy)));

            if (Factory.Settings.IsCommentsEnabled)
            {
                select.SetComment("load collection " + collectionPersister.Role);
            }

            SqlString = select.ToSqlString();
        }
Ejemplo n.º 22
0
        public void TestExistFilter()
        {
            var outerQuery = new SqlSelectBuilder("SELECT * FROM Stuff ORDER BY [WidgetName];");
            var innerQuery = new SqlSelectBuilder("[Foo]");

            innerQuery.Columns.Add(new SqlLiteralColumn <int>(1));

            outerQuery.Filters.Add(new SqlExistFilter(innerQuery));

            var stmt = outerQuery.Render();

            Assert.AreEqual("SELECT * FROM (SELECT * FROM Stuff) AS [t0] WHERE (EXISTS (SELECT 1 FROM [Foo] AS [t1])) ORDER BY [WidgetName];", stmt.CommandText);
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Adds an EXISTS(selectStatement) filter critera.
        /// </summary>
        /// <param name="where"></param>
        /// <param name="innerQuery">The value to render as the inner SELECT statement</param>
        /// <returns></returns>
        public static IDbQueryWhereClause Exists(this IDbQueryWhereClause where, string sqlText, Action <IDbQueryWhereClause> subQueryFilters)
        {
            var innerTable = SqlTable.Create(sqlText);
            var innerQuery = new SqlSelectBuilder(innerTable);
            var innerWhere = new DbQueryWhereClause(innerTable, SqlLogic.And);

            innerQuery.Columns.Add(new SqlRawColumn("1"));
            subQueryFilters(innerWhere);
            innerWhere.ApplyTo(innerQuery.Filters);
            where.AddFilter(new Sql.SqlExistFilter(innerQuery));

            return(where);
        }
Ejemplo n.º 24
0
        private void ConstructBody()
        {
            var    usingBlock = new CSBlock("using (SqlCommand sqlCommand = new SqlCommand())");
            string sqlString  = $"${Quotes}{SqlSelectBuilder.CreateSelectByKeyword(datatable)}{Quotes};";

            usingBlock.Statements.Add($"sqlCommand.CommandText = {sqlString} ");

            usingBlock.Statements.Add($"{NewLine}sqlCommand.Parameters.AddWithValue({$"{Quotes}@Keyword{Quotes}"}, keyword);");
            usingBlock.Statements.Add($"sqlCommand.Parameters.AddWithValue({Quotes}@Start{Quotes}, start);");
            usingBlock.Statements.Add($"sqlCommand.Parameters.AddWithValue({Quotes}@End{Quotes}, end);");
            usingBlock.Statements.Add($"return ToList(sqlCommand);");
            this.Statements.Add(usingBlock.ToString());
        }
Ejemplo n.º 25
0
        private void ConstructBody()
        {
            VBBlock usingBlock = new VBBlock(VBBlockStatement.Using, "Using sqlCommand As New SqlCommand()");
            string  sqlString  = $"${Quotes}{SqlSelectBuilder.CreateSelectByKeyword(datatable)}{Quotes}";

            usingBlock.Statements.Add($"sqlCommand.CommandText = {sqlString} ");

            usingBlock.Statements.Add($"{NewLine}sqlCommand.Parameters.AddWithValue({$"{Quotes}@Keyword{Quotes}"}, keyword)");
            usingBlock.Statements.Add($"sqlCommand.Parameters.AddWithValue({Quotes}@Start{Quotes}, start)");
            usingBlock.Statements.Add($"sqlCommand.Parameters.AddWithValue({Quotes}@End{Quotes}, _end)");
            usingBlock.Statements.Add($"Return ToList(sqlCommand)");
            this.Statements.Add(usingBlock.ToString());
        }
Ejemplo n.º 26
0
        private void ConstructBody()
        {
            VBBlock usingBlock     = new VBBlock(VBBlockStatement.Using, "Using sqlCommand As New SqlCommand()");
            string  parameterName  = $"{Quotes}@{datacolumn.ColumnName.Replace(" ","")}{Quotes}";
            string  parameterValue = ProperVarName.Get(datacolumn.ColumnName.ToLower());
            string  columnName     = datacolumn.ColumnName.Contains(" ") ? $"[{datacolumn.ColumnName}]" : datacolumn.ColumnName;
            string  sqlString      = $"{Quotes}{SqlSelectBuilder.CreateSelectAllWhere(datatable, $"{columnName} = @{datacolumn.ColumnName.Replace(" ", "")}")}{Quotes}";

            usingBlock.Statements.Add($"sqlCommand.CommandText = {sqlString}");
            usingBlock.Statements.Add($"sqlCommand.Parameters.AddWithValue({parameterName}, {parameterValue})");
            usingBlock.Statements.Add($"Return ToList(sqlCommand)");
            this.Statements.Add(usingBlock.ToString());
        }
Ejemplo n.º 27
0
        public void TestPrefix()
        {
            var test    = "SET ROWCOUNT 10;SELECT [t0].[FirstName] FROM [dbo].[Contact] AS [t0];";
            var builder = new SqlSelectBuilder();

            builder.Table = new SqlTable("dbo.Contact");
            builder.Columns.Add(new SqlColumn(builder.Table, "FirstName"));
            builder.Prefix = "SET ROWCOUNT 10";

            var stmt = builder.Render();

            Assert.IsNotNull(stmt.CommandText);
            Assert.AreEqual(stmt.CommandText, test);
        }
Ejemplo n.º 28
0
        public void TestSuffix()
        {
            var test    = "SELECT [t0].[FirstName] FROM [dbo].[Contact] AS [t0];A Suffix Statement Goes Here;";
            var builder = new SqlSelectBuilder();

            builder.Table = new SqlTable("dbo.Contact");
            builder.Columns.Add(new SqlColumn(builder.Table, "FirstName"));
            builder.Suffix = "A Suffix Statement Goes Here";

            var stmt = builder.Render();

            Assert.IsNotNull(stmt.CommandText);
            Assert.AreEqual(stmt.CommandText, test);
        }
        protected SqlString GenerateIdInsertSelect(IQueryable persister, string tableAlias, IASTNode whereClause)
        {
            var            select         = new SqlSelectBuilder(Factory);
            SelectFragment selectFragment = new SelectFragment(Factory.Dialect)
                                            .AddColumns(tableAlias, persister.IdentifierColumnNames, persister.IdentifierColumnNames);

            select.SetSelectClause(selectFragment.ToFragmentString().Substring(2));

            string    rootTableName    = persister.TableName;
            SqlString fromJoinFragment = persister.FromJoinFragment(tableAlias, true, false);

            select.SetFromClause(rootTableName + " " + tableAlias + fromJoinFragment);

            var whereJoinFragment = GetWhereJoinFragment(persister, tableAlias);

            SqlString userWhereClause = SqlString.Empty;

            if (whereClause.ChildCount != 0)
            {
                // If a where clause was specified in the update/delete query, use it to limit the
                // returned ids here...
                try
                {
                    var nodes = new CommonTreeNodeStream(whereClause);
                    var gen   = new SqlGenerator(Factory, nodes);
                    gen.whereClause();
                    userWhereClause = gen.GetSQL().Substring(7);
                }
                catch (RecognitionException e)
                {
                    throw new HibernateException("Unable to generate id select for DML operation", e);
                }
                if (whereJoinFragment.Length > 0)
                {
                    whereJoinFragment = whereJoinFragment.Append(" and ");
                }
            }

            select.SetWhereClause(whereJoinFragment + userWhereClause);

            var insert = new InsertSelect();

            if (Factory.Settings.IsCommentsEnabled)
            {
                insert.SetComment("insert-select for " + persister.EntityName + " ids");
            }
            insert.SetTableName(persister.TemporaryIdTableName);
            insert.SetSelect(select);
            return(insert.ToSqlString());
        }
Ejemplo n.º 30
0
        public void TestGreaterThanFilter()
        {
            string              test = "SELECT * FROM (SELECT WidgetName,WidgetID FROM DimWidget) AS [t0] WHERE ([t0].[OfficeKey]>@p0) ORDER BY [WidgetName];";
            SqlSelectBuilder    q    = new SqlSelectBuilder("SELECT WidgetName,WidgetID FROM DimWidget ORDER BY [WidgetName];");
            SqlStatement        s;
            SqlFilterCollection filters = new SqlFilterCollection();

            q.Filters.Add(q.Table, "OfficeKey", SqlOperator.GreaterThan, System.Data.DbType.Int32, 10);
            s = q.Render();

            Assert.IsTrue((s.Parameters.Count > 0), "Parameter count should be 1.");
            Assert.IsTrue(((int)s.Parameters.Single().Value == 10), "Parameter value not correct");
            Assert.IsTrue(string.Equals(s.CommandText, test, StringComparison.OrdinalIgnoreCase), "Output CommandText does not match expected result");
        }
        public void BootStrapTheApplication()
        {
            EventStoreDatabaseBootStrapper.BootStrap();
            ReportingDatabaseBootStrapper.BootStrap();

            var bus = new FakeBus();
            ServiceLocator.Bus = bus;
            //var storage = new InMemoryEventStore(bus);
            //var storage = new NHibernateSqliteEventStore(bus, NHibernateSessionHelper.CreateSessionFactory(), new BinaryFormatter());
            var storage = new SqliteEventStore(bus, new BinaryFormatter(), "Data Source=eventStore.db3");

            var rep = new DomainRepository<InventoryItem>(storage);
            var commands = new InventoryCommandHandlers(rep);
            bus.RegisterHandler<CheckInItemsToInventory>(commands.Handle);
            bus.RegisterHandler<CreateInventoryItem>(commands.Handle);
            bus.RegisterHandler<DeactivateInventoryItem>(commands.Handle);
            bus.RegisterHandler<RemoveItemsFromInventory>(commands.Handle);
            bus.RegisterHandler<RenameInventoryItem>(commands.Handle);

            var sqlInsertBuilder = new SqlInsertBuilder();
            var sqlSelectBuilder = new SqlSelectBuilder();
            var sqlUpdateBuilder = new SqlUpdateBuilder();
            var sqlDeleteBuilder = new SqlDeleteBuilder();
            var reportingRepository = new SQLiteReportingRepository("Data Source=reportingDataBase.db3", sqlSelectBuilder,
                                                                    sqlInsertBuilder, sqlUpdateBuilder, sqlDeleteBuilder);
            var detail = new InventoryItemDetailViewHandler(reportingRepository);
            ServiceLocator.ReportingRepository = reportingRepository;
            bus.RegisterHandler<InventoryItemCreated>(detail.Handle);
            bus.RegisterHandler<InventoryItemDeactivated>(detail.Handle);
            bus.RegisterHandler<InventoryItemRenamed>(detail.Handle);
            bus.RegisterHandler<ItemsCheckedInToInventory>(detail.Handle);
            bus.RegisterHandler<ItemsRemovedFromInventory>(detail.Handle);
            var list = new InventoryItemListViewHandler(reportingRepository);
            bus.RegisterHandler<InventoryItemCreated>(list.Handle);
            bus.RegisterHandler<InventoryItemRenamed>(list.Handle);
            bus.RegisterHandler<InventoryItemDeactivated>(list.Handle);
        }
Ejemplo n.º 32
0
 public void SetUp()
 {
     _sqlSelectBuilder = new SqlSelectBuilder();
 }