Exemplo n.º 1
0
		/// <summary>
		/// Verify parameter order when using unnamed parameters
		/// </summary>
		public void ExecuteTestUnnamedParameterOrder( string providerName )
		{
			GentleSettings.AnalyzerLevel = AnalyzerLevel.None;
			PersistenceBroker broker = new PersistenceBroker( providerName, "..." );
			GentleSqlFactory sf = broker.GetSqlFactory();
			if( ! sf.HasCapability( Capability.NamedParameters ) )
			{
				// create parameterized query
				SqlBuilder sb = new SqlBuilder( broker, StatementType.Select, typeof(MailingList) );
				sb.AddConstraint( Operator.Equals, "SenderAddress", "SenderAddress" );
				sb.AddConstraint( Operator.Equals, "Name", "Name" );
				SqlStatement stmt = sb.GetStatement( true );
				foreach( IDataParameter param in stmt.Command.Parameters )
				{
					Assert.IsTrue( param.ParameterName.IndexOf( (string) param.Value ) >= 0, "1: Parameter order not correctly maintained." );
				}
				// retry using parameters in reverse order 
				sb = new SqlBuilder( broker, StatementType.Select, typeof(MailingList) );
				sb.AddConstraint( Operator.Equals, "Name", "Name" );
				sb.AddConstraint( Operator.Equals, "SenderAddress", "SenderAddress" );
				stmt = sb.GetStatement( true );
				foreach( IDataParameter param in stmt.Command.Parameters )
				{
					Assert.IsTrue( param.ParameterName.IndexOf( (string) param.Value ) >= 0, "2: Parameter order not correctly maintained." );
				}
			}
		}
Exemplo n.º 2
0
        public void BuilderSelectClause()
        {
            using (var connection = GetOpenConnection())
            {
                var rand = new Random(8675309);
                var data = new List<User>();
                for (int i = 0; i < 100; i++)
                {
                    var nU = new User { Age = rand.Next(70), Id = i, Name = Guid.NewGuid().ToString() };
                    data.Add(nU);
                    nU.Id = (int)connection.Insert<User>(nU);
                }

                var builder = new SqlBuilder();
                var justId = builder.AddTemplate("SELECT /**select**/ FROM Users");
                var all = builder.AddTemplate("SELECT Name, /**select**/, Age FROM Users");

                builder.Select("Id");

                var ids = connection.Query<int>(justId.RawSql, justId.Parameters);
                var users = connection.Query<User>(all.RawSql, all.Parameters);

                foreach (var u in data)
                {
                    if (!ids.Any(i => u.Id == i)) throw new Exception("Missing ids in select");
                    if (!users.Any(a => a.Id == u.Id && a.Name == u.Name && a.Age == u.Age)) throw new Exception("Missing users in select");
                }
            }
        }
        public void BuilderSelectClause()
        {
            var rand = new Random(8675309);
            var data = new List<User>();
            for (var i = 0; i < 100; i++)
            {
                var nU = new User { Age = rand.Next(70), Id = i, Name = Guid.NewGuid().ToString() };
                data.Add(nU);
                nU.Id = (int) db.Insert(nU, selectIdentity: true);
            }

            var builder = new SqlBuilder();
            var justId = builder.AddTemplate("SELECT /**select**/ FROM Users");
            var all = builder.AddTemplate("SELECT /**select**/, Name, Age FROM Users");

            builder.Select("Id");

            var ids = db.Column<int>(justId.RawSql, justId.Parameters);
            var users = db.Select<User>(all.RawSql, all.Parameters);

            foreach (var u in data)
            {
                Assert.That(ids.Any(i => u.Id == i), "Missing ids in select");
                Assert.That(users.Any(a => a.Id == u.Id && a.Name == u.Name && a.Age == u.Age), "Missing users in select");
            }
        }
Exemplo n.º 4
0
        private static IEntity findById_Private( long id, ObjectInfo state )
        {
            if (id < 0) return null;

            IEntity result = null;

            SqlBuilder sh = new SqlBuilder( state.EntityInfo );
            processIncluder( state.Includer );
            String sql = sh.GetFindById( id, state.Includer.SelectedProperty );
            IDbCommand cmd = DataFactory.GetCommand( sql, DbContext.getConnection( state.EntityInfo ) );
            IList list = new ArrayList();
            IDataReader rd = null;
            try {
                rd = cmd.ExecuteReader();
                while (rd.Read()) {
                    list.Add( FillUtil.Populate( rd, state ) );
                }
            }
            catch (Exception ex) {
                logger.Error( ex.Message );
                logger.Error( ex.StackTrace );
                throw new OrmException( ex.Message, ex );
            }
            finally {
                OrmHelper.CloseDataReader( rd );
            }

            if (list.Count > 0) result = list[0] as IEntity;

            result = setEntityProperty( result, id, state );

            return result;
        }
        /// <summary>
        /// Maps the results of the <paramref name="query"/> to dynamic objects.
        /// The query is deferred-executed.
        /// </summary>
        /// <param name="query">The query.</param>
        /// <returns>The results of the query as dynamic objects.</returns>
        /// <seealso cref="Extensions.Map(IDbCommand, TextWriter)"/>
        public IEnumerable<dynamic> Map(SqlBuilder query)
        {
            var mapper = new DynamicMapper {
            Log = this.Log
             };

             return Extensions.Map<dynamic>(CreateCommand, query, mapper, this.Log);
        }
        public void BuilderTemplateWOComposition()
        {
            var builder = new SqlBuilder();
            var template = builder.AddTemplate("SELECT COUNT(*) FROM Users WHERE Age = @age", new { age = 5 });

            if (template.RawSql == null) throw new Exception("RawSql null");
            if (template.Parameters == null) throw new Exception("Parameters null");

            db.Insert(new User { Age = 5, Name = "Testy McTestington" });

            Assert.That(db.Scalar<int>(template.RawSql, template.Parameters), Is.EqualTo(1));
        }         
Exemplo n.º 7
0
		public void Init()
		{
			// make sure we have only 4 members 
			SqlBuilder sb = new SqlBuilder( StatementType.Delete, typeof(Member) );
			sb.AddConstraint( Operator.GreaterThan, "Id", 4 );
			Broker.Execute( sb.GetStatement( true ) );
			// make sure we have only 3 lists 
			sb = new SqlBuilder( StatementType.Delete, typeof(MailingList) );
			sb.AddConstraint( Operator.GreaterThan, "Id", 3 );
			Broker.Execute( sb.GetStatement( true ) );
			GentleSettings.CacheObjects = false;
			CacheManager.Clear();
		}
Exemplo n.º 8
0
        private static IEntity findById_Private( int id, ObjectInfo state ) {

            if (id < 0) return null;

            IEntity result = null;

            SqlBuilder sh = new SqlBuilder( state.EntityInfo );
            processIncluder( state.Includer );
            String sql = sh.GetFindById(id, state.Includer.SelectedProperty);
            var conn = DbContext.getConnection(state.EntityInfo);
            if (conn.State == System.Data.ConnectionState.Closed)
            {
                conn.Open();
                OrmHelper.initCount++;
                LogManager.GetLogger("Class:System.ORM.Operation.FindByIdOperation Method:findById_Private").Info("数据库连接已开启【" + OrmHelper.initCount + "】");
            }
            IDbCommand cmd = DataFactory.GetCommand(sql, conn);
            IList list = new ArrayList();
            IDataReader rd = null;
            try {
                rd = cmd.ExecuteReader();
                while (rd.Read()) {
                    list.Add( FillUtil.Populate( rd, state ) );
                }
            }
            catch (Exception ex) {
                logger.Error( ex.Message );
                logger.Error( ex.StackTrace );
                throw ex;
            }
            finally
            {
                if (!DbContext.shouldTransaction())
                {
                    if (conn.State != ConnectionState.Closed)
                    {
                        conn.Close();
                        conn.Dispose();
                        OrmHelper.clostCount++;
                        LogManager.GetLogger("Class:System.ORM.Operation.FindByIdOperation Method:findById_Private").Info("数据库连接已关闭【" + OrmHelper.clostCount + "】");
                    }
                }
                OrmHelper.CloseDataReader(rd);
            }

            if (list.Count > 0) result = list[0] as IEntity;

            result = setEntityProperty( result, id, state );

            return result;
        }
        public void BuilderTemplateWOComposition()
        {
            SuppressIfOracle("Oracle provider is not smart enough to replace '@' parameter delimiter with ':'");

            var builder = new SqlBuilder();
            var template = builder.AddTemplate("SELECT COUNT(*) FROM Users WHERE Age = @age", new { age = 5 });

            if (template.RawSql == null) throw new Exception("RawSql null");
            if (template.Parameters == null) throw new Exception("Parameters null");

            db.Insert(new User { Age = 5, Name = "Testy McTestington" });

            Assert.That(db.Scalar<int>(template.RawSql, template.Parameters), Is.EqualTo(1));
        }         
Exemplo n.º 10
0
        protected SqlBuilder GetColumnSqlType(Column column, string defaultValuePostfix = "")
        {
            if (column.Type == null)
                throw new ArgumentException($"Column {column.Name} must have a type");

            var sql = new SqlBuilder();

            var sqlColumn = SqlTypeMap.Convert(column);
            sql.Append(new SqlParameter { DbType = sqlColumn.DbType }.SqlDbType.ToString());
            sql.Append(sqlColumn.Length != null, "(" + sqlColumn.Length + ")");
            sql.Append(column.Nullable, "NULL").Or("NOT NULL");
            sql.Append(column.DefaultValue != null, "DEFAULT '{0}'", column.DefaultValue);
            sql.Append(column.IsPrimaryKey, " PRIMARY KEY");

            return sql;
        }
Exemplo n.º 11
0
        public static int DeleteBatch( String condition, EntityInfo entityInfo ) {

            if (strUtil.IsNullOrEmpty( condition )) {
                return 0;
            }

            String deleteSql = new SqlBuilder( entityInfo ).GetDeleteSql( condition );
            logger.Info(LoggerUtil.SqlPrefix+ "delete sql : " + deleteSql );

            List<IInterceptor> ilist = MappingClass.Instance.InterceptorList;
            for (int i = 0; i < ilist.Count; i++) {
                ilist[i].BeforDeleteBatch( entityInfo.Type, condition );
            }
            var conn = DbContext.getConnection(entityInfo);
            if (conn.State == System.Data.ConnectionState.Closed)
            {
                conn.Open();
                OrmHelper.initCount++;
                LogManager.GetLogger("Class:System.ORM.Operation.DeleteOperation Method:DeleteBatch").Info("数据库连接已开启【" + OrmHelper.initCount + "】");
            }
            IDbCommand cmd = DataFactory.GetCommand(deleteSql, conn);
            int rowAffected = cmd.ExecuteNonQuery();
            logger.Info("delete : " + rowAffected + " records affected");
            cmd.Connection.Close();

            if (!DbContext.shouldTransaction())
            {
                if (conn.State == ConnectionState.Open)
                {
                    conn.Close();
                    conn.Dispose();
                    OrmHelper.clostCount++;
                    LogManager.GetLogger("Class:System.ORM.Operation.DeleteOperation Method:DeleteBatch").Info("数据库连接已关闭【" + OrmHelper.clostCount + "】");
                }
            }

            for (int i = 0; i < ilist.Count; i++) {
                ilist[i].AfterDeleteBatch( entityInfo.Type, condition );
            }

            // update cache  timestamp
            CacheTime.updateTable( entityInfo.Type );

            return rowAffected;
        }
Exemplo n.º 12
0
        private static int Count( String condition, EntityInfo entityInfo ) {
            String countSql;
            int result = 0;
            SqlBuilder builder = new SqlBuilder( entityInfo );
            if (strUtil.IsNullOrEmpty( condition )) {
                countSql = String.Format( "select count(*) from {0}", entityInfo.TableName );
            }
            else {
                countSql = builder.GetCountSql( condition );
            }
            logger.Info(LoggerUtil.SqlPrefix + "[Count(String condition) Sql]:" + countSql);
            var conn = DbContext.getConnection(entityInfo);
            if (conn.State == System.Data.ConnectionState.Closed)
            {
                conn.Open();
                OrmHelper.initCount++;
                LogManager.GetLogger("Class:System.ORM.Operation.CountOperation Method:Count").Info("数据库连接已开启【" + OrmHelper.initCount + "】");
            }
            try
            {
                IDbCommand command = DataFactory.GetCommand(countSql, conn);
                result = cvt.ToInt( command.ExecuteScalar() );
            }
            catch (Exception exception) {
                logger.Error( exception.Message );
                throw exception;
            }
            finally
            {
                if (!DbContext.shouldTransaction())
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                        conn.Dispose();
                        OrmHelper.clostCount++;
                        LogManager.GetLogger("Class:System.ORM.Operation.CountOperation Method:Count").Info("数据库连接已关闭【" + OrmHelper.clostCount + "】");
                    }
                }
            }

            return result;
        }
Exemplo n.º 13
0
		public void TestNullValueForLong()
		{
			// get map to make sure object map is ok
			ObjectMap om = ObjectFactory.GetMap( null, typeof(BigNull) );
			FieldMap fm = om.GetFieldMap( "bigNull" );
			Assert.IsTrue( fm.NullValue != null, "NullValue not set." );
			Assert.IsTrue( fm.IsNullable, "Database column not marked as nullable." );
			Assert.IsTrue( fm.IsValueType, "Type not a value type (can hold null)." );
			Assert.IsFalse( fm.IsNullAssignable, "Type can hold null." );
			long x = 0;
			Assert.AreEqual( x, fm.NullValue, "Comparison 1 of object and long failed." );
			Assert.IsTrue( x.Equals( fm.NullValue ), "Comparison 2 of object and long failed." );
			Assert.IsTrue( fm.NullValue.Equals( x ), "Comparison 3 of object and long failed." );
			// create test statement with bigint parameter
			SqlBuilder sb = new SqlBuilder( StatementType.Insert, typeof(BigNull) );
			SqlStatement stmt = sb.GetStatement();
			// create object and set statement params
			BigNull bn = new BigNull();
			stmt.SetParameters( bn, true );
			// verify parameter values (assume bigNull is first and only param)
			IDbDataParameter param = stmt.Command.Parameters[ 0 ] as IDbDataParameter;
			Assert.AreEqual( DBNull.Value, param.Value, "Parameter 0 not converted to DBNull." );
		}
Exemplo n.º 14
0
        private static int Count( String condition, EntityInfo entityInfo )
        {
            String countSql;
            int result = 0;
            SqlBuilder builder = new SqlBuilder( entityInfo );
            if (strUtil.IsNullOrEmpty( condition )) {
                countSql = String.Format( "select count(*) from {0}", entityInfo.TableName );
            }
            else {
                countSql = builder.GetCountSql( condition );
            }
            logger.Info( LoggerUtil.SqlPrefix + "[Count(String condition) Sql]:" + countSql );
            IDbCommand command = DataFactory.GetCommand( countSql, DbContext.getConnection( entityInfo ) );
            try {
                result = cvt.ToInt( command.ExecuteScalar() );
            }
            catch (Exception exception) {
                logger.Error( exception.Message );
                throw new OrmException( exception.Message, exception );
            }

            return result;
        }
Exemplo n.º 15
0
        public static IList FindPage( ObjectInfo state, String queryString )
        {
            // see: System/Web/Mvc/Routes/RouteTool.cs, line 211

            if (state.Pager.getCurrent() <= 0) {
                int page = CurrentRequest.getCurrentPage();
                state.Pager.setCurrent( page );
            }

            if ( queryString != null && queryString.ToLower().StartsWith( "order " )) {
                queryString = " " + queryString;
            }

            PageCondition pc = new PageCondition();
            pc.ConditionStr = queryString;
            pc.Property = state.Includer.SelectedProperty;
            pc.CurrentPage = state.Pager.getCurrent();
            pc.Size = state.Pager.getSize();
            pc.OrderStr = state.Order;
            pc.Pager = state.Pager;

            String sql = new SqlBuilder( state.EntityInfo ).GetPageSql( pc );
            return EntityPropertyUtil.FindList( state, sql );
        }
Exemplo n.º 16
0
		public void TestCRUD()
		{
			l1 = new MailingList( "Test 1", "*****@*****.**" );
			// insert
			l1.Persist();
			Assert.IsTrue( l1.Id > 0, "The List object was not assigned an id by the database!" );
			Assert.AreEqual( l1.Name, "Test 1", "The List object was not properly inserted!" );
			Assert.AreEqual( l1.SenderAddress, "*****@*****.**", "The List object was not properly inserted!" );
			// select
			l2 = MailingList.Retrieve( l1.Id );
			// verify select/insert
			Assert.IsTrue( l2.Id != 0, "The List object could not be retrieved from the database!" );
			Assert.AreEqual( l1.Id, l2.Id, "The List object could not be retrieved from the database!" );
			Assert.AreEqual( "Test 1", l2.Name, "The List object was not properly retrieved on construction!" );
			Assert.AreEqual( "*****@*****.**", l2.SenderAddress,
			                 "The List object was not properly retrieved on construction!" );
			// update
			l2.Name = "Test 2";
			l2.SenderAddress = "*****@*****.**";
			l2.Persist();
			// verify update
			l1 = MailingList.Retrieve( l2.Id );
			Assert.AreEqual( l2.Name, l1.Name, "Name not updated!" );
			Assert.AreEqual( l2.SenderAddress, l1.SenderAddress, "SenderAddress not updated!" );
			// delete
			l2.Remove();
			// verify delete by counting the number of rows
			SqlBuilder sb = new SqlBuilder( StatementType.Count, typeof(MailingList) );
			sb.AddConstraint( Operator.Equals, "Id", l1.Id );
			SqlResult sr = Broker.Execute( sb.GetStatement( true ) );
			Assert.AreEqual( 0, sr.Count, "Object not removed" );
		}
Exemplo n.º 17
0
		public virtual void TestNullNotEquals()
		{
			SqlBuilder sb = new SqlBuilder( StatementType.Select, typeof(Member) );
			sb.AddConstraint( Operator.NotEquals, "MemberName", null );
			SqlStatement stmt = sb.GetStatement( true );
		}
Exemplo n.º 18
0
		public virtual void TestSqlOverride()
		{
			if( ! Broker.ProviderName.Equals( "PostgreSQL" ) )
			{
				SqlBuilder sql = new SqlBuilder( StatementType.Select, typeof(MailingList) );
				SqlStatement statement = sql.GetStatement( true );
				ObjectMap map = ObjectFactory.GetMap( null, typeof(MailingList) );
				statement.Command.CommandText = String.Format( "select * from {0}", map.TableName );
				SqlResult result = statement.Execute();
				IList list = ObjectFactory.GetCollection( typeof(MailingList), result );
				Assert.AreEqual( 3, list.Count );
			}
		}
Exemplo n.º 19
0
		public void TestMultiBroker()
		{
			if( GentleSettings.DefaultProviderConnectionString.IndexOf( "127.0.0.1" ) != -1 )
			{
				// use modified connection string
				string connStr = GentleSettings.DefaultProviderConnectionString.Replace( "127.0.0.1", "(local)" );
				PersistenceBroker pb = new PersistenceBroker( GentleSettings.DefaultProviderName, connStr );
				// fetch list
				IList pbList = pb.RetrieveList( typeof(MailingList) );
				Assert.AreEqual( Broker.RetrieveList( typeof(MailingList) ).Count, pbList.Count, "Not same result." );
				// check that connstr remains same when using SqlBuilder with custom broker
				SqlBuilder sb = new SqlBuilder( pb, StatementType.Select, typeof(MailingList) );
				SqlStatement stmt = sb.GetStatement( true );
				SqlResult sr = stmt.Execute();
				Assert.AreEqual( sr.SessionBroker.Provider.ConnectionString, connStr, "ConnStr not preserved." );
			}
		}
Exemplo n.º 20
0
		public void TestComplexSql()
		{
			if( Broker.SessionBroker.ProviderName == "SQLServer" )
			{
				string sql = "select * from list, listmember where list.listid = listmember.listid order by list.listid, memberid";
				SqlBuilder sb = new SqlBuilder();
				SqlStatement stmt = sb.GetStatement( sql, StatementType.Select, typeof(MailingList) );
				SqlResult sr = Broker.Execute( stmt );
				Assert.IsNotNull( sr );
				Assert.IsNotNull( sr.Rows );
				Assert.AreEqual( 4, sr.Rows.Count, "Complex Sql Error " );
			}
		}
Exemplo n.º 21
0
		public void TestSimpleSql()
		{
			GentleSqlFactory sf = Broker.GetSqlFactory();
			string sql = String.Format( "select count(*) as RecordCount from {0}{1}",
			                            sf.GetTableName( "List" ), sf.GetStatementTerminator() );
			SqlBuilder sb = new SqlBuilder();
			SqlStatement stmt = sb.GetStatement( sql, StatementType.Select, typeof(MailingList) );
			Assert.IsNotNull( stmt, "stmt is null" );
			SqlResult sr = Broker.Execute( stmt );
			Assert.IsNotNull( sr );
			Assert.AreEqual( 0, sr.ErrorCode );
			Assert.IsNotNull( sr.Rows.Count );
			Assert.AreEqual( 1, sr.Rows.Count );
			object[] row = (object[]) sr.Rows[ 0 ];
			int expected = Convert.ToInt32( row[ 0 ] );
			// verify StatementType.Count retrieval
			sr = Broker.Execute( sb.GetStatement( StatementType.Count, typeof(MailingList) ) );
			Assert.AreEqual( expected, sr.Count );
		}
Exemplo n.º 22
0
		public void TestSqlResultViewGeneration()
		{
			SqlBuilder sb = new SqlBuilder( StatementType.Select, typeof(MailingList) );
			SqlResult sr = sb.GetStatement().Execute();
			DataView dv = ObjectView.GetDataView( sr );
			// TODO add stuff to validate the contents of the view
		}
Exemplo n.º 23
0
		public void TestCustomListUsingInConstraint()
		{
			// subselects not supported by the inferior mysql engine - skip test. 
			if( ! Broker.ProviderName.Equals( "MySQL" ) )
			{
				GentleSqlFactory sf = Broker.GetSqlFactory();
				// first, select the number of expected entries
				SqlBuilder sb = new SqlBuilder( StatementType.Count, typeof(MailingList) );
				string sql = String.Format( "select distinct MemberAddress from {0}",
				                            sf.GetTableName( "ListMember" ) );
				sb.AddConstraint( Operator.In, "SenderAddress", Broker.Execute( sql ), "MemberAddress" );
				SqlResult sr = Broker.Execute( sb.GetStatement() );
				int expected = sr.Count;
				// verify list retrieval (using IList data)
				IList lists = MailingList.ListByCustomListConstraint();
				Assert.IsNotNull( lists );
				Assert.AreEqual( expected, lists.Count );
				// verify same result using alternative approach (using SqlResult data)
				sb = new SqlBuilder( StatementType.Select, typeof(Member) );
				SqlResult members = sb.GetStatement( true ).Execute();
				sb = new SqlBuilder( StatementType.Select, typeof(MailingList) );
				// use column name as indexer into SqlResult for list constraints
				sb.AddConstraint( Operator.In, "SenderAddress", members, "MemberAddress" );
				SqlStatement stmt = sb.GetStatement( true );
				lists = ObjectFactory.GetCollection( typeof(MailingList), stmt.Execute() );
				Assert.IsNotNull( lists );
				Assert.AreEqual( expected, lists.Count );
			}
		}
Exemplo n.º 24
0
		public void TestCustomListUsingLikeConstraint()
		{
			GentleSqlFactory sf = Broker.GetSqlFactory();
			// first, select the number of expected entries
			SqlBuilder sb = new SqlBuilder( StatementType.Count, typeof(MailingList) );
			sb.AddConstraint( Operator.Like, "SenderAddress", "%.com" );
			SqlResult sr = Broker.Execute( sb.GetStatement( true ) );
			int expected = sr.Count;
			// verify list retrieval 
			IList lists = MailingList.ListByDomain( ".com" );
			Assert.IsNotNull( lists );
			Assert.AreEqual( expected, lists.Count );
		}
Exemplo n.º 25
0
 internal SqlMetadataDatabase(SqlBuilder Builder, bool UseCache = true, string FileName = null)
 {
     Initialize(Builder.ConnectionString ?? SqlBuilder.DefaultConnection, UseCache, FileName);
     this.builder = Builder;
 }
Exemplo n.º 26
0
        public static int DeleteBatch( String condition, EntityInfo entityInfo )
        {
            if (strUtil.IsNullOrEmpty( condition )) {
                return 0;
            }

            String deleteSql = new SqlBuilder( entityInfo ).GetDeleteSql( condition );
            logger.Info(LoggerUtil.SqlPrefix+ "delete sql : " + deleteSql );

            List<IInterceptor> ilist = MappingClass.Instance.InterceptorList;
            for (int i = 0; i < ilist.Count; i++) {
                ilist[i].BeforDeleteBatch( entityInfo.Type, condition );
            }

            IDbCommand cmd = DataFactory.GetCommand( deleteSql, DbContext.getConnection( entityInfo ) );
            int rowAffected = cmd.ExecuteNonQuery();
            logger.Info( "delete : " + rowAffected + " records affected" );
            cmd.Connection.Close();

            for (int i = 0; i < ilist.Count; i++) {
                ilist[i].AfterDeleteBatch( entityInfo.Type, condition );
            }

            // update cache  timestamp
            CacheTime.updateTable( entityInfo.Type );

            return rowAffected;
        }
Exemplo n.º 27
0
 private static ServerConnection GetConnection(SqlBuilder Builder)
 {
     return GetConnection(Builder.ConnectionString ?? SqlBuilder.DefaultConnection);
 }
Exemplo n.º 28
0
		public void TestOrderByRetrieval()
		{
			GentleSqlFactory sf = Broker.GetSqlFactory();
			// first verify that data set is ok for test
			SqlBuilder sb = new SqlBuilder( StatementType.Select, typeof(MailingList) );
			// get ascending
			sb.AddOrderByField( true, "SenderAddress" );
			SqlResult sr = Broker.Execute( sb.GetStatement( true ) );
			Assert.IsTrue( sr.ErrorCode == 0 && sr.RowsContained == MailingList.ListAll.Count,
			               "Wrong number of rows were selected." );
			IList lists = ObjectFactory.GetCollection( typeof(MailingList), sr );
			Assert.IsNotNull( lists, "Test case invalid if row count is not 3." );
			Assert.IsTrue( lists.Count == 3, "Test case invalid if row count is not 3." );
			l1 = lists[ 0 ] as MailingList;
			l2 = lists[ 2 ] as MailingList;
			Assert.IsTrue( l1.SenderAddress.StartsWith( "ann" ), "Test case invalid if row order is wrong." );
			Assert.IsTrue( l2.SenderAddress.StartsWith( "inf" ), "Test case invalid if row order is wrong." );
			// now fetch the reverse ordered list
			sb = new SqlBuilder( StatementType.Select, typeof(MailingList) );
			sb.AddOrderByField( false, "SenderAddress" );
			sr = Broker.Execute( sb.GetStatement( true ) );
			Assert.IsTrue( sr.ErrorCode == 0 && sr.RowsContained == MailingList.ListAll.Count,
			               "Wrong number of rows were selected." );
			IList lists2 = ObjectFactory.GetCollection( typeof(MailingList), sr );
			l1 = lists2[ 0 ] as MailingList;
			l2 = lists2[ 2 ] as MailingList;
			Assert.IsTrue( l1.SenderAddress.StartsWith( "inf" ), "Result set was in wrong order." );
			Assert.IsTrue( l2.SenderAddress.StartsWith( "ann" ), "Result set was in wrong order." );
		}
Exemplo n.º 29
0
 public static SqlMetadataDatabase FromBuilder(SqlBuilder Builder, bool UseCache = true, string FileName = null)
 {
     return new SqlMetadataDatabase(Builder, UseCache, FileName);
 }
Exemplo n.º 30
0
		public void TestOtherTypeListRetrieval()
		{
			GentleSqlFactory sf = Broker.GetSqlFactory();
			// select all lists
			IList lists = MailingList.ListAll;
			foreach( MailingList list in lists )
			{
				// get the expected member count
				SqlBuilder sb = new SqlBuilder( StatementType.Count, typeof(Member) );
				sb.AddConstraint( Operator.Equals, "ListId", list.Id );
				SqlResult sr = Broker.Execute( sb.GetStatement( true ) );
				int expected = sr.Count;
				// verify list retrieval (entire table)
				IList members = list.Members;
				Assert.IsNotNull( members );
				Assert.AreEqual( expected, members.Count );
			}
		}