/// <summary> /// 使对象实体化,根据IsPersistent决定是更新还是插入操作 /// 如果IsPersistent为True,则自动会进行Update操作,在使用Retrieve()后会自动赋上此值,如: /// entity.Retrieve(); /// if(entity.IsPersistent) /// {会进行更新操作} /// 虽然IsPersistent是public的,但一般的情况下,不建议进行赋值。 /// </summary> public int Save() { PersistenceBroker broker = PersistenceBroker.Instance(); this._IsSaveInMemory = broker.GetClassMap(thisType.Name).IsSaveToMemory; return(broker.SaveObject(this)); }
/// <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."); } } }
/// <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." ); } } }
/// <summary> /// 根据对象的主键获取唯一对象 /// 注意,这个方法必须与只能通过主键来获取,因为只有主键在逻辑能确定唯一 /// 支持双主键,如果是双主键,则两个主键属性必须都要赋上 /// 如果不能通过主键唯一确定的,则可以通过RetrieveCriteria对象来获取。 /// </summary> /// <returns></returns> public bool Retrieve() { PersistenceBroker broker = PersistenceBroker.Instance(); this._IsSaveInMemory = broker.GetClassMap(thisType.Name).IsSaveToMemory; return(broker.RetrieveObject(this, true, false)); }
/// <summary> /// 执行存储过程,返回DataTable /// </summary> /// <param name="storeProcName">存储过程名</param> /// <param name="ps">存储过程所需参数数组</param> /// <param name="dbName">数据库名</param> /// <returns>存储过程返回的DataTable</returns> public static DataTable RunProcedure(string storeProcName, IDataParameter[] ps, string dbName) { IDbCommand cmd = Query.BuildQueryCommand(storeProcName, ps, dbName); PersistenceBroker broker = PersistenceBroker.Instance(); return(broker.ExecuteQuery(cmd, dbName)); }
/// <summary> /// 生成一个Query实例 /// </summary> /// <param name="className">EntityObject的类名</param> public Query(string className) { ClassMap cm = PersistenceBroker.Instance().GetClassMap(className); this.queryClass = cm; sTemp = " AS " + cm.RelationalDatabase.QuotationMarksStart; endQuostationMarks = cm.RelationalDatabase.QuotationMarksEnd; }
public void TestMultipleProviders() { PersistenceBroker pb1 = new PersistenceBroker( "SQLServer", "first" ); Assert.AreEqual( "first", pb1.Provider.ConnectionString ); PersistenceBroker pb2 = new PersistenceBroker( "SQLServer", "second" ); Assert.AreEqual( "second", pb2.Provider.ConnectionString ); Assert.AreEqual( "first", pb1.Provider.ConnectionString ); }
//public static DataTable PageQuery(string needfields, string fromcondition,string keyfields ,string keyfieldsdeclare, int pagesize, int pages, out int counts, string db) //{ // string sqlCreate = "declare @indextable table(indextableid int identity(1,1) PRIMARY KEY," + keyfieldsdeclare + ") ;"; // string KeySql = "select "+keyfields+" from "+fromcondition+" "; // string sqlKeyinsert = "insert into @indextable(" + keyfields + ") " + KeySql + ";"; // string sqlCt = "select recrowcount= @@rowcount;"; // string[] needf = needfields.Split(new char[] { ',' }); // for (int i = 0; i < needf.Length; i++) // { // needf[i] = "t1."+needf[i].ToString(); // } // string sqlSearch = "select "+string.Join(",",needf)+" from @indextable t0,(" + orgSql + ") t1 where t0.indextableid>=" + ((page - 1) * pageSize + 1).ToString() + " and t0.indextableid<" + (page * pageSize + 1).ToString() + tempKey3; //} /// <summary> /// 执行Sql语句返回影响条数 /// </summary> /// <param name="sql">SQL语句</param> /// <param name="dbName">操作的数据库名</param> /// <returns>SQL语句影响条数</returns> public static int ProcessSqlNonQuery(string sql, string dbName) { PersistenceBroker broker = PersistenceBroker.Instance(); IDbCommand cmd = broker.GetCommand(dbName); cmd.CommandText = sql; Logger.Write(sql); //add by duhu return(broker.Execute(dbName, cmd)); }
/// <summary> /// 执行Sql语句返回DataTable /// </summary> /// <param name="sql">SQL语句</param> /// <param name="dbName">操作的数据库名</param> /// <returns>SQL语句查询结果集</returns> public static DataSet ProcessMultiSql(string sql, string dbName) { PersistenceBroker broker = PersistenceBroker.Instance(); IDbCommand cmd = broker.GetCommand(dbName); cmd.CommandTimeout = 120; cmd.CommandText = sql; Logger.Write(sql); //add by duhu return(broker.ExecuteMultiQuery(cmd, dbName)); }
/// <summary> /// 生成一个Query实例 /// </summary> /// <param name="classType">EntityObject对象的Type实例</param> /// <param name="DatabaseName">多帐套数据库的数据库名</param> public Query(Type classType, string DatabaseName) { string className = EntityObject.GetClassName(classType); ClassMap cm = PersistenceBroker.Instance().GetClassMap(className); this.queryClass = cm; sTemp = " AS " + cm.RelationalDatabase.QuotationMarksStart; endQuostationMarks = cm.RelationalDatabase.QuotationMarksEnd; this.DatabaseName = DatabaseName; }
public void TestMultipleProviders() { PersistenceBroker pb1 = new PersistenceBroker("SQLServer", "first"); Assert.AreEqual("first", pb1.Provider.ConnectionString); PersistenceBroker pb2 = new PersistenceBroker("SQLServer", "second"); Assert.AreEqual("second", pb2.Provider.ConnectionString); Assert.AreEqual("first", pb1.Provider.ConnectionString); }
/// <summary> /// Construct a TableMap instance to hold information on the given table. /// </summary> /// <param name="broker">The PersistenceBroker instance used to obtain metadata on the table. /// If null is passed the DefaultProvider settings will be used.</param> /// <param name="tableName">The name of the table for which to hold information.</param> public TableMap( PersistenceBroker broker, string tableName ) : base( broker ) { provider = SessionBroker.Provider; // use property accessor to also set quoted name if( tableName != null ) { TableName = tableName; } fields = new FieldList(); }
/// <summary> /// 环境初始化 /// </summary> public void Initialize() { if (this.m_DatabaseMapFile == "*") { throw new PlException("请先设置xml文件的位置!", ErrorTypes.PesistentError); } else { PersistenceBroker.Instance(); } }
/// <summary> /// Construct an ObjectMap instance for the given type. /// </summary> /// <param name="broker">The PersistenceBroker instance to which this map is related.</param> /// <param name="type">The type for which this instance is a map</param> public ObjectMap( PersistenceBroker broker, Type type ) : base( broker ) { this.type = type; if( type != null ) { SetTableName( type ); } //this.dbMaps = new Hashtable(); views = new Hashtable(); validations = new ArrayList(); objectConstructor = new ObjectConstructor( this ); }
/// <summary> /// This is the generic base constructor will a full argument set. /// </summary> /// <param name="version">The version of this record in the database or 0 for new instances.</param> /// <param name="isPersisted">A boolean to indicate whether this object has been persisted.</param> /// <param name="broker">The PersistenceBroker to use for connecting to the database.</param> public ContextPersistent( int version, bool isPersisted, PersistenceBroker broker ) { databaseVersion = version; this.isPersisted = isPersisted; if( broker == null ) { this.broker = new PersistenceBroker( GetType() ); } else // use supplied broker and associated provider { this.broker = broker; } }
/// <summary> /// Constructor for error conditions. /// </summary> /// <param name="broker">The PersistenceBroker instance to use for database access.</param> /// <param name="error">The exception raised by the .NET framework</param> public SqlResult( PersistenceBroker broker, Exception error ) : base( broker ) { this.error = error; // SQL Server specific: if( error.GetType().Equals( typeof(SqlException) ) ) { errorCode = ((SqlException) error).Number; } else { errorCode = 42; // it's magic } }
/// <summary> /// 获取前N条记录(未实现Oracle功能) /// add by tintown at 2004-09-06 /// </summary> /// <param name="cmd"></param> /// <param name="top"></param> /// <returns></returns> public override DataTable AsDataTable(IDbCommand cmd, int top) { cmd.Connection = this.connection; cmd.Transaction = this.transaction; string cmdText = cmd.CommandText; //使用ORCALE添加rownum的方法重装SQL语句 cmd.CommandText = PersistenceBroker.AddOracleTopWhere(cmdText, top);; OleDbDataAdapter adapter = new OleDbDataAdapter((OleDbCommand)cmd); DataTable dt = new DataTable(); adapter.Fill(dt); return(dt); }
public virtual void Init(string providerName) { ObjectFactory.ClearMaps(); Broker.ClearPersistenceBroker(); ObjectFactory.ClearMaps(); IGentleProvider provider = ProviderFactory.GetProvider(providerName, ""); Assert.AreEqual(provider.Name, providerName, "Wrong provider returned from factory!"); sf = provider.GetSqlFactory(); broker = new PersistenceBroker(provider); sb = new SqlBuilder(provider); // make sure analyzer errors are ignored for this test origLevel = GentleSettings.AnalyzerLevel; GentleSettings.AnalyzerLevel = AnalyzerLevel.None; }
public void TestManualProviderCreation() { string name = Configurator.GetKey(null, "Gentle.Framework/DefaultProvider/@name"); string connStr = Configurator.GetKey(null, "Gentle.Framework/DefaultProvider/@connectionString"); string schema = Configurator.GetKey(null, "Gentle.Framework/DefaultProvider/@schema"); //connStr = @"Server=(local)\SQLExpress;Database=Gentle;Integrated Security=true"; PersistenceBroker broker = ProviderFactory.GetProvider("test", name, connStr, schema).Broker; IList list = broker.RetrieveList(typeof(MailingList)); Assert.IsNotNull(list, "No result returned."); Assert.IsTrue(list.Count > 0, "List was empty."); MailingList ml = list[0] as MailingList; ml.Persist(); }
protected BrokerLock( PersistenceBroker broker, Type type ) { if( broker == null ) { if( type == null ) { type = GetType(); } this.broker = new PersistenceBroker( type ); } else // use supplied broker and associated provider { this.broker = broker; } }
public void TestAnalyzerDataOverride() { PersistenceBroker broker = new PersistenceBroker(); // Dont run test if the current provider does not have an Analyzer GentleAnalyzer analyzer = broker.Provider.GetAnalyzer(); if( analyzer != null && GentleSettings.AnalyzerLevel != AnalyzerLevel.None ) { ObjectMap map = ObjectFactory.GetMap( broker, typeof(PropertyHolder) ); // test that analyzer data overrides any TableColumn attributes FieldMap fm = map.GetFieldMap( "TDouble" ); if( analyzer.HasCapability( ColumnInformation.IsNullable ) ) { Assert.IsTrue( fm.IsNullable ); } } }
public void TestAnalyzerDataOverride() { PersistenceBroker broker = new PersistenceBroker(); // Dont run test if the current provider does not have an Analyzer GentleAnalyzer analyzer = broker.Provider.GetAnalyzer(); if (analyzer != null && GentleSettings.AnalyzerLevel != AnalyzerLevel.None) { ObjectMap map = ObjectFactory.GetMap(broker, typeof(PropertyHolder)); // test that analyzer data overrides any TableColumn attributes FieldMap fm = map.GetFieldMap("TDouble"); if (analyzer.HasCapability(ColumnInformation.IsNullable)) { Assert.IsTrue(fm.IsNullable); } } }
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."); } }
/// <summary> /// add by tintown 2008-7-3使用Parameter的方式进行传参执行SQL ///如:string sql = "select top 100 * from Line_TCPF_Line where memberid=@id"; ///IDataParameter para = PersistenceLayer.Query.GetParameter("hotel"); ///para.ParameterName = "@id"; /// para.Value = 6632; /// IDataParameter[] paras = new IDataParameter[1]; ///paras[0] = para; /// DataTable dt = PersistenceLayer.Query.ProcessSql(sql, paras, "hotel"); /// </summary> /// <param name="sql">自己写的SQL语句</param> /// <param name="param">参数数组</param> /// <param name="dbName">数据源名</param> /// <returns>查询结果集</returns> public static DataTable ProcessSql(string sql, IDataParameter[] param, string dbName) { PersistenceBroker broker = PersistenceBroker.Instance(); IDbCommand cmd = broker.GetCommand(dbName); cmd.CommandTimeout = 120; cmd.CommandText = sql; if (param != null) { for (int i = 0; i < param.Length; i++) { IDataParameter p = param[i]; cmd.Parameters.Add(p); } } Logger.Write(sql); // add by duhu return(broker.ExecuteQuery(cmd, dbName)); }
//创建新的Sql命令对象:需要的参数加入IDbCommand.Parameters集合 private static IDbCommand BuildQueryCommand(string storedProcName, IDataParameter[] param, string dbName) { PersistenceBroker broker = PersistenceBroker.Instance(); IDbCommand cmd = broker.GetCommand(dbName); cmd.CommandText = storedProcName; cmd.CommandType = CommandType.StoredProcedure; if (param != null) { for (int i = 0; i < param.Length; i++) { IDataParameter p = param[i]; cmd.Parameters.Add(p); } } return(cmd); }
/// <summary> /// 执行查询,并返回查询所返回结果集的第一行第一列。忽略额外的行或列 /// </summary> /// <returns></returns> public object ExecuteScalar() { PersistenceBroker broker = PersistenceBroker.Instance(); RelationalDatabase rdb = broker.GetDatabaseCopy(this.DatabaseName); IDbCommand cmd = rdb.GetCommand(); cmd.CommandText = this.BuildForQuery(cmd); DataTable dt = broker.ExecuteQuery(cmd, this.DatabaseName); if (dt.Rows.Count == 0) { return(null); } else { return(dt.Rows[0][0]); } }
/// <summary> /// Create a new list for storing the specified type of objects. /// </summary> public GentleRelation( PersistenceBroker broker, Type containedType, IPersistent parent, params Type[] relatedTypes ) : base( broker ) { Check.VerifyNotNull( relatedTypes, Error.NullParameter, "relatedTypes" ); /*Check.Verify( parent == null && relatedTypes.Length == 2 || parent != null && relatedTypes.Length == 1, Error.NotImplemented, "The GentleRelation class is currently only able to manage two-way relations." ); */ this.relatedTypes = relatedTypes; this.parent = parent; containedMap = ObjectFactory.GetMap( broker, containedType ); // note: "this." required on broker param or original null param might get passed relations = new GentleList( this.broker, containedType, parent ); // verify that the linked types are supported by Gentle foreach( Type relatedType in relatedTypes ) { Check.Verify( relatedType.IsSubclassOf( typeof(Persistent) ) || relatedType.GetInterface( "IPersistent" ) != null, Error.UnsupportedType, relatedType ); } }
/// <summary> /// 执行存储过程 /// </summary> /// <param name="storeProcName">存储过程名</param> /// <param name="param">存储过程所需参数数组</param> /// <param name="affected">存储过程影响的行数</param> /// <param name="dbName">数据库名</param> /// <returns>存储过程的返回代码</returns> public static int RunProcedure(string storeProcName, IDataParameter[] param, out int affected, string dbName) { int result; PersistenceBroker broker; broker = PersistenceBroker.Instance(); IDbCommand cmd = Query.BuildQueryCommand(storeProcName, param, dbName); //增加返回值参数 IDataParameter p = cmd.CreateParameter(); p.Direction = ParameterDirection.ReturnValue; p.ParameterName = "ReturnValue"; p.DbType = DbType.Int32; cmd.Parameters.Insert(0, p); affected = broker.Execute(dbName, cmd); p = (IDataParameter)cmd.Parameters["ReturnValue"]; result = (int)p.Value; return(result); }
/// <summary> /// 执行查询,并返回查询结果集 /// </summary> /// <returns>查询结果</returns> public DataTable Execute() { PersistenceBroker broker = PersistenceBroker.Instance(); RelationalDatabase rdb = broker.GetDatabaseCopy(this.DatabaseName); IDbCommand cmd = rdb.GetCommand(); cmd.CommandText = this.BuildForQuery(cmd); string cmdText = cmd.CommandText; if (rdb.Vendor == DatabaseVendor.Oracle) { int topInd = cmdText.IndexOf("Top"); if (topInd != -1) { cmdText = cmdText.Substring(0, topInd) + cmdText.Substring(topInd + 6); //使用ORCALE添加rownum的方法重装SQL语句 cmdText = PersistenceBroker.AddOracleTopWhere(cmdText, this.Top); } } cmd.CommandText = cmdText; return(broker.ExecuteQuery(cmd, this.DatabaseName)); }
/// <summary> /// 事务处理 /// </summary> /// <returns>如果事务成功返回true,失败返回false</returns> public bool Process() { bool result = true; try { PersistenceBroker broker = PersistenceBroker.Instance(); //if (broker.MultiDatabase ) //{ result = broker.ProcessTransactionMultiDatabases(this); //} //else //{ // broker.ProcessTransactionSingleDatabase (this); //} } catch (Exception e) { result = false; throw e; } return(result); }
/// <summary> /// Constructor for ExecuteScalar results. /// </summary> /// <param name="broker">The PersistenceBroker instance to use for database access.</param> /// <param name="retval">The object returned by the .NET database provider.</param> /// <param name="stmt">The SqlStatement leading to this SqlResult</param> public SqlResult( PersistenceBroker broker, object retval, SqlStatement stmt ) : base( broker ) { this.stmt = stmt; if( retval != null ) { try { // some rdbms' return 64-bit row identities long lastId = Convert.ToInt64( retval ); returnValue = Convert.ToInt32( lastId ); if( stmt.StatementType != StatementType.Count ) { rowsAffected = 1; } } catch( Exception e ) { throw new GentleException( Common.Error.NoIdentityReturned, stmt.Sql, e ); } } }
/// <summary> /// 返回一个IDataParameter,是SqlParameter,还是OleDbParameter /// 由databaseName对应数据库的数据库类型确定 /// </summary> /// <param name="databaseName">数据库名</param> /// <returns></returns> public static IDataParameter GetParameter(string databaseName) { PersistenceBroker broker = PersistenceBroker.Instance(); return(broker.GetCommand(databaseName).CreateParameter()); }
public virtual void Init( string providerName ) { ObjectFactory.ClearMaps(); Broker.ClearPersistenceBroker(); ObjectFactory.ClearMaps(); IGentleProvider provider = ProviderFactory.GetProvider( providerName, "" ); Assert.AreEqual( provider.Name, providerName, "Wrong provider returned from factory!" ); sf = provider.GetSqlFactory(); broker = new PersistenceBroker( provider ); sb = new SqlBuilder( provider ); // make sure analyzer errors are ignored for this test origLevel = GentleSettings.AnalyzerLevel; GentleSettings.AnalyzerLevel = AnalyzerLevel.None; }
/// <summary> /// Use this This is the recommended constructor /// The supplied PersistenceBroker instance will be used to access the database. /// </summary> /// <param name="isPersisted">A boolean to indicate whether this object has been persisted.</param> /// <param name="broker">The PersistenceBroker to use for connecting to the database.</param> protected Persistent( bool isPersisted, PersistenceBroker broker ) : base( broker ) { this.isPersisted = isPersisted; }
/// <summary> /// Retrieve the object of the specified type and identified by the given key. This method will /// throw an exception if not exactly one row in the database matches. /// </summary> /// <param name="broker">The PersistenceBroker and associated provider used fetch the data</param> /// <param name="type">The type of the Persistent descendant</param> /// <param name="key">The key identifying the object</param> /// <returns>An object instance of the specified type</returns> public static object Retrieve( PersistenceBroker broker, Type type, Key key ) { if( broker == null ) { // use default broker instance by use of the Broker class return Broker.RetrieveInstance( type, key ); } else // use supplied broker instance { return broker.RetrieveInstance( type, key ); } }
/// <summary> /// Construct a new SqlStatement instance of the specified type. The command object to be used /// for executing the query and the fully specified sql query string must be specified. /// </summary> /// <param name="broker">The PersistenceBroker instance to use for database access.</param> /// <param name="stmtType">The type of this statement.</param> /// <param name="cmd">The command object to use when executing the query.</param> /// <param name="sql">The fully specified sql query string.</param> /// <param name="type">The type of object being selected by this query or null if /// not applicable.</param> /// <param name="rowLimit">The maximum number of rows to be returned by this query /// or 0 for no limit.</param> /// <param name="rowOffset">The number of rows to be skipped by this statement. Note that /// for SQL Server this is applied after execution, whereas for other databases it is /// embedded in the SQL string.</param> public SqlStatement( PersistenceBroker broker, StatementType stmtType, IDbCommand cmd, string sql, Type type, int rowLimit, int rowOffset ) : base( broker, type ) { this.cmd = cmd; cmd.CommandText = sql; statementType = stmtType == StatementType.Unknown ? GetStatementType( sql ) : stmtType; map = type != null ? ObjectFactory.GetMap( broker, type ) : null; this.rowLimit = rowLimit; this.rowOffset = rowOffset; }
/// <summary> /// 获取数据源的数据库提供者 /// </summary> /// <param name="dbName">数据源名称</param> /// <returns></returns> public DatabaseVendor GetDatabaseVendor(string dbName) { return(PersistenceBroker.Instance().GetDatabase(dbName).Vendor); }
public IEntity Construct( object[] row, PersistenceBroker broker ) { object result; // if row content and element order matches constructor exactly if( isPerfectMatch ) { result = constructorInfo.Invoke( Reflector.InstanceCriteria, null, row, null ); } else { object[] constructorParams = GetParams( row ); result = constructorInfo.Invoke( Reflector.InstanceCriteria, null, constructorParams, null ); if( AnySet( columnReflectionMask ) ) { UpdateMembers( result, row ); } } if( broker != null && result is BrokerLock ) { (result as BrokerLock).SessionBroker = broker; } return result as IEntity; }
/// <summary> /// Construct a new SqlStatement instance of the specified type. The command object to be used /// for executing the query and the fully specified sql query string must be specified. /// </summary> /// <param name="broker">The PersistenceBroker instance to use for database access.</param> /// <param name="stmtType">The type of this statement.</param> /// <param name="cmd">The command object to use when executing the query.</param> /// <param name="sql">The fully specified sql query string.</param> /// <param name="rowLimit">The maximum number of rows to be returned by this query /// or 0 for no limit.</param> /// <param name="rowOffset">The number of rows to be skipped by this statement. Note that /// for SQL Server this is applied after execution, whereas for other databases it is /// embedded in the SQL string.</param> public SqlStatement( PersistenceBroker broker, StatementType stmtType, IDbCommand cmd, string sql, int rowLimit, int rowOffset ) : this( broker, stmtType, cmd, sql, null, rowLimit, rowOffset ) { }
/// <summary> /// Obtain a new key for the specified object instance. The returned key will contain the /// primary keys of the given instance. /// </summary> /// <param name="broker">The optional PersistenceBroker instance to use for obtaining the /// ObjectMap for the supplied object instance. If this parameter is null, Gentle will try /// to infer the broker from the object instance. If that fails, it will use the default /// provider.</param> /// <param name="key">An optional existing key to add the values to</param> /// <param name="isPropertyKeys">False is key indexers are column names, true for property names</param> /// <param name="instance">The object instance whose property values will be used</param> /// <returns>A key instance containing the primary key values of the given object instance</returns> public static Key GetKey( PersistenceBroker broker, Key key, bool isPropertyKeys, object instance ) { // try to infer broker from instance if( broker == null && instance is IBrokerLock ) { broker = (instance as IBrokerLock).SessionBroker; } // WARNING/TODO if broker is null here and no ObjectMap yet exists for the type, // the DefaultProvider will be used to create the ObjectMap ObjectMap map = ObjectFactory.GetMap( broker, instance ); return GetKey( broker, key, isPropertyKeys, instance, map.GetPrimaryKeyNames( isPropertyKeys ) ); }
/// <summary> /// Obtain a new key for the specified object instance. The returned key will contain the /// primary keys of the given instance. /// </summary> /// <param name="broker">The optional PersistenceBroker instance to use for obtaining the /// ObjectMap for the supplied object instance. If this parameter is null, Gentle will try /// to infer the broker from the object instance. If that fails, it will use the default /// provider.</param> /// <param name="isPropertyKeys">False is key indexers are column names, true for property names</param> /// <param name="instance">The object instance whose property values will be used</param> /// <returns>A key instance containing the primary key values of the given object instance</returns> public static Key GetKey( PersistenceBroker broker, bool isPropertyKeys, object instance ) { return GetKey( broker, null, isPropertyKeys, instance ); }
public void Init() { broker = new PersistenceBroker(); Check.VerifyNotNull(broker.Provider, Error.DeveloperError, "No default provider information specified in the configuration file."); }
/// <summary> /// 追加数据源,此方法提供代码追加数据源的可能性 /// 在多帐套的情况下,一般是需要动态追加数据源的 /// 如果数据源名称重复,则会自动覆盖原连接,如果数据源名称不同,则会自动追加进去。 /// /// </summary> /// <param name="name">数据源名</param> /// <param name="databaseType">类型</param> /// <param name="connectionString">连接字符串</param> public void AppendDatabase(string name, DatabaseType databaseType, string connectionString) { string thisNameSpace = this.ToString().Substring(0, this.ToString().LastIndexOf('.') + 1); PersistenceBroker.Instance().AppendDatabase(name, thisNameSpace + databaseType.ToString(), connectionString); }
/// <summary> /// Construct a new SqlStatement instance of the specified type. The command object to be used /// for executing the query and the fully specified sql query string must be specified. /// </summary> /// <param name="broker">The PersistenceBroker instance to use for database access.</param> /// <param name="stmtType">The type of this statement.</param> /// <param name="cmd">The command object to use when executing the query.</param> /// <param name="sql">The fully specified sql query string.</param> public SqlStatement( PersistenceBroker broker, StatementType stmtType, IDbCommand cmd, string sql ) : this( broker, stmtType, cmd, sql, null, 0, 0 ) { }
/// <summary> /// Retrieve a statement from the cache. If the statement is not present it will be generated /// and added to the cache. /// </summary> /// <param name="type">The business object with which the statement is associated</param> /// <param name="tableName">The table used in the statement</param> /// <param name="stmtType">The type of the SQL statement</param> /// <returns>An SqlStatement instance</returns> public SqlStatement GetStatement( Type type, string tableName, StatementType stmtType ) { Initialize(); // ensure thread local variables have been initialized SqlStatement stmt; Hashtable stmts = (Hashtable) stmtByType[ type ]; // check if an SqlStatement has been cached for the given type and StatementType bool isCached = stmts != null && stmts.ContainsKey( stmtType ); if( isCached ) { stmt = (SqlStatement) stmts[ stmtType ]; // the npgsql library for postgres does not allow us to update the connection // property when a transaction is active if( stmt.Command.Connection == null || providerName != "PostgreSQL" ) { // make sure statement broker reference is updated before returning it stmt.SessionBroker = Broker; return stmt; } } // otherwise create and return fresh object PersistenceBroker broker = new PersistenceBroker( this ); SqlBuilder sb = new SqlBuilder( broker, stmtType, type ); // set the table name specified in the key (if null the default will be used instead) sb.SetTable( tableName ); // get the statement using primary key fields as constraints stmt = sb.GetStatement( false ); // dont cache statements for objects that map to multiple tables ObjectMap map = ObjectFactory.GetMap( broker, type ); if( ! (map.IsDynamicTable || isCached) ) { // TODO Prepare only works with a connection :-( // stmt.Prepare(); CacheStatement( type, stmtType, stmt ); } return stmt; }
/// <summary> /// constructor /// </summary> public EntityObject() { this.thisType = this.GetType(); this._IsSaveInMemory = PersistenceBroker.Instance().GetClassMap(thisType.Name).IsSaveToMemory; }
/// <summary> /// Obtain a new key for the specified object instance and property names. The returned /// key will contain the corresponding column names for the type, and thus foreign /// key columns must use identical naming for this to work. /// </summary> /// <param name="broker">The optional PersistenceBroker instance to use for obtaining the /// ObjectMap for the supplied object instance. If this parameter is null, Gentle will try /// to infer the broker from the object instance. If that fails, it will use the default /// provider.</param> /// <param name="isPropertyKeys">False is key indexers are column names, true for property names</param> /// <param name="instance">The object instance whose property values will be used</param> /// <param name="properties">The names of the properties to include in the key</param> /// <returns>The requested key</returns> public static Key GetKey( PersistenceBroker broker, bool isPropertyKeys, object instance, params string[] properties ) { return GetKey( broker, null, isPropertyKeys, instance, properties ); }
public IEntity Construct( int columnComboHashCode, object[] row, PersistenceBroker broker ) { // TODO improve error msg Check.Verify( constructorMaps.ContainsKey( columnComboHashCode ), Error.Unspecified, "Invalid columnComboHashCode parameter (no associated ConstructorMap instance)." ); ConstructorMap cm = constructorMaps[ columnComboHashCode ] as ConstructorMap; IEntity result = null; // perform object uniqing and caching if( GentleSettings.CacheObjects && objectMap.CacheStrategy != CacheStrategy.Never ) { string key = cm.GetRowHashKey( row ); result = CacheManager.Get( key ) as IEntity; if( result == null ) { result = cm.Construct( row, broker ); CacheManager.Insert( key, result, objectMap.CacheStrategy ); } else { GentleStatistics.UniqingCount += 1; } } else { result = cm.Construct( row, broker ); } return result; }
/// <summary> /// Obtain a key for the specified object instance and property names. The returned /// key will contain the corresponding column names for the type, and thus foreign /// key columns must use identical naming for this to work. /// </summary> /// <param name="broker">The optional PersistenceBroker instance to use for obtaining the /// ObjectMap for the supplied object instance. If this parameter is null, Gentle will try /// to infer the broker from the object instance. If that fails, it will use the default /// provider.</param> /// <param name="key">An optional existing key to add the values to</param> /// <param name="isPropertyKeys">False is key indexers are column names, true for property names</param> /// <param name="instance">The object instance whose property values will be used</param> /// <param name="members">The names of the properties to include in the key</param> /// <returns>The key</returns> public static Key GetKey( PersistenceBroker broker, Key key, bool isPropertyKeys, object instance, params string[] members ) { Check.VerifyNotNull( instance, Error.NullParameter, "instance" ); // try to infer broker from instance if( broker == null && instance is IBrokerLock ) { broker = (instance as IBrokerLock).SessionBroker; } // WARNING/TODO if broker is null here and no ObjectMap yet exists for the type, // the DefaultProvider will be used to create the ObjectMap ObjectMap map = ObjectFactory.GetMap( broker, instance ); // only set source type reference if this is a new key if( key == null ) { key = new Key( map.GetTableName( instance ), instance.GetType(), isPropertyKeys ); } //else // Check.Verify( ! key.isPropertyKeys, Error.DeveloperError, // "Unable to combine keys containing property names due to possible name clashes." ); Check.VerifyEquals( key.isPropertyKeys, isPropertyKeys, "Cannot combine property and " + "column names in a single key - use one or the other." ); Check.VerifyNotNull( members, Error.NullParameter, "members" ); // process the list of specified properties foreach( string memberName in members ) { FieldMap fm = isPropertyKeys ? map.GetFieldMap( memberName ) : map.GetFieldMapFromColumn( memberName ); Check.VerifyNotNull( fm, Error.NoProperty, map.Type, memberName ); // FIXME outdated error message object memberValue = fm.GetValue( instance ); // translate foreign references to local names if( key.SourceType != map.Type ) { // WARNING/TODO if broker is null here and no ObjectMap yet exists for the type, // the DefaultProvider will be used to create the ObjectMap ObjectMap keyMap = ObjectFactory.GetMap( broker, key.SourceType ); fm = keyMap.GetForeignKeyFieldMap( map.TableName, fm.ColumnName ); } key[ isPropertyKeys ? fm.MemberName : fm.ColumnName ] = memberValue; } // add concurrency value if enabled and instance has revision column if( GentleSettings.ConcurrencyControl && map.ConcurrencyMap != null ) { long version = Convert.ToInt64( map.ConcurrencyMap.GetValue( instance ) ); key[ isPropertyKeys ? map.ConcurrencyMap.MemberName : map.ConcurrencyMap.ColumnName ] = version; } return key; }
/// <summary> /// Construct a TableMap instance for an unspecified table. /// </summary> public TableMap( PersistenceBroker broker ) : this( broker, null ) { }
private static ObjectView GetObjectView( PersistenceBroker broker, Type type, string viewName ) { ObjectMap map = ObjectFactory.GetMap( broker, type ); Check.VerifyNotNull( viewName, Error.NullParameter, "viewName" ); ObjectView view = map.Views[ viewName ] as ObjectView; Check.VerifyNotNull( view, Error.NoSuchView, viewName, type ); return view; }
/// <summary> /// Retrieve all objects of a certain type (plain select of all rows in a the /// table, i.e. a statement without any where-clause). /// </summary> /// <param name="broker">The PersistenceBroker and associated provider used fetch the data</param> /// <param name="type">The type of the Persistent descendant to retrieve</param> /// <returns>A collection of objects of the given type</returns> public static IList RetrieveList( PersistenceBroker broker, Type type ) { if( broker == null ) { // use default broker instance by use of the Broker class return Broker.RetrieveList( type ); } else // use supplied broker instance { return broker.RetrieveList( type ); } }
/// <summary> /// 手动加载ClassMap文件。 /// </summary> /// <param name="classMapPath">ClassMap地址</param> public void LoadClassMap(string classMapPath) { PersistenceBroker.Instance().LoadClassMap(classMapPath); }
/// <summary> /// Constructor for the GentleAnalyzer base class. /// </summary> /// <param name="provider"></param> protected GentleAnalyzer( IGentleProvider provider ) { this.provider = provider; if( maps == null ) { maps = new Hashtable(); done = false; } // make sure we use our own PB to avoid using the DefaultProvider when analyzing the database broker = new PersistenceBroker( provider ); // this.broker = new PersistenceBroker( provider.Name, provider.ConnectionString ); // set the default analyzer level level = GentleSettings.AnalyzerLevel; }
public RestaurantRepositoryImpl(PersistenceBroker<RestaurantConfiguration> persistenceBroker) { _persistenceBroker = persistenceBroker; }
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." ); } }
/// <summary> /// Create a new list for storing the specified type of objects. /// </summary> public GentleRelation( PersistenceBroker broker, Type containedType, params Type[] relatedTypes ) : this( broker, containedType, null, relatedTypes ) { }