init lserp cs 5.0

This commit is contained in:
cyf
2026-07-10 15:25:05 +08:00
commit 90f3fda86a
3799 changed files with 976868 additions and 0 deletions
@@ -0,0 +1,129 @@
using System;
using System.Collections;
using System.Collections.Generic;
using Zhaizj.Framework.ORM;
namespace Zhaizj.Framework.Data {
/// <summary>
/// 缓存对象,常驻内存,同时以json格式存储在磁盘中
/// </summary>
[Serializable]
public class CacheObject {
private int _id;
private String _name;
/// <summary>
/// 对象的 id
/// </summary>
public int Id {
get { return _id; }
set { _id = value; }
}
/// <summary>
/// 对象名称
/// </summary>
public String Name {
get { return _name; }
set { _name = value; }
}
/// <summary>
/// 根据 id 检索对象
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public CacheObject findById( int id ) {
return MemoryDB.FindById( this.GetType(), id );
}
/// <summary>
/// 检索出所有对象
/// </summary>
/// <returns></returns>
public IList findAll() {
return MemoryDB.FindAll( this.GetType() );
}
/// <summary>
/// 根据名称检索出对象列表
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public IList findByName( String name ) {
return this.findBy( "Name", name );
}
/// <summary>
/// 根据属性名,检索出对象
/// </summary>
/// <param name="propertyName"></param>
/// <param name="val"></param>
/// <returns></returns>
public IList findBy( String propertyName, Object val ) {
findAll();
return MemoryDB.FindBy( this.GetType(), propertyName, val );
}
/// <summary>
/// 插入数据:并对所有属性做索引,速度较慢
/// </summary>
public void insert() {
MemoryDB.Insert( this );
}
/// <summary>
/// 插入数据:只针对特定属性做索引,提高速度
/// </summary>
/// <param name="propertyName"></param>
/// <param name="pValue"></param>
public void insertByIndex( String propertyName, Object pValue ) {
MemoryDB.InsertByIndex( this, propertyName, pValue );
}
/// <summary>
/// 插入数据:针对若干属性做索引
/// </summary>
/// <param name="dic"></param>
public void insertByIndex( Dictionary<String, Object> dic ) {
MemoryDB.InsertByIndex( this, dic );
}
/// <summary>
/// 更新数据
/// </summary>
/// <returns></returns>
public Result update() {
return MemoryDB.Update( this );
}
/// <summary>
/// 更新数据:只针对特性数据做索引
/// </summary>
/// <param name="dic"></param>
public void updateByIndex( Dictionary<String, Object> dic ) {
MemoryDB.updateByIndex( this, dic );
}
/// <summary>
/// 不持久化,也不做索引
/// </summary>
/// <returns></returns>
public Result updateNoIndex() {
return new Result();
}
/// <summary>
/// 删除数据
/// </summary>
public void delete() {
MemoryDB.Delete( this );
}
}
}
@@ -0,0 +1,480 @@
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using System.Web;
using Zhaizj.Framework.ORM;
using Zhaizj.Framework.Serialization;
using Zhaizj.Framework.Web;
namespace Zhaizj.Framework.Data {
internal class MemoryDB {
private static readonly ILog logger = LogManager.GetLogger( typeof( MemoryDB ) );
private static IDictionary objectList = Hashtable.Synchronized( new Hashtable() );
private static IDictionary indexList = Hashtable.Synchronized( new Hashtable() );
public static IDictionary GetObjectsMap() {
return objectList;
}
public static IDictionary GetIndexMap() {
return indexList;
}
private static Object objLock = new object();
private static Object chkLock = new object();
private static IList GetObjectsByName( Type t ) {
if (isCheckFileDB( t )) {
lock (chkLock) {
if (isCheckFileDB( t )) {
loadDataFromFile( t );
_hasCheckedFileDB[t] = true;
}
}
}
return (objectList[t.FullName] as IList);
}
private static Hashtable _hasCheckedFileDB = new Hashtable();
private static Boolean isCheckFileDB( Type t ) {
if (_hasCheckedFileDB[t] == null) return true;
return false;
}
private static void loadDataFromFile( Type t ) {
if (Zhaizj.Framework.IO.File.Exists( getCachePath( t ) )) {
IList list = getListWithIndex( Zhaizj.Framework.IO.File.Read( getCachePath( t ) ), t );
objectList[t.FullName] = list;
}
else {
objectList[t.FullName] = new ArrayList();
}
}
private static IList getListWithIndex( String jsonString, Type t ) {
IList list = new ArrayList();
if (strUtil.IsNullOrEmpty( jsonString )) return list;
List<object> lists = JsonParser.Parse( jsonString ) as List<object>;
foreach (Dictionary<String, object> map in lists) {
CacheObject obj = JSON.setValueToObject( t, map ) as CacheObject;
int index = list.Add( obj );
addIdIndex( t.FullName, obj.Id, index );
makeIndexByInsert( obj );
}
return list;
}
private static void Serialize( Type t ) {
Serialize( t, GetObjectsByName( t ) );
}
private static void Serialize( Type t, IList list ) {
String target = SimpleJsonString.ConvertList( list );
if (strUtil.IsNullOrEmpty( target )) return;
String absolutePath = getCachePath( t );
lock (objLock) {
Zhaizj.Framework.IO.File.Write( absolutePath, target );
}
}
private static void UpdateObjects( String key, IList list ) {
objectList[key] = list;
}
//------------------------------------------------------------------------------
internal static CacheObject FindById( Type t, int id ) {
IList list = GetObjectsByName( t );
if (list.Count > 0) {
int objIndex = getIndex( t.FullName, id );
if (objIndex >= 0 && objIndex < list.Count) {
return list[objIndex] as CacheObject;
}
}
return null;
}
internal static IList FindBy( Type t, String propertyName, Object val ) {
String propertyKey = getPropertyKey( t.FullName, propertyName );
NameValueCollection valueCollection = getValueCollection( propertyKey );
String ids = valueCollection[val.ToString()];
if (strUtil.IsNullOrEmpty( ids )) return new ArrayList();
IList results = new ArrayList();
String[] arrItem = ids.Split( ',' );
foreach (String strId in arrItem) {
int id = cvt.ToInt( strId );
if (id < 0) continue;
CacheObject obj = FindById( t, id );
if (obj != null) results.Add( obj );
}
return results;
}
internal static IList FindAll( Type t ) {
return new ArrayList( GetObjectsByName( t ) );
}
internal static void Insert( CacheObject obj ) {
Type t = obj.GetType();
String _typeFullName = t.FullName;
IList list = FindAll( t );
obj.Id = getNextId( list );
int index = list.Add( obj );
addIdIndex( _typeFullName, obj.Id, index );
UpdateObjects( _typeFullName, list );
makeIndexByInsert( obj );
if (isInMemory( t )) return;
Serialize( t );
}
internal static void InsertByIndex( CacheObject obj, String propertyName, Object pValue ) {
Type t = obj.GetType();
String _typeFullName = t.FullName;
IList list = FindAll( t );
obj.Id = getNextId( list );
int index = list.Add( obj );
addIdIndex( _typeFullName, obj.Id, index );
UpdateObjects( _typeFullName, list );
makeIndexByInsert( obj, propertyName, pValue );
if (isInMemory( t )) return;
Serialize( t );
}
internal static void InsertByIndex( CacheObject obj, Dictionary<String, Object> dic ) {
Type t = obj.GetType();
String _typeFullName = t.FullName;
IList list = FindAll( t );
obj.Id = getNextId( list );
int index = list.Add( obj );
addIdIndex( _typeFullName, obj.Id, index );
UpdateObjects( _typeFullName, list );
foreach (KeyValuePair<String, Object> kv in dic) {
makeIndexByInsert( obj, kv.Key, kv.Value );
}
if (isInMemory( t )) return;
Serialize( t );
}
internal static Result Update( CacheObject obj ) {
Type t = obj.GetType();
makeIndexByUpdate( obj );
if (isInMemory( t )) return new Result();
try {
Serialize( t );
return new Result();
}
catch (Exception ex) {
throw ex;
}
}
internal static Result updateByIndex( CacheObject obj, Dictionary<String, Object> dic ) {
Type t = obj.GetType();
makeIndexByUpdate( obj );
if (isInMemory( t )) return new Result();
try {
Serialize( t );
return new Result();
}
catch (Exception ex) {
throw ex;
}
}
internal static void Delete( CacheObject obj ) {
Type t = obj.GetType();
String _typeFullName = t.FullName;
makeIndexByDelete( obj );
IList list = FindAll( t );
list.Remove( obj );
UpdateObjects( _typeFullName, list );
deleteIdIndex( _typeFullName, obj.Id );
if (isInMemory( t )) return;
Serialize( t, list );
}
private static int getNextId( IList list ) {
if (list.Count == 0) return 1;
CacheObject preObject = list[list.Count - 1] as CacheObject;
return preObject.Id + 1;
}
private static Boolean isInMemory( Type t ) {
return rft.GetAttribute( t, typeof( NotSaveAttribute ) ) != null;
}
//----------------------------------------------------------------------------------------------
private static Object objIndexLock = new object();
private static Object objIndexLockInsert = new object();
private static Object objIndexLockUpdate = new object();
private static Object objIndexLockDelete = new object();
private static void makeIndexByInsert( CacheObject cacheObject, String propertyName, Object pValue ) {
if (cacheObject == null || pValue == null) return;
Type t = cacheObject.GetType();
String propertyKey = getPropertyKey( t.FullName, propertyName );
lock (objIndexLock) {
NameValueCollection valueCollection = getValueCollection( propertyKey );
valueCollection.Add( pValue.ToString(), cacheObject.Id.ToString() );
indexList[propertyKey] = valueCollection;
}
}
private static void makeIndexByInsert( CacheObject cacheObject ) {
if (cacheObject == null) return;
Type t = cacheObject.GetType();
PropertyInfo[] properties = getProperties( t );
foreach (PropertyInfo p in properties) {
String propertyKey = getPropertyKey( t.FullName, p.Name );
lock (objIndexLockInsert) {
NameValueCollection valueCollection = getValueCollection( propertyKey );
addNewValueMap( valueCollection, cacheObject, p );
}
}
}
private static void makeIndexByUpdate( CacheObject cacheObject ) {
if (cacheObject == null) return;
Type t = cacheObject.GetType();
PropertyInfo[] properties = getProperties( t );
foreach (PropertyInfo p in properties) {
String propertyKey = getPropertyKey( t.FullName, p.Name );
lock (objIndexLockUpdate) {
NameValueCollection valueCollection = getValueCollection( propertyKey );
deleteOldValueIdMap( valueCollection, cacheObject.Id );
addNewValueMap( valueCollection, cacheObject, p );
}
}
}
private static void makeIndexByUpdate( CacheObject cacheObject, String propertyName, Object pValue ) {
if (cacheObject == null || pValue == null) return;
Type t = cacheObject.GetType();
String propertyKey = getPropertyKey( t.FullName, propertyName );
lock (objIndexLockUpdate) {
NameValueCollection valueCollection = getValueCollection( propertyKey );
deleteOldValueIdMap( valueCollection, cacheObject.Id );
valueCollection.Add( pValue.ToString(), cacheObject.Id.ToString() );
indexList[propertyKey] = valueCollection;
}
}
private static void makeIndexByDelete( CacheObject cacheObject ) {
if (cacheObject == null) return;
Type t = cacheObject.GetType();
PropertyInfo[] properties = getProperties( t );
foreach (PropertyInfo p in properties) {
String propertyKey = getPropertyKey( t.FullName, p.Name );
lock (objIndexLockDelete) {
NameValueCollection valueCollection = getValueCollection( propertyKey );
deleteOldValueIdMap( valueCollection, cacheObject.Id );
}
}
}
private static PropertyInfo[] getProperties( Type t ) {
return t.GetProperties( BindingFlags.Public | BindingFlags.Instance );
}
private static NameValueCollection getValueCollection( String propertyKey ) {
NameValueCollection valueCollection = indexList[propertyKey] as NameValueCollection;
if (valueCollection == null) valueCollection = new NameValueCollection();
return valueCollection;
}
private static void addNewValueMap( NameValueCollection valueCollection, CacheObject cacheObject, PropertyInfo p ) {
Attribute attr = rft.GetAttribute( p, typeof( NotSaveAttribute ) );
if (attr != null) return;
String propertyKey = getPropertyKey( cacheObject.GetType().FullName, p.Name );
Object pValue = rft.GetPropertyValue( cacheObject, p.Name );
if (pValue == null || strUtil.IsNullOrEmpty( pValue.ToString() )) return;
valueCollection.Add( pValue.ToString(), cacheObject.Id.ToString() );
indexList[propertyKey] = valueCollection;
}
// TODO 优化
private static void deleteOldValueIdMap( NameValueCollection valueCollection, int oid ) {
foreach (String key in valueCollection.AllKeys) {
String val = valueCollection[key];
String[] arrItem = val.Split( ',' );
StringBuilder result = new StringBuilder();
foreach (String strId in arrItem) {
int id = cvt.ToInt( strId );
if (id == oid) continue;
result.Append( strId );
result.Append( "," );
}
String resultStr = result.ToString();
if (strUtil.HasText( resultStr ))
valueCollection[key] = resultStr.Trim().TrimEnd( ',' );
else
valueCollection.Remove( key );
}
}
private static String getPropertyKey( String typeFullName, String propertyName ) {
return typeFullName + "_" + propertyName;
}
//-------------------------- Id Index --------------------------------
private static IDictionary GetIdIndexMap( String key ) {
if (objectList[key] == null) {
objectList[key] = new Hashtable();
}
return (objectList[key] as IDictionary);
}
private static void UpdateIdIndexMap( String key, IDictionary map ) {
objectList[key] = map;
}
private static void clearIdIndexMap( String key ) {
objectList.Remove( key );
}
private static void addIdIndex( String typeFullName, int oid, int index ) {
String key = getIdIndexMapKey( typeFullName );
IDictionary indexMap = GetIdIndexMap( key );
indexMap[oid] = index;
UpdateIdIndexMap( key, indexMap );
}
private static void deleteIdIndex( String typeFullName, int oid ) {
String key = getIdIndexMapKey( typeFullName );
clearIdIndexMap( key );
IList results = objectList[typeFullName] as IList;
foreach (CacheObject obj in results) {
addIdIndex( typeFullName, obj.Id, results.IndexOf( obj ) );
}
IDictionary indexMap = GetIdIndexMap( key );
UpdateIdIndexMap( key, indexMap );
}
private static int getIndex( String typeFullName, int oid ) {
int result = -1;
Object objIndex = GetIdIndexMap( getIdIndexMapKey( typeFullName ) )[oid];
if (objIndex != null) {
result = (int)objIndex;
}
return result;
}
private static String getIdIndexMapKey( String typeFullName ) {
return String.Format( "{0}_oid_index", typeFullName );
}
//----------------------------------------------------------
private static String getCachePath( Type t ) {
if (SystemInfo.IsWeb == false) {
return getCacheFileName( t.FullName );
}
return getWebCacheFileName( t.FullName );
}
private static String getCacheFileName( String name ) {
return PathHelper.CombineAbs( new String[] {
AppDomain.CurrentDomain.BaseDirectory,
cfgHelper.FrameworkRoot,
"data",
name + fileExt
} );
}
private static String getWebCacheFileName( String name ) {
String rpath = strUtil.Join( cfgHelper.FrameworkRoot, "data" );
rpath = strUtil.Join( rpath, name + fileExt );
return PathHelper.Map( rpath );
}
private static readonly String fileExt = ".config";
}
}
@@ -0,0 +1,120 @@
using System;
using System.Collections.Generic;
using System.Text;
using Zhaizj.Framework.Config.DotNetConfig;
using System.Configuration;
namespace Zhaizj.Framework.Data.Config
{
/// <summary>
/// 数据库配置方式
/// </summary>
/// <remarks>
/// 配置文件格式和说明:
/// <code>
/// <configSections>
/// <sectionGroup name="Zhaizj.Config" type="Zhaizj.Framework.Config.GroupHandler,Zhaizj.Framework">;
/// <section name="DataBase" type="Zhaizj.Framework.Data.Config.SectionHandler, Zhaizj.Framework"/>;
/// </sectionGroup>
/// </configSections>
/// <Zhaizj.Config>
/// <log>
/// <log/>
/// <Zhaizj.Config/>
/// ......
/// </code>
/// </remarks>
public class SectionDataHandler : SectionBaseHandler<SectionDataHandler>
{
/// <summary>
/// 配置数据库连接
/// </summary>
[ConfigurationProperty("ConnectionStringTable", DefaultValue = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=zhaizj.mdb")]
public string ConnectionStringTable
{
get { return (string)this["ConnectionStringTable"]; }
}
/// <summary>
/// 配置数据库类型
/// </summary>
[ConfigurationProperty("DbType", DefaultValue = "access")]
public string DbType
{
get { return (string)this["DbType"]; }
}
/// <summary>
/// 配置多数据库
/// </summary>
[ConfigurationProperty("Mapping", DefaultValue = "")]
public string Mapping
{
get { return (string)this["Mapping"]; }
}
/// <summary>
///是否启用缓存
/// </summary>
[ConfigurationProperty("ApplicationCache", DefaultValue = "false")]
public string ApplicationCache
{
get { return (string)this["ApplicationCache"]; }
}
/// <summary>
///设置缓存时间-999 是永久缓存
/// </summary>
[ConfigurationProperty("ApplicationCacheMinutes", DefaultValue = "-999")]
public string ApplicationCacheMinutes
{
get { return (string)this["ApplicationCacheMinutes"]; }
}
/// <summary>
///缓存管理
/// </summary>
[ConfigurationProperty("ApplicationCacheManager", DefaultValue = "")]
public string ApplicationCacheManager
{
get { return (string)this["ApplicationCacheManager"]; }
}
/// <summary>
//程序集初始化
/// </summary>
[ConfigurationProperty("AssemblyList", DefaultValue = "Zhaizj.CoreApps")]
public string AssemblyList
{
get { return (string)this["AssemblyList"]; }
}
/// <summary>
/// 拦截器
/// </summary>
[ConfigurationProperty("Interceptor", DefaultValue = "Zhaizj.CoreApps")]
public string Interceptor
{
get { return (string)this["Interceptor"]; }
}
/// <summary>
/// 拼接代码
/// </summary>
/// <returns></returns>
public string GetDataConfig()
{
StringBuilder tagData = new StringBuilder();
tagData.Append("{");
tagData.Append("ConnectionStringTable : {default:\"" + ConnectionStringTable + "\"},");
tagData.Append("DbType : { default:\"" + DbType + "\"},");
tagData.Append("Mapping:[" + Mapping + "],");
tagData.Append("ApplicationCache:" + ApplicationCache + ",");
tagData.Append("ApplicationCacheMinutes:" + ApplicationCacheMinutes + ",");
tagData.Append("ApplicationCacheManager:\"" + ApplicationCacheManager + "\",");
tagData.Append("AssemblyList : [\"" + AssemblyList + "\"], Interceptor:[]");
tagData.Append("}");
return tagData.ToString();
}
}
}
@@ -0,0 +1,39 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace Zhaizj.Framework
{
public enum TableName2
{
,
,
}
public enum DictEnum
{
= 85,
= 89,
= 1,
= 102,
= -1,
= 2,
= 12,
= 15,
= 23,
= 35,
= 47,
= 37,
= 36,
= 74,
= 75,
= 76,
= 80,
= 84,
= 93,
= 107,
= 110,
= 113
}
}
@@ -0,0 +1,62 @@
using System;
using System.Data;
using System.IO;
using System.Web;
using Zhaizj.Framework.Reflection;
using Zhaizj.Framework.Web;
using Zhaizj.Framework.Web.Mvc;
namespace Zhaizj.Framework.Data {
internal class DatabaseBuilder {
public static String ConnectionStringPrefix = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=";
private static readonly ILog logger = LogManager.GetLogger( typeof( DatabaseBuilder ) );
public static String BuildAccessDb4o() {
String dbPath = getDbPath();
BuildAccessDb4o( dbPath );
return dbPath;
}
public static void BuildAccessDb4o( String dbPath ) {
String str = ConnectionStringPrefix + dbPath;
logger.Info( "creating database : " + str );
Object instanceFromProgId = ReflectionUtil.GetInstanceFromProgId( "ADOX.Catalog" );
try {
ReflectionUtil.CallMethod( instanceFromProgId, "Create", new object[] { str } );
}
catch (Exception exception) {
logger.Info( "creating database error : " + exception.Message );
LogManager.Flush();
throw exception;
}
logger.Info( "create database ok" );
}
//public static void Compact( String dbPath ) {
// if (!File.Exists( dbPath )) {
// throw new Exception( "database not found" );
// }
// IDbConnection connection = DbContext.getConnection();
// if ((connection != null) && (connection.State == ConnectionState.Open)) {
// connection.Close();
// }
// String sourceFileName = dbPath + ".bak";
// ReflectionUtil.CallMethod( ReflectionUtil.GetInstanceFromProgId( "JRO.JetEngine" ), "CompactDatabase", new object[] { ConnectionStringPrefix + dbPath, ConnectionStringPrefix + sourceFileName } );
// File.Copy( sourceFileName, dbPath, true );
// File.Delete( sourceFileName );
//}
private static String getDbPath() {
DateTime now = DateTime.Now;
String path = "Zhaizj.FrameworkDB_" + Guid.NewGuid().ToString().Replace( "-", "" ) + ".mdb";
path = PathHelper.Map( path );
return path;
}
}
}
@@ -0,0 +1,82 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.IO;
using Zhaizj.Framework.ORM;
namespace Zhaizj.Framework.Data {
internal class AccessDatabaseChecker : IDatabaseChecker {
private static readonly ILog logger = LogManager.GetLogger( typeof( AccessDatabaseChecker ) );
private String _connectionString;
private List<String> existTables = new List<String>();
public String ConnectionString {
get { return _connectionString; }
set { _connectionString = value; }
}
public DatabaseType DatabaseType {
get { return DatabaseType.Access; }
set { }
}
public void CheckDatabase() {
logger.Info( "begin check database" );
if (strUtil.IsNullOrEmpty( _connectionString )) {
logger.Info( "connection String is empty. begin to create access database and set connection string" );
createDatabaseAndSaveConnectionString();
}
else {
String connectionItem = DataFactory.GetDialect( DatabaseType.Access ).GetConnectionItem( _connectionString, ConnectionItemType.Database );
if (strUtil.IsNullOrEmpty( connectionItem )) {
logger.Info( "connection String is found, but database is empty. begin to create access database and set connection string" );
createDatabaseAndSaveConnectionString();
}
else if (!File.Exists( connectionItem )) {
logger.Info( "ConnectionString:" + _connectionString );
logger.Info( "the database [" + connectionItem + "] is not found. begin to create access database and set connection string" );
DatabaseBuilder.BuildAccessDb4o( connectionItem );
}
}
}
public void CheckTable( MappingClass mapping, String db ) {
logger.Info( "[access] begin check table" );
OleDbConnection connection = DataFactory.GetConnection( _connectionString, this.DatabaseType ) as OleDbConnection;
connection.Open();
IDbCommand cmd = new OleDbCommand();
cmd.Connection = connection;
object[] restrictions = new object[4];
restrictions[3] = "TABLE";
DataTable oleDbSchemaTable = connection.GetOleDbSchemaTable( OleDbSchemaGuid.Tables, restrictions );
foreach (DataRow row in oleDbSchemaTable.Rows) {
existTables.Add( row["TABLE_NAME"].ToString() );
logger.Info( "table found£º" + row["TABLE_NAME"].ToString() );
}
existTables = new AccessTableBuilder().CheckMappingTableIsExist( cmd, db, existTables, mapping );
connection.Close();
}
private void createDatabaseAndSaveConnectionString() {
_connectionString = DatabaseBuilder.ConnectionStringPrefix + DatabaseBuilder.BuildAccessDb4o();
logger.Info( "connection String : " + _connectionString );
DbConfig.SaveConnectionString( _connectionString );
logger.Info( "the connection String is resetted" );
}
public List<String> GetTables() {
return existTables;
}
}
}
@@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using Zhaizj.Framework.ORM;
namespace Zhaizj.Framework.Data {
internal interface IDatabaseChecker {
String ConnectionString { get; set; }
DatabaseType DatabaseType { get; set; }
void CheckDatabase();
void CheckTable( MappingClass mapping, String db );
List<String> GetTables();
}
}
@@ -0,0 +1,72 @@
using System;
using System.Data;
using System.Collections;
using System.Collections.Generic;
using Zhaizj.Framework.ORM;
namespace Zhaizj.Framework.Data {
internal class MysqlDatabaseChecker : IDatabaseChecker {
private static readonly ILog logger = LogManager.GetLogger( typeof( MysqlDatabaseChecker ) );
private List<String> existTables = new List<String>();
private String _connectionString;
public String ConnectionString {
get { return _connectionString; }
set { _connectionString = value; }
}
public DatabaseType DatabaseType {
get { return DatabaseType.MySql; }
set { }
}
public void CheckDatabase() {
if (strUtil.IsNullOrEmpty( this._connectionString )) {
throw new Exception( "connection string can not be empty" );
}
IDatabaseDialect dialect = DataFactory.GetDialect( DatabaseType.MySql );
if (strUtil.IsNullOrEmpty( dialect.GetConnectionItem( this._connectionString, ConnectionItemType.Server ) )) {
throw new Exception( "[mysql] server address is empty" );
}
if (strUtil.IsNullOrEmpty( dialect.GetConnectionItem( _connectionString, ConnectionItemType.Database ) )) {
throw new Exception( "[mysql] database is empty" );
}
}
public void CheckTable( MappingClass mapping, String db ) {
logger.Info( "[mysql] begin check table" );
IDbConnection connection = DataFactory.GetConnection( _connectionString, this.DatabaseType );
connection.Open();
IDbCommand cmd = connection.CreateCommand();
cmd.CommandText = "show tables";
IDataReader reader = cmd.ExecuteReader();
while (reader.Read()) {
existTables.Add( reader[0].ToString() );
logger.Info( "table found£º" + reader[0].ToString() );
}
reader.Close();
existTables = new MySqlTableBuilder().CheckMappingTableIsExist( cmd, db, existTables, mapping );
connection.Close();
}
public List<String> GetTables() {
return existTables;
}
}
}
@@ -0,0 +1,67 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.SqlClient;
using Zhaizj.Framework.ORM;
namespace Zhaizj.Framework.Data {
internal class SQLServerDatabaseChecker : IDatabaseChecker {
private static readonly ILog logger = LogManager.GetLogger( typeof( SQLServerDatabaseChecker ) );
private String _connectionString;
private DatabaseType _databaseType;
public String ConnectionString {
get { return _connectionString; }
set { _connectionString = value; }
}
public DatabaseType DatabaseType {
get { return _databaseType; }
set { _databaseType = value; }
}
private List<String> existTables = new List<String>();
public void CheckDatabase() {
if (strUtil.IsNullOrEmpty( _connectionString )) {
throw new Exception( "[sqlserver] connection String is not found" );
}
IDatabaseDialect dialect = DataFactory.GetDialect( DatabaseType.SqlServer );
if (strUtil.IsNullOrEmpty( dialect.GetConnectionItem( _connectionString, ConnectionItemType.Server ) )) {
throw new Exception( "[sqlserver] address is empty" );
}
if (strUtil.IsNullOrEmpty( dialect.GetConnectionItem( _connectionString, ConnectionItemType.Database ) )) {
throw new Exception( "[sqlserver] database is empty" );
}
}
public void CheckTable( MappingClass mapping, String db ) {
logger.Info( "[sqlserver] begin check table" );
SqlConnection connection = new SqlConnection( _connectionString );
connection.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = connection;
cmd.CommandText = "SELECT OBJECT_NAME(id) as name FROM sysobjects WHERE xtype='U' AND OBJECTPROPERTY(id, 'IsMSShipped') = 0";
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read()) {
existTables.Add( reader["name"].ToString() );
logger.Info( "table found" + reader["name"].ToString() );
}
reader.Close();
existTables = new SqlServerTableBuilder().CheckMappingTableIsExist( cmd, db, existTables, mapping );
connection.Close();
}
public List<String> GetTables() {
return existTables;
}
}
}
+309
View File
@@ -0,0 +1,309 @@
using System;
using System.Collections.Generic;
using System.Text;
using Zhaizj.Framework.ORM;
using Zhaizj.Framework.Reflection;
using Zhaizj.Framework.Serialization;
using Zhaizj.Framework.Web;
using System.IO;
using System.Web;
using Zhaizj.Framework.IO;
using Zhaizj.Framework.Data.Config;
namespace Zhaizj.Framework.Data {
/// <summary>
/// 数据库连接字符串内容的封装
/// </summary>
public class ConnectionString {
public String Name { get; set; }
public String StringContent { get; set; }
public DatabaseType DbType { get; set; }
}
/// <summary>
/// ORM 的数据库配置
/// </summary>
public class DbConfig {
private static readonly ILog logger = LogManager.GetLogger( typeof( DbConfig ) );
public DbConfig() {
this.ConnectionStringTable = new Dictionary<String, object>();
this.AssemblyList = new List<object>();
this.DbType = new Dictionary<String, object>();
this.IdType = Zhaizj.Framework.Data.IdType.Auto;
this.Interceptor = new List<object>();
this.IsCheckDatabase = true;
this.ContextCache = true;
this.Mapping = new List<object>();
}
/// <summary>
/// 默认数据库名称(值为default)
/// </summary>
public static readonly String DefaultDbName = "default";
/// <summary>
/// 配置的缓存内容(单例模式缓存)
/// </summary>
public static DbConfig Instance = loadConfig( getConfigPath() );
/// <summary>
/// 直接解析json的结果:多个数据库连接字符串(connectionString)的键值对
/// </summary>
public Dictionary<String, object> ConnectionStringTable { get; set; }
private Dictionary<String, ConnectionString> _connectionStringMap = new Dictionary<String, ConnectionString>();
/// <summary>
/// 多个数据库连接字符串对象的map,值是ConnectionString对象(包括Name/StringContent/DbType)
/// </summary>
/// <returns></returns>
public Dictionary<String, ConnectionString> GetConnectionStringMap() {
return _connectionStringMap;
}
internal void SetConnectionStringMap( Dictionary<String, ConnectionString> cmap ) {
_connectionStringMap = cmap;
}
/// <summary>
/// 直接解析json的结果:数据库类型
/// </summary>
public Dictionary<String, object> DbType { get; set; }
/// <summary>
/// 实体键值类型
/// </summary>
public String IdType { get; set; }
/// <summary>
/// 自动键值
/// </summary>
[NotSerialize]
public bool IsAutoId
{
get { return IdType.Equals(Zhaizj.Framework.Data.IdType.Auto, StringComparison.OrdinalIgnoreCase); }
}
/// <summary>
/// 直接解析json的结果:程序集列表
/// </summary>
public List<object> AssemblyList { get; set; }
/// <summary>
/// 是否坚持数据库,如果检查,则会将尚未创建的数据表自动创建
/// </summary>
public Boolean IsCheckDatabase { get; set; }
/// <summary>
/// 数据表的前缀(默认没有前缀)
/// </summary>
public String TablePrefix { get; set; }
/// <summary>
/// 是否开启一级缓存,默认开启,并且建议开启
/// </summary>
public Boolean ContextCache { get; set; }
/// <summary>
/// 是否开启二级缓存
/// </summary>
public Boolean ApplicationCache { get; set; }
/// <summary>
/// 二级缓存的时间(分钟)
/// </summary>
public int ApplicationCacheMinutes { get; set; }
/// <summary>
/// 二级缓存管理程序,请填写类型(type)的全名(full name),比如 Zhaizj.Framework.somens.myCache
/// 如果不填写,则使用默认的System.Web.Caching
/// </summary>
public String ApplicationCacheManager { get; set; }
/// <summary>
/// ORM 的元数据文件名称,一般不需填写(建议不要填写)。如果为了提高网站启动时候的速度,可以填写。
/// 系统会根据文件名自动生成元数据文件,可以避免以后网站启动过程中的反射,能略微提高启动速度;
/// 文件名不包括路径(必须放在bin目录中),比如 Zhaizj.Framework.meta.dll
/// </summary>
public String MetaDLL { get; set; }
/// <summary>
/// 直接解析json的结果:数据表映射
/// </summary>
public List<object> Mapping { get; set; }
/// <summary>
/// 拦截器列表
/// </summary>
public List<object> Interceptor { get; set; }
/// <summary>
/// 反射优化模式,目前只实现了 CodeDom 方式
/// </summary>
[NotSerialize]
internal OptimizeMode OptimizeMode {
get { return OptimizeMode.CodeDom; }
set { }
}
/// <summary>
/// 获取元数据库文件的绝对路径
/// </summary>
/// <returns></returns>
public String GetMetaDllAbsPath() {
if (strUtil.IsNullOrEmpty( this.MetaDLL )) return "";
String dllPath = this.MetaDLL;
if (dllPath.ToLower().EndsWith( ".dll" ) == false)
dllPath = dllPath + ".dll";
dllPath = Path.Combine( PathTool.GetBinDirectory(), dllPath );
return dllPath;
}
private Dictionary<String, MappingInfo> _mappings = new Dictionary<String, MappingInfo>();
private void addMapping( MappingInfo mi ) {
_mappings.Add( mi.TypeName, mi );
}
/// <summary>
/// 获取映射信息
/// </summary>
/// <returns></returns>
internal Dictionary<String, MappingInfo> GetMappingInfo() {
return _mappings;
}
//----------------------------------------------------------------------
private static DbConfig loadConfig( String cfgPath ) {
String str = SectionDataHandler.Current.GetDataConfig();//file.Read( cfgPath );
DbConfig dbc = JSON.ToObject<DbConfig>( str );
loadMappingInfo( dbc );
checkConnectionString( dbc );
return dbc;
}
private static void loadMappingInfo( DbConfig dbc ) {
if (dbc.Mapping.Count == 0) return;
foreach (Dictionary<String, object> dic in dbc.Mapping) {
MappingInfo mi = new MappingInfo();
if (dic.ContainsKey( "name" )) mi.TypeName = dic["name"].ToString();
if (dic.ContainsKey( "database" )) mi.Database = dic["database"].ToString();
if (dic.ContainsKey( "table" )) mi.Table = dic["table"].ToString();
dbc.addMapping( mi );
}
}
private static String getConfigPath() {
return PathHelper.Map( strUtil.Join( cfgHelper.ConfigRoot, "orm.config" ) );
}
private static void checkConnectionString( DbConfig result ) {
logger.Info( "checkConnectionString..." );
if (result.ConnectionStringTable == null) return;
Dictionary<String, ConnectionString> connStringMap = new Dictionary<String, ConnectionString>();
Dictionary<String, String> newString = new Dictionary<string, string>();
foreach (KeyValuePair<String, object> kv in result.ConnectionStringTable) {
String connectionString = kv.Value.ToString();
DatabaseType dbtype = getDbType( kv.Key, connectionString, result );
ConnectionString objConnString = new ConnectionString {
Name = kv.Key,
StringContent = connectionString,
DbType = dbtype
};
connStringMap.Add( kv.Key, objConnString );
logger.Info( "connectionString:" + connectionString );
IDatabaseDialect dialect = DataFactory.GetDialect( dbtype );
if ((dbtype == DatabaseType.Access)) {
String connectionItem = dialect.GetConnectionItem( connectionString, ConnectionItemType.Database );
logger.Info( "database path original:" + connectionItem );
if (IsRelativePath( connectionItem )) {
connectionItem = PathHelper.Map( strUtil.Join( SystemInfo.ApplicationPath, connectionItem ) );
logger.Info( "database path now:" + connectionItem );
String newConnString = String.Format( "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}", connectionItem );
newString.Add( kv.Key, newConnString );
}
}
}
foreach (KeyValuePair<String, String> kv in newString) {
result.ConnectionStringTable[kv.Key] = kv.Value;
connStringMap[kv.Key].StringContent = kv.Value;
}
result.SetConnectionStringMap( connStringMap );
}
private static bool IsRelativePath( string connectionItem ) {
return connectionItem.IndexOf( ":" ) < 0;
}
private static DatabaseType getDbType( String dbname, String connectionString, DbConfig result ) {
foreach (KeyValuePair<String, Object> kv in result.DbType) {
if (kv.Key == dbname) return DbTypeChecker.GetFromString( kv.Value.ToString() );
}
DatabaseType dbtype = DbTypeChecker.GetDatabaseType( connectionString );
return dbtype;
}
//----------------------------------------------------------------------
/// <summary>
/// 根据命名,获取数据库连接字符串
/// </summary>
/// <param name="db"></param>
/// <returns></returns>
public static String GetConnectionString( String db ) {
if (DbConfig.Instance.ConnectionStringTable.ContainsKey( db ) == false)
throw new Exception( lang.get( "dbNotExist" ) + ": " + db );
return (String)DbConfig.Instance.ConnectionStringTable[db];
}
internal static void SaveConnectionString( String connectionString ) {
String cfgPath = getConfigPath();
if (DbConfig.Instance.ConnectionStringTable == null)
DbConfig.Instance.ConnectionStringTable = new Dictionary<String, object>();
DbConfig.Instance.ConnectionStringTable[DefaultDbName] = connectionString;
String str = JsonString.ConvertObject( DbConfig.Instance, true );
file.Write( cfgPath, str );
}
}
}
@@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
namespace Zhaizj.Framework.Data {
internal class DbConst {
public static List<String> SqlKeyWords = getSqlKeyWords();
private static List<String> getSqlKeyWords() {
String[] strArray = "action/absolute/any/add/are/admindb/as/all/asc/alphanumeric/assertion/alter/authorization/alter/table/autoincrement/and/avg/as/begin/both/collation/between/column/binary/commit/bit/bit_length/comp/compression/connect/boolean/connection/constraint/constraints/by/container/byte/contains/cascade/convert/catalog/count/char/character/counter/char_length/create/character_length/currency/check/current_date/close/current_time/clustered/current_timestamp/coalesce/current_user/collate/cursor/database/disallow/date/disconnect/datetime/distinct/day/distinctrow/dec/decimal/domain/declare/double/delete/drop/desc/eqv/foreign/exclusiveconnect/from/exec/execute/exists/general/extract/grant/false/group/fetch/guid/first/having/float/float8/hour/float4/identity/input/ieeedouble/insensitive/ieeesingle/insert/ignore/insert/into/image/int/integer/integer4/imp/integer1/integer2/interval/index/indexcreatedb/is/inner/isolation/join/longtext/key/lower/language/match/last/max/left/memo/level/min/like/minute/logical/logical1/mod/long/money/longbinary/month/longchar/national/outer/nchar/output/nonclustered/owneraccess/not/pad/ntext/parameters/null/partial/number/password/numeric/percent/nvarchar/pivot/octet_length/position/oleobject/precision/on/prepare/open/primary/option/privileges/or/proc/procedure/order/public/smalldatetime/references/smallint/restrict/smallmoney/revoke/some/right/space/rollback/sql/schema/sqlcode/sqlerror/sqlstate/second/stdev/select/stdevp/selectschema/string/selectsecurity/substring/set/sum/short/sysname/single/system_user/size/table/updateowner/tableid/updatesecurity/temporary/upper/text/usage/time/user/timestamp/using/timezone_hour/value/timezone_minute/values/tinyint/var/to/varbinary/top/varchar/trailing/varp/transaction/varying/transform/view/translate/when/translation/whenever/trim/where/true/with/union/work/unique/xor/uniqueidentifier/year/unknown/yesno/update/zone/updateidentity".Split( new char[] { '/' } );
return new List<String>( strArray );
}
}
}
@@ -0,0 +1,225 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Threading;
using Zhaizj.Framework.Web;
using Zhaizj.Framework.ORM;
using Zhaizj.Framework.ORM.Caching;
namespace Zhaizj.Framework.Data {
/// <summary>
/// 数据库上下文,主要用于获取数据库连接
/// </summary>
public class DbContext {
/// <summary>
/// 获取数据库连接,返回的连接已经打开(open);在 mvc 框架中不用关闭,框架会自动关闭连接。
/// 之所以要传入 Type,因为 ORM 支持多个数据库,不同的类型有可能映射到不同的数据库。
/// </summary>
/// <param name="t">实体的类型</param>
/// <returns></returns>
public static IDbConnection getConnection( Type t ) {
return getConnection( Entity.GetInfo( t ) );
}
/// <summary>
/// 获取数据库连接,返回的连接已经打开(open);在 mvc 框架中不用关闭,框架会自动关闭连接。
/// 之所以要传入 EntityInfo,因为 ORM 支持多个数据库,不同的类型有可能映射到不同的数据库。
/// </summary>
/// <param name="et"></param>
/// <returns></returns>
public static IDbConnection getConnection( EntityInfo et ) {
String db = et.Database;
String connectionString = DbConfig.GetConnectionString( db );
IDbConnection connection;
getConnectionAll().TryGetValue( db, out connection );
if (connection == null) {
connection = DataFactory.GetConnection( connectionString, et.DbType );
connection.Open();
setConnection( db, connection );
if (shouldTransaction()) {
IDbTransaction trans = connection.BeginTransaction();
setTransaction( db, trans );
}
return connection;
}
if (connection.State == ConnectionState.Closed) {
connection.ConnectionString = connectionString;
connection.Open();
}
return connection;
}
/// <summary>
/// 关闭数据库连接。因为ORM支持多个数据库,所以所有可能的数据库连接都会一起关闭。
/// </summary>
public static void closeConnectionAll() {
ContextCache.Clear();
Dictionary<String, IDbConnection> dic = getConnectionAll();
foreach (KeyValuePair<String, IDbConnection> kv in dic) {
IDbConnection connection = kv.Value;
if ((connection != null) && (connection.State == ConnectionState.Open)) {
connection.Close();
connection.Dispose();
}
}
freeItem( _connectionKey );
}
//------------------------------------------------------------------------------
/// <summary>
/// 获取所有的数据库连接
/// </summary>
/// <returns></returns>
public static Dictionary<String, IDbConnection> getConnectionAll() {
Dictionary<String, IDbConnection> dic;
dic = CurrentRequest.getItem( _connectionKey ) as Dictionary<String, IDbConnection>;
if (dic == null) {
dic = new Dictionary<String, IDbConnection>();
CurrentRequest.setItem( _connectionKey, dic );
}
return dic;
}
private static Dictionary<String, IDbTransaction> getTransactionAll() {
Dictionary<String, IDbTransaction> dic;
dic = CurrentRequest.getItem( _transactionKey ) as Dictionary<String, IDbTransaction>;
if (dic == null) {
dic = new Dictionary<String, IDbTransaction>();
CurrentRequest.setItem( _transactionKey, dic );
}
return dic;
}
private static void setConnection( String key, IDbConnection cn ) {
getConnectionAll()[key] = cn;
}
private static void setTransaction( String key, IDbTransaction trans ) {
getTransactionAll()[key] = trans;
}
//------------------------------------------------------------------------------
public static void beginAndMarkTransactionAll() {
CurrentRequest.setItem( _beginTransactionAll, true ); // 如果当前没有打开的数据库连接,则打上标记,等真正打开的时候启用事务
beginTransactionAll();
}
private static bool shouldTransaction() {
Object trans = CurrentRequest.getItem( _beginTransactionAll );
if (trans == null) return false;
return (Boolean)trans;
}
/// <summary>
/// 针对所有数据库连接,开启数据库事务
/// </summary>
public static void beginTransactionAll() {
Dictionary<String, IDbConnection> list = getConnectionAll();
foreach (KeyValuePair<String, IDbConnection> kv in list) {
IDbTransaction trans = kv.Value.BeginTransaction();
setTransaction( kv.Key, trans );
}
}
public static void setTransaction( IDbCommand cmd ) {
Dictionary<String, IDbTransaction> transTable = getTransactionAll();
foreach (KeyValuePair<String, IDbTransaction> kv in transTable) {
IDbTransaction trans = kv.Value;
if (cmd.Connection == trans.Connection) {
cmd.Transaction = trans;
return;
}
}
}
private static void clearTransactionAll() {
Dictionary<String, IDbTransaction> dic = CurrentRequest.getItem( _transactionKey ) as Dictionary<String, IDbTransaction>;
if (dic == null) return;
dic.Clear();
CurrentRequest.setItem( _transactionKey, dic );
}
/// <summary>
/// 提交全部的数据库事务
/// </summary>
public static void commitAll() {
Dictionary<String, IDbTransaction> transTable = getTransactionAll();
foreach (KeyValuePair<String, IDbTransaction> kv in transTable) {
IDbTransaction trans = kv.Value;
if (trans != null && trans.Connection != null ) trans.Commit();
}
clearTransactionAll();
}
/// <summary>
/// 回滚所有数据库事务
/// </summary>
public static void rollbackAll() {
Dictionary<String, IDbTransaction> transTable = getTransactionAll();
foreach (KeyValuePair<String, IDbTransaction> kv in transTable) {
IDbTransaction trans = kv.Value;
if (trans != null && trans.Connection != null) trans.Rollback();
}
clearTransactionAll();
}
//------------------------------------------------------------------------------
private static void freeItem( String key ) {
if (!SystemInfo.IsWeb) {
Thread.FreeNamedDataSlot( key );
}
}
internal static IDictionary getContextCache() {
Object dic = CurrentRequest.getItem( _contextCacheKey );
if (dic == null) {
dic = new Hashtable();
CurrentRequest.setItem( _contextCacheKey, dic );
}
return dic as IDictionary;
}
/// <summary>
/// 获取存储在上下文中的 sql 执行次数
/// </summary>
/// <returns></returns>
public static int getSqlCount() {
Object count = CurrentRequest.getItem( "sqlcount" );
if (count == null) return 0;
return cvt.ToInt( count );
}
private static readonly String _beginTransactionAll = "__beginTransactionAll";
private static readonly String _connectionKey = "__Zhaizj.FrameworkConnection";
private static readonly String _transactionKey = "__Zhaizj.FrameworkDbTransaction";
private static readonly String _contextCacheKey = "__contextCacheDictionary";
}
}
@@ -0,0 +1,84 @@
/*
* Copyright 2010 www.Zhaizj.Framework.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Web;
using Zhaizj.Framework.Web;
using Zhaizj.Framework.Web.Mvc;
namespace Zhaizj.Framework.Data {
/// <summary>
/// access ÌØÊâÓï·¨´¦ÀíÆ÷
/// </summary>
[Serializable]
public class AccessDialect : IDatabaseDialect {
public String GetConnectionItem( String connectionString, ConnectionItemType connectionItem ) {
String str = connectionItem.ToString().ToLower().Replace( "database", "data source" ).Replace( "userid", "user id" );
String[] arrItem = connectionString.ToLower().Split( new char[] { ';' } );
foreach (String item in arrItem) {
if (item.Trim().ToLower().StartsWith( str )) {
return item.Replace( str, "" ).Replace( "=", "" ).Replace( " ", "" );
}
}
return null;
}
public String GetLimit( String sql, int limit ) {
return sql.ToLower().Replace( "select ", "select top " + limit + " " );
}
public String GetLimit( String sql) {
return sql;
}
public String GetTimeQuote() {
return "#";
}
public String GetParameter( String parameterName ) {
return "?";
}
public String GetParameterAdder( String parameterName ) {
return ("@" + parameterName);
}
public static String MapPath( String connectionString ) {
if (SystemInfo.IsWeb==false) {
return connectionString;
}
String connectionItem = new AccessDialect().GetConnectionItem( connectionString, ConnectionItemType.Database );
String newValue = PathHelper.Map( connectionItem );
return connectionString.Replace( connectionItem, newValue );
}
public String Top {
get { return "top"; }
}
public string GetLeftQuote() {
return "[";
}
public string GetRightQuote() {
return "]";
}
}
}
@@ -0,0 +1,43 @@
/*
* Copyright 2010 www.Zhaizj.Framework.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
namespace Zhaizj.Framework.Data {
/// <summary>
/// 各种数据库的特殊语法处理接口
/// </summary>
public interface IDatabaseDialect {
String GetConnectionItem( String connectionString, ConnectionItemType connectionItem );
String GetLimit( String sql, int limit );
String GetLimit( String sql );
String GetParameter( String parameterName );
String GetParameterAdder( String parameterName );
String GetTimeQuote();
String GetLeftQuote();
String GetRightQuote();
String Top { get; }
}
}
@@ -0,0 +1,99 @@
using System;
namespace Zhaizj.Framework.Data {
/// <summary>
/// mysql ÌØÊâÓï·¨´¦ÀíÆ÷
/// </summary>
public class MysqlDialect : IDatabaseDialect {
public String GetConnectionItem( String connectionString, ConnectionItemType connectionItem ) {
return getConnectionItem( connectionString, connectionItem );
}
public static String getConnectionItem( String connStr, ConnectionItemType connectionItemType ) {
if (strUtil.IsNullOrEmpty( connStr )) throw new Exception( "mysql connection string is empty" );
String[] arrItems = connStr.ToLower().Split( ';' );
foreach (String item in arrItems) {
if (strUtil.IsNullOrEmpty( item )) continue;
String[] arrPair = item.Split( '=' );
if (arrPair.Length != 2) continue;
String key = arrPair[0].Trim();
String val = arrPair[1].Trim();
if (keyEqual( key, connectionItemType )) return val;
}
return "";
}
private static Boolean keyEqual( String key, ConnectionItemType connectionItemType ) {
if (connectionItemType == ConnectionItemType.Server) return key == "server";
if (connectionItemType == ConnectionItemType.Database) return key == "database";
if (connectionItemType == ConnectionItemType.UserId) return key == "user" || key == "uid" || key == "user id";
if (connectionItemType == ConnectionItemType.Password) return key == "password" || key == "pwd";
return false;
}
public String GetLimit( String sql, int limit ) {
return (sql + " limit " + limit);
}
public String GetLimit( String rSql ) {
if (rSql == null) return null;
String sql = rSql.ToLower();
if (sql.ToLower().IndexOf( " top " ) > 0) {
// selec top 10 * from
// 10 * from
String rMainSql = sql.Split( new String[] { " top " }, StringSplitOptions.None )[1].Trim();
String[] arrItem = rMainSql.Split( ' ' );
int limit = cvt.ToInt( arrItem[0] );
String mainSql = strUtil.TrimStart( rMainSql, arrItem[0] );
return this.GetLimit( "select " + mainSql, limit );
}
return sql;
}
public String GetTimeQuote() {
return "'";
}
public String GetParameter( String parameterName ) {
return ("@" + parameterName);
}
public String GetParameterAdder( String parameterName ) {
return ("@" + parameterName);
}
public String Top {
get { return "limit"; }
}
public string GetLeftQuote() {
return "`";
}
public string GetRightQuote() {
return "`";
}
}
}
@@ -0,0 +1,54 @@
using System;
namespace Zhaizj.Framework.Data {
/// <summary>
/// sqlserver ÌØÊâÓï·¨´¦ÀíÆ÷
/// </summary>
public class SQLServerDialect : IDatabaseDialect {
public String GetConnectionItem( String connectionString, ConnectionItemType connectionItem ) {
String str = connectionItem.ToString().ToLower().Replace( "userid", "uid" ).Replace( "password", "pwd" );
String[] strArray = connectionString.ToLower().Split( new char[] { ';' } );
foreach (String item in strArray) {
if (item.Trim().ToLower().StartsWith( str )) {
return item.Replace( str, "" ).Replace( "=", "" ).Replace( " ", "" );
}
}
return null;
}
public String GetTimeQuote() {
return "'";
}
public String GetLimit( String sql, int limit ) {
return sql.ToLower().Replace( "select ", "select top " + limit + " " );
}
public String GetLimit( String sql ) {
return sql;
}
public String GetParameter( String parameterName ) {
return ("@" + parameterName);
}
public String GetParameterAdder( String parameterName ) {
return ("@" + parameterName);
}
public String Top {
get { return "top"; }
}
public string GetLeftQuote() {
return "[";
}
public string GetRightQuote() {
return "]";
}
}
}
+142
View File
@@ -0,0 +1,142 @@
using System;
using System.Collections;
using System.Data;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Xml.Serialization;
using Zhaizj.Framework.Log;
namespace Zhaizj.Framework.Data {
/// <summary>
/// 简易数据库操作工具,兼容多种数据库,可执行sql,返回DataReader等
/// </summary>
public class EasyDB {
private static readonly ILog logger = LogManager.GetLogger( typeof( EasyDB ) );
public static int Execute( String sql, IDbConnection cn ) {
logger.Info( LoggerUtil.SqlPrefix+"execute sql : " + sql );
IDbCommand cmd = DataFactory.GetCommand( sql, cn );
int result = cmd.ExecuteNonQuery();
logger.Info( "affected : " + result );
return result;
}
public static IDataReader ExecuteReader( String sql, IDbConnection cn ) {
logger.Info( LoggerUtil.SqlPrefix+"execute sql" + sql );
return DataFactory.GetCommand( sql, cn ).ExecuteReader();
}
public static Object ExecuteScalar( String sql, IDbConnection cn ) {
Object result = null;
logger.Info( LoggerUtil.SqlPrefix+"execute sql" + sql );
result = DataFactory.GetCommand( sql, cn ).ExecuteScalar();
if (result == DBNull.Value) {
return null;
}
return result;
}
public static DataTable ExecuteTable( String sql, IDbConnection cn ) {
DataTable dataTable = new DataTable();
logger.Info(LoggerUtil.SqlPrefix+ "execute sql" + sql );
DataFactory.GetAdapter( sql, cn ).Fill( dataTable );
return dataTable;
}
//-----------------------------------------------------------------------------------------------------------
public static Hashtable LoadDicFromString( String targetString ) {
Hashtable hashtable = new Hashtable();
if (!strUtil.IsNullOrEmpty( targetString )) {
String target = "";
String[] strArray = targetString.Split( '=' );
if (strArray.Length == 2) {
target = strArray[1];
}
if (strUtil.HasText( target )) {
foreach (String item in target.Split( '|' )) {
String[] arr = item.Split( ':' );
hashtable[arr[0]] = arr[1];
}
}
}
return hashtable;
}
public static Object LoadFromFile( String absFilePath ) {
if (!Zhaizj.Framework.IO.File.Exists( absFilePath )) {
return null;
}
IFormatter formatter = new BinaryFormatter();
Stream serializationStream = new FileStream( absFilePath, FileMode.Open, FileAccess.Read, FileShare.Read );
Object result = formatter.Deserialize( serializationStream );
serializationStream.Close();
return result;
}
public static Object LoadFromString( String targetString, Type targetType ) {
XmlSerializer serializer = new XmlSerializer( targetType );
TextReader textReader = new StringReader( targetString );
Object result = serializer.Deserialize( textReader );
textReader.Close();
return result;
}
public static Object LoadFromXml( String filePath, Type targetType ) {
if (!System.IO.File.Exists( filePath )) {
return null;
}
XmlSerializer serializer = new XmlSerializer( targetType );
Stream stream = new FileStream( filePath, FileMode.Open );
Object result = serializer.Deserialize( stream );
stream.Close();
return result;
}
//-----------------------------------------------------------------------------------------------------------
public static String SaveDicToString( Hashtable tbl ) {
if (tbl == null) {
return null;
}
String str = "HashTable";
StringBuilder builder = new StringBuilder();
builder.Append( str );
builder.Append( "=" );
foreach (DictionaryEntry entry in tbl) {
builder.Append( entry.Key.ToString() + ":" + entry.Value.ToString() + "|" );
}
return builder.ToString().TrimEnd( new char[] { '|' } );
}
public static void SaveToFile( Object target, String absFilePath ) {
IFormatter formatter = new BinaryFormatter();
Stream serializationStream = new FileStream( absFilePath, FileMode.Create, FileAccess.Write, FileShare.None );
formatter.Serialize( serializationStream, target );
serializationStream.Close();
}
public static String SaveToString( Object target ) {
StringBuilder sb = new StringBuilder();
XmlSerializer serializer = new XmlSerializer( target.GetType() );
TextWriter textWriter = new StringWriter( sb );
serializer.Serialize( textWriter, target );
textWriter.Close();
return sb.ToString();
}
public static void SaveToXml( String filePath, Object target ) {
XmlSerializer serializer = new XmlSerializer( target.GetType() );
TextWriter textWriter = new StreamWriter( filePath );
serializer.Serialize( textWriter, target );
textWriter.Close();
}
//-----------------------------------------------------------------------------------------------------------
}
}
@@ -0,0 +1,15 @@
using System;
namespace Zhaizj.Framework.Data {
/// <summary>
/// 数据库连接项的类型
/// </summary>
public enum ConnectionItemType {
Server,
UserId,
Password,
Database
}
}
@@ -0,0 +1,19 @@
using System;
namespace Zhaizj.Framework.Data {
/// <summary>
/// Zhaizj.Framework ORM 支持的数据库类型
/// </summary>
public enum DatabaseType {
Access,
SqlServer,
SqlServer2000,
MySql,
SQLite,
Oracle,
Other
}
}
@@ -0,0 +1,35 @@
using System;
namespace Zhaizj.Framework.Data {
/// <summary>
/// 实体键值类型
/// </summary>
public static class IdType
{
/// <summary>
/// 自动(默认类型)
/// </summary>
public static readonly string Auto="auto";
/// <summary>
/// 整型
/// </summary>
public static readonly string Int = "int";
/// <summary>
/// 长整型
/// </summary>
public static readonly string Long = "long";
/// <summary>
/// Globally Unique Identifier(全球唯一标识符) 也称作 UUID(Universally Unique IDentifier) 。
/// </summary>
public static readonly string Guid = "guid";
/// <summary>
/// 字符型
/// </summary>
public static readonly string String = "string";
}
}
@@ -0,0 +1,14 @@
using System;
namespace Zhaizj.Framework.Data {
/// <summary>
/// 参数类型
/// </summary>
public enum ParameterType {
Integer,
Char,
VarChar
}
}
@@ -0,0 +1,45 @@
using System;
using System.Data;
using System.Data.Common;
namespace Zhaizj.Framework.Data {
/// <summary>
/// 数据工厂,可以不用考虑数据库差异而获取 Connection, Command, DataAdapter
/// </summary>
public class DataFactory {
public static IDbConnection GetConnection( String connectionString, DatabaseType dbtype ) {
return DbFactoryBase.Instance( dbtype ).GetConnection( connectionString );
}
public static IDbCommand GetCommand( String CommandText, IDbConnection cn ) {
return DbFactoryBase.Instance( cn ).GetCommand( CommandText );
}
internal static IDatabaseChecker GetDatabaseChecker( DatabaseType dbtype ) {
return DbFactoryBase.Instance( dbtype ).GetDatabaseChecker();
}
public static IDatabaseDialect GetDialect( DatabaseType dbtype ) {
return DbFactoryBase.Instance( dbtype ).GetDialect();
}
public static Object SetParameter( IDbCommand cmd, String parameterName, Object parameterValue ) {
return DbFactoryBase.Instance( cmd ).SetParameter( cmd, parameterName, parameterValue );
}
public static DbDataAdapter GetAdapter( IDbCommand cmd ) {
return DbFactoryBase.Instance( cmd ).GetAdapter();
}
public static DbDataAdapter GetAdapter( String CommandText, IDbConnection cn ) {
return DbFactoryBase.Instance( cn ).GetAdapter( CommandText );
}
}
}
@@ -0,0 +1,83 @@
using System;
using System.Data;
using System.Data.Common;
namespace Zhaizj.Framework.Data {
/// <summary>
/// 数据工厂抽象基类,可以不用考虑数据库差异而获取 Connection, Command, DataAdapter
/// </summary>
public abstract class DbFactoryBase {
public static DbFactoryBase Instance( String connectionString ) {
DbFactoryBase result = Instance( DbTypeChecker.GetDatabaseType( connectionString ) );
result.cn = result.GetConnection( connectionString );
return result;
}
public static DbFactoryBase Instance( IDbConnection cn ) {
DbFactoryBase result = Instance( DbTypeChecker.GetDatabaseType( cn ) );
result.cn = cn;
return result;
}
public static DbFactoryBase Instance( IDbCommand cmd ) {
DbFactoryBase result = Instance( DbTypeChecker.GetDatabaseType( cmd ) );
result.cmd = cmd;
return result;
}
public static DbFactoryBase Instance( DatabaseType dbtype ) {
if (dbtype == DatabaseType.SqlServer) return new MsSqlDbFactory();
if (dbtype == DatabaseType.SqlServer2000) return new MsSqlDbFactory();
if (dbtype == DatabaseType.Access) return new AccessFactory();
if (dbtype == DatabaseType.MySql) return new MysqlFactory();
if (dbtype == DatabaseType.Oracle) return new OracleFactory();
throw new Exception( lang.get( "dbNotSupport" ) );
}
public abstract IDbConnection GetConnection( String connectionString );
public abstract IDbCommand GetCommand( String CommandText );
internal abstract IDatabaseChecker GetDatabaseChecker();
public abstract IDatabaseDialect GetDialect();
public abstract Object SetParameter( IDbCommand cmd, String parameterName, Object parameterValue );
public abstract DbDataAdapter GetAdapter();
public abstract DbDataAdapter GetAdapter( String CommandText );
protected IDbConnection cn;
protected IDbCommand cmd;
protected virtual void setTransaction( IDbCommand cmd ) {
DbContext.setTransaction( cmd );
}
protected virtual Object processValue( Object parameterValue ) {
if (parameterValue is DateTime) {
DateTime time = (DateTime)parameterValue;
if ((time < new DateTime( 1800, 1, 1 )) || (time > new DateTime( 9000, 1, 1 ))) {
parameterValue = DateTime.Now;
}
}
else if (parameterValue is string) {
parameterValue = parameterValue.ToString().Trim();
}
else if (parameterValue is int && (int)parameterValue == 0) {
parameterValue = Convert.ToInt32( parameterValue );
}
return parameterValue;
}
}
}
@@ -0,0 +1,85 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Data.OracleClient;
using System.Data;
using System.Reflection;
namespace Zhaizj.Framework.Data {
/// <summary>
/// 检查数据库类型的工具
/// </summary>
public class DbTypeChecker {
public static DatabaseType GetDatabaseType( IDbCommand cmd ) {
if (cmd is SqlCommand) {
return DatabaseType.SqlServer;
}
if (cmd is OleDbCommand) {
return DatabaseType.Access;
}
if (cmd.GetType() == MysqlFactory.mySqlCommandType) {
return DatabaseType.MySql;
}
if (cmd is OracleCommand) {
return DatabaseType.Oracle;
}
return DatabaseType.Other;
}
public static DatabaseType GetDatabaseType( IDbConnection cn ) {
if (cn is OleDbConnection) {
return DatabaseType.Access;
}
if (cn is SqlConnection) {
return DatabaseType.SqlServer;
}
if (cn.GetType() == MysqlFactory.mySqlConnectionType) {
return DatabaseType.MySql;
}
if (cn is OracleConnection) {
return DatabaseType.Oracle;
}
return DatabaseType.Other;
}
public static DatabaseType GetDatabaseType( String connectionString ) {
if (!strUtil.IsNullOrEmpty( connectionString )) {
if (connectionString.ToLower().IndexOf( "oledb" ) > 0) {
return DatabaseType.Access;
}
if (connectionString.ToLower().IndexOf( "uid" ) > 0) {
return DatabaseType.SqlServer;
}
if (connectionString.ToLower().IndexOf( "initial catalog" ) > 0) {
return DatabaseType.SqlServer;
}
if (connectionString.ToLower().IndexOf( "user id" ) > 0) {
return DatabaseType.MySql;
}
}
return DatabaseType.Access;
}
public static DatabaseType GetFromString( String typeString ) {
try {
return (DatabaseType)Enum.Parse( typeof( DatabaseType ), typeString, true );
}
catch (Exception ex) {
throw new Exception( "数据库类型设置错误:" + ex.Message );
}
}
}
}
@@ -0,0 +1,57 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
namespace Zhaizj.Framework.Data {
/// <summary>
/// sqlserver Êý¾Ý¹¤³§£¬»ñÈ¡ Connection, Command, DataAdapter
/// </summary>
public class MsSqlDbFactory : DbFactoryBase {
public override IDbConnection GetConnection( String connectionString ) {
return new SqlConnection( connectionString );
}
public override IDbCommand GetCommand( String CommandText ) {
IDbCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandText = CommandText;
setTransaction( cmd );
return cmd;
}
internal override IDatabaseChecker GetDatabaseChecker() {
return new SQLServerDatabaseChecker();
}
public override IDatabaseDialect GetDialect() {
return new SQLServerDialect();
}
public override Object SetParameter( IDbCommand cmd, String parameterName, Object parameterValue ) {
parameterValue = base.processValue( parameterValue );
parameterName = new SQLServerDialect().GetParameterAdder( parameterName );
IDbDataParameter parameter = new SqlParameter( parameterName, parameterValue );
cmd.Parameters.Add( parameter );
return parameterValue;
}
public override DbDataAdapter GetAdapter() {
return new SqlDataAdapter( (SqlCommand)cmd );
}
public override DbDataAdapter GetAdapter( String CommandText ) {
return new SqlDataAdapter( (SqlCommand)GetCommand( CommandText ) );
}
}
}
@@ -0,0 +1,87 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.Common;
using System.Reflection;
namespace Zhaizj.Framework.Data {
/// <summary>
/// mysql Êý¾Ý¹¤³§£¬»ñÈ¡ Connection, Command, DataAdapter
/// </summary>
public class MysqlFactory : DbFactoryBase {
public override IDbConnection GetConnection( String connectionString ) {
return getMySqlConnection( connectionString );
}
public override IDbCommand GetCommand( String CommandText ) {
IDbCommand cmd = getMySqlCommand();
cmd.Connection = cn;
cmd.CommandText = CommandText;
setTransaction( cmd );
return cmd;
}
internal override IDatabaseChecker GetDatabaseChecker() {
return new MysqlDatabaseChecker();
}
public override IDatabaseDialect GetDialect() {
return new MysqlDialect();
}
public override Object SetParameter( IDbCommand cmd, String parameterName, Object parameterValue ) {
parameterValue = base.processValue( parameterValue );
parameterName = new MysqlDialect().GetParameterAdder( parameterName );
IDbDataParameter parameter = getMySqlParameter( parameterName, parameterValue );
cmd.Parameters.Add( parameter );
return parameterValue;
}
public override DbDataAdapter GetAdapter() {
return getMySqlDataAdapter( cmd );
}
public override DbDataAdapter GetAdapter( String CommandText ) {
return getMySqlDataAdapter( GetCommand( CommandText ) );
}
//-----------------------------------
private static IDbCommand getMySqlCommand() {
return (rft.GetInstance( mySqlCommandType ) as IDbCommand);
}
private static IDbConnection getMySqlConnection( String connectionString ) {
return (rft.GetInstance( mySqlConnectionType, new object[] { connectionString } ) as IDbConnection);
}
private static DbDataAdapter getMySqlDataAdapter( Object cmd ) {
return (rft.GetInstance( mySqlDataAssembly.GetType( "MySql.Data.MySqlClient.MySqlDataAdapter" ), new object[] { cmd } ) as DbDataAdapter);
}
private static IDbDataParameter getMySqlParameter( String parameterName, Object parameterValue ) {
return (rft.GetInstance( mySqlDataAssembly.GetType( "MySql.Data.MySqlClient.MySqlParameter" ), new object[] { parameterName, parameterValue } ) as IDbDataParameter);
}
public static Type mySqlCommandType {
get { return mySqlDataAssembly.GetType( "MySql.Data.MySqlClient.MySqlCommand" ); }
}
public static Type mySqlConnectionType {
get { return mySqlDataAssembly.GetType( "MySql.Data.MySqlClient.MySqlConnection" ); }
}
public static Assembly mySqlDataAssembly {
get { return Assembly.Load( "MySql.Data" ); }
}
}
}
@@ -0,0 +1,63 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.OleDb;
using System.Data.Common;
namespace Zhaizj.Framework.Data {
/// <summary>
/// access Êý¾Ý¹¤³§£¬»ñÈ¡ Connection, Command, DataAdapter
/// </summary>
public class AccessFactory : DbFactoryBase {
public override IDbConnection GetConnection( String connectionString ) {
return new OleDbConnection( connectionString );
}
public override IDbCommand GetCommand( String CommandText ) {
IDbCommand cmd = new OleDbCommand();
cmd.Connection = cn;
cmd.CommandText = CommandText;
setTransaction( cmd );
return cmd;
}
internal override IDatabaseChecker GetDatabaseChecker() {
return new AccessDatabaseChecker();
}
public override IDatabaseDialect GetDialect() {
return new AccessDialect();
}
public override Object SetParameter( IDbCommand cmd, String parameterName, Object parameterValue ) {
parameterValue = base.processValue( parameterValue );
parameterName = new AccessDialect().GetParameterAdder( parameterName );
IDbDataParameter parameter;
if (parameterValue is DateTime) {
parameter = new OleDbParameter( parameterName, parameterValue.ToString() );
}
else {
parameter = new OleDbParameter( parameterName, parameterValue );
}
cmd.Parameters.Add( parameter );
return parameterValue;
}
public override DbDataAdapter GetAdapter() {
return new OleDbDataAdapter( (OleDbCommand)cmd );
}
public override DbDataAdapter GetAdapter( String CommandText ) {
return new OleDbDataAdapter( (OleDbCommand)GetCommand( CommandText ) );
}
}
}
@@ -0,0 +1,60 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.OracleClient;
using System.Data.Common;
namespace Zhaizj.Framework.Data {
/// <summary>
/// oracle Êý¾Ý¹¤³§£¬»ñÈ¡ Connection, Command, DataAdapter
/// </summary>
public class OracleFactory : DbFactoryBase {
public override IDbConnection GetConnection( String connectionString ) {
return new OracleConnection( connectionString );
}
public override IDbCommand GetCommand( String CommandText ) {
IDbCommand cmd = new OracleCommand();
cmd.Connection = cn;
cmd.CommandText = CommandText;
setTransaction( cmd );
return cmd;
}
// TODO
internal override IDatabaseChecker GetDatabaseChecker() {
throw new Exception( lang.get( "dbNotSupport" ) );
}
// TODO
public override IDatabaseDialect GetDialect() {
throw new Exception( lang.get( "dbNotSupport" ) );
}
public override Object SetParameter( IDbCommand cmd, String parameterName, Object parameterValue ) {
parameterValue = base.processValue( parameterValue );
// TODO
//parameterName = new SQLServerDialect().GetParameterAdder( parameterName );
IDbDataParameter parameter = new OracleParameter( parameterName, parameterValue );
cmd.Parameters.Add( parameter );
return parameterValue;
}
public override DbDataAdapter GetAdapter() {
return new OracleDataAdapter( (OracleCommand)cmd );
}
public override DbDataAdapter GetAdapter( String CommandText ) {
return new OracleDataAdapter( (OracleCommand)GetCommand( CommandText ) );
}
}
}
@@ -0,0 +1,38 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using Zhaizj.Framework.ORM;
namespace Zhaizj.Framework.Data {
internal class AccessTableBuilder : TableBuilderBase {
private Boolean isAddIdentityKey( Type t ) {
if (OrmHelper.IsEntityBase( t.BaseType )) return true;
if (t.BaseType.IsAbstract) return true;
return false;
}
protected override void addColumn_Decimal( EntityInfo entity, StringBuilder sb, EntityPropertyInfo ep, String columnName ) {
if (ep.MoneyAttribute != null) {
sb.Append( columnName );
sb.Append( " currency default 0, " );
}
else {
DecimalAttribute da = ep.DecimalAttribute;
if (da == null) throw new Exception( "DecimalAttribute not found=" + entity.FullName + "_" + ep.Name );
sb.Append( columnName );
sb.Append( " decimal(" + da.Precision + "," + da.Scale + ") default 0, " );
}
}
protected override void addColumn_MiddleText( EntityInfo entity, StringBuilder sb, EntityPropertyInfo temP, string columnName ) {
addColumn_LongText( entity, sb, columnName );
}
}
}
@@ -0,0 +1,75 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using Zhaizj.Framework.ORM;
namespace Zhaizj.Framework.Data {
internal class MySqlTableBuilder : TableBuilderBase {
protected override void addColumn_PrimaryKey( EntityInfo entity, StringBuilder sb, IDictionary clsList ) {
sb.Append( " Id int unsigned not null auto_increment primary key, " );
}
protected override void addColumn_Int( StringBuilder sb, EntityPropertyInfo ep, String columnName ) {
sb.Append( columnName );
if (ep.Property.IsDefined( typeof( TinyIntAttribute ), false )) {
sb.Append( " tinyint unsigned default 0, " );
}
else {
sb.Append( " int unsigned default 0, " );
}
}
protected override void addColumn_LongText( EntityInfo entity, StringBuilder sb, String columnName ) {
sb.Append( columnName );
sb.Append( " text, " );
}
protected override void addColumn_ShortText( StringBuilder sb, String columnName, int length ) {
sb.Append( columnName );
sb.Append( " varchar(" );
sb.Append( length );
sb.Append( "), " );
}
protected override void addColumn_Decimal( EntityInfo entity, StringBuilder sb, EntityPropertyInfo ep, String columnName ) {
if (ep.MoneyAttribute != null) {
sb.Append( columnName );
sb.Append( " decimal(19, 4) default 0, " );
}
else {
DecimalAttribute da = ep.DecimalAttribute;
if (da == null) throw new Exception( "DecimalAttribute not found=" + entity.FullName + "_" + ep.Name );
sb.Append( columnName );
sb.Append( " decimal(" + da.Precision + "," + da.Scale + ") default 0, " );
}
}
protected override void addColumn_Double( EntityInfo entity, StringBuilder sb, string columnName ) {
sb.Append( columnName );
sb.Append( " double default 0, " );
}
protected override void addColumn_Single( EntityInfo entity, StringBuilder sb, string columnName ) {
sb.Append( columnName );
sb.Append( " float default 0, " );
}
}
}
@@ -0,0 +1,10 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace Zhaizj.Framework.Data {
internal class SqlServerTableBuilder : TableBuilderBase {
}
}
@@ -0,0 +1,226 @@
using System;
using System.Data;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using Zhaizj.Framework.ORM;
using Zhaizj.Framework.Log;
namespace Zhaizj.Framework.Data {
internal class TableBuilderBase {
private static readonly ILog logger = LogManager.GetLogger( typeof( TableBuilderBase ) );
public List<String> CheckMappingTableIsExist( IDbCommand cmd, String db, List<String> existTables, MappingClass mapping ) {
foreach (DictionaryEntry entry in mapping.ClassList) {
EntityInfo entity = entry.Value as EntityInfo;
if (entity.Database.Equals( db ) == false) continue;
if (!isTableCreated( existTables, entity )) {
existTables = createTable( entity, cmd, existTables, mapping.ClassList );
}
}
return existTables;
}
private List<String> createTable( EntityInfo entity, IDbCommand cmd, List<String> existTables, IDictionary clsList ) {
StringBuilder sb = new StringBuilder();
sb.AppendFormat( "Create Table {0} (", getFullName( entity.TableName, entity ) );
addColumn_PrimaryKey( entity, sb, clsList );
addColumns( entity, sb );
String str = sb.ToString().Trim().TrimEnd( new char[] { ',' } ) + " )";
cmd.CommandText = str;
logger.Info( "create table:" + str );
if (cmd.Connection == null) throw new Exception( "connection is null" );
if (cmd.Connection.State == ConnectionState.Closed) {
cmd.Connection.Open();
}
cmd.ExecuteNonQuery();
existTables.Add( entity.TableName );
logger.Info( LoggerUtil.SqlPrefix + String.Format( "create table {0} ({1})", entity.TableName, entity.FullName ) );
return existTables;
}
private void addColumns( EntityInfo entity, StringBuilder sb ) {
for (int i = 0; i < entity.SavedPropertyList.Count; i++) {
EntityPropertyInfo ep = entity.SavedPropertyList[i];
String columnName = getFullName( ep.ColumnName, entity );
if ((ep.SaveToDB && !ep.IsList) && !(ep.Name == "Id")) {
addColumnSingle( entity, sb, ep, columnName );
}
}
}
private void addColumnSingle( EntityInfo entity, StringBuilder sb, EntityPropertyInfo ep, String columnName ) {
if (ep.Type == typeof( int )) {
addColumn_Int( sb, ep, columnName );
}
else if (ep.Type == typeof( DateTime )) {
addColumn_Time( sb, columnName );
}
else if (ep.Type == typeof( decimal )) {
addColumn_Decimal( entity, sb, ep, columnName );
}
else if (ep.Type == typeof( double )) {
addColumn_Double( entity, sb, columnName );
}
else if (ep.Type == typeof( float )) {
addColumn_Single( entity, sb, columnName );
}
else if (ep.Type == typeof( String )) {
addColumn_String( entity, sb, ep, columnName );
}
else if (ep.IsEntity) {
addColumn_entity( sb, columnName );
}
}
//------------------------------------------------------------------------------------------------------------------------
protected virtual void addColumn_PrimaryKey( EntityInfo entity, StringBuilder sb, IDictionary clsList ) {
// 不是自动编号
if (!DbConfig.Instance.IsAutoId || isAddIdentityKey( entity.Type ) == false) {
sb.Append( " Id int primary key default 0, " );
}
else {
sb.Append( " Id int identity(1,1) primary key, " );
}
}
private Boolean isAddIdentityKey( Type t ) {
if (OrmHelper.IsEntityBase( t.BaseType )) return true;
if (t.BaseType.IsAbstract) return true;
return false;
}
protected virtual void addColumn_Int( StringBuilder sb, EntityPropertyInfo ep, String columnName ) {
sb.Append( columnName );
if (ep.Property.IsDefined( typeof( TinyIntAttribute ), false )) {
sb.Append( " tinyint default 0, " );
}
else {
sb.Append( " int default 0, " );
}
}
protected virtual void addColumn_Time( StringBuilder sb, String columnName ) {
sb.Append( columnName );
sb.Append( " DateTime, " );
}
protected virtual void addColumn_Decimal( EntityInfo entity, StringBuilder sb, EntityPropertyInfo ep, String columnName ) {
if (ep.MoneyAttribute != null) {
sb.Append( columnName );
sb.Append( " money default 0, " );
}
else {
DecimalAttribute da = ep.DecimalAttribute;
if (da == null) throw new Exception( "DecimalAttribute not found=" + entity.FullName + "_" + ep.Name );
sb.Append( columnName );
sb.Append( " decimal(" + da.Precision + "," + da.Scale + ") default 0, " );
}
}
protected virtual void addColumn_Double( EntityInfo entity, StringBuilder sb, string columnName ) {
sb.Append( columnName );
sb.Append( " float default 0, " );
}
protected virtual void addColumn_Single( EntityInfo entity, StringBuilder sb, string columnName ) {
sb.Append( columnName );
sb.Append( " real default 0, " );
}
protected virtual void addColumn_String( EntityInfo entity, StringBuilder sb, EntityPropertyInfo ep, String columnName ) {
if (ep.LongTextAttribute != null) {
addColumn_LongText( entity, sb, columnName );
}
else if (ep.SaveAttribute != null) {
addColumn_ByColumnAttribute( entity, sb, ep, columnName );
}
else {
addColumn_ShortText( sb, columnName, 250 );
}
}
protected virtual void addColumn_LongText( EntityInfo entity, StringBuilder sb, String columnName ) {
sb.Append( columnName );
sb.Append( " ntext, " );
}
protected virtual void addColumn_ShortText( StringBuilder sb, String columnName, int length ) {
sb.Append( columnName );
sb.Append( " nvarchar(" );
sb.Append( length );
sb.Append( "), " );
}
protected virtual void addColumn_ByColumnAttribute( EntityInfo entity, StringBuilder sb, EntityPropertyInfo ep, String columnName ) {
if (ep.SaveAttribute.Length < 255) {
addColumn_ShortText( sb, columnName, ep.SaveAttribute.Length );
}
else if ((ep.SaveAttribute.Length > 255) && (ep.SaveAttribute.Length < 4000)) {
addColumn_MiddleText( entity, sb, ep, columnName );
}
else {
addColumn_LongText( entity, sb, columnName );
}
}
protected virtual void addColumn_MiddleText( EntityInfo entity, StringBuilder sb, EntityPropertyInfo ep, String columnName ) {
addColumn_ShortText( sb, columnName, ep.SaveAttribute.Length );
}
protected virtual void addColumn_entity( StringBuilder sb, String columnName ) {
sb.Append( columnName );
sb.Append( " int default 0, " );
}
//------------------------------------------------------------------------------------------------------------------------
private String getFullName( String name, EntityInfo entity ) {
if (DbConst.SqlKeyWords.Contains( name.ToLower() )) {
String message = String.Format( "'{0}' is reserved word. Entity:{1}, Table:{2}", name, entity.FullName, entity.TableName );
logger.Info( message );
throw new Exception( message );
}
return name;
}
private Boolean isTableCreated( IList existTables, EntityInfo entity ) {
for (int i = 0; i < existTables.Count; i++) {
if (string.Compare( existTables[i].ToString(), entity.TableName.Replace( "[", "" ).Replace( "]", "" ), true ) == 0) {
logger.Info( "table map : " + entity.FullName + " => " + existTables[i] );
return true;
}
}
return false;
}
}
}